context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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 Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class TransactionTest { [Fact] public static void TestYukon() { new TransactionTestWorker((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString).StartTest(); } [Fact] public static void TestKatmai() { new TransactionTestWorker((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString).StartTest(); } private sealed class TransactionTestWorker { private readonly string _tempTableName1; private readonly string _tempTableName2; private string _connectionString; public TransactionTestWorker(string connectionString) { _connectionString = connectionString; _tempTableName1 = string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_'); _tempTableName2 = _tempTableName1 + "_2"; } public void StartTest() { try { PrepareTables(); CommitTransactionTest(); ResetTables(); RollbackTransactionTest(); ResetTables(); ScopedTransactionTest(); ResetTables(); ExceptionTest(); ResetTables(); ReadUncommitedIsolationLevel_ShouldReturnUncommitedData(); ResetTables(); ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction(); ResetTables(); } finally { //make sure to clean up DropTempTables(); } } private void PrepareTables() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); SqlCommand command = new SqlCommand(string.Format("CREATE TABLE [{0}]([CustomerID] [nchar](5) NOT NULL PRIMARY KEY, [CompanyName] [nvarchar](40) NOT NULL, [ContactName] [nvarchar](30) NULL)", _tempTableName1), conn); command.ExecuteNonQuery(); command.CommandText = "create table " + _tempTableName2 + "(col1 int, col2 varchar(32))"; command.ExecuteNonQuery(); } } private void DropTempTables() { using (var conn = new SqlConnection(_connectionString)) { SqlCommand command = new SqlCommand( string.Format("DROP TABLE [{0}]; DROP TABLE [{1}]", _tempTableName1, _tempTableName2), conn); conn.Open(); command.ExecuteNonQuery(); } } public void ResetTables() { using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(string.Format("TRUNCATE TABLE [{0}]; TRUNCATE TABLE [{1}]", _tempTableName1, _tempTableName2), connection)) { command.ExecuteNonQuery(); } } } private void CommitTransactionTest() { using (SqlConnection connection = new SqlConnection(_connectionString)) { SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection); connection.Open(); SqlTransaction tx = connection.BeginTransaction(); command.Transaction = tx; using (SqlDataReader reader = command.ExecuteReader()) { Assert.False(reader.HasRows, "Error: table is in incorrect state for test."); } using (SqlCommand command2 = connection.CreateCommand()) { command2.Transaction = tx; command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );"; command2.ExecuteNonQuery(); } tx.Commit(); using (SqlDataReader reader = command.ExecuteReader()) { int count = 0; while (reader.Read()) { count++; } Assert.True(count == 1, "Error: incorrect number of rows in table after update."); Assert.Equal(count, 1); } } } private void RollbackTransactionTest() { using (SqlConnection connection = new SqlConnection(_connectionString)) { SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection); connection.Open(); SqlTransaction tx = connection.BeginTransaction(); command.Transaction = tx; using (SqlDataReader reader = command.ExecuteReader()) { Assert.False(reader.HasRows, "Error: table is in incorrect state for test."); } using (SqlCommand command2 = connection.CreateCommand()) { command2.Transaction = tx; command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );"; command2.ExecuteNonQuery(); } tx.Rollback(); using (SqlDataReader reader = command.ExecuteReader()) { Assert.False(reader.HasRows, "Error Rollback Test : incorrect number of rows in table after rollback."); int count = 0; while (reader.Read()) count++; Assert.Equal(count, 0); } connection.Close(); } } private void ScopedTransactionTest() { using (SqlConnection connection = new SqlConnection(_connectionString)) { SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection); connection.Open(); SqlTransaction tx = connection.BeginTransaction("transName"); command.Transaction = tx; using (SqlDataReader reader = command.ExecuteReader()) { Assert.False(reader.HasRows, "Error: table is in incorrect state for test."); } using (SqlCommand command2 = connection.CreateCommand()) { command2.Transaction = tx; command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );"; command2.ExecuteNonQuery(); } tx.Save("saveName"); //insert another one using (SqlCommand command2 = connection.CreateCommand()) { command2.Transaction = tx; command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXW2', 'XY2', 'KK' );"; command2.ExecuteNonQuery(); } tx.Rollback("saveName"); using (SqlDataReader reader = command.ExecuteReader()) { Assert.True(reader.HasRows, "Error Scoped Transaction Test : incorrect number of rows in table after rollback to save state one."); int count = 0; while (reader.Read()) count++; Assert.Equal(count, 1); } tx.Rollback(); connection.Close(); } } private void ExceptionTest() { using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); SqlTransaction tx = connection.BeginTransaction(); string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName; string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery"); string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch; string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection"); AssertException<InvalidOperationException>(() => { SqlCommand command = new SqlCommand("sql", connection); command.ExecuteNonQuery(); }, executeCommandWithoutTransactionMessage); AssertException<InvalidOperationException>(() => { SqlConnection con1 = new SqlConnection(_connectionString); con1.Open(); SqlCommand command = new SqlCommand("sql", con1); command.Transaction = tx; command.ExecuteNonQuery(); }, transactionConflictErrorMessage); AssertException<InvalidOperationException>(() => { connection.BeginTransaction(null); }, parallelTransactionErrorMessage); AssertException<InvalidOperationException>(() => { connection.BeginTransaction(""); }, parallelTransactionErrorMessage); AssertException<ArgumentException>(() => { tx.Rollback(null); }, invalidSaveStateMessage); AssertException<ArgumentException>(() => { tx.Rollback(""); }, invalidSaveStateMessage); AssertException<ArgumentException>(() => { tx.Save(null); }, invalidSaveStateMessage); AssertException<ArgumentException>(() => { tx.Save(""); }, invalidSaveStateMessage); } } public static void AssertException<T>(Action action, string expectedErrorMessage) where T : Exception { var exception = Assert.Throws<T>(action); Assert.Equal(exception.Message, expectedErrorMessage); } private void ReadUncommitedIsolationLevel_ShouldReturnUncommitedData() { using (SqlConnection connection1 = new SqlConnection(_connectionString)) { connection1.Open(); SqlTransaction tx1 = connection1.BeginTransaction(); using (SqlCommand command1 = connection1.CreateCommand()) { command1.Transaction = tx1; command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );"; command1.ExecuteNonQuery(); } using (SqlConnection connection2 = new SqlConnection(_connectionString)) { SqlCommand command2 = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection2); connection2.Open(); SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadUncommitted); command2.Transaction = tx2; using (SqlDataReader reader = command2.ExecuteReader()) { int count = 0; while (reader.Read()) count++; Assert.True(count == 1, "Should Expected 1 row because Isolation Level is read uncommitted which should return uncommitted data."); } tx2.Rollback(); connection2.Close(); } tx1.Rollback(); connection1.Close(); } } private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction() { using (SqlConnection connection1 = new SqlConnection(_connectionString)) { connection1.Open(); SqlTransaction tx1 = connection1.BeginTransaction(); using (SqlCommand command1 = connection1.CreateCommand()) { command1.Transaction = tx1; command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );"; command1.ExecuteNonQuery(); } using (SqlConnection connection2 = new SqlConnection(_connectionString)) { SqlCommand command2 = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection2); connection2.Open(); SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted); command2.Transaction = tx2; AssertException<SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string); tx2.Rollback(); connection2.Close(); } tx1.Rollback(); connection1.Close(); } } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class RandomizeGroupTargetTests : NLogTestBase { [Fact] public void RandomizeGroupSyncTest1() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new RandomizeGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Assert.Equal(10, myTarget1.WriteCount + myTarget2.WriteCount + myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } Assert.Equal(1, myTarget1.FlushCount); Assert.Equal(1, myTarget2.FlushCount); Assert.Equal(1, myTarget3.FlushCount); } [Fact] public void RandomizeGroupSyncTest2() { var wrapper = new RandomizeGroupTarget() { // no targets }; wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Exception flushException = new Exception("Flush not hit synchronously."); wrapper.Flush(ex => flushException = ex); if (flushException != null) { Assert.True(false, flushException.ToString()); } } public class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public MyAsyncTarget() : base() { } public MyAsyncTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; if (FailCounter > 0) { FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } }
using System; using System.Collections; using System.Windows.Forms; namespace joveClient { public class StringRegistryEntry { public string Host; public string Name; public object Obj; public StringRegistryEntry(string h, string n, object o) { Host = h; Name = n; Obj = o; } public StringRegistryRep copyRep() { StringRegistryRep srr = new StringRegistryRep(); srr.Host = Host; srr.Name = Name; return srr; } } public class StringRegistry { private ArrayList _data; private ArrayList _hosts; public StringRegistry() { _data = new ArrayList(); _hosts = new ArrayList(); } public void Clear() { _data = new ArrayList(); } public ArrayList copyRep() { ArrayList d = new ArrayList(); foreach(StringRegistryEntry sre in _data) d.Add(sre.copyRep()); return d; } public void RegisterHost(string host) { if(! _hosts.Contains(host)) _hosts.Add(host); } public void RegisterObject(string host, string name, object o) { if(! _hosts.Contains(host)) _hosts.Add(host); if(Get(host,name)==null) _data.Add( new StringRegistryEntry(host,name,o)); } public void RemapString(string host, string nameOld, string nameNew) { foreach(StringRegistryEntry sre in _data) { if(sre.Host.Equals(host) && sre.Name.Equals(nameOld)) { sre.Name = nameNew; return; } } } public bool Exists(string host, string name) { foreach(StringRegistryEntry sre in _data) { if(sre.Host.Equals(host) && sre.Name.Equals(name)) { return true; } } return false; } public StringRegistryEntry Get(string host, string name) { foreach(StringRegistryEntry sre in _data) { if(sre.Host.ToLower().Trim().Equals(host.ToLower().Trim()) && sre.Name.ToLower().Trim().Equals(name.ToLower().Trim())) { return sre; } } return null; } public ArrayList GetAll() { return _data; } public void Unregister(string host, string name) { StringRegistryEntry sre = Get(host,name); if(sre != null) _data.Remove(sre); } public void Unregister(StringRegistryEntry sre) { if(sre != null) _data.Remove(sre); } public StringRegistryEntry GetEntry(TreeNode tn) { TreeNode top = tn; TreeNode trace = tn; string name = ""; string host = ""; while(trace.Parent != null) { if(name.Equals("")) { name = trace.Text; } else { name = trace.Text + "/" + name; } trace = trace.Parent; } host = trace.Text; return Get(host,name); } private bool _dirty = true; private void InsertHost(TreeNode node, string name) { int kF = name.IndexOf("/"); if(kF >= 0) { string grp = name.Substring(0,kF).Trim(); string nxt = name.Substring(kF+1).Trim(); foreach(TreeNode child in node.Nodes) { if(child.Text.Equals(grp)) { InsertHost(child,nxt); return; } } _dirty = true; TreeNode child2 = new TreeNode(grp); node.Nodes.Add(child2); InsertHost(child2,nxt); } else { bool found = false; foreach(TreeNode child in node.Nodes) { if(child.Text.Equals(name)) { found = true; } } if(!found) { _dirty = true; node.Nodes.Add( new TreeNode( name ) ); } } } private void PopulateHost(TreeNode root, string host) { foreach(StringRegistryEntry sre in _data) { if(sre.Host.Equals(host)) { InsertHost(root, sre.Name.ToLower().Trim()); } } } public void PopulateTree(TreeView tv) { tv.Nodes.Clear(); foreach(string x in _hosts) { TreeNode tn = new TreeNode(x); tv.Nodes.Add(tn); PopulateHost(tn,x); } tv.Sort(); } private bool CleanTree(TreeNode tn, string host, string x) { if(tn.Nodes.Count == 0) { return Get(host,x) == null; } else { ArrayList killList = new ArrayList(); foreach(TreeNode c in tn.Nodes) { bool killMe = false; if(x.Equals("")) killMe = CleanTree(c,host,c.Text); else killMe = CleanTree(c,host,x + "/" + c.Text); if(killMe) { killList.Add(c); } } if(killList.Count > 0) _dirty = true; foreach(TreeNode c in killList) { tn.Nodes.Remove(c); } return tn.Nodes.Count == 0; } } public void UpdateTree(TreeView tv) { _dirty = false; foreach(TreeNode c in tv.Nodes) { foreach(StringRegistryEntry sre in _data) { if(sre.Host.ToLower().Trim().Equals(c.Text.ToLower().Trim())) { InsertHost(c,sre.Name); } } } if(_dirty) tv.Sort(); } public void CleanTree(TreeView tv) { foreach(TreeNode tn in tv.Nodes) { CleanTree(tn, tn.Text, ""); } } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Apis.Upload; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Threading.Tasks; using System.Xml.Linq; using Xunit; namespace Google.Cloud.Storage.V1.IntegrationTests { using static TestHelpers; [Collection(nameof(StorageFixture))] public class UrlSignerTest { private static readonly TimeSpan _duration = TimeSpan.FromSeconds(5); private readonly StorageFixture _fixture; public UrlSignerTest(StorageFixture fixture) { _fixture = fixture; _fixture.RegisterDelayTests(this); } private static string GetTestName([CallerMemberName] string methodName = null) { return $"{nameof(UrlSignerTest)}.{methodName}"; } [Fact] public async Task DeleteTest() => await _fixture.FinishDelayTest(GetTestName()); private void DeleteTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, name, duration, HttpMethod.Delete); // Upload an object which can be deleted with the URL. await _fixture.Client.UploadObjectAsync(bucket, name, "", new MemoryStream(_fixture.SmallContent)); // Verify that the URL works initially. var response = await _fixture.HttpClient.DeleteAsync(url); await VerifyResponseAsync(response); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); // Restore the object. await _fixture.Client.UploadObjectAsync(bucket, name, "", new MemoryStream(_fixture.SmallContent)); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.DeleteAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.NotNull(obj); // Cleanup await _fixture.Client.DeleteObjectAsync(bucket, name); }); } [Fact] public async Task GetTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetTest_InitDelayTest() { string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(_fixture.ReadBucket, _fixture.SmallObject, duration); // Verify that the URL works initially. var response = await _fixture.HttpClient.GetAsync(url); var result = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(_fixture.SmallContent, result); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.GetAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task GetBucketTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetBucketTest_InitDelayTest() { var bucket = _fixture.ReadBucket; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, null, duration); // Verify that the URL works initially. var response = await _fixture.HttpClient.GetAsync(url); var result = await response.Content.ReadAsStringAsync(); var document = XDocument.Parse(result); var ns = document.Root.GetDefaultNamespace(); var keys = document.Root.Elements(ns + "Contents").Select(contents => contents.Element(ns + "Key").Value).ToList(); var objectNames = await _fixture.Client.ListObjectsAsync(bucket, null).Select(o => o.Name).ToList(); Assert.Equal(objectNames, keys); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.GetAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task GetObjectWithSpacesTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetObjectWithSpacesTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName() + " with spaces"; var content = _fixture.SmallContent; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { _fixture.Client.UploadObject(bucket, name, null, new MemoryStream(content)); url = _fixture.UrlSigner.Sign(bucket, name, duration); // Verify that the URL works initially. var response = await _fixture.HttpClient.GetAsync(url); await VerifyResponseAsync(response); var result = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(content, result); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.GetAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task GetWithCustomerSuppliedEncryptionKeysTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetWithCustomerSuppliedEncryptionKeysTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; string url = null; EncryptionKey key = EncryptionKey.Generate(); Func<HttpRequestMessage> createGetRequest = () => { var request = new HttpRequestMessage { Method = HttpMethod.Get }; key.ModifyRequest(request); return request; }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var encryptingClient = StorageClient.Create(encryptionKey: key); encryptingClient.UploadObject(bucket, name, "application/octet-stream", new MemoryStream(data)); var request = createGetRequest(); url = _fixture.UrlSigner.Sign(bucket, name, duration, request); request.RequestUri = new Uri(url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(request); var result = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(data, result); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createGetRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); // Cleanup await _fixture.Client.DeleteObjectAsync(bucket, name); }); } [Fact] public async Task GetNoExpirationTest() { var url = _fixture.UrlSigner.Sign(_fixture.ReadBucket, _fixture.SmallObject, expiration: null); // Verify that the URL works. var response = await _fixture.HttpClient.GetAsync(url); var result = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(_fixture.SmallContent, result); } [Fact] public async Task GetWithCustomHeadersTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetWithCustomHeadersTest_InitDelayTest() { string url = null; Func<HttpRequestMessage> createRequest = () => new HttpRequestMessage() { Method = HttpMethod.Get, Headers = { { "x-goog-foo", "xy\r\n z" }, { "x-goog-bar", " 12345 " }, { "x-goog-foo", new [] { "A B C", "def" } } } }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var request = createRequest(); url = _fixture.UrlSigner.Sign( _fixture.ReadBucket, _fixture.SmallObject, duration, request); request.RequestUri = new Uri(url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(request); var result = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(_fixture.SmallContent, result); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task HeadTest() => await _fixture.FinishDelayTest(GetTestName()); private void HeadTest_InitDelayTest() { Func<HttpRequestMessage> createRequest = null; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign( _fixture.ReadBucket, _fixture.SmallObject, duration, HttpMethod.Head); createRequest = () => new HttpRequestMessage(HttpMethod.Head, url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(createRequest()); await VerifyResponseAsync(response); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.SendAsync(createRequest()); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task HeadWithGetMethodSignedURLTest() => await _fixture.FinishDelayTest(GetTestName()); private void HeadWithGetMethodSignedURLTest_InitDelayTest() { Func<HttpRequestMessage> createRequest = null; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign( _fixture.ReadBucket, _fixture.SmallObject, duration, HttpMethod.Get); createRequest = () => new HttpRequestMessage(HttpMethod.Head, url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(createRequest()); await VerifyResponseAsync(response); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.SendAsync(createRequest()); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task PutTest() => await _fixture.FinishDelayTest(GetTestName()); private void PutTest_InitDelayTest() { Func<Task> expireAction1 = null; Func<Task> expireAction2 = null; Func<Task> expireAction3 = null; Func<Task> expireAction4 = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { expireAction1 = await PutTestHelper(duration, useContentMD5: false, useContentType: false); expireAction2 = await PutTestHelper(duration, useContentMD5: true, useContentType: false); expireAction3 = await PutTestHelper(duration, useContentMD5: false, useContentType: true); expireAction4 = await PutTestHelper(duration, useContentMD5: true, useContentType: true); }, afterDelay: async () => { await expireAction1(); await expireAction2(); await expireAction3(); await expireAction4(); }); } private async Task<Func<Task>> PutTestHelper(TimeSpan duration, bool useContentMD5, bool useContentType) { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; Func<ByteArrayContent> createPutContent = () => { var putContent = new ByteArrayContent(data); if (useContentMD5) { using (var md5 = MD5.Create()) { putContent.Headers.ContentMD5 = md5.ComputeHash(data); } } if (useContentType) { putContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); } return putContent; }; var content = createPutContent(); var url = _fixture.UrlSigner.Sign( bucket, name, duration, HttpMethod.Put, contentHeaders: content.Headers.ToDictionary(h => h.Key, h => h.Value)); // Verify that the URL works initially. var response = await _fixture.HttpClient.PutAsync(url, content); await VerifyResponseAsync(response); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); Assert.Equal(result.ToArray(), _fixture.SmallContent); // Reset the state and wait until the URL expires. await _fixture.Client.DeleteObjectAsync(bucket, name); return async () => { // Verify that the URL no longer works. content = createPutContent(); response = await _fixture.HttpClient.PutAsync(url, content); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }; } [Fact] public async Task PutWithCustomerSuppliedEncryptionKeysTest() => await _fixture.FinishDelayTest(GetTestName()); private void PutWithCustomerSuppliedEncryptionKeysTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; string url = null; EncryptionKey key = EncryptionKey.Generate(); Func<HttpRequestMessage> createPutRequest = () => { var request = new HttpRequestMessage { Method = HttpMethod.Put, Content = new ByteArrayContent(data) }; key.ModifyRequest(request); return request; }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var request = createPutRequest(); url = _fixture.UrlSigner.Sign(bucket, name, duration, request); // Verify that the URL works initially. request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); await VerifyResponseAsync(response); // Make sure the encryption succeeded. var downloadedData = new MemoryStream(); await Assert.ThrowsAsync<GoogleApiException>( () => _fixture.Client.DownloadObjectAsync(bucket, name, downloadedData)); await _fixture.Client.DownloadObjectAsync(bucket, name, downloadedData, new DownloadObjectOptions { EncryptionKey = key }); Assert.Equal(data, downloadedData.ToArray()); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createPutRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); // Cleanup await _fixture.Client.DeleteObjectAsync(bucket, name); }); } [Fact] public async Task PutWithCustomHeadersTest() => await _fixture.FinishDelayTest(GetTestName()); private void PutWithCustomHeadersTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; string url = null; Func<HttpRequestMessage> createRequest = () => { using (var md5 = MD5.Create()) { return new HttpRequestMessage() { Content = new ByteArrayContent(data) { Headers = { { "Content-MD5", Convert.ToBase64String(md5.ComputeHash(data)) }, { "Content-Type", "text/plain" }, { "x-goog-z-content-foo", "val1" }, { "x-goog-a-content-bar", "val2" }, { "x-goog-foo", new [] { "val3", "val4" } } } }, Method = HttpMethod.Put, Headers = { { "x-goog-foo2", "xy\r\n z" }, { "x-goog-bar", " 12345 " }, { "x-goog-foo2", new [] { "A B C", "def" } } } }; } }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var request = createRequest(); url = _fixture.UrlSigner.Sign(bucket, name, duration, request); request.RequestUri = new Uri(url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(request); await VerifyResponseAsync(response); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); Assert.Equal(result.ToArray(), _fixture.SmallContent); // Reset the state. await _fixture.Client.DeleteObjectAsync(bucket, name); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }); } [Fact] public async Task ResumableUploadTest() => await _fixture.FinishDelayTest(GetTestName()); private void ResumableUploadTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, name, duration, UrlSigner.ResumableHttpMethod); // Verify that the URL works initially. var uploader = SignedUrlResumableUpload.Create(url, new MemoryStream(data)); var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Completed, progress.Status); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); Assert.Equal(result.ToArray(), data); // Reset the state. await _fixture.Client.DeleteObjectAsync(bucket, name); }, afterDelay: async () => { var uploader = SignedUrlResumableUpload.Create(url, new MemoryStream(data)); // Verify that the URL no longer works. var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Failed, progress.Status); Assert.IsType<GoogleApiException>(progress.Exception); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }); } [Fact] public async Task ResumableUploadResumeTest() => await _fixture.FinishDelayTest(GetTestName()); private void ResumableUploadResumeTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, name, duration, UrlSigner.ResumableHttpMethod); var sessionUri = await SignedUrlResumableUpload.InitiateSessionAsync(url); // Verify that the URL works initially. var uploader = ResumableUpload.CreateFromUploadUri(sessionUri, new MemoryStream(data)); var progress = await uploader.ResumeAsync(sessionUri); Assert.Null(progress.Exception); Assert.Equal(UploadStatus.Completed, progress.Status); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); Assert.Equal(result.ToArray(), data); // Reset the state. await _fixture.Client.DeleteObjectAsync(bucket, name); }, afterDelay: async () => { // Verify that the URL no longer works. await Assert.ThrowsAsync<GoogleApiException>(() => SignedUrlResumableUpload.InitiateSessionAsync(url)); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }); } [Fact] public async Task ResumableUploadWithCustomerSuppliedEncryptionKeysTest() => await _fixture.FinishDelayTest(GetTestName()); private void ResumableUploadWithCustomerSuppliedEncryptionKeysTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = GenerateName(); var data = _fixture.SmallContent; string url = null; EncryptionKey key = EncryptionKey.Generate(); _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign( bucket, name, duration, UrlSigner.ResumableHttpMethod, requestHeaders: new Dictionary<string, IEnumerable<string>> { { "x-goog-encryption-algorithm", new [] { "AES256" } } }); // Verify that the URL works initially. var uploader = SignedUrlResumableUpload.Create( url, new MemoryStream(data), new ResumableUploadOptions { ModifySessionInitiationRequest = key.ModifyRequest }); var progress = await uploader.UploadAsync(); Assert.Null(progress.Exception); Assert.Equal(UploadStatus.Completed, progress.Status); // Make sure the encryption succeeded. var downloadedData = new MemoryStream(); await Assert.ThrowsAsync<GoogleApiException>( () => _fixture.Client.DownloadObjectAsync(bucket, name, downloadedData)); await _fixture.Client.DownloadObjectAsync(bucket, name, downloadedData, new DownloadObjectOptions { EncryptionKey = key }); Assert.Equal(data, downloadedData.ToArray()); }, afterDelay: async () => { var uploader = SignedUrlResumableUpload.Create( url, new MemoryStream(data), new ResumableUploadOptions { ModifySessionInitiationRequest = key.ModifyRequest }); // Verify that the URL no longer works. var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Failed, progress.Status); Assert.IsType<GoogleApiException>(progress.Exception); }); } private static async Task VerifyResponseAsync(HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { // This will automatically fail, but gives more information about the failure cause than // simply asserting that IsSuccessStatusCode is true. Assert.Null(await response.Content.ReadAsStringAsync()); } } } }
// dnlib: See LICENSE.txt for more info using System; using System.Threading; using dnlib.DotNet.MD; using dnlib.Threading; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the ExportedType table /// </summary> public abstract class ExportedType : IHasCustomAttribute, IImplementation, IType { /// <summary> /// The row id in its table /// </summary> protected uint rid; #if THREAD_SAFE readonly Lock theLock = Lock.Create(); #endif /// <summary> /// The owner module /// </summary> protected ModuleDef module; /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.ExportedType, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <inheritdoc/> public int HasCustomAttributeTag { get { return 17; } } /// <inheritdoc/> public int ImplementationTag { get { return 2; } } /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes == null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() { Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); } /// <inheritdoc/> public bool HasCustomAttributes { get { return CustomAttributes.Count > 0; } } /// <inheritdoc/> public bool IsValueType { get { var td = Resolve(); return td != null && td.IsValueType; } } /// <inheritdoc/> public bool IsPrimitive { get { return this.IsPrimitive(); } } /// <inheritdoc/> string IType.TypeName { get { return FullNameCreator.Name(this, false, null); } } /// <inheritdoc/> public UTF8String Name { get { return typeName; } set { typeName = value; } } /// <inheritdoc/> public string ReflectionName { get { return FullNameCreator.Name(this, true, null); } } /// <inheritdoc/> public string Namespace { get { return FullNameCreator.Namespace(this, false, null); } } /// <inheritdoc/> public string ReflectionNamespace { get { return FullNameCreator.Namespace(this, true, null); } } /// <inheritdoc/> public string FullName { get { return FullNameCreator.FullName(this, false, null, null); } } /// <inheritdoc/> public string ReflectionFullName { get { return FullNameCreator.FullName(this, true, null, null); } } /// <inheritdoc/> public string AssemblyQualifiedName { get { return FullNameCreator.AssemblyQualifiedName(this, null, null); } } /// <inheritdoc/> public IAssembly DefinitionAssembly { get { return FullNameCreator.DefinitionAssembly(this); } } /// <inheritdoc/> public IScope Scope { get { return FullNameCreator.Scope(this); } } /// <inheritdoc/> public ITypeDefOrRef ScopeType { get { return FullNameCreator.ScopeType(this); } } /// <summary> /// Always returns <c>false</c> since a <see cref="ExportedType"/> does not contain any /// <see cref="GenericVar"/> or <see cref="GenericMVar"/>. /// </summary> public bool ContainsGenericParameter { get { return false; } } /// <inheritdoc/> public ModuleDef Module { get { return module; } } /// <inheritdoc/> bool IIsTypeOrMethod.IsMethod { get { return false; } } /// <inheritdoc/> bool IIsTypeOrMethod.IsType { get { return true; } } /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters { get { return 0; } } /// <summary> /// From column ExportedType.Flags /// </summary> public TypeAttributes Attributes { get { return (TypeAttributes)attributes; } set { attributes = (int)value; } } /// <summary>Attributes</summary> protected int attributes; /// <summary> /// From column ExportedType.TypeDefId /// </summary> public uint TypeDefId { get { return typeDefId; } set { typeDefId = value; } } /// <summary/> protected uint typeDefId; /// <summary> /// From column ExportedType.TypeName /// </summary> public UTF8String TypeName { get { return typeName; } set { typeName = value; } } /// <summary/> protected UTF8String typeName; /// <summary> /// From column ExportedType.TypeNamespace /// </summary> public UTF8String TypeNamespace { get { return typeNamespace; } set { typeNamespace = value; } } /// <summary/> protected UTF8String typeNamespace; /// <summary> /// From column ExportedType.Implementation /// </summary> public IImplementation Implementation { get { if (!implementation_isInitialized) InitializeImplementation(); return implementation; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif implementation = value; implementation_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected IImplementation implementation; /// <summary/> protected bool implementation_isInitialized; void InitializeImplementation() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (implementation_isInitialized) return; implementation = GetImplementation_NoLock(); implementation_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="implementation"/></summary> protected virtual IImplementation GetImplementation_NoLock() { return null; } /// <summary> /// <c>true</c> if it's nested within another <see cref="ExportedType"/> /// </summary> public bool IsNested { get { return DeclaringType != null; } } /// <summary> /// Gets the declaring type, if any /// </summary> public ExportedType DeclaringType { get { if (!implementation_isInitialized) InitializeImplementation(); return implementation as ExportedType; } } /// <summary> /// Modify <see cref="attributes"/> property: <see cref="attributes"/> = /// (<see cref="attributes"/> &amp; <paramref name="andMask"/>) | <paramref name="orMask"/>. /// </summary> /// <param name="andMask">Value to <c>AND</c></param> /// <param name="orMask">Value to OR</param> void ModifyAttributes(TypeAttributes andMask, TypeAttributes orMask) { #if THREAD_SAFE int origVal, newVal; do { origVal = attributes; newVal = (origVal & (int)andMask) | (int)orMask; } while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal); #else attributes = (attributes & (int)andMask) | (int)orMask; #endif } /// <summary> /// Set or clear flags in <see cref="attributes"/> /// </summary> /// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should /// be cleared</param> /// <param name="flags">Flags to set or clear</param> void ModifyAttributes(bool set, TypeAttributes flags) { #if THREAD_SAFE int origVal, newVal; do { origVal = attributes; if (set) newVal = origVal | (int)flags; else newVal = origVal & ~(int)flags; } while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal); #else if (set) attributes |= (int)flags; else attributes &= ~(int)flags; #endif } /// <summary> /// Gets/sets the visibility /// </summary> public TypeAttributes Visibility { get { return (TypeAttributes)attributes & TypeAttributes.VisibilityMask; } set { ModifyAttributes(~TypeAttributes.VisibilityMask, value & TypeAttributes.VisibilityMask); } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NotPublic"/> is set /// </summary> public bool IsNotPublic { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.Public"/> is set /// </summary> public bool IsPublic { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NestedPublic"/> is set /// </summary> public bool IsNestedPublic { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NestedPrivate"/> is set /// </summary> public bool IsNestedPrivate { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NestedFamily"/> is set /// </summary> public bool IsNestedFamily { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NestedAssembly"/> is set /// </summary> public bool IsNestedAssembly { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NestedFamANDAssem"/> is set /// </summary> public bool IsNestedFamilyAndAssembly { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.NestedFamORAssem"/> is set /// </summary> public bool IsNestedFamilyOrAssembly { get { return ((TypeAttributes)attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem; } } /// <summary> /// Gets/sets the layout /// </summary> public TypeAttributes Layout { get { return (TypeAttributes)attributes & TypeAttributes.LayoutMask; } set { ModifyAttributes(~TypeAttributes.LayoutMask, value & TypeAttributes.LayoutMask); } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.AutoLayout"/> is set /// </summary> public bool IsAutoLayout { get { return ((TypeAttributes)attributes & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.SequentialLayout"/> is set /// </summary> public bool IsSequentialLayout { get { return ((TypeAttributes)attributes & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.ExplicitLayout"/> is set /// </summary> public bool IsExplicitLayout { get { return ((TypeAttributes)attributes & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout; } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Interface"/> bit /// </summary> public bool IsInterface { get { return ((TypeAttributes)attributes & TypeAttributes.Interface) != 0; } set { ModifyAttributes(value, TypeAttributes.Interface); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Class"/> bit /// </summary> public bool IsClass { get { return ((TypeAttributes)attributes & TypeAttributes.Interface) == 0; } set { ModifyAttributes(!value, TypeAttributes.Interface); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Abstract"/> bit /// </summary> public bool IsAbstract { get { return ((TypeAttributes)attributes & TypeAttributes.Abstract) != 0; } set { ModifyAttributes(value, TypeAttributes.Abstract); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Sealed"/> bit /// </summary> public bool IsSealed { get { return ((TypeAttributes)attributes & TypeAttributes.Sealed) != 0; } set { ModifyAttributes(value, TypeAttributes.Sealed); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.SpecialName"/> bit /// </summary> public bool IsSpecialName { get { return ((TypeAttributes)attributes & TypeAttributes.SpecialName) != 0; } set { ModifyAttributes(value, TypeAttributes.SpecialName); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Import"/> bit /// </summary> public bool IsImport { get { return ((TypeAttributes)attributes & TypeAttributes.Import) != 0; } set { ModifyAttributes(value, TypeAttributes.Import); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Serializable"/> bit /// </summary> public bool IsSerializable { get { return ((TypeAttributes)attributes & TypeAttributes.Serializable) != 0; } set { ModifyAttributes(value, TypeAttributes.Serializable); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.WindowsRuntime"/> bit /// </summary> public bool IsWindowsRuntime { get { return ((TypeAttributes)attributes & TypeAttributes.WindowsRuntime) != 0; } set { ModifyAttributes(value, TypeAttributes.WindowsRuntime); } } /// <summary> /// Gets/sets the string format /// </summary> public TypeAttributes StringFormat { get { return (TypeAttributes)attributes & TypeAttributes.StringFormatMask; } set { ModifyAttributes(~TypeAttributes.StringFormatMask, value & TypeAttributes.StringFormatMask); } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.AnsiClass"/> is set /// </summary> public bool IsAnsiClass { get { return ((TypeAttributes)attributes & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.UnicodeClass"/> is set /// </summary> public bool IsUnicodeClass { get { return ((TypeAttributes)attributes & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.AutoClass"/> is set /// </summary> public bool IsAutoClass { get { return ((TypeAttributes)attributes & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass; } } /// <summary> /// <c>true</c> if <see cref="TypeAttributes.CustomFormatClass"/> is set /// </summary> public bool IsCustomFormatClass { get { return ((TypeAttributes)attributes & TypeAttributes.StringFormatMask) == TypeAttributes.CustomFormatClass; } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.BeforeFieldInit"/> bit /// </summary> public bool IsBeforeFieldInit { get { return ((TypeAttributes)attributes & TypeAttributes.BeforeFieldInit) != 0; } set { ModifyAttributes(value, TypeAttributes.BeforeFieldInit); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.Forwarder"/> bit. See also <see cref="MovedToAnotherAssembly"/> /// </summary> public bool IsForwarder { get { return ((TypeAttributes)attributes & TypeAttributes.Forwarder) != 0; } set { ModifyAttributes(value, TypeAttributes.Forwarder); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.RTSpecialName"/> bit /// </summary> public bool IsRuntimeSpecialName { get { return ((TypeAttributes)attributes & TypeAttributes.RTSpecialName) != 0; } set { ModifyAttributes(value, TypeAttributes.RTSpecialName); } } /// <summary> /// Gets/sets the <see cref="TypeAttributes.HasSecurity"/> bit /// </summary> public bool HasSecurity { get { return ((TypeAttributes)attributes & TypeAttributes.HasSecurity) != 0; } set { ModifyAttributes(value, TypeAttributes.HasSecurity); } } const int MAX_LOOP_ITERS = 50; /// <summary> /// <c>true</c> if this type has been moved to another assembly /// </summary> public bool MovedToAnotherAssembly { get { ExportedType et = this; for (int i = 0; i < MAX_LOOP_ITERS; i++) { var impl = et.Implementation; if (impl is AssemblyRef) return et.IsForwarder; et = impl as ExportedType; if (et == null) break; } return false; } } /// <summary> /// Resolves the type /// </summary> /// <returns>A <see cref="TypeDef"/> instance or <c>null</c> if it couldn't be resolved</returns> public TypeDef Resolve() { return Resolve(null); } /// <summary> /// Resolves the type /// </summary> /// <param name="sourceModule">Source module or <c>null</c></param> /// <returns>A <see cref="TypeDef"/> instance or <c>null</c> if it couldn't be resolved</returns> public TypeDef Resolve(ModuleDef sourceModule) { if (module == null) return null; return Resolve(sourceModule, this); } static TypeDef Resolve(ModuleDef sourceModule, ExportedType et) { for (int i = 0; i < MAX_LOOP_ITERS; i++) { if (et == null || et.module == null) break; var resolver = et.module.Context.AssemblyResolver; var etAsm = resolver.Resolve(et.DefinitionAssembly, sourceModule ?? et.module); if (etAsm == null) break; var td = etAsm.Find(et.FullName, false); if (td != null) return td; et = FindExportedType(etAsm, et); } return null; } static ExportedType FindExportedType(AssemblyDef asm, ExportedType et) { foreach (var mod in asm.Modules.GetSafeEnumerable()) { foreach (var et2 in mod.ExportedTypes.GetSafeEnumerable()) { if (new SigComparer(SigComparerOptions.DontCompareTypeScope).Equals(et, et2)) return et2; } } return null; } /// <summary> /// Resolves the type /// </summary> /// <returns>A <see cref="TypeDef"/> instance</returns> /// <exception cref="TypeResolveException">If the type couldn't be resolved</exception> public TypeDef ResolveThrow() { var type = Resolve(); if (type != null) return type; throw new TypeResolveException(string.Format("Could not resolve type: {0} ({1})", this, DefinitionAssembly)); } /// <summary> /// Converts this instance to a <see cref="TypeRef"/> /// </summary> /// <returns>A new <see cref="TypeRef"/> instance</returns> public TypeRef ToTypeRef() { TypeRef result = null, prev = null; var mod = module; IImplementation impl = this; for (int i = 0; i < MAX_LOOP_ITERS && impl != null; i++) { var et = impl as ExportedType; if (et != null) { var newTr = mod.UpdateRowId(new TypeRefUser(mod, et.TypeNamespace, et.TypeName)); if (result == null) result = newTr; if (prev != null) prev.ResolutionScope = newTr; prev = newTr; impl = et.Implementation; continue; } var asmRef = impl as AssemblyRef; if (asmRef != null) { // prev is never null when we're here prev.ResolutionScope = asmRef; return result; } var file = impl as FileDef; if (file != null) { // prev is never null when we're here prev.ResolutionScope = FindModule(mod, file); return result; } break; } return result; } static ModuleDef FindModule(ModuleDef module, FileDef file) { if (module == null || file == null) return null; if (UTF8String.CaseInsensitiveEquals(module.Name, file.Name)) return module; var asm = module.Assembly; if (asm == null) return null; return asm.FindModule(file.Name); } /// <inheritdoc/> public override string ToString() { return FullName; } } /// <summary> /// An ExportedType row created by the user and not present in the original .NET file /// </summary> public class ExportedTypeUser : ExportedType { /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> public ExportedTypeUser(ModuleDef module) { this.module = module; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="typeDefId">TypeDef ID</param> /// <param name="typeName">Type name</param> /// <param name="typeNamespace">Type namespace</param> /// <param name="flags">Flags</param> /// <param name="implementation">Implementation</param> public ExportedTypeUser(ModuleDef module, uint typeDefId, UTF8String typeNamespace, UTF8String typeName, TypeAttributes flags, IImplementation implementation) { this.module = module; this.typeDefId = typeDefId; this.typeName = typeName; this.typeNamespace = typeNamespace; this.attributes = (int)flags; this.implementation = implementation; this.implementation_isInitialized = true; } } /// <summary> /// Created from a row in the ExportedType table /// </summary> sealed class ExportedTypeMD : ExportedType, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; readonly uint implementationRid; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.MetaData.GetCustomAttributeRidList(Table.ExportedType, origRid); var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <inheritdoc/> protected override IImplementation GetImplementation_NoLock() { return readerModule.ResolveImplementation(implementationRid); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>ExportedType</c> row</param> /// <param name="rid">Row ID</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public ExportedTypeMD(ModuleDefMD readerModule, uint rid) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.ExportedTypeTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("ExportedType rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; this.readerModule = readerModule; this.module = readerModule; uint name, @namespace; this.implementationRid = readerModule.TablesStream.ReadExportedTypeRow(origRid, out this.attributes, out this.typeDefId, out name, out @namespace); this.typeName = readerModule.StringsStream.ReadNoNull(name); this.typeNamespace = readerModule.StringsStream.ReadNoNull(@namespace); } } }
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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; namespace Firebase.Database.Internal { /// <summary>Helper class for Child events (Added, Changed, Moved, Removed).</summary> /// Each instance of this class will listen to one C++ Query and then forward the callback /// to the C# event listeners registered with the C# Query. internal sealed class InternalChildListener : InternalListener { // Delegate definitions for C++ -> C# callbacks. public delegate void OnCancelledDelegate(int callbackId, Error error, string msg); public delegate void OnChildChangeDelegate(int callbackId, ChildChangeType changeType, System.IntPtr snapshot, string previousChildName); public delegate void OnChildRemovedDelegate(int callbackId, System.IntPtr snapshot); // Gets the ChildListener for the given callbackId. private static bool TryGetListener( int callbackId, out InternalChildListener childListener) { InternalListener listener = null; if (InternalListener.TryGetListener(callbackId, out listener)) { childListener = listener as InternalChildListener; return childListener != null; } else { childListener = null; return false; } } [MonoPInvokeCallback(typeof(OnChildChangeDelegate))] private static void OnChildChangeHandler(int callbackId, ChildChangeType changeType, System.IntPtr snapshot, string previousChildName) { ExceptionAggregator.Wrap(() => { InternalDataSnapshot s = new InternalDataSnapshot(snapshot, true); EventHandler<ChildChangedEventArgs> handler = null; InternalChildListener listener = null; if (TryGetListener(callbackId, out listener)) { switch (changeType) { case ChildChangeType.Added: handler = listener.childAddedImpl; break; case ChildChangeType.Changed: handler = listener.childChangedImpl; break; case ChildChangeType.Moved: handler = listener.childMovedImpl; break; } } if (handler != null) { handler(null, new ChildChangedEventArgs( DataSnapshot.CreateSnapshot(s, listener.database), previousChildName)); } else { // If there's no listeners, we dispose the snapshot immediately. // This also deletes the C++ snapshot, which we own. s.Dispose(); } }); } [MonoPInvokeCallback(typeof(OnChildRemovedDelegate))] private static void OnChildRemovedHandler(int callbackId, System.IntPtr snapshot) { ExceptionAggregator.Wrap(() => { InternalDataSnapshot s = new InternalDataSnapshot(snapshot, true); EventHandler<ChildChangedEventArgs> handler = null; InternalChildListener listener = null; if (TryGetListener(callbackId, out listener)) { handler = listener.childRemovedImpl; } if (handler != null) { handler(null, new ChildChangedEventArgs( DataSnapshot.CreateSnapshot(s, listener.database), null)); } else { // If there's no listeners, we dispose the snapshot immediately. // This also deletes the C++ snapshot, which we own. s.Dispose(); } }); } [MonoPInvokeCallback(typeof(OnCancelledDelegate))] private static void OnCancelledHandler(int callbackId, Error error, string msg) { ExceptionAggregator.Wrap(() => { EventHandler<ChildChangedEventArgs> handler = null; InternalChildListener listener; if (TryGetListener(callbackId, out listener)) { handler = listener.cancelledImpl; } if (handler != null) { handler(null, new ChildChangedEventArgs(DatabaseError.FromError(error, msg))); } }); } static InternalChildListener() { InternalQuery.RegisterChildListenerCallbacks( OnCancelledHandler, OnChildChangeHandler, OnChildRemovedHandler); } private object eventLock = new object(); private InternalQuery internalQuery; // We manage the ValueListenerImpl's lifetime, so we need to keep a pointer. // We lazily create it when a first listener registers with this instance. private System.IntPtr cppListener = System.IntPtr.Zero; // We only keep a reference to the database to ensure that it's kept alive, // as the underlying C++ code needs that. private FirebaseDatabase database; public InternalChildListener(InternalQuery internalQuery, FirebaseDatabase database) { this.internalQuery = internalQuery; this.database = database; } protected override void CreateCppListener(int callbackId) { if (cppListener == System.IntPtr.Zero) { // SHOULD be true cppListener = internalQuery.CreateChildListener(callbackId); } } protected override void DestroyCppListener() { if (cppListener != System.IntPtr.Zero) { InternalQuery.DestroyChildListener(cppListener); cppListener = System.IntPtr.Zero; } } protected override bool HasNoListeners() { // All listeners are added to the cancelledImpl event handler, so if it is // empty, there should be no listeners. return cancelledImpl == null; } // Handler for "cancelled" callbacks - given that there is only one C++ listner, // all C# child listeners will receive the "cancelled" callback at the same time. private event EventHandler<ChildChangedEventArgs> cancelledImpl; private event EventHandler<ChildChangedEventArgs> childAddedImpl; public event EventHandler<ChildChangedEventArgs> ChildAdded { add { lock(eventLock) { BeforeAddingListener(); childAddedImpl += value; cancelledImpl += value; } } remove { lock(eventLock) { childAddedImpl -= value; cancelledImpl -= value; AfterRemovingListener(); } } } public event EventHandler<ChildChangedEventArgs> childChangedImpl; public event EventHandler<ChildChangedEventArgs> ChildChanged { add { lock(eventLock) { BeforeAddingListener(); childChangedImpl += value; cancelledImpl += value; } } remove { lock(eventLock) { childChangedImpl -= value; cancelledImpl -= value; AfterRemovingListener(); } } } public event EventHandler<ChildChangedEventArgs> childMovedImpl; public event EventHandler<ChildChangedEventArgs> ChildMoved { add { lock(eventLock) { BeforeAddingListener(); childMovedImpl += value; cancelledImpl += value; } } remove { lock(eventLock) { childMovedImpl -= value; cancelledImpl -= value; AfterRemovingListener(); } } } public event EventHandler<ChildChangedEventArgs> childRemovedImpl; public event EventHandler<ChildChangedEventArgs> ChildRemoved { add { lock(eventLock) { BeforeAddingListener(); childRemovedImpl += value; cancelledImpl += value; } } remove { lock(eventLock) { childRemovedImpl -= value; cancelledImpl -= value; AfterRemovingListener(); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsModelFlattening { using Microsoft.Rest; using Models; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial class AutoRestResourceFlatteningTestService : Microsoft.Rest.ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestResourceFlatteningTestService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestResourceFlatteningTestService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("http://localhost"); SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); } /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutArrayWithHttpMessagesAsync(System.Collections.Generic.IList<Resource> resourceArray = default(System.Collections.Generic.IList<Resource>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceArray", resourceArray); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceArray != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<FlattenedProduct>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutDictionaryWithHttpMessagesAsync(System.Collections.Generic.IDictionary<string, FlattenedProduct> resourceDictionary = default(System.Collections.Generic.IDictionary<string, FlattenedProduct>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceDictionary", resourceDictionary); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceDictionary != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IDictionary<string, FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IDictionary<string, FlattenedProduct>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceComplexObject", resourceComplexObject); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceComplexObject != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<ResourceCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put Simple Product with client flattening true on the model /// <see href="http://tempuri.org" /> /// </summary> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<SimpleProduct>> PutSimpleProductWithHttpMessagesAsync(SimpleProduct simpleBodyProduct = default(SimpleProduct), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (simpleBodyProduct != null) { simpleBodyProduct.Validate(); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(simpleBodyProduct != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put Flattened Simple Product with client flattening true on the parameter /// <see href="http://tempuri.org" /> /// </summary> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<SimpleProduct>> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (productId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "productId"); } if (maxProductDisplayName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "maxProductDisplayName"); } SimpleProduct simpleBodyProduct = default(SimpleProduct); if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostFlattenedSimpleProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(simpleBodyProduct != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put Simple Product with client flattening true on the model /// <see href="http://tempuri.org" /> /// </summary> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<SimpleProduct>> PutSimpleProductWithGroupingWithHttpMessagesAsync(FlattenParameterGroup flattenParameterGroup, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (flattenParameterGroup == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "flattenParameterGroup"); } if (flattenParameterGroup != null) { flattenParameterGroup.Validate(); } string name = default(string); if (flattenParameterGroup != null) { name = flattenParameterGroup.Name; } string productId = default(string); if (flattenParameterGroup != null) { productId = flattenParameterGroup.ProductId; } string description = default(string); if (flattenParameterGroup != null) { description = flattenParameterGroup.Description; } string maxProductDisplayName = default(string); if (flattenParameterGroup != null) { maxProductDisplayName = flattenParameterGroup.MaxProductDisplayName; } string genericValue = default(string); if (flattenParameterGroup != null) { genericValue = flattenParameterGroup.GenericValue; } string odatavalue = default(string); if (flattenParameterGroup != null) { odatavalue = flattenParameterGroup.Odatavalue; } SimpleProduct simpleBodyProduct = default(SimpleProduct); if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("name", name); tracingParameters.Add("productId", productId); tracingParameters.Add("description", description); tracingParameters.Add("maxProductDisplayName", maxProductDisplayName); tracingParameters.Add("genericValue", genericValue); tracingParameters.Add("odatavalue", odatavalue); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProductWithGrouping", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening/parametergrouping/{name}/").ToString(); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(simpleBodyProduct != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Reflection; using System.Globalization; using System.Resources; using System.Text; using System.Threading; using System.ComponentModel; using System.Security.Permissions; namespace Microsoft.VisualStudio.Project { [AttributeUsage(AttributeTargets.All)] internal sealed class SRDescriptionAttribute : DescriptionAttribute { private bool replaced; public SRDescriptionAttribute(string description) : base(description) { } public override string Description { get { if(!replaced) { replaced = true; DescriptionValue = SR.GetString(base.Description, CultureInfo.CurrentUICulture); } return base.Description; } } } [AttributeUsage(AttributeTargets.All)] internal sealed class SRCategoryAttribute : CategoryAttribute { public SRCategoryAttribute(string category) : base(category) { } protected override string GetLocalizedString(string value) { return SR.GetString(value, CultureInfo.CurrentUICulture); } } internal sealed class SR { internal const string AddReferenceDialogTitle = "AddReferenceDialogTitle"; internal const string AddToNullProjectError = "AddToNullProjectError"; internal const string Advanced = "Advanced"; internal const string AssemblyReferenceAlreadyExists = "AssemblyReferenceAlreadyExists"; internal const string AttributeLoad = "AttributeLoad"; internal const string BuildAction = "BuildAction"; internal const string BuildActionDescription = "BuildActionDescription"; internal const string BuildCaption = "BuildCaption"; internal const string BuildVerbosity = "BuildVerbosity"; internal const string BuildVerbosityDescription = "BuildVerbosityDescription"; internal const string BuildEventError = "BuildEventError"; internal const string CancelQueryEdit = "CancelQueryEdit"; internal const string CannotAddFileThatIsOpenInEditor = "CannotAddFileThatIsOpenInEditor"; internal const string CanNotSaveFileNotOpeneInEditor = "CanNotSaveFileNotOpeneInEditor"; internal const string cli1 = "cli1"; internal const string Compile = "Compile"; internal const string ConfirmExtensionChange = "ConfirmExtensionChange"; internal const string Content = "Content"; internal const string CopyToLocal = "CopyToLocal"; internal const string CopyToLocalDescription = "CopyToLocalDescription"; internal const string EmbedInteropTypes = "EmbedInteropTypes"; internal const string EmbedInteropTypesDescription = "EmbedInteropTypesDescription"; internal const string CustomTool = "CustomTool"; internal const string CustomToolDescription = "CustomToolDescription"; internal const string CustomToolNamespace = "CustomToolNamespace"; internal const string CustomToolNamespaceDescription = "CustomToolNamespaceDescription"; internal const string DetailsImport = "DetailsImport"; internal const string DetailsUserImport = "DetailsUserImport"; internal const string DetailsItem = "DetailsItem"; internal const string DetailsItemLocation = "DetailsItemLocation"; internal const string DetailsProperty = "DetailsProperty"; internal const string DetailsTarget = "DetailsTarget"; internal const string DetailsUsingTask = "DetailsUsingTask"; internal const string Detailed = "Detailed"; internal const string Diagnostic = "Diagnostic"; internal const string DirectoryExistError = "DirectoryExistError"; internal const string EditorViewError = "EditorViewError"; internal const string EmbeddedResource = "EmbeddedResource"; internal const string Error = "Error"; internal const string ErrorInvalidFileName = "ErrorInvalidFileName"; internal const string ErrorInvalidProjectName = "ErrorInvalidProjectName"; internal const string ErrorReferenceCouldNotBeAdded = "ErrorReferenceCouldNotBeAdded"; internal const string ErrorMsBuildRegistration = "ErrorMsBuildRegistration"; internal const string ErrorSaving = "ErrorSaving"; internal const string Exe = "Exe"; internal const string ExpectedObjectOfType = "ExpectedObjectOfType"; internal const string FailedToGetService = "FailedToGetService"; internal const string FailedToRetrieveProperties = "FailedToRetrieveProperties"; internal const string FileNameCannotContainALeadingPeriod = "FileNameCannotContainALeadingPeriod"; internal const string FileCannotBeRenamedToAnExistingFile = "FileCannotBeRenamedToAnExistingFile"; internal const string FileAlreadyExistsAndCannotBeRenamed = "FileAlreadyExistsAndCannotBeRenamed"; internal const string FileAlreadyExists = "FileAlreadyExists"; internal const string FileAlreadyExistsCaption = "FileAlreadyExistsCaption"; internal const string FileAlreadyInProject = "FileAlreadyInProject"; internal const string FileAlreadyInProjectCaption = "FileAlreadyInProjectCaption"; internal const string FileCopyError = "FileCopyError"; internal const string FileName = "FileName"; internal const string FileNameDescription = "FileNameDescription"; internal const string FileOrFolderAlreadyExists = "FileOrFolderAlreadyExists"; internal const string FileOrFolderCannotBeFound = "FileOrFolderCannotBeFound"; internal const string FileProperties = "FileProperties"; internal const string FolderName = "FolderName"; internal const string FolderNameDescription = "FolderNameDescription"; internal const string FolderProperties = "FolderProperties"; internal const string FullPath = "FullPath"; internal const string FullPathDescription = "FullPathDescription"; internal const string ItemDoesNotExistInProjectDirectory = "ItemDoesNotExistInProjectDirectory"; internal const string InvalidAutomationObject = "InvalidAutomationObject"; internal const string InvalidLoggerType = "InvalidLoggerType"; internal const string InvalidParameter = "InvalidParameter"; internal const string Library = "Library"; internal const string LinkedItemsAreNotSupported = "LinkedItemsAreNotSupported"; internal const string Minimal = "Minimal"; internal const string Misc = "Misc"; internal const string None = "None"; internal const string Normal = "Normal"; internal const string NestedProjectFailedToReload = "NestedProjectFailedToReload"; internal const string OutputPath = "OutputPath"; internal const string OutputPathDescription = "OutputPathDescription"; internal const string PasteFailed = "PasteFailed"; internal const string ParameterMustBeAValidGuid = "ParameterMustBeAValidGuid"; internal const string ParameterMustBeAValidItemId = "ParameterMustBeAValidItemId"; internal const string ParameterCannotBeNullOrEmpty = "ParameterCannotBeNullOrEmpty"; internal const string PathTooLong = "PathTooLong"; internal const string ProjectContainsCircularReferences = "ProjectContainsCircularReferences"; internal const string Program = "Program"; internal const string Project = "Project"; internal const string ProjectFile = "ProjectFile"; internal const string ProjectFileDescription = "ProjectFileDescription"; internal const string ProjectFolder = "ProjectFolder"; internal const string ProjectFolderDescription = "ProjectFolderDescription"; internal const string ProjectProperties = "ProjectProperties"; internal const string Quiet = "Quiet"; internal const string QueryReloadNestedProject = "QueryReloadNestedProject"; internal const string ReferenceAlreadyExists = "ReferenceAlreadyExists"; internal const string ReferencesNodeName = "ReferencesNodeName"; internal const string ReferenceProperties = "ReferenceProperties"; internal const string RefName = "RefName"; internal const string RefNameDescription = "RefNameDescription"; internal const string RenameFolder = "RenameFolder"; internal const string RTL = "RTL"; internal const string SaveCaption = "SaveCaption"; internal const string SaveModifiedDocuments = "SaveModifiedDocuments"; internal const string SaveOfProjectFileOutsideCurrentDirectory = "SaveOfProjectFileOutsideCurrentDirectory"; internal const string StandardEditorViewError = "StandardEditorViewError"; internal const string Settings = "Settings"; internal const string URL = "URL"; internal const string UseOfDeletedItemError = "UseOfDeletedItemError"; internal const string Warning = "Warning"; internal const string WinExe = "WinExe"; internal const string CannotLoadUnknownTargetFrameworkProject = "CannotLoadUnknownTargetFrameworkProject"; internal const string ReloadPromptOnTargetFxChanged = "ReloadPromptOnTargetFxChanged"; internal const string ReloadPromptOnTargetFxChangedCaption = "ReloadPromptOnTargetFxChangedCaption"; static SR loader; ResourceManager resources; private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } internal SR() { resources = new System.Resources.ResourceManager("Microsoft.VisualStudio.Project", this.GetType().Assembly); } private static SR GetLoader() { if(loader == null) { lock(InternalSyncObject) { if(loader == null) { loader = new SR(); } } } return loader; } private static CultureInfo Culture { get { return null/*use ResourceManager default, CultureInfo.CurrentUICulture*/; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static ResourceManager Resources { get { return GetLoader().resources; } } public static string GetString(string name, params object[] args) { SR sys = GetLoader(); if(sys == null) return null; string res = sys.resources.GetString(name, SR.Culture); if(args != null && args.Length > 0) { return String.Format(CultureInfo.CurrentCulture, res, args); } else { return res; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string GetString(string name) { SR sys = GetLoader(); if(sys == null) return null; return sys.resources.GetString(name, SR.Culture); } public static string GetString(string name, CultureInfo culture) { SR sys = GetLoader(); if(sys == null) return null; return sys.resources.GetString(name, culture); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static object GetObject(string name) { SR sys = GetLoader(); if(sys == null) return null; return sys.resources.GetObject(name, SR.Culture); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Numerics; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using Xunit; namespace System.Text.Tests { // Since many of the methods we'll be testing are internal, we'll need to invoke // them via reflection. public static unsafe partial class AsciiUtilityTests { private const int SizeOfVector128 = 128 / 8; // The delegate definitions and members below provide us access to CoreLib's internals. // We use UIntPtr instead of nuint everywhere here since we don't know what our target arch is. private delegate UIntPtr FnGetIndexOfFirstNonAsciiByte(byte* pBuffer, UIntPtr bufferLength); private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte> _fnGetIndexOfFirstNonAsciiByte = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte>("GetIndexOfFirstNonAsciiByte"); private delegate UIntPtr FnGetIndexOfFirstNonAsciiChar(char* pBuffer, UIntPtr bufferLength); private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar> _fnGetIndexOfFirstNonAsciiChar = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar>("GetIndexOfFirstNonAsciiChar"); private delegate UIntPtr FnNarrowUtf16ToAscii(char* pUtf16Buffer, byte* pAsciiBuffer, UIntPtr elementCount); private static readonly UnsafeLazyDelegate<FnNarrowUtf16ToAscii> _fnNarrowUtf16ToAscii = new UnsafeLazyDelegate<FnNarrowUtf16ToAscii>("NarrowUtf16ToAscii"); private delegate UIntPtr FnWidenAsciiToUtf16(byte* pAsciiBuffer, char* pUtf16Buffer, UIntPtr elementCount); private static readonly UnsafeLazyDelegate<FnWidenAsciiToUtf16> _fnWidenAsciiToUtf16 = new UnsafeLazyDelegate<FnWidenAsciiToUtf16>("WidenAsciiToUtf16"); [Fact] public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NullReference() { Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(null, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NonNullReference() { byte b = default; Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(&b, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiByte_Vector128InnerLoop() { // The purpose of this test is to make sure we're identifying the correct // vector (of the two that we're reading simultaneously) when performing // the final ASCII drain at the end of the method once we've broken out // of the inner loop. using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(1024)) { Span<byte> bytes = mem.Span; for (int i = 0; i < bytes.Length; i++) { bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII } // Two vectors have offsets 0 .. 31. We'll go backward to avoid having to // re-clear the vector every time. for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--) { bytes[100 + i * 13] = 0x80; // 13 is relatively prime to 32, so it ensures all possible positions are hit Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiByte(bytes)); } } } [Fact] public static void GetIndexOfFirstNonAsciiByte_Boundaries() { // The purpose of this test is to make sure we're hitting all of the vectorized // and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened // code paths. We shouldn't be reading beyond the boundaries we were given. // The 5 * Vector test should make sure that we're exercising all possible // code paths across both implementations. using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(5 * Vector<byte>.Count)) { Span<byte> bytes = mem.Span; // First, try it with all-ASCII buffers. for (int i = 0; i < bytes.Length; i++) { bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII } for (int i = bytes.Length; i >= 0; i--) { Assert.Equal(i, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i))); } // Then, try it with non-ASCII bytes. for (int i = bytes.Length; i >= 1; i--) { bytes[i - 1] = 0x80; // set non-ASCII Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i))); } } } [Fact] public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NullReference() { Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(null, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NonNullReference() { char c = default; Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(&c, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiChar_Vector128InnerLoop() { // The purpose of this test is to make sure we're identifying the correct // vector (of the two that we're reading simultaneously) when performing // the final ASCII drain at the end of the method once we've broken out // of the inner loop. // // Use U+0123 instead of U+0080 for this test because if our implementation // uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII, // causing our test to produce a false negative. using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(1024)) { Span<char> chars = mem.Span; for (int i = 0; i < chars.Length; i++) { chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII } // Two vectors have offsets 0 .. 31. We'll go backward to avoid having to // re-clear the vector every time. for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--) { chars[100 + i * 13] = '\u0123'; // 13 is relatively prime to 32, so it ensures all possible positions are hit Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiChar(chars)); } } } [Fact] public static void GetIndexOfFirstNonAsciiChar_Boundaries() { // The purpose of this test is to make sure we're hitting all of the vectorized // and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened // code paths. We shouldn't be reading beyond the boundaries we were given. // // The 5 * Vector test should make sure that we're exercising all possible // code paths across both implementations. The sizeof(char) is because we're // specifying element count, but underlying implementation reintepret casts to bytes. // // Use U+0123 instead of U+0080 for this test because if our implementation // uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII, // causing our test to produce a false negative. using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(5 * Vector<byte>.Count / sizeof(char))) { Span<char> chars = mem.Span; for (int i = 0; i < chars.Length; i++) { chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII } for (int i = chars.Length; i >= 0; i--) { Assert.Equal(i, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i))); } // Then, try it with non-ASCII bytes. for (int i = chars.Length; i >= 1; i--) { chars[i - 1] = '\u0123'; // set non-ASCII Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i))); } } } [Fact] public static void WidenAsciiToUtf16_EmptyInput_NullReferences() { Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(null, null, UIntPtr.Zero)); } [Fact] public static void WidenAsciiToUtf16_EmptyInput_NonNullReference() { byte b = default; char c = default; Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(&b, &c, UIntPtr.Zero)); } [Fact] public static void WidenAsciiToUtf16_AllAsciiInput() { using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); // Fill source with 00 .. 7F, then trap future writes. Span<byte> asciiSpan = asciiMem.Span; for (int i = 0; i < asciiSpan.Length; i++) { asciiSpan[i] = (byte)i; } asciiMem.MakeReadonly(); // We'll write to the UTF-16 span. // We test with a variety of span lengths to test alignment and fallthrough code paths. Span<char> utf16Span = utf16Mem.Span; for (int i = 0; i < asciiSpan.Length; i++) { utf16Span.Clear(); // remove any data from previous iteration // First, validate that the workhorse saw the incoming data as all-ASCII. Assert.Equal(128 - i, CallWidenAsciiToUtf16(asciiSpan.Slice(i), utf16Span.Slice(i))); // Then, validate that the data was transcoded properly. for (int j = i; j < 128; j++) { Assert.Equal((ushort)asciiSpan[i], (ushort)utf16Span[i]); } } } [Fact] public static void WidenAsciiToUtf16_SomeNonAsciiInput() { using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); // Fill source with 00 .. 7F, then trap future writes. Span<byte> asciiSpan = asciiMem.Span; for (int i = 0; i < asciiSpan.Length; i++) { asciiSpan[i] = (byte)i; } // We'll write to the UTF-16 span. Span<char> utf16Span = utf16Mem.Span; for (int i = asciiSpan.Length - 1; i >= 0; i--) { RandomNumberGenerator.Fill(MemoryMarshal.Cast<char, byte>(utf16Span)); // fill with garbage // First, keep track of the garbage we wrote to the destination. // We want to ensure it wasn't overwritten. char[] expectedTrailingData = utf16Span.Slice(i).ToArray(); // Then, set the desired byte as non-ASCII, then check that the workhorse // correctly saw the data as non-ASCII. asciiSpan[i] |= (byte)0x80; Assert.Equal(i, CallWidenAsciiToUtf16(asciiSpan, utf16Span)); // Next, validate that the ASCII data was transcoded properly. for (int j = 0; j < i; j++) { Assert.Equal((ushort)asciiSpan[j], (ushort)utf16Span[j]); } // Finally, validate that the trailing data wasn't overwritten with non-ASCII data. Assert.Equal(expectedTrailingData, utf16Span.Slice(i).ToArray()); } } [Fact] public unsafe static void NarrowUtf16ToAscii_EmptyInput_NullReferences() { Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(null, null, UIntPtr.Zero)); } [Fact] public static void NarrowUtf16ToAscii_EmptyInput_NonNullReference() { char c = default; byte b = default; Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(&c, &b, UIntPtr.Zero)); } [Fact] public static void NarrowUtf16ToAscii_AllAsciiInput() { using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); // Fill source with 00 .. 7F. Span<char> utf16Span = utf16Mem.Span; for (int i = 0; i < utf16Span.Length; i++) { utf16Span[i] = (char)i; } utf16Mem.MakeReadonly(); // We'll write to the ASCII span. // We test with a variety of span lengths to test alignment and fallthrough code paths. Span<byte> asciiSpan = asciiMem.Span; for (int i = 0; i < utf16Span.Length; i++) { asciiSpan.Clear(); // remove any data from previous iteration // First, validate that the workhorse saw the incoming data as all-ASCII. Assert.Equal(128 - i, CallNarrowUtf16ToAscii(utf16Span.Slice(i), asciiSpan.Slice(i))); // Then, validate that the data was transcoded properly. for (int j = i; j < 128; j++) { Assert.Equal((ushort)utf16Span[i], (ushort)asciiSpan[i]); } } } [Fact] public static void NarrowUtf16ToAscii_SomeNonAsciiInput() { using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); // Fill source with 00 .. 7F. Span<char> utf16Span = utf16Mem.Span; for (int i = 0; i < utf16Span.Length; i++) { utf16Span[i] = (char)i; } // We'll write to the ASCII span. Span<byte> asciiSpan = asciiMem.Span; for (int i = utf16Span.Length - 1; i >= 0; i--) { RandomNumberGenerator.Fill(asciiSpan); // fill with garbage // First, keep track of the garbage we wrote to the destination. // We want to ensure it wasn't overwritten. byte[] expectedTrailingData = asciiSpan.Slice(i).ToArray(); // Then, set the desired byte as non-ASCII, then check that the workhorse // correctly saw the data as non-ASCII. utf16Span[i] = '\u0123'; // use U+0123 instead of U+0080 since it catches inappropriate pmovmskb usage Assert.Equal(i, CallNarrowUtf16ToAscii(utf16Span, asciiSpan)); // Next, validate that the ASCII data was transcoded properly. for (int j = 0; j < i; j++) { Assert.Equal((ushort)utf16Span[j], (ushort)asciiSpan[j]); } // Finally, validate that the trailing data wasn't overwritten with non-ASCII data. Assert.Equal(expectedTrailingData, asciiSpan.Slice(i).ToArray()); } } private static int CallGetIndexOfFirstNonAsciiByte(ReadOnlySpan<byte> buffer) { fixed (byte* pBuffer = &MemoryMarshal.GetReference(buffer)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnGetIndexOfFirstNonAsciiByte.Delegate(pBuffer, (UIntPtr)buffer.Length)); } } private static int CallGetIndexOfFirstNonAsciiChar(ReadOnlySpan<char> buffer) { fixed (char* pBuffer = &MemoryMarshal.GetReference(buffer)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnGetIndexOfFirstNonAsciiChar.Delegate(pBuffer, (UIntPtr)buffer.Length)); } } private static int CallNarrowUtf16ToAscii(ReadOnlySpan<char> utf16, Span<byte> ascii) { Assert.Equal(utf16.Length, ascii.Length); fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16)) fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnNarrowUtf16ToAscii.Delegate(pUtf16, pAscii, (UIntPtr)utf16.Length)); } } private static int CallWidenAsciiToUtf16(ReadOnlySpan<byte> ascii, Span<char> utf16) { Assert.Equal(ascii.Length, utf16.Length); fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii)) fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnWidenAsciiToUtf16.Delegate(pAscii, pUtf16, (UIntPtr)ascii.Length)); } } private static Type GetAsciiUtilityType() { return typeof(object).Assembly.GetType("System.Text.ASCIIUtility"); } private sealed class UnsafeLazyDelegate<TDelegate> where TDelegate : class { private readonly Lazy<TDelegate> _lazyDelegate; public UnsafeLazyDelegate(string methodName) { _lazyDelegate = new Lazy<TDelegate>(() => { Assert.True(typeof(TDelegate).IsSubclassOf(typeof(MulticastDelegate))); // Get the MethodInfo for the target method MethodInfo methodInfo = GetAsciiUtilityType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(methodInfo); // Construct the TDelegate pointing to this method return (TDelegate)Activator.CreateInstance(typeof(TDelegate), new object[] { null, methodInfo.MethodHandle.GetFunctionPointer() }); }); } public TDelegate Delegate => _lazyDelegate.Value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Xunit; public class CreatedTests { [Fact] public static void FileSystemWatcher_Created_File() { using (var watcher = new FileSystemWatcher(".")) { string fileName = Guid.NewGuid().ToString(); watcher.Filter = fileName; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); watcher.EnableRaisingEvents = true; using (var file = new TemporaryTestFile(fileName)) { Utility.ExpectEvent(eventOccurred, "created"); } } } [Fact] public static void FileSystemWatcher_Created_File_ForceRestart() { using (var watcher = new FileSystemWatcher(".")) { string fileName = Guid.NewGuid().ToString(); watcher.Filter = fileName; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); watcher.EnableRaisingEvents = true; watcher.NotifyFilter = NotifyFilters.FileName; // change filter to force restart using (var file = new TemporaryTestFile(fileName)) { Utility.ExpectEvent(eventOccurred, "created"); } } } [Fact] public static void FileSystemWatcher_Created_Directory() { using (var watcher = new FileSystemWatcher(".")) { string dirName = Guid.NewGuid().ToString(); watcher.Filter = dirName; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); watcher.EnableRaisingEvents = true; using (var dir = new TemporaryTestDirectory(dirName)) { Utility.ExpectEvent(eventOccurred, "created"); } } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Created_MoveDirectory() { // create two test directories using (TemporaryTestDirectory dir = Utility.CreateTestDirectory(), targetDir = new TemporaryTestDirectory(dir.Path + "_target")) using (var watcher = new FileSystemWatcher(".")) { string testFileName = "testFile.txt"; // watch the target dir watcher.Path = Path.GetFullPath(targetDir.Path); watcher.Filter = testFileName; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); string sourceFile = Path.Combine(dir.Path, testFileName); string targetFile = Path.Combine(targetDir.Path, testFileName); // create a test file in source File.WriteAllText(sourceFile, "test content"); watcher.EnableRaisingEvents = true; // move the test file from source to target directory File.Move(sourceFile, targetFile); Utility.ExpectEvent(eventOccurred, "created"); } } [Fact] public static void FileSystemWatcher_Created_Negative() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); // run all scenarios together to avoid unnecessary waits, // assert information is verbose enough to trace to failure cause using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file"))) using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir"))) { // start listening after we've created these watcher.EnableRaisingEvents = true; // change a file testFile.WriteByte(0xFF); testFile.Flush(); // renaming a directory // // We don't do this on Linux because depending on the timing of MOVED_FROM and MOVED_TO events, // a rename can trigger delete + create as a deliberate handling of an edge case, and this // test is checking that no create events are raised. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { testDir.Move(testDir.Path + "_rename"); } // deleting a file & directory by leaving the using block } Utility.ExpectNoEvent(eventOccurred, "created"); } } [Fact] public static void FileSystemWatcher_Created_FileCreatedInNestedDirectory() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Created, (AutoResetEvent are, TemporaryTestDirectory ttd) => { using (var nestedFile = new TemporaryTestFile(Path.Combine(ttd.Path, "nestedFile"))) { Utility.ExpectEvent(are, "nested file created"); } }); } // This can potentially fail, depending on where the test is run from, due to // the MAX_PATH limitation. When issue 645 is closed, this shouldn't be a problem [Fact, ActiveIssue(645, PlatformID.Any)] public static void FileSystemWatcher_Created_DeepDirectoryStructure() { // List of created directories List<TemporaryTestDirectory> lst = new List<TemporaryTestDirectory>(); try { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; watcher.IncludeSubdirectories = true; watcher.EnableRaisingEvents = true; // Priming directory TemporaryTestDirectory priming = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir")); lst.Add(priming); Utility.ExpectEvent(eventOccurred, "priming create"); // Create a deep directory structure and expect things to work for (int i = 1; i < 20; i++) { lst.Add(new TemporaryTestDirectory(Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i)))); Utility.ExpectEvent(eventOccurred, lst[i].Path + " create"); } // Put a file at the very bottom and expect it to raise an event using (var file = new TemporaryTestFile(Path.Combine(lst[lst.Count - 1].Path, "temp file"))) { Utility.ExpectEvent(eventOccurred, "temp file create"); } } } finally { // Cleanup foreach (TemporaryTestDirectory d in lst) d.Dispose(); } } [Fact, OuterLoop] [ActiveIssue(1477, PlatformID.Windows)] [ActiveIssue(3215, PlatformID.OSX)] public static void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFile() { using (var dir = Utility.CreateTestDirectory()) using (var temp = Utility.CreateTestFile(Path.GetTempFileName())) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.EnableRaisingEvents = true; // Make the symlink in our path (to the temp file) and make sure an event is raised Utility.CreateSymLink(Path.GetFullPath(temp.Path), Path.Combine(dir.Path, Path.GetFileName(temp.Path)), false); Utility.ExpectEvent(eventOccurred, "symlink created"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFolder() { using (var dir = Utility.CreateTestDirectory()) using (var temp = Utility.CreateTestDirectory(Path.Combine(Path.GetTempPath(), "FooBar"))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created); // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.EnableRaisingEvents = true; // Make the symlink in our path (to the temp folder) and make sure an event is raised Utility.CreateSymLink(Path.GetFullPath(temp.Path), Path.Combine(dir.Path, Path.GetFileName(temp.Path)), true); Utility.ExpectEvent(eventOccurred, "symlink created"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WEBAPI_Server_App.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.OpsWorks.Model { /// <summary> /// Container for the parameters to the CreateApp operation. /// Creates an app for a specified stack. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingapps-creating.html">Creating /// Apps</a>. /// /// /// <para> /// <b>Required Permissions</b>: To use this action, an IAM user must have a Manage permissions /// level for the stack, or an attached policy that explicitly grants permissions. For /// more information on user permissions, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html">Managing /// User Permissions</a>. /// </para> /// </summary> public partial class CreateAppRequest : AmazonOpsWorksRequest { private Source _appSource; private Dictionary<string, string> _attributes = new Dictionary<string, string>(); private List<DataSource> _dataSources = new List<DataSource>(); private string _description; private List<string> _domains = new List<string>(); private bool? _enableSsl; private List<EnvironmentVariable> _environment = new List<EnvironmentVariable>(); private string _name; private string _shortname; private SslConfiguration _sslConfiguration; private string _stackId; private AppType _type; /// <summary> /// Gets and sets the property AppSource. /// <para> /// A <code>Source</code> object that specifies the app repository. /// </para> /// </summary> public Source AppSource { get { return this._appSource; } set { this._appSource = value; } } // Check to see if AppSource property is set internal bool IsSetAppSource() { return this._appSource != null; } /// <summary> /// Gets and sets the property Attributes. /// <para> /// One or more user-defined key/value pairs to be added to the stack attributes. /// </para> /// </summary> public Dictionary<string, string> Attributes { get { return this._attributes; } set { this._attributes = value; } } // Check to see if Attributes property is set internal bool IsSetAttributes() { return this._attributes != null && this._attributes.Count > 0; } /// <summary> /// Gets and sets the property DataSources. /// <para> /// The app's data source. /// </para> /// </summary> public List<DataSource> DataSources { get { return this._dataSources; } set { this._dataSources = value; } } // Check to see if DataSources property is set internal bool IsSetDataSources() { return this._dataSources != null && this._dataSources.Count > 0; } /// <summary> /// Gets and sets the property Description. /// <para> /// A description of the app. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property Domains. /// <para> /// The app virtual host settings, with multiple domains separated by commas. For example: /// <code>'www.example.com, example.com'</code> /// </para> /// </summary> public List<string> Domains { get { return this._domains; } set { this._domains = value; } } // Check to see if Domains property is set internal bool IsSetDomains() { return this._domains != null && this._domains.Count > 0; } /// <summary> /// Gets and sets the property EnableSsl. /// <para> /// Whether to enable SSL for the app. /// </para> /// </summary> public bool EnableSsl { get { return this._enableSsl.GetValueOrDefault(); } set { this._enableSsl = value; } } // Check to see if EnableSsl property is set internal bool IsSetEnableSsl() { return this._enableSsl.HasValue; } /// <summary> /// Gets and sets the property Environment. /// <para> /// An array of <code>EnvironmentVariable</code> objects that specify environment variables /// to be associated with the app. After you deploy the app, these variables are defined /// on the associated app server instance. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingapps-creating.html#workingapps-creating-environment"> /// Environment Variables</a>. /// </para> /// /// <para> /// There is no specific limit on the number of environment variables. However, the size /// of the associated data structure - which includes the variables' names, values, and /// protected flag values - cannot exceed 10 KB (10240 Bytes). This limit should accommodate /// most if not all use cases. Exceeding it will cause an exception with the message, /// "Environment: is too large (maximum is 10KB)." /// </para> /// <note>This parameter is supported only by Chef 11.10 stacks. If you have specified /// one or more environment variables, you cannot modify the stack's Chef version.</note> /// </summary> public List<EnvironmentVariable> Environment { get { return this._environment; } set { this._environment = value; } } // Check to see if Environment property is set internal bool IsSetEnvironment() { return this._environment != null && this._environment.Count > 0; } /// <summary> /// Gets and sets the property Name. /// <para> /// The app name. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Shortname. /// <para> /// The app's short name. /// </para> /// </summary> public string Shortname { get { return this._shortname; } set { this._shortname = value; } } // Check to see if Shortname property is set internal bool IsSetShortname() { return this._shortname != null; } /// <summary> /// Gets and sets the property SslConfiguration. /// <para> /// An <code>SslConfiguration</code> object with the SSL configuration. /// </para> /// </summary> public SslConfiguration SslConfiguration { get { return this._sslConfiguration; } set { this._sslConfiguration = value; } } // Check to see if SslConfiguration property is set internal bool IsSetSslConfiguration() { return this._sslConfiguration != null; } /// <summary> /// Gets and sets the property StackId. /// <para> /// The stack ID. /// </para> /// </summary> public string StackId { get { return this._stackId; } set { this._stackId = value; } } // Check to see if StackId property is set internal bool IsSetStackId() { return this._stackId != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The app type. Each supported type is associated with a particular layer. For example, /// PHP applications are associated with a PHP layer. AWS OpsWorks deploys an application /// to those instances that are members of the corresponding layer. If your app isn't /// one of the standard types, or you prefer to implement your own Deploy recipes, specify /// <code>other</code>. /// </para> /// </summary> public AppType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
using System.Diagnostics; namespace Lucene.Net.Codecs.Compressing { using Lucene.Net.Support; using System; using ArrayUtil = Lucene.Net.Util.ArrayUtil; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; /// <summary> /// A compression mode. Tells how much effort should be spent on compression and /// decompression of stored fields. /// @lucene.experimental /// </summary> public abstract class CompressionMode { /// <summary> /// A compression mode that trades compression ratio for speed. Although the /// compression ratio might remain high, compression and decompression are /// very fast. Use this mode with indices that have a high update rate but /// should be able to load documents from disk quickly. /// </summary> public static readonly CompressionMode FAST = new CompressionModeAnonymousInnerClassHelper(); private class CompressionModeAnonymousInnerClassHelper : CompressionMode { public CompressionModeAnonymousInnerClassHelper() { } public override Compressor NewCompressor() { return new LZ4FastCompressor(); } public override Decompressor NewDecompressor() { return LZ4_DECOMPRESSOR; } public override string ToString() { return "FAST"; } } /// <summary> /// A compression mode that trades speed for compression ratio. Although /// compression and decompression might be slow, this compression mode should /// provide a good compression ratio. this mode might be interesting if/when /// your index size is much bigger than your OS cache. /// </summary> public static readonly CompressionMode HIGH_COMPRESSION = new CompressionModeAnonymousInnerClassHelper2(); private class CompressionModeAnonymousInnerClassHelper2 : CompressionMode { public CompressionModeAnonymousInnerClassHelper2() { } public override Compressor NewCompressor() { return new DeflateCompressor(Deflater.BEST_COMPRESSION); } public override Decompressor NewDecompressor() { return new DeflateDecompressor(); } public override string ToString() { return "HIGH_COMPRESSION"; } } /// <summary> /// this compression mode is similar to <seealso cref="#FAST"/> but it spends more time /// compressing in order to improve the compression ratio. this compression /// mode is best used with indices that have a low update rate but should be /// able to load documents from disk quickly. /// </summary> public static readonly CompressionMode FAST_DECOMPRESSION = new CompressionModeAnonymousInnerClassHelper3(); private class CompressionModeAnonymousInnerClassHelper3 : CompressionMode { public CompressionModeAnonymousInnerClassHelper3() { } public override Compressor NewCompressor() { return new LZ4HighCompressor(); } public override Decompressor NewDecompressor() { return LZ4_DECOMPRESSOR; } public override string ToString() { return "FAST_DECOMPRESSION"; } } /// <summary> /// Sole constructor. </summary> protected internal CompressionMode() { } /// <summary> /// Create a new <seealso cref="Compressor"/> instance. /// </summary> public abstract Compressor NewCompressor(); /// <summary> /// Create a new <seealso cref="Decompressor"/> instance. /// </summary> public abstract Decompressor NewDecompressor(); private static readonly Decompressor LZ4_DECOMPRESSOR = new DecompressorAnonymousInnerClassHelper(); private class DecompressorAnonymousInnerClassHelper : Decompressor { public DecompressorAnonymousInnerClassHelper() { } public override void Decompress(DataInput @in, int originalLength, int offset, int length, BytesRef bytes) { Debug.Assert(offset + length <= originalLength); // add 7 padding bytes, this is not necessary but can help decompression run faster if (bytes.Bytes.Length < originalLength + 7) { bytes.Bytes = new byte[ArrayUtil.Oversize(originalLength + 7, 1)]; } int decompressedLength = LZ4.Decompress(@in, offset + length, bytes.Bytes, 0); if (decompressedLength > originalLength) { throw new CorruptIndexException("Corrupted: lengths mismatch: " + decompressedLength + " > " + originalLength + " (resource=" + @in + ")"); } bytes.Offset = offset; bytes.Length = length; } public override object Clone() { return this; } } private sealed class LZ4FastCompressor : Compressor { private readonly LZ4.HashTable Ht; internal LZ4FastCompressor() { Ht = new LZ4.HashTable(); } public override void Compress(byte[] bytes, int off, int len, DataOutput @out) { LZ4.Compress(bytes, off, len, @out, Ht); } } private sealed class LZ4HighCompressor : Compressor { internal readonly LZ4.HCHashTable Ht; internal LZ4HighCompressor() { Ht = new LZ4.HCHashTable(); } public override void Compress(byte[] bytes, int off, int len, DataOutput @out) { LZ4.CompressHC(bytes, off, len, @out, Ht); } } private sealed class DeflateDecompressor : Decompressor { internal readonly Inflater decompressor; internal byte[] Compressed; internal DeflateDecompressor() { decompressor = SharpZipLib.CreateInflater(); Compressed = new byte[0]; } public override void Decompress(DataInput @in, int originalLength, int offset, int length, BytesRef bytes) { Debug.Assert(offset + length <= originalLength); if (length == 0) { bytes.Length = 0; return; } int compressedLength = @in.ReadVInt(); if (compressedLength > Compressed.Length) { Compressed = new byte[ArrayUtil.Oversize(compressedLength, 1)]; } @in.ReadBytes(Compressed, 0, compressedLength); decompressor.Reset(); decompressor.SetInput(Compressed, 0, compressedLength); bytes.Offset = bytes.Length = 0; while (true) { int count; try { int remaining = bytes.Bytes.Length - bytes.Length; count = decompressor.Inflate((byte[])(Array)(bytes.Bytes), bytes.Length, remaining); } catch (System.FormatException e) { throw new System.IO.IOException("See inner", e); } bytes.Length += count; if (decompressor.IsFinished) { break; } else { bytes.Bytes = ArrayUtil.Grow(bytes.Bytes); } } if (bytes.Length != originalLength) { throw new CorruptIndexException("Lengths mismatch: " + bytes.Length + " != " + originalLength + " (resource=" + @in + ")"); } bytes.Offset = offset; bytes.Length = length; } public override object Clone() { return new DeflateDecompressor(); } } private class DeflateCompressor : Compressor { private readonly Deflater Compressor; private byte[] Compressed; internal DeflateCompressor(int level) { Compressor = SharpZipLib.CreateDeflater(); Compressed = new byte[64]; } public override void Compress(byte[] bytes, int off, int len, DataOutput @out) { Compressor.Reset(); Compressor.SetInput((byte[])(Array)bytes, off, len); Compressor.Finish(); if (Compressor.NeedsInput) { // no output Debug.Assert(len == 0, len.ToString()); @out.WriteVInt(0); return; } int totalCount = 0; for (; ; ) { int count = Compressor.Deflate(Compressed, totalCount, Compressed.Length - totalCount); totalCount += count; Debug.Assert(totalCount <= Compressed.Length); if (Compressor.IsFinished) { break; } else { Compressed = ArrayUtil.Grow(Compressed); } } @out.WriteVInt(totalCount); @out.WriteBytes(Compressed, totalCount); } } } }
using System; using System.Collections.Generic; using NinthChevron.Data; using NinthChevron.Data.Entity; using NinthChevron.Helpers; using NinthChevron.ComponentModel.DataAnnotations; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.HumanResourcesSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PersonSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PurchasingSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.SalesSchema; namespace NinthChevron.Data.SqlServer.Test.AdventureWorks2012.ProductionSchema { [Table("BillOfMaterials", "Production", "AdventureWorks2012")] public partial class BillOfMaterials : Entity<BillOfMaterials> { static BillOfMaterials() { Join<Product>(t => t.ComponentProduct, (t, f) => t.ComponentID == f.ProductID); // Relation Join<Product>(t => t.ProductAssemblyProduct, (t, f) => t.ProductAssemblyID == f.ProductID); // Relation Join<UnitMeasure>(t => t.UnitMeasureCodeUnitMeasure, (t, f) => t.UnitMeasureCode == f.UnitMeasureCode); // Relation } [NotifyPropertyChanged, Column("BillOfMaterialsID", true, true, false)] public int BillOfMaterialsID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("ProductAssemblyID", true, false, true)] public System.Nullable<int> ProductAssemblyID { get; set; } [NotifyPropertyChanged, Column("ComponentID", true, false, false)] public int ComponentID { get; set; } [NotifyPropertyChanged, Column("StartDate", true, false, false)] public System.DateTime StartDate { get; set; } [NotifyPropertyChanged, Column("EndDate", true, false, true)] public System.Nullable<System.DateTime> EndDate { get; set; } [NotifyPropertyChanged, Column("UnitMeasureCode", true, false, false)] public string UnitMeasureCode { get; set; } [NotifyPropertyChanged, Column("BOMLevel", true, false, false)] public short BOMLevel { get; set; } [NotifyPropertyChanged, Column("PerAssemblyQty", true, false, false)] public decimal PerAssemblyQty { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ComponentProduct { get; set; } [InnerJoinColumn] public Product ProductAssemblyProduct { get; set; } [InnerJoinColumn] public UnitMeasure UnitMeasureCodeUnitMeasure { get; set; } } [Table("Culture", "Production", "AdventureWorks2012")] public partial class Culture : Entity<Culture> { static Culture() { Join<ProductModelProductDescriptionCulture>(t => t.CultureProductModelProductDescriptionCulture, (t, f) => t.CultureID == f.CultureID); // Reverse Relation } [NotifyPropertyChanged, Column("CultureID", true, false, false)] public string CultureID { get; set; } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductModelProductDescriptionCulture CultureProductModelProductDescriptionCulture { get; set; } } [Table("Document", "Production", "AdventureWorks2012")] public partial class Document : Entity<Document> { static Document() { Join<Employee>(t => t.OwnerEmployee, (t, f) => t.Owner == f.BusinessEntityID); // Relation Join<ProductDocument>(t => t.DocumentNodeProductDocument, (t, f) => t.DocumentNode == f.DocumentNode); // Reverse Relation } [NotifyPropertyChanged, Column("DocumentNode", true, false, false)] public object DocumentNode { get; set; } [NotifyPropertyChanged, Column("DocumentLevel", false, false, true)] public System.Nullable<short> DocumentLevel { get; set; } [NotifyPropertyChanged, Column("Title", false, false, false)] public string Title { get; set; } [NotifyPropertyChanged, Column("Owner", true, false, false)] public int Owner { get; set; } [NotifyPropertyChanged, Column("FolderFlag", false, false, false)] public bool FolderFlag { get; set; } [NotifyPropertyChanged, Column("FileName", false, false, false)] public string FileName { get; set; } [NotifyPropertyChanged, Column("FileExtension", false, false, false)] public string FileExtension { get; set; } [NotifyPropertyChanged, Column("Revision", false, false, false)] public string Revision { get; set; } [NotifyPropertyChanged, Column("ChangeNumber", false, false, false)] public int ChangeNumber { get; set; } [NotifyPropertyChanged, Column("Status", true, false, false)] public byte Status { get; set; } [NotifyPropertyChanged, Column("DocumentSummary", false, false, true)] public string DocumentSummary { get; set; } [NotifyPropertyChanged, Column("Document", false, false, true)] public byte[] Document_ { get; set; } [NotifyPropertyChanged, Column("rowguid", true, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Employee OwnerEmployee { get; set; } [InnerJoinColumn] public ProductDocument DocumentNodeProductDocument { get; set; } } [Table("Illustration", "Production", "AdventureWorks2012")] public partial class Illustration : Entity<Illustration> { static Illustration() { Join<ProductModelIllustration>(t => t.IllustrationProductModelIllustration, (t, f) => t.IllustrationID == f.IllustrationID); // Reverse Relation } [NotifyPropertyChanged, Column("IllustrationID", true, true, false)] public int IllustrationID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("Diagram", false, false, true)] public object Diagram { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductModelIllustration IllustrationProductModelIllustration { get; set; } } [Table("Location", "Production", "AdventureWorks2012")] public partial class Location : Entity<Location> { static Location() { Join<ProductInventory>(t => t.LocationProductInventory, (t, f) => t.LocationID == f.LocationID); // Reverse Relation Join<WorkOrderRouting>(t => t.LocationWorkOrderRouting, (t, f) => t.LocationID == f.LocationID); // Reverse Relation } [NotifyPropertyChanged, Column("LocationID", true, true, false)] public short LocationID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<short>() : (short)Convert.ChangeType(this.EntityIdentity, typeof(short)); } set { this.EntityIdentity = (short)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("CostRate", true, false, false)] public object CostRate { get; set; } [NotifyPropertyChanged, Column("Availability", true, false, false)] public decimal Availability { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductInventory LocationProductInventory { get; set; } [InnerJoinColumn] public WorkOrderRouting LocationWorkOrderRouting { get; set; } } [Table("Product", "Production", "AdventureWorks2012")] public partial class Product : Entity<Product> { static Product() { Join<TransactionHistory>(t => t.ProductTransactionHistory, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<WorkOrder>(t => t.ProductWorkOrder, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductProductPhoto>(t => t.ProductProductProductPhoto, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductReview>(t => t.ProductProductReview, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductVendor>(t => t.ProductProductVendor, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<PurchaseOrderDetail>(t => t.ProductPurchaseOrderDetail, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductInventory>(t => t.ProductProductInventory, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductListPriceHistory>(t => t.ProductProductListPriceHistory, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductDocument>(t => t.ProductProductDocument, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductCostHistory>(t => t.ProductProductCostHistory, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<BillOfMaterials>(t => t.ComponentBillOfMaterials, (t, f) => t.ProductID == f.ComponentID); // Reverse Relation Join<BillOfMaterials>(t => t.ProductAssemblyBillOfMaterials, (t, f) => t.ProductID == f.ProductAssemblyID); // Reverse Relation Join<ShoppingCartItem>(t => t.ProductShoppingCartItem, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<SpecialOfferProduct>(t => t.ProductSpecialOfferProduct, (t, f) => t.ProductID == f.ProductID); // Reverse Relation Join<ProductModel>(t => t.ProductModelProductModel, (t, f) => t.ProductModelID == f.ProductModelID); // Relation Join<ProductSubcategory>(t => t.ProductSubcategoryProductSubcategory, (t, f) => t.ProductSubcategoryID == f.ProductSubcategoryID); // Relation Join<UnitMeasure>(t => t.SizeUnitMeasureCodeUnitMeasure, (t, f) => t.SizeUnitMeasureCode == f.UnitMeasureCode); // Relation Join<UnitMeasure>(t => t.WeightUnitMeasureCodeUnitMeasure, (t, f) => t.WeightUnitMeasureCode == f.UnitMeasureCode); // Relation } [NotifyPropertyChanged, Column("ProductID", true, true, false)] public int ProductID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("ProductNumber", false, false, false)] public string ProductNumber { get; set; } [NotifyPropertyChanged, Column("MakeFlag", false, false, false)] public bool MakeFlag { get; set; } [NotifyPropertyChanged, Column("FinishedGoodsFlag", false, false, false)] public bool FinishedGoodsFlag { get; set; } [NotifyPropertyChanged, Column("Color", false, false, true)] public string Color { get; set; } [NotifyPropertyChanged, Column("SafetyStockLevel", true, false, false)] public short SafetyStockLevel { get; set; } [NotifyPropertyChanged, Column("ReorderPoint", true, false, false)] public short ReorderPoint { get; set; } [NotifyPropertyChanged, Column("StandardCost", true, false, false)] public object StandardCost { get; set; } [NotifyPropertyChanged, Column("ListPrice", true, false, false)] public object ListPrice { get; set; } [NotifyPropertyChanged, Column("Size", false, false, true)] public string Size { get; set; } [NotifyPropertyChanged, Column("SizeUnitMeasureCode", true, false, true)] public string SizeUnitMeasureCode { get; set; } [NotifyPropertyChanged, Column("WeightUnitMeasureCode", true, false, true)] public string WeightUnitMeasureCode { get; set; } [NotifyPropertyChanged, Column("Weight", true, false, true)] public System.Nullable<decimal> Weight { get; set; } [NotifyPropertyChanged, Column("DaysToManufacture", true, false, false)] public int DaysToManufacture { get; set; } [NotifyPropertyChanged, Column("ProductLine", true, false, true)] public string ProductLine { get; set; } [NotifyPropertyChanged, Column("Class", true, false, true)] public string Class { get; set; } [NotifyPropertyChanged, Column("Style", true, false, true)] public string Style { get; set; } [NotifyPropertyChanged, Column("ProductSubcategoryID", true, false, true)] public System.Nullable<int> ProductSubcategoryID { get; set; } [NotifyPropertyChanged, Column("ProductModelID", true, false, true)] public System.Nullable<int> ProductModelID { get; set; } [NotifyPropertyChanged, Column("SellStartDate", true, false, false)] public System.DateTime SellStartDate { get; set; } [NotifyPropertyChanged, Column("SellEndDate", true, false, true)] public System.Nullable<System.DateTime> SellEndDate { get; set; } [NotifyPropertyChanged, Column("DiscontinuedDate", false, false, true)] public System.Nullable<System.DateTime> DiscontinuedDate { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public TransactionHistory ProductTransactionHistory { get; set; } [InnerJoinColumn] public WorkOrder ProductWorkOrder { get; set; } [InnerJoinColumn] public ProductProductPhoto ProductProductProductPhoto { get; set; } [InnerJoinColumn] public ProductReview ProductProductReview { get; set; } [InnerJoinColumn] public ProductVendor ProductProductVendor { get; set; } [InnerJoinColumn] public PurchaseOrderDetail ProductPurchaseOrderDetail { get; set; } [InnerJoinColumn] public ProductInventory ProductProductInventory { get; set; } [InnerJoinColumn] public ProductListPriceHistory ProductProductListPriceHistory { get; set; } [InnerJoinColumn] public ProductDocument ProductProductDocument { get; set; } [InnerJoinColumn] public ProductCostHistory ProductProductCostHistory { get; set; } [InnerJoinColumn] public BillOfMaterials ComponentBillOfMaterials { get; set; } [InnerJoinColumn] public BillOfMaterials ProductAssemblyBillOfMaterials { get; set; } [InnerJoinColumn] public ShoppingCartItem ProductShoppingCartItem { get; set; } [InnerJoinColumn] public SpecialOfferProduct ProductSpecialOfferProduct { get; set; } [InnerJoinColumn] public ProductModel ProductModelProductModel { get; set; } [InnerJoinColumn] public ProductSubcategory ProductSubcategoryProductSubcategory { get; set; } [InnerJoinColumn] public UnitMeasure SizeUnitMeasureCodeUnitMeasure { get; set; } [InnerJoinColumn] public UnitMeasure WeightUnitMeasureCodeUnitMeasure { get; set; } } [Table("ProductCategory", "Production", "AdventureWorks2012")] public partial class ProductCategory : Entity<ProductCategory> { static ProductCategory() { Join<ProductSubcategory>(t => t.ProductCategoryProductSubcategory, (t, f) => t.ProductCategoryID == f.ProductCategoryID); // Reverse Relation } [NotifyPropertyChanged, Column("ProductCategoryID", true, true, false)] public int ProductCategoryID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductSubcategory ProductCategoryProductSubcategory { get; set; } } [Table("ProductCostHistory", "Production", "AdventureWorks2012")] public partial class ProductCostHistory : Entity<ProductCostHistory> { static ProductCostHistory() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("StartDate", true, false, false)] public System.DateTime StartDate { get; set; } [NotifyPropertyChanged, Column("EndDate", true, false, true)] public System.Nullable<System.DateTime> EndDate { get; set; } [NotifyPropertyChanged, Column("StandardCost", true, false, false)] public object StandardCost { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } } [Table("ProductDescription", "Production", "AdventureWorks2012")] public partial class ProductDescription : Entity<ProductDescription> { static ProductDescription() { Join<ProductModelProductDescriptionCulture>(t => t.ProductDescriptionProductModelProductDescriptionCulture, (t, f) => t.ProductDescriptionID == f.ProductDescriptionID); // Reverse Relation } [NotifyPropertyChanged, Column("ProductDescriptionID", true, true, false)] public int ProductDescriptionID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("Description", false, false, false)] public string Description { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductModelProductDescriptionCulture ProductDescriptionProductModelProductDescriptionCulture { get; set; } } [Table("ProductDocument", "Production", "AdventureWorks2012")] public partial class ProductDocument : Entity<ProductDocument> { static ProductDocument() { Join<Document>(t => t.DocumentNodeDocument, (t, f) => t.DocumentNode == f.DocumentNode); // Relation Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("DocumentNode", true, false, false)] public object DocumentNode { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Document DocumentNodeDocument { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } } [Table("ProductInventory", "Production", "AdventureWorks2012")] public partial class ProductInventory : Entity<ProductInventory> { static ProductInventory() { Join<Location>(t => t.LocationLocation, (t, f) => t.LocationID == f.LocationID); // Relation Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("LocationID", true, false, false)] public short LocationID { get; set; } [NotifyPropertyChanged, Column("Shelf", true, false, false)] public string Shelf { get; set; } [NotifyPropertyChanged, Column("Bin", true, false, false)] public byte Bin { get; set; } [NotifyPropertyChanged, Column("Quantity", false, false, false)] public short Quantity { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Location LocationLocation { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } } [Table("ProductListPriceHistory", "Production", "AdventureWorks2012")] public partial class ProductListPriceHistory : Entity<ProductListPriceHistory> { static ProductListPriceHistory() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("StartDate", true, false, false)] public System.DateTime StartDate { get; set; } [NotifyPropertyChanged, Column("EndDate", true, false, true)] public System.Nullable<System.DateTime> EndDate { get; set; } [NotifyPropertyChanged, Column("ListPrice", true, false, false)] public object ListPrice { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } } [Table("ProductModel", "Production", "AdventureWorks2012")] public partial class ProductModel : Entity<ProductModel> { static ProductModel() { Join<ProductModelProductDescriptionCulture>(t => t.ProductModelProductModelProductDescriptionCulture, (t, f) => t.ProductModelID == f.ProductModelID); // Reverse Relation Join<ProductModelIllustration>(t => t.ProductModelProductModelIllustration, (t, f) => t.ProductModelID == f.ProductModelID); // Reverse Relation Join<Product>(t => t.ProductModelProduct, (t, f) => t.ProductModelID == f.ProductModelID); // Reverse Relation } [NotifyPropertyChanged, Column("ProductModelID", true, true, false)] public int ProductModelID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("CatalogDescription", false, false, true)] public object CatalogDescription { get; set; } [NotifyPropertyChanged, Column("Instructions", false, false, true)] public object Instructions { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductModelProductDescriptionCulture ProductModelProductModelProductDescriptionCulture { get; set; } [InnerJoinColumn] public ProductModelIllustration ProductModelProductModelIllustration { get; set; } [InnerJoinColumn] public Product ProductModelProduct { get; set; } } [Table("ProductModelIllustration", "Production", "AdventureWorks2012")] public partial class ProductModelIllustration : Entity<ProductModelIllustration> { static ProductModelIllustration() { Join<Illustration>(t => t.IllustrationIllustration, (t, f) => t.IllustrationID == f.IllustrationID); // Relation Join<ProductModel>(t => t.ProductModelProductModel, (t, f) => t.ProductModelID == f.ProductModelID); // Relation } [NotifyPropertyChanged, Column("ProductModelID", true, false, false)] public int ProductModelID { get; set; } [NotifyPropertyChanged, Column("IllustrationID", true, false, false)] public int IllustrationID { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Illustration IllustrationIllustration { get; set; } [InnerJoinColumn] public ProductModel ProductModelProductModel { get; set; } } [Table("ProductModelProductDescriptionCulture", "Production", "AdventureWorks2012")] public partial class ProductModelProductDescriptionCulture : Entity<ProductModelProductDescriptionCulture> { static ProductModelProductDescriptionCulture() { Join<Culture>(t => t.CultureCulture, (t, f) => t.CultureID == f.CultureID); // Relation Join<ProductDescription>(t => t.ProductDescriptionProductDescription, (t, f) => t.ProductDescriptionID == f.ProductDescriptionID); // Relation Join<ProductModel>(t => t.ProductModelProductModel, (t, f) => t.ProductModelID == f.ProductModelID); // Relation } [NotifyPropertyChanged, Column("ProductModelID", true, false, false)] public int ProductModelID { get; set; } [NotifyPropertyChanged, Column("ProductDescriptionID", true, false, false)] public int ProductDescriptionID { get; set; } [NotifyPropertyChanged, Column("CultureID", true, false, false)] public string CultureID { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Culture CultureCulture { get; set; } [InnerJoinColumn] public ProductDescription ProductDescriptionProductDescription { get; set; } [InnerJoinColumn] public ProductModel ProductModelProductModel { get; set; } } [Table("ProductPhoto", "Production", "AdventureWorks2012")] public partial class ProductPhoto : Entity<ProductPhoto> { static ProductPhoto() { Join<ProductProductPhoto>(t => t.ProductPhotoProductProductPhoto, (t, f) => t.ProductPhotoID == f.ProductPhotoID); // Reverse Relation } [NotifyPropertyChanged, Column("ProductPhotoID", true, true, false)] public int ProductPhotoID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("ThumbNailPhoto", false, false, true)] public byte[] ThumbNailPhoto { get; set; } [NotifyPropertyChanged, Column("ThumbnailPhotoFileName", false, false, true)] public string ThumbnailPhotoFileName { get; set; } [NotifyPropertyChanged, Column("LargePhoto", false, false, true)] public byte[] LargePhoto { get; set; } [NotifyPropertyChanged, Column("LargePhotoFileName", false, false, true)] public string LargePhotoFileName { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductProductPhoto ProductPhotoProductProductPhoto { get; set; } } [Table("ProductProductPhoto", "Production", "AdventureWorks2012")] public partial class ProductProductPhoto : Entity<ProductProductPhoto> { static ProductProductPhoto() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation Join<ProductPhoto>(t => t.ProductPhotoProductPhoto, (t, f) => t.ProductPhotoID == f.ProductPhotoID); // Relation } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("ProductPhotoID", true, false, false)] public int ProductPhotoID { get; set; } [NotifyPropertyChanged, Column("Primary", false, false, false)] public bool Primary { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } [InnerJoinColumn] public ProductPhoto ProductPhotoProductPhoto { get; set; } } [Table("ProductReview", "Production", "AdventureWorks2012")] public partial class ProductReview : Entity<ProductReview> { static ProductReview() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation } [NotifyPropertyChanged, Column("ProductReviewID", true, true, false)] public int ProductReviewID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("ReviewerName", false, false, false)] public string ReviewerName { get; set; } [NotifyPropertyChanged, Column("ReviewDate", false, false, false)] public System.DateTime ReviewDate { get; set; } [NotifyPropertyChanged, Column("EmailAddress", false, false, false)] public string EmailAddress { get; set; } [NotifyPropertyChanged, Column("Rating", true, false, false)] public int Rating { get; set; } [NotifyPropertyChanged, Column("Comments", false, false, true)] public string Comments { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } } [Table("ProductSubcategory", "Production", "AdventureWorks2012")] public partial class ProductSubcategory : Entity<ProductSubcategory> { static ProductSubcategory() { Join<ProductCategory>(t => t.ProductCategoryProductCategory, (t, f) => t.ProductCategoryID == f.ProductCategoryID); // Relation Join<Product>(t => t.ProductSubcategoryProduct, (t, f) => t.ProductSubcategoryID == f.ProductSubcategoryID); // Reverse Relation } [NotifyPropertyChanged, Column("ProductSubcategoryID", true, true, false)] public int ProductSubcategoryID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("ProductCategoryID", true, false, false)] public int ProductCategoryID { get; set; } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductCategory ProductCategoryProductCategory { get; set; } [InnerJoinColumn] public Product ProductSubcategoryProduct { get; set; } } [Table("ScrapReason", "Production", "AdventureWorks2012")] public partial class ScrapReason : Entity<ScrapReason> { static ScrapReason() { Join<WorkOrder>(t => t.ScrapReasonWorkOrder, (t, f) => t.ScrapReasonID == f.ScrapReasonID); // Reverse Relation } [NotifyPropertyChanged, Column("ScrapReasonID", true, true, false)] public short ScrapReasonID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<short>() : (short)Convert.ChangeType(this.EntityIdentity, typeof(short)); } set { this.EntityIdentity = (short)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public WorkOrder ScrapReasonWorkOrder { get; set; } } [Table("TransactionHistory", "Production", "AdventureWorks2012")] public partial class TransactionHistory : Entity<TransactionHistory> { static TransactionHistory() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation } [NotifyPropertyChanged, Column("TransactionID", true, true, false)] public int TransactionID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("ReferenceOrderID", false, false, false)] public int ReferenceOrderID { get; set; } [NotifyPropertyChanged, Column("ReferenceOrderLineID", false, false, false)] public int ReferenceOrderLineID { get; set; } [NotifyPropertyChanged, Column("TransactionDate", false, false, false)] public System.DateTime TransactionDate { get; set; } [NotifyPropertyChanged, Column("TransactionType", true, false, false)] public string TransactionType { get; set; } [NotifyPropertyChanged, Column("Quantity", false, false, false)] public int Quantity { get; set; } [NotifyPropertyChanged, Column("ActualCost", false, false, false)] public object ActualCost { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } } [Table("TransactionHistoryArchive", "Production", "AdventureWorks2012")] public partial class TransactionHistoryArchive : Entity<TransactionHistoryArchive> { static TransactionHistoryArchive() { } [NotifyPropertyChanged, Column("TransactionID", true, false, false)] public int TransactionID { get; set; } [NotifyPropertyChanged, Column("ProductID", false, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("ReferenceOrderID", false, false, false)] public int ReferenceOrderID { get; set; } [NotifyPropertyChanged, Column("ReferenceOrderLineID", false, false, false)] public int ReferenceOrderLineID { get; set; } [NotifyPropertyChanged, Column("TransactionDate", false, false, false)] public System.DateTime TransactionDate { get; set; } [NotifyPropertyChanged, Column("TransactionType", true, false, false)] public string TransactionType { get; set; } [NotifyPropertyChanged, Column("Quantity", false, false, false)] public int Quantity { get; set; } [NotifyPropertyChanged, Column("ActualCost", false, false, false)] public object ActualCost { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } } [Table("UnitMeasure", "Production", "AdventureWorks2012")] public partial class UnitMeasure : Entity<UnitMeasure> { static UnitMeasure() { Join<ProductVendor>(t => t.UnitMeasureCodeProductVendor, (t, f) => t.UnitMeasureCode == f.UnitMeasureCode); // Reverse Relation Join<Product>(t => t.SizeUnitMeasureCodeProduct, (t, f) => t.UnitMeasureCode == f.SizeUnitMeasureCode); // Reverse Relation Join<Product>(t => t.WeightUnitMeasureCodeProduct, (t, f) => t.UnitMeasureCode == f.WeightUnitMeasureCode); // Reverse Relation Join<BillOfMaterials>(t => t.UnitMeasureCodeBillOfMaterials, (t, f) => t.UnitMeasureCode == f.UnitMeasureCode); // Reverse Relation } [NotifyPropertyChanged, Column("UnitMeasureCode", true, false, false)] public string UnitMeasureCode { get; set; } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public ProductVendor UnitMeasureCodeProductVendor { get; set; } [InnerJoinColumn] public Product SizeUnitMeasureCodeProduct { get; set; } [InnerJoinColumn] public Product WeightUnitMeasureCodeProduct { get; set; } [InnerJoinColumn] public BillOfMaterials UnitMeasureCodeBillOfMaterials { get; set; } } [Table("WorkOrder", "Production", "AdventureWorks2012")] public partial class WorkOrder : Entity<WorkOrder> { static WorkOrder() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation Join<ScrapReason>(t => t.ScrapReasonScrapReason, (t, f) => t.ScrapReasonID == f.ScrapReasonID); // Relation Join<WorkOrderRouting>(t => t.WorkOrderWorkOrderRouting, (t, f) => t.WorkOrderID == f.WorkOrderID); // Reverse Relation } [NotifyPropertyChanged, Column("WorkOrderID", true, true, false)] public int WorkOrderID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("OrderQty", true, false, false)] public int OrderQty { get; set; } [NotifyPropertyChanged, Column("StockedQty", false, false, false)] public int StockedQty { get; set; } [NotifyPropertyChanged, Column("ScrappedQty", true, false, false)] public short ScrappedQty { get; set; } [NotifyPropertyChanged, Column("StartDate", true, false, false)] public System.DateTime StartDate { get; set; } [NotifyPropertyChanged, Column("EndDate", true, false, true)] public System.Nullable<System.DateTime> EndDate { get; set; } [NotifyPropertyChanged, Column("DueDate", false, false, false)] public System.DateTime DueDate { get; set; } [NotifyPropertyChanged, Column("ScrapReasonID", true, false, true)] public System.Nullable<short> ScrapReasonID { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } [InnerJoinColumn] public ScrapReason ScrapReasonScrapReason { get; set; } [InnerJoinColumn] public WorkOrderRouting WorkOrderWorkOrderRouting { get; set; } } [Table("WorkOrderRouting", "Production", "AdventureWorks2012")] public partial class WorkOrderRouting : Entity<WorkOrderRouting> { static WorkOrderRouting() { Join<Location>(t => t.LocationLocation, (t, f) => t.LocationID == f.LocationID); // Relation Join<WorkOrder>(t => t.WorkOrderWorkOrder, (t, f) => t.WorkOrderID == f.WorkOrderID); // Relation } [NotifyPropertyChanged, Column("WorkOrderID", true, false, false)] public int WorkOrderID { get; set; } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("OperationSequence", true, false, false)] public short OperationSequence { get; set; } [NotifyPropertyChanged, Column("LocationID", true, false, false)] public short LocationID { get; set; } [NotifyPropertyChanged, Column("ScheduledStartDate", true, false, false)] public System.DateTime ScheduledStartDate { get; set; } [NotifyPropertyChanged, Column("ScheduledEndDate", true, false, false)] public System.DateTime ScheduledEndDate { get; set; } [NotifyPropertyChanged, Column("ActualStartDate", true, false, true)] public System.Nullable<System.DateTime> ActualStartDate { get; set; } [NotifyPropertyChanged, Column("ActualEndDate", true, false, true)] public System.Nullable<System.DateTime> ActualEndDate { get; set; } [NotifyPropertyChanged, Column("ActualResourceHrs", true, false, true)] public System.Nullable<decimal> ActualResourceHrs { get; set; } [NotifyPropertyChanged, Column("PlannedCost", true, false, false)] public object PlannedCost { get; set; } [NotifyPropertyChanged, Column("ActualCost", true, false, true)] public object ActualCost { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Location LocationLocation { get; set; } [InnerJoinColumn] public WorkOrder WorkOrderWorkOrder { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Xml; using System.Text; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Reflection; namespace System.Xml.Schema { // This is an atomic value converted for Silverlight XML core that knows only how to convert to and from string. // It does not recognize XmlAtomicValue or XPathItemType. internal class XmlUntypedStringConverter { // Fields private bool _listsAllowed; private XmlUntypedStringConverter _listItemConverter; // Cached types private static readonly Type s_decimalType = typeof(decimal); private static readonly Type s_int32Type = typeof(int); private static readonly Type s_int64Type = typeof(long); private static readonly Type s_stringType = typeof(string); private static readonly Type s_objectType = typeof(object); private static readonly Type s_byteType = typeof(byte); private static readonly Type s_int16Type = typeof(short); private static readonly Type s_SByteType = typeof(sbyte); private static readonly Type s_UInt16Type = typeof(ushort); private static readonly Type s_UInt32Type = typeof(uint); private static readonly Type s_UInt64Type = typeof(ulong); private static readonly Type s_doubleType = typeof(double); private static readonly Type s_singleType = typeof(float); private static readonly Type s_dateTimeType = typeof(DateTime); private static readonly Type s_dateTimeOffsetType = typeof(DateTimeOffset); private static readonly Type s_booleanType = typeof(bool); private static readonly Type s_byteArrayType = typeof(Byte[]); private static readonly Type s_xmlQualifiedNameType = typeof(XmlQualifiedName); private static readonly Type s_uriType = typeof(Uri); private static readonly Type s_timeSpanType = typeof(TimeSpan); private static readonly string s_untypedStringTypeName = "xdt:untypedAtomic"; // Static convertor instance internal static XmlUntypedStringConverter Instance = new XmlUntypedStringConverter(true); private XmlUntypedStringConverter(bool listsAllowed) { _listsAllowed = listsAllowed; if (listsAllowed) { _listItemConverter = new XmlUntypedStringConverter(false); } } internal string ToString(object value, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException("value"); Type sourceType = value.GetType(); //we can consider avoiding the type equality checks and instead doing a "is" check //similar to what we did for Uri and XmlQualifiedName below if (sourceType == s_booleanType) return XmlConvert.ToString((bool)value); if (sourceType == s_byteType) return XmlConvert.ToString((byte)value); if (sourceType == s_byteArrayType) return Base64BinaryToString((byte[])value); if (sourceType == s_dateTimeType) return DateTimeToString((DateTime)value); if (sourceType == s_dateTimeOffsetType) return DateTimeOffsetToString((DateTimeOffset)value); if (sourceType == s_decimalType) return XmlConvert.ToString((decimal)value); if (sourceType == s_doubleType) return XmlConvert.ToString((double)value); if (sourceType == s_int16Type) return XmlConvert.ToString((short)value); if (sourceType == s_int32Type) return XmlConvert.ToString((int)value); if (sourceType == s_int64Type) return XmlConvert.ToString((long)value); if (sourceType == s_SByteType) return XmlConvert.ToString((sbyte)value); if (sourceType == s_singleType) return XmlConvert.ToString((float)value); if (sourceType == s_stringType) return ((string)value); if (sourceType == s_timeSpanType) return DurationToString((TimeSpan)value); if (sourceType == s_UInt16Type) return XmlConvert.ToString((ushort)value); if (sourceType == s_UInt32Type) return XmlConvert.ToString((uint)value); if (sourceType == s_UInt64Type) return XmlConvert.ToString((ulong)value); if (value is Uri) return AnyUriToString((Uri)value); if (value is XmlQualifiedName) return QNameToString((XmlQualifiedName)value, nsResolver); return (string)ListTypeToString(value, nsResolver); } internal object FromString(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException("value"); if (destinationType == null) throw new ArgumentNullException("destinationType"); if (destinationType == s_objectType) destinationType = typeof(string); if (destinationType == s_booleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == s_byteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_byteArrayType) return StringToBase64Binary((string)value); if (destinationType == s_dateTimeType) return StringToDateTime((string)value); if (destinationType == s_dateTimeOffsetType) return StringToDateTimeOffset((string)value); if (destinationType == s_decimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == s_doubleType) return XmlConvert.ToDouble((string)value); if (destinationType == s_int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == s_int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == s_SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_singleType) return XmlConvert.ToSingle((string)value); if (destinationType == s_timeSpanType) return StringToDuration((string)value); if (destinationType == s_UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == s_UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == s_uriType) return XmlConvert.ToUri((string)value); if (destinationType == s_xmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == s_stringType) return ((string)value); return StringToListType(value, destinationType, nsResolver); } private byte Int32ToByte(int value) { if (value < (int)Byte.MinValue || value > (int)Byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "Byte")); return (byte)value; } private short Int32ToInt16(int value) { if (value < (int)Int16.MinValue || value > (int)Int16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "Int16")); return (short)value; } private sbyte Int32ToSByte(int value) { if (value < (int)SByte.MinValue || value > (int)SByte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "SByte")); return (sbyte)value; } private ushort Int32ToUInt16(int value) { if (value < (int)UInt16.MinValue || value > (int)UInt16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "UInt16")); return (ushort)value; } private uint Int64ToUInt32(long value) { if (value < (long)UInt32.MinValue || value > (long)UInt32.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "UInt32")); return (uint)value; } private ulong DecimalToUInt64(decimal value) { if (value < (decimal)UInt64.MinValue || value > (decimal)UInt64.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, XmlConvert.ToString(value), "UInt64")); return (ulong)value; } private string Base64BinaryToString(byte[] value) { return Convert.ToBase64String(value); } private byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvert.TrimString(value)); } private string DateTimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } private static DateTime StringToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private static string DateTimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } private static DateTimeOffset StringToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private string DurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToString(XsdDuration.DurationType.Duration); } private TimeSpan StringToDuration(string value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToTimeSpan(XsdDuration.DurationType.Duration); } private string AnyUriToString(Uri value) { return value.OriginalString; } protected static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResolver nsResolver) { string prefix; if (nsResolver == null) { return string.Concat("{", qname.Namespace, "}", qname.Name); } prefix = nsResolver.LookupPrefix(qname.Namespace); if (prefix == null) { throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname.ToString(), qname.Namespace)); } return (prefix.Length != 0) ? string.Concat(prefix, ":", qname.Name) : qname.Name; } private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver nsResolver) { string prefix, localName, ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName return new XmlQualifiedName(localName, ns); } private string ListTypeToString(object value, IXmlNamespaceResolver nsResolver) { if (!_listsAllowed || !(value is IEnumerable)) { throw CreateInvalidClrMappingException(value.GetType(), typeof(string)); } StringBuilder bldr = new StringBuilder(); foreach (object item in ((IEnumerable)value)) { // skip null values if (item != null) { // Separate values by single space character if (bldr.Length != 0) bldr.Append(' '); // Append string value of next item in the list bldr.Append(_listItemConverter.ToString(item, nsResolver)); } } return bldr.ToString(); } private object StringToListType(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (_listsAllowed && destinationType.IsArray) { Type itemTypeDst = destinationType.GetElementType(); if (itemTypeDst == s_objectType) return ToArray<object>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_booleanType) return ToArray<bool>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteType) return ToArray<byte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteArrayType) return ToArray<byte[]>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeType) return ToArray<DateTime>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeOffsetType) return ToArray<DateTimeOffset>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_decimalType) return ToArray<decimal>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_doubleType) return ToArray<double>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int16Type) return ToArray<short>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int32Type) return ToArray<int>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int64Type) return ToArray<long>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_SByteType) return ToArray<sbyte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_singleType) return ToArray<float>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_stringType) return ToArray<string>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_timeSpanType) return ToArray<TimeSpan>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt16Type) return ToArray<ushort>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt32Type) return ToArray<uint>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt64Type) return ToArray<ulong>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_uriType) return ToArray<Uri>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_xmlQualifiedNameType) return ToArray<XmlQualifiedName>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); } throw CreateInvalidClrMappingException(typeof(string), destinationType); } private T[] ToArray<T>(string[] stringArray, IXmlNamespaceResolver nsResolver) { T[] arrDst = new T[stringArray.Length]; for (int i = 0; i < stringArray.Length; i++) { arrDst[i] = (T)_listItemConverter.FromString(stringArray[i], typeof(T), nsResolver); } return arrDst; } private Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping2, s_untypedStringTypeName, sourceType.ToString(), destinationType.ToString())); } } }
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; // <auto-generated /> namespace Northwind { /// <summary> /// Strongly-typed collection for the TextEntry class. /// </summary> [Serializable] public partial class TextEntryCollection : ActiveList<TextEntry, TextEntryCollection> { public TextEntryCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>TextEntryCollection</returns> public TextEntryCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { TextEntry o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the TextEntry table. /// </summary> [Serializable] public partial class TextEntry : ActiveRecord<TextEntry>, IActiveRecord { #region .ctors and Default Settings public TextEntry() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public TextEntry(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public TextEntry(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public TextEntry(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("TextEntry", TableType.Table, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarContentID = new TableSchema.TableColumn(schema); colvarContentID.ColumnName = "contentID"; colvarContentID.DataType = DbType.Int32; colvarContentID.MaxLength = 0; colvarContentID.AutoIncrement = true; colvarContentID.IsNullable = false; colvarContentID.IsPrimaryKey = true; colvarContentID.IsForeignKey = false; colvarContentID.IsReadOnly = false; colvarContentID.DefaultSetting = @""; colvarContentID.ForeignKeyTableName = ""; schema.Columns.Add(colvarContentID); TableSchema.TableColumn colvarContentGUID = new TableSchema.TableColumn(schema); colvarContentGUID.ColumnName = "contentGUID"; colvarContentGUID.DataType = DbType.Guid; colvarContentGUID.MaxLength = 0; colvarContentGUID.AutoIncrement = false; colvarContentGUID.IsNullable = false; colvarContentGUID.IsPrimaryKey = false; colvarContentGUID.IsForeignKey = false; colvarContentGUID.IsReadOnly = false; colvarContentGUID.DefaultSetting = @"(newid())"; colvarContentGUID.ForeignKeyTableName = ""; schema.Columns.Add(colvarContentGUID); TableSchema.TableColumn colvarTitle = new TableSchema.TableColumn(schema); colvarTitle.ColumnName = "title"; colvarTitle.DataType = DbType.String; colvarTitle.MaxLength = 500; colvarTitle.AutoIncrement = false; colvarTitle.IsNullable = true; colvarTitle.IsPrimaryKey = false; colvarTitle.IsForeignKey = false; colvarTitle.IsReadOnly = false; colvarTitle.DefaultSetting = @""; colvarTitle.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitle); TableSchema.TableColumn colvarContentName = new TableSchema.TableColumn(schema); colvarContentName.ColumnName = "contentName"; colvarContentName.DataType = DbType.String; colvarContentName.MaxLength = 50; colvarContentName.AutoIncrement = false; colvarContentName.IsNullable = false; colvarContentName.IsPrimaryKey = false; colvarContentName.IsForeignKey = false; colvarContentName.IsReadOnly = false; colvarContentName.DefaultSetting = @""; colvarContentName.ForeignKeyTableName = ""; schema.Columns.Add(colvarContentName); TableSchema.TableColumn colvarContent = new TableSchema.TableColumn(schema); colvarContent.ColumnName = "content"; colvarContent.DataType = DbType.String; colvarContent.MaxLength = 3000; colvarContent.AutoIncrement = false; colvarContent.IsNullable = true; colvarContent.IsPrimaryKey = false; colvarContent.IsForeignKey = false; colvarContent.IsReadOnly = false; colvarContent.DefaultSetting = @""; colvarContent.ForeignKeyTableName = ""; schema.Columns.Add(colvarContent); TableSchema.TableColumn colvarIconPath = new TableSchema.TableColumn(schema); colvarIconPath.ColumnName = "iconPath"; colvarIconPath.DataType = DbType.String; colvarIconPath.MaxLength = 250; colvarIconPath.AutoIncrement = false; colvarIconPath.IsNullable = true; colvarIconPath.IsPrimaryKey = false; colvarIconPath.IsForeignKey = false; colvarIconPath.IsReadOnly = false; colvarIconPath.DefaultSetting = @""; colvarIconPath.ForeignKeyTableName = ""; schema.Columns.Add(colvarIconPath); TableSchema.TableColumn colvarDateExpires = new TableSchema.TableColumn(schema); colvarDateExpires.ColumnName = "dateExpires"; colvarDateExpires.DataType = DbType.DateTime; colvarDateExpires.MaxLength = 0; colvarDateExpires.AutoIncrement = false; colvarDateExpires.IsNullable = true; colvarDateExpires.IsPrimaryKey = false; colvarDateExpires.IsForeignKey = false; colvarDateExpires.IsReadOnly = false; colvarDateExpires.DefaultSetting = @""; colvarDateExpires.ForeignKeyTableName = ""; schema.Columns.Add(colvarDateExpires); TableSchema.TableColumn colvarLastEditedBy = new TableSchema.TableColumn(schema); colvarLastEditedBy.ColumnName = "lastEditedBy"; colvarLastEditedBy.DataType = DbType.String; colvarLastEditedBy.MaxLength = 100; colvarLastEditedBy.AutoIncrement = false; colvarLastEditedBy.IsNullable = true; colvarLastEditedBy.IsPrimaryKey = false; colvarLastEditedBy.IsForeignKey = false; colvarLastEditedBy.IsReadOnly = false; colvarLastEditedBy.DefaultSetting = @""; colvarLastEditedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarLastEditedBy); TableSchema.TableColumn colvarExternalLink = new TableSchema.TableColumn(schema); colvarExternalLink.ColumnName = "externalLink"; colvarExternalLink.DataType = DbType.String; colvarExternalLink.MaxLength = 250; colvarExternalLink.AutoIncrement = false; colvarExternalLink.IsNullable = true; colvarExternalLink.IsPrimaryKey = false; colvarExternalLink.IsForeignKey = false; colvarExternalLink.IsReadOnly = false; colvarExternalLink.DefaultSetting = @""; colvarExternalLink.ForeignKeyTableName = ""; schema.Columns.Add(colvarExternalLink); TableSchema.TableColumn colvarStatus = new TableSchema.TableColumn(schema); colvarStatus.ColumnName = "status"; colvarStatus.DataType = DbType.String; colvarStatus.MaxLength = 50; colvarStatus.AutoIncrement = false; colvarStatus.IsNullable = true; colvarStatus.IsPrimaryKey = false; colvarStatus.IsForeignKey = false; colvarStatus.IsReadOnly = false; colvarStatus.DefaultSetting = @""; colvarStatus.ForeignKeyTableName = ""; schema.Columns.Add(colvarStatus); TableSchema.TableColumn colvarListOrder = new TableSchema.TableColumn(schema); colvarListOrder.ColumnName = "listOrder"; colvarListOrder.DataType = DbType.Int32; colvarListOrder.MaxLength = 0; colvarListOrder.AutoIncrement = false; colvarListOrder.IsNullable = false; colvarListOrder.IsPrimaryKey = false; colvarListOrder.IsForeignKey = false; colvarListOrder.IsReadOnly = false; colvarListOrder.DefaultSetting = @"((1))"; colvarListOrder.ForeignKeyTableName = ""; schema.Columns.Add(colvarListOrder); TableSchema.TableColumn colvarCallOut = new TableSchema.TableColumn(schema); colvarCallOut.ColumnName = "callOut"; colvarCallOut.DataType = DbType.String; colvarCallOut.MaxLength = 250; colvarCallOut.AutoIncrement = false; colvarCallOut.IsNullable = true; colvarCallOut.IsPrimaryKey = false; colvarCallOut.IsForeignKey = false; colvarCallOut.IsReadOnly = false; colvarCallOut.DefaultSetting = @""; colvarCallOut.ForeignKeyTableName = ""; schema.Columns.Add(colvarCallOut); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "createdOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = true; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @"(getdate())"; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "createdBy"; colvarCreatedBy.DataType = DbType.String; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = true; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @""; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "modifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = true; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @"(getdate())"; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "modifiedBy"; colvarModifiedBy.DataType = DbType.String; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = true; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @""; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("TextEntry",schema); } } #endregion #region Props [XmlAttribute("ContentID")] [Bindable(true)] public int ContentID { get { return GetColumnValue<int>(Columns.ContentID); } set { SetColumnValue(Columns.ContentID, value); } } [XmlAttribute("ContentGUID")] [Bindable(true)] public Guid ContentGUID { get { return GetColumnValue<Guid>(Columns.ContentGUID); } set { SetColumnValue(Columns.ContentGUID, value); } } [XmlAttribute("Title")] [Bindable(true)] public string Title { get { return GetColumnValue<string>(Columns.Title); } set { SetColumnValue(Columns.Title, value); } } [XmlAttribute("ContentName")] [Bindable(true)] public string ContentName { get { return GetColumnValue<string>(Columns.ContentName); } set { SetColumnValue(Columns.ContentName, value); } } [XmlAttribute("Content")] [Bindable(true)] public string Content { get { return GetColumnValue<string>(Columns.Content); } set { SetColumnValue(Columns.Content, value); } } [XmlAttribute("IconPath")] [Bindable(true)] public string IconPath { get { return GetColumnValue<string>(Columns.IconPath); } set { SetColumnValue(Columns.IconPath, value); } } [XmlAttribute("DateExpires")] [Bindable(true)] public DateTime? DateExpires { get { return GetColumnValue<DateTime?>(Columns.DateExpires); } set { SetColumnValue(Columns.DateExpires, value); } } [XmlAttribute("LastEditedBy")] [Bindable(true)] public string LastEditedBy { get { return GetColumnValue<string>(Columns.LastEditedBy); } set { SetColumnValue(Columns.LastEditedBy, value); } } [XmlAttribute("ExternalLink")] [Bindable(true)] public string ExternalLink { get { return GetColumnValue<string>(Columns.ExternalLink); } set { SetColumnValue(Columns.ExternalLink, value); } } [XmlAttribute("Status")] [Bindable(true)] public string Status { get { return GetColumnValue<string>(Columns.Status); } set { SetColumnValue(Columns.Status, value); } } [XmlAttribute("ListOrder")] [Bindable(true)] public int ListOrder { get { return GetColumnValue<int>(Columns.ListOrder); } set { SetColumnValue(Columns.ListOrder, value); } } [XmlAttribute("CallOut")] [Bindable(true)] public string CallOut { get { return GetColumnValue<string>(Columns.CallOut); } set { SetColumnValue(Columns.CallOut, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime? CreatedOn { get { return GetColumnValue<DateTime?>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime? ModifiedOn { get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varContentGUID,string varTitle,string varContentName,string varContent,string varIconPath,DateTime? varDateExpires,string varLastEditedBy,string varExternalLink,string varStatus,int varListOrder,string varCallOut,DateTime? varCreatedOn,string varCreatedBy,DateTime? varModifiedOn,string varModifiedBy) { TextEntry item = new TextEntry(); item.ContentGUID = varContentGUID; item.Title = varTitle; item.ContentName = varContentName; item.Content = varContent; item.IconPath = varIconPath; item.DateExpires = varDateExpires; item.LastEditedBy = varLastEditedBy; item.ExternalLink = varExternalLink; item.Status = varStatus; item.ListOrder = varListOrder; item.CallOut = varCallOut; item.CreatedOn = varCreatedOn; item.CreatedBy = varCreatedBy; item.ModifiedOn = varModifiedOn; item.ModifiedBy = varModifiedBy; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varContentID,Guid varContentGUID,string varTitle,string varContentName,string varContent,string varIconPath,DateTime? varDateExpires,string varLastEditedBy,string varExternalLink,string varStatus,int varListOrder,string varCallOut,DateTime? varCreatedOn,string varCreatedBy,DateTime? varModifiedOn,string varModifiedBy) { TextEntry item = new TextEntry(); item.ContentID = varContentID; item.ContentGUID = varContentGUID; item.Title = varTitle; item.ContentName = varContentName; item.Content = varContent; item.IconPath = varIconPath; item.DateExpires = varDateExpires; item.LastEditedBy = varLastEditedBy; item.ExternalLink = varExternalLink; item.Status = varStatus; item.ListOrder = varListOrder; item.CallOut = varCallOut; item.CreatedOn = varCreatedOn; item.CreatedBy = varCreatedBy; item.ModifiedOn = varModifiedOn; item.ModifiedBy = varModifiedBy; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn ContentIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn ContentGUIDColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn TitleColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn ContentNameColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn ContentColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn IconPathColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn DateExpiresColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn LastEditedByColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn ExternalLinkColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn StatusColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn ListOrderColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn CallOutColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[15]; } } #endregion #region Columns Struct public struct Columns { public static string ContentID = @"contentID"; public static string ContentGUID = @"contentGUID"; public static string Title = @"title"; public static string ContentName = @"contentName"; public static string Content = @"content"; public static string IconPath = @"iconPath"; public static string DateExpires = @"dateExpires"; public static string LastEditedBy = @"lastEditedBy"; public static string ExternalLink = @"externalLink"; public static string Status = @"status"; public static string ListOrder = @"listOrder"; public static string CallOut = @"callOut"; public static string CreatedOn = @"createdOn"; public static string CreatedBy = @"createdBy"; public static string ModifiedOn = @"modifiedOn"; public static string ModifiedBy = @"modifiedBy"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:41 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.resizer { #region Resizer /// <inheritdocs /> /// <summary> /// <p>Applies drag handles to an element or component to make it resizable. The drag handles are inserted into the element /// (or component's element) and positioned absolute.</p> /// <p>Textarea and img elements will be wrapped with an additional div because these elements do not support child nodes. /// The original element can be accessed through the originalTarget property.</p> /// <p>Here is the list of valid resize handles:</p> /// <pre><code>Value Description /// ------ ------------------- /// 'n' north /// 's' south /// 'e' east /// 'w' west /// 'nw' northwest /// 'sw' southwest /// 'se' southeast /// 'ne' northeast /// 'all' all /// </code></pre> /// <p><p><i></i></p></p> /// <p>Here's an example showing the creation of a typical Resizer:</p> /// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.resizer.Resizer">Ext.resizer.Resizer</see>', { /// el: 'elToResize', /// handles: 'all', /// minWidth: 200, /// minHeight: 100, /// maxWidth: 500, /// maxHeight: 400, /// pinned: true /// }); /// </code></pre> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class Resizer : Ext.Base, Ext.util.Observable { /// <summary> /// An element, or a Region into which the resize operation must be constrained. /// </summary> public object constrainTo; /// <summary> /// Specify as true to update the target (Element or Component) dynamically during /// dragging. This is true by default, but the Component class passes false when it is /// configured as Ext.Component.resizable. /// If specified as <c>false</c>, a proxy element is displayed during the resize operation, and the <see cref="Ext.resizer.ResizerConfig.target">target</see> is /// updated on mouseup. /// Defaults to: <c>true</c> /// </summary> public bool dynamic; /// <summary> /// String consisting of the resize handles to display. Defaults to 's e se' for Elements and fixed position /// Components. Defaults to 8 point resizing for floating Components (such as Windows). Specify either 'all' or any /// of 'n s e w ne nw se sw'. /// Defaults to: <c>&quot;s e se&quot;</c> /// </summary> public JsString handles; /// <summary> /// Optional. The height to set target to in pixels /// Defaults to: <c>null</c> /// </summary> public JsNumber height; /// <summary> /// The increment to snap the height resize in pixels. /// Defaults to: <c>0</c> /// </summary> public JsNumber heightIncrement; /// <summary> /// A config object containing one or more event handlers to be added to this object during initialization. This /// should be a valid listeners config object as specified in the addListener example for attaching multiple /// handlers at once. /// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong> /// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually /// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a /// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a /// DOM listener to: /// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// width: 400, /// height: 200, /// dockedItems: [{ /// xtype: 'toolbar' /// }], /// listeners: { /// click: { /// element: 'el', //bind to the underlying el property on the panel /// fn: function(){ console.log('click el'); } /// }, /// dblclick: { /// element: 'body', //bind to the underlying body property on the panel /// fn: function(){ console.log('dblclick body'); } /// } /// } /// }); /// </code> /// </summary> public JsObject listeners; /// <summary> /// The maximum height for the element /// Defaults to: <c>10000</c> /// </summary> public JsNumber maxHeight; /// <summary> /// The maximum width for the element /// Defaults to: <c>10000</c> /// </summary> public JsNumber maxWidth; /// <summary> /// The minimum height for the element /// Defaults to: <c>20</c> /// </summary> public JsNumber minHeight; /// <summary> /// The minimum width for the element /// Defaults to: <c>20</c> /// </summary> public JsNumber minWidth; /// <summary> /// True to ensure that the resize handles are always visible, false indicates resizing by cursor changes only /// Defaults to: <c>false</c> /// </summary> public bool pinned; /// <summary> /// True to preserve the original ratio between height and width during resize /// Defaults to: <c>false</c> /// </summary> public bool preserveRatio; /// <summary> /// The Element or Component to resize. /// </summary> public object target; /// <summary> /// True for transparent handles. This is only applied at config time. /// Defaults to: <c>false</c> /// </summary> public bool transparent; /// <summary> /// Optional. The width to set the target to in pixels /// Defaults to: <c>null</c> /// </summary> public JsNumber width; /// <summary> /// The increment to snap the width resize in pixels. /// Defaults to: <c>0</c> /// </summary> public JsNumber widthIncrement; /// <summary> /// Outer element for resizing behavior. /// </summary> public Ext.dom.Element el{get;set;} /// <summary> /// Initial suspended call count. Incremented when suspendEvents is called, decremented when resumeEvents is called. /// Defaults to: <c>0</c> /// </summary> public JsNumber eventsSuspended{get;set;} /// <summary> /// This object holds a key for any event that has a listener. The listener may be set /// directly on the instance, or on its class or a super class (via observe) or /// on the MVC EventBus. The values of this object are truthy /// (a non-zero number) and falsy (0 or undefined). They do not represent an exact count /// of listeners. The value for an event is truthy if the event must be fired and is /// falsy if there is no need to fire the event. /// The intended use of this property is to avoid the expense of fireEvent calls when /// there are no listeners. This can be particularly helpful when one would otherwise /// have to call fireEvent hundreds or thousands of times. It is used like this: /// <code> if (this.hasListeners.foo) { /// this.fireEvent('foo', this, arg1); /// } /// </code> /// </summary> public JsObject hasListeners{get;set;} /// <summary> /// true in this class to identify an object as an instantiated Observable, or subclass thereof. /// Defaults to: <c>true</c> /// </summary> public bool isObservable{get;set;} /// <summary> /// Reference to the original resize target if the element of the original resize target was a /// Field, or an IMG or a TEXTAREA which must be wrapped in a DIV. /// </summary> public object originalTarget{get;set;} /// <summary> /// </summary> public ResizeTracker resizeTracker{get;set;} /// <summary> /// Adds the specified events to the list of events which this Observable may fire. /// </summary> /// <param name="eventNames"><p>Either an object with event names as properties with /// a value of <c>true</c>. For example:</p> /// <pre><code>this.addEvents({ /// storeloaded: true, /// storecleared: true /// }); /// </code></pre> /// <p>Or any number of event names as separate parameters. For example:</p> /// <pre><code>this.addEvents('storeloaded', 'storecleared'); /// </code></pre> /// </param> public virtual void addEvents(object eventNames){} /// <summary> /// Appends an event handler to this object. For example: /// <code>myGridPanel.on("mouseover", this.onMouseOver, this); /// </code> /// The method also allows for a single argument to be passed which is a config object /// containing properties which specify multiple events. For example: /// <code>myGridPanel.on({ /// cellClick: this.onCellClick, /// mouseover: this.onMouseOver, /// mouseout: this.onMouseOut, /// scope: this // Important. Ensure "this" is correct during handler execution /// }); /// </code> /// One can also specify options for each event handler separately: /// <code>myGridPanel.on({ /// cellClick: {fn: this.onCellClick, scope: this, single: true}, /// mouseover: {fn: panel.onMouseOver, scope: panel} /// }); /// </code> /// <em>Names</em> of methods in a specified scope may also be used. Note that /// <c>scope</c> MUST be specified to use this option: /// <code>myGridPanel.on({ /// cellClick: {fn: 'onCellClick', scope: this, single: true}, /// mouseover: {fn: 'onMouseOver', scope: panel} /// }); /// </code> /// </summary> /// <param name="eventName"><p>The name of the event to listen for. /// May also be an object who's property names are event names.</p> /// </param> /// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within /// the specified <c>scope</c>. Will be called with arguments /// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p> /// </param> /// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is /// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p> /// </param> /// <param name="options"><p>An object containing handler configuration.</p> /// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last /// argument to every event handler.</p> /// <p>This object may contain any of the following properties:</p> /// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted, /// defaults to the object which fired the event.</strong></p> /// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p> /// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p> /// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed /// by the specified number of milliseconds. If the event fires again within that time, /// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p> /// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event /// was bubbled up from a child Observable.</p> /// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong> /// The name of a Component property which references an element to add a listener to.</p> /// <p> This option is useful during Component construction to add DOM event listeners to elements of /// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered. /// For example, to add a click listener to a Panel's body:</p> /// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// title: 'The title', /// listeners: { /// click: this.handlePanelClick, /// element: 'body' /// } /// }); /// </code></pre> /// <p><strong>Combining Options</strong></p> /// <p>Using the options argument, it is possible to combine different types of listeners:</p> /// <p>A delayed, one-time listener.</p> /// <pre><code>myPanel.on('hide', this.handleClick, this, { /// single: true, /// delay: 100 /// }); /// </code></pre> /// </div></li></ul></param> public virtual void addListener(object eventName, System.Delegate fn=null, object scope=null, object options=null){} /// <summary> /// Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is /// destroyed. /// </summary> /// <param name="item"><p>The item to which to add a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> /// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the /// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p> /// </param> public virtual void addManagedListener(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){} /// <summary> /// Removes all listeners for this object including the managed listeners /// </summary> public virtual void clearListeners(){} /// <summary> /// Removes all managed listeners for this object. /// </summary> public virtual void clearManagedListeners(){} /// <summary> /// Continue to fire event. /// </summary> /// <param name="eventName"> /// </param> /// <param name="args"> /// </param> /// <param name="bubbles"> /// </param> public virtual void continueFireEvent(JsString eventName, object args=null, object bubbles=null){} /// <summary> /// Creates an event handling function which refires the event from this object as the passed event name. /// </summary> /// <param name="newName"> /// </param> /// <param name="beginEnd"><p>The caller can specify on which indices to slice</p> /// </param> /// <returns> /// <span><see cref="Function">Function</see></span><div> /// </div> /// </returns> public virtual System.Delegate createRelayer(object newName, object beginEnd=null){return null;} /// <summary> /// Enables events fired by this Observable to bubble up an owner hierarchy by calling this.getBubbleTarget() if /// present. There is no implementation in the Observable base class. /// This is commonly used by Ext.Components to bubble events to owner Containers. /// See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>. The default implementation in <see cref="Ext.Component">Ext.Component</see> returns the /// Component's immediate owner. But if a known target is required, this can be overridden to access the /// required target more quickly. /// Example: /// <code><see cref="Ext.ExtContext.override">Ext.override</see>(<see cref="Ext.form.field.Base">Ext.form.field.Base</see>, { /// // Add functionality to Field's initComponent to enable the change event to bubble /// initComponent : <see cref="Ext.Function.createSequence">Ext.Function.createSequence</see>(Ext.form.field.Base.prototype.initComponent, function() { /// this.enableBubble('change'); /// }), /// // We know that we want Field's events to bubble directly to the FormPanel. /// getBubbleTarget : function() { /// if (!this.formPanel) { /// this.formPanel = this.findParentByType('form'); /// } /// return this.formPanel; /// } /// }); /// var myForm = new Ext.formPanel({ /// title: 'User Details', /// items: [{ /// ... /// }], /// listeners: { /// change: function() { /// // Title goes red if form has been modified. /// myForm.header.setStyle('color', 'red'); /// } /// } /// }); /// </code> /// </summary> /// <param name="eventNames"><p>The event name to bubble, or an Array of event names.</p> /// </param> public virtual void enableBubble(object eventNames){} /// <summary> /// Fires the specified event with the passed parameters (minus the event name, plus the options object passed /// to addListener). /// An event may be set to bubble up an Observable parent hierarchy (See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>) by /// calling <see cref="Ext.util.Observable.enableBubble">enableBubble</see>. /// </summary> /// <param name="eventName"><p>The name of the event to fire.</p> /// </param> /// <param name="args"><p>Variable number of parameters are passed to handlers.</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div><p>returns false if any of the handlers return false otherwise it returns true.</p> /// </div> /// </returns> public virtual bool fireEvent(JsString eventName, params object[] args){return false;} /// <summary> /// Fix IE6 handle height issue. /// </summary> private void forceHandlesHeight(){} /// <summary> /// Gets the bubbling parent for an Observable /// </summary> /// <returns> /// <span><see cref="Ext.util.Observable">Ext.util.Observable</see></span><div><p>The bubble parent. null is returned if no bubble target exists</p> /// </div> /// </returns> public virtual Ext.util.Observable getBubbleParent(){return null;} /// <summary> /// Returns the element that was configured with the el or target config property. If a component was configured with /// the target property then this will return the element of this component. /// Textarea and img elements will be wrapped with an additional div because these elements do not support child /// nodes. The original element can be accessed through the originalTarget property. /// </summary> /// <returns> /// <span><see cref="Ext.dom.Element">Ext.Element</see></span><div><p>element</p> /// </div> /// </returns> public Ext.dom.Element getEl(){return null;} /// <summary> /// Returns the element or component that was configured with the target config property. /// Textarea and img elements will be wrapped with an additional div because these elements do not support child /// nodes. The original element can be accessed through the originalTarget property. /// </summary> /// <returns> /// <span><see cref="Ext.dom.Element">Ext.Element</see>/<see cref="Ext.Component">Ext.Component</see></span><div> /// </div> /// </returns> public object getTarget(){return null;} /// <summary> /// Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer /// indicates whether the event needs firing or not. /// </summary> /// <param name="eventName"><p>The name of the event to check for</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div><p><c>true</c> if the event is being listened for or bubbles, else <c>false</c></p> /// </div> /// </returns> public virtual bool hasListener(JsString eventName){return false;} /// <summary> /// Shorthand for addManagedListener. /// Adds listeners to any Observable object (or <see cref="Ext.dom.Element">Ext.Element</see>) which are automatically removed when this Component is /// destroyed. /// </summary> /// <param name="item"><p>The item to which to add a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> /// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the /// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p> /// </param> public virtual void mon(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){} /// <summary> /// Shorthand for removeManagedListener. /// Removes listeners that were added by the <see cref="Ext.util.Observable.mon">mon</see> method. /// </summary> /// <param name="item"><p>The item from which to remove a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> public virtual void mun(object item, object ename, System.Delegate fn=null, object scope=null){} /// <summary> /// Shorthand for addListener. /// Appends an event handler to this object. For example: /// <code>myGridPanel.on("mouseover", this.onMouseOver, this); /// </code> /// The method also allows for a single argument to be passed which is a config object /// containing properties which specify multiple events. For example: /// <code>myGridPanel.on({ /// cellClick: this.onCellClick, /// mouseover: this.onMouseOver, /// mouseout: this.onMouseOut, /// scope: this // Important. Ensure "this" is correct during handler execution /// }); /// </code> /// One can also specify options for each event handler separately: /// <code>myGridPanel.on({ /// cellClick: {fn: this.onCellClick, scope: this, single: true}, /// mouseover: {fn: panel.onMouseOver, scope: panel} /// }); /// </code> /// <em>Names</em> of methods in a specified scope may also be used. Note that /// <c>scope</c> MUST be specified to use this option: /// <code>myGridPanel.on({ /// cellClick: {fn: 'onCellClick', scope: this, single: true}, /// mouseover: {fn: 'onMouseOver', scope: panel} /// }); /// </code> /// </summary> /// <param name="eventName"><p>The name of the event to listen for. /// May also be an object who's property names are event names.</p> /// </param> /// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within /// the specified <c>scope</c>. Will be called with arguments /// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p> /// </param> /// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is /// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p> /// </param> /// <param name="options"><p>An object containing handler configuration.</p> /// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last /// argument to every event handler.</p> /// <p>This object may contain any of the following properties:</p> /// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted, /// defaults to the object which fired the event.</strong></p> /// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p> /// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p> /// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed /// by the specified number of milliseconds. If the event fires again within that time, /// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p> /// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event /// was bubbled up from a child Observable.</p> /// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong> /// The name of a Component property which references an element to add a listener to.</p> /// <p> This option is useful during Component construction to add DOM event listeners to elements of /// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered. /// For example, to add a click listener to a Panel's body:</p> /// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// title: 'The title', /// listeners: { /// click: this.handlePanelClick, /// element: 'body' /// } /// }); /// </code></pre> /// <p><strong>Combining Options</strong></p> /// <p>Using the options argument, it is possible to combine different types of listeners:</p> /// <p>A delayed, one-time listener.</p> /// <pre><code>myPanel.on('hide', this.handleClick, this, { /// single: true, /// delay: 100 /// }); /// </code></pre> /// </div></li></ul></param> public virtual void on(object eventName, System.Delegate fn=null, object scope=null, object options=null){} /// <summary> /// Relay the Tracker's mousedown event as beforeresize /// </summary> /// <param name="tracker"><p>The Resizer</p> /// </param> /// <param name="e"><p>The Event</p> /// </param> private void onBeforeResize(object tracker, object e){} /// <summary> /// Relay the Tracker's drag event as resizedrag /// </summary> /// <param name="tracker"><p>The Resizer</p> /// </param> /// <param name="e"><p>The Event</p> /// </param> private void onResize(object tracker, object e){} /// <summary> /// Relay the Tracker's dragend event as resize /// </summary> /// <param name="tracker"><p>The Resizer</p> /// </param> /// <param name="e"><p>The Event</p> /// </param> private void onResizeEnd(object tracker, object e){} /// <summary> /// Prepares a given class for observable instances. This method is called when a /// class derives from this class or uses this class as a mixin. /// </summary> /// <param name="T"><p>The class constructor to prepare.</p> /// </param> public virtual void prepareClass(System.Delegate T){} /// <summary> /// Relays selected events from the specified Observable as if the events were fired by this. /// For example if you are extending Grid, you might decide to forward some events from store. /// So you can do this inside your initComponent: /// <code>this.relayEvents(this.getStore(), ['load']); /// </code> /// The grid instance will then have an observable 'load' event which will be passed the /// parameters of the store's load event and any function fired with the grid's load event /// would have access to the grid using the <c>this</c> keyword. /// </summary> /// <param name="origin"><p>The Observable whose events this object is to relay.</p> /// </param> /// <param name="events"><p>Array of event names to relay.</p> /// </param> /// <param name="prefix"><p>A common prefix to prepend to the event names. For example:</p> /// <pre><code>this.relayEvents(this.getStore(), ['load', 'clear'], 'store'); /// </code></pre> /// <p>Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'.</p> /// </param> public virtual void relayEvents(object origin, JsArray<String> events, object prefix=null){} /// <summary> /// Removes an event handler. /// </summary> /// <param name="eventName"><p>The type of event the handler was associated with.</p> /// </param> /// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the /// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p> /// </param> /// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the /// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p> /// </param> public virtual void removeListener(JsString eventName, System.Delegate fn, object scope=null){} /// <summary> /// Removes listeners that were added by the mon method. /// </summary> /// <param name="item"><p>The item from which to remove a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> public virtual void removeManagedListener(object item, object ename, System.Delegate fn=null, object scope=null){} /// <summary> /// Remove a single managed listener item /// </summary> /// <param name="isClear"><p>True if this is being called during a clear</p> /// </param> /// <param name="managedListener"><p>The managed listener item /// See removeManagedListener for other args</p> /// </param> public virtual void removeManagedListenerItem(bool isClear, object managedListener){} /// <summary> /// Perform a manual resize and fires the 'resize' event. /// </summary> /// <param name="width"> /// </param> /// <param name="height"> /// </param> public void resizeTo(JsNumber width, JsNumber height){} /// <summary> /// Resumes firing events (see suspendEvents). /// If events were suspended using the <c>queueSuspended</c> parameter, then all events fired /// during event suspension will be sent to any listeners now. /// </summary> public virtual void resumeEvents(){} /// <summary> /// Suspends the firing of all events. (see resumeEvents) /// </summary> /// <param name="queueSuspended"><p>Pass as true to queue up suspended events to be fired /// after the <see cref="Ext.util.Observable.resumeEvents">resumeEvents</see> call instead of discarding all suspended events.</p> /// </param> public virtual void suspendEvents(bool queueSuspended){} /// <summary> /// Shorthand for removeListener. /// Removes an event handler. /// </summary> /// <param name="eventName"><p>The type of event the handler was associated with.</p> /// </param> /// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the /// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p> /// </param> /// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the /// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p> /// </param> public virtual void un(JsString eventName, System.Delegate fn, object scope=null){} public Resizer(ResizerConfig config){} public Resizer(){} public Resizer(params object[] args){} } #endregion #region ResizerConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ResizerConfig : Ext.BaseConfig { /// <summary> /// An element, or a Region into which the resize operation must be constrained. /// </summary> public object constrainTo; /// <summary> /// Specify as true to update the target (Element or Component) dynamically during /// dragging. This is true by default, but the Component class passes false when it is /// configured as Ext.Component.resizable. /// If specified as <c>false</c>, a proxy element is displayed during the resize operation, and the <see cref="Ext.resizer.ResizerConfig.target">target</see> is /// updated on mouseup. /// Defaults to: <c>true</c> /// </summary> public bool dynamic; /// <summary> /// String consisting of the resize handles to display. Defaults to 's e se' for Elements and fixed position /// Components. Defaults to 8 point resizing for floating Components (such as Windows). Specify either 'all' or any /// of 'n s e w ne nw se sw'. /// Defaults to: <c>&quot;s e se&quot;</c> /// </summary> public JsString handles; /// <summary> /// Optional. The height to set target to in pixels /// Defaults to: <c>null</c> /// </summary> public JsNumber height; /// <summary> /// The increment to snap the height resize in pixels. /// Defaults to: <c>0</c> /// </summary> public JsNumber heightIncrement; /// <summary> /// A config object containing one or more event handlers to be added to this object during initialization. This /// should be a valid listeners config object as specified in the addListener example for attaching multiple /// handlers at once. /// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong> /// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually /// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a /// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a /// DOM listener to: /// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// width: 400, /// height: 200, /// dockedItems: [{ /// xtype: 'toolbar' /// }], /// listeners: { /// click: { /// element: 'el', //bind to the underlying el property on the panel /// fn: function(){ console.log('click el'); } /// }, /// dblclick: { /// element: 'body', //bind to the underlying body property on the panel /// fn: function(){ console.log('dblclick body'); } /// } /// } /// }); /// </code> /// </summary> public JsObject listeners; /// <summary> /// The maximum height for the element /// Defaults to: <c>10000</c> /// </summary> public JsNumber maxHeight; /// <summary> /// The maximum width for the element /// Defaults to: <c>10000</c> /// </summary> public JsNumber maxWidth; /// <summary> /// The minimum height for the element /// Defaults to: <c>20</c> /// </summary> public JsNumber minHeight; /// <summary> /// The minimum width for the element /// Defaults to: <c>20</c> /// </summary> public JsNumber minWidth; /// <summary> /// True to ensure that the resize handles are always visible, false indicates resizing by cursor changes only /// Defaults to: <c>false</c> /// </summary> public bool pinned; /// <summary> /// True to preserve the original ratio between height and width during resize /// Defaults to: <c>false</c> /// </summary> public bool preserveRatio; /// <summary> /// The Element or Component to resize. /// </summary> public object target; /// <summary> /// True for transparent handles. This is only applied at config time. /// Defaults to: <c>false</c> /// </summary> public bool transparent; /// <summary> /// Optional. The width to set the target to in pixels /// Defaults to: <c>null</c> /// </summary> public JsNumber width; /// <summary> /// The increment to snap the width resize in pixels. /// Defaults to: <c>0</c> /// </summary> public JsNumber widthIncrement; public ResizerConfig(params object[] args){} } #endregion #region ResizerEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ResizerEvents : Ext.BaseEvents { /// <summary> /// Fired before resize is allowed. Return false to cancel resize. /// </summary> /// <param name="this"> /// </param> /// <param name="width"><p>The start width</p> /// </param> /// <param name="height"><p>The start height</p> /// </param> /// <param name="e"><p>The mousedown event</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeresize(Resizer @this, JsNumber width, JsNumber height, EventObject e, object eOpts){} /// <summary> /// Fired after a resize. /// </summary> /// <param name="this"> /// </param> /// <param name="width"><p>The new width</p> /// </param> /// <param name="height"><p>The new height</p> /// </param> /// <param name="e"><p>The mouseup event</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void resize(Resizer @this, JsNumber width, JsNumber height, EventObject e, object eOpts){} /// <summary> /// Fires during resizing. Return false to cancel resize. /// </summary> /// <param name="this"> /// </param> /// <param name="width"><p>The new width</p> /// </param> /// <param name="height"><p>The new height</p> /// </param> /// <param name="e"><p>The mousedown event</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void resizedrag(Resizer @this, JsNumber width, JsNumber height, EventObject e, object eOpts){} public ResizerEvents(params object[] args){} } #endregion }
using System; using System.Text; using Google.GData.AccessControl; using Google.GData.Calendar; using Google.GData.Client; using Google.GData.Extensions; namespace CalendarDemoConsoleApplication { class CalendarDemo { private static String userName, userPassword, feedUri; /// <summary> /// Prints a list of the user's calendars. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> static void PrintUserCalendars(CalendarService service) { FeedQuery query = new FeedQuery(); query.Uri = new Uri("http://www.google.com/calendar/feeds/default"); // Tell the service to query: AtomFeed calFeed = service.Query(query); Console.WriteLine("Your calendars:"); Console.WriteLine(); for (int i = 0; i < calFeed.Entries.Count; i++) { Console.WriteLine(calFeed.Entries[i].Title.Text); } Console.WriteLine(); } /// <summary> /// Prints the titles of all events on the specified calendar. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> static void PrintAllEvents(CalendarService service) { EventQuery myQuery = new EventQuery(feedUri); EventFeed myResultsFeed = service.Query(myQuery) as EventFeed; Console.WriteLine("All events on your calendar:"); Console.WriteLine(); for (int i = 0; i < myResultsFeed.Entries.Count; i++) { Console.WriteLine(myResultsFeed.Entries[i].Title.Text); } Console.WriteLine(); } /// <summary> /// Prints the titles of all events matching a full-text query. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="queryString">The text for which to query.</param> static void FullTextQuery(CalendarService service, String queryString) { EventQuery myQuery = new EventQuery(feedUri); myQuery.Query = queryString; EventFeed myResultsFeed = service.Query(myQuery) as EventFeed; Console.WriteLine("Events matching \"{0}\":", queryString); Console.WriteLine(); for (int i = 0; i < myResultsFeed.Entries.Count; i++) { Console.WriteLine(myResultsFeed.Entries[i].Title.Text); } Console.WriteLine(); } /// <summary> /// Prints the titles of all events in a specified date/time range. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="startTime">Start time (inclusive) of events to print.</param> /// <param name="endTime">End time (exclusive) of events to print.</param> static void DateRangeQuery(CalendarService service, DateTime startTime, DateTime endTime) { EventQuery myQuery = new EventQuery(feedUri); myQuery.StartTime = startTime; myQuery.EndTime = endTime; EventFeed myResultsFeed = service.Query(myQuery) as EventFeed; Console.WriteLine("Matching events from {0} to {1}:", startTime.ToShortDateString(), endTime.ToShortDateString()); Console.WriteLine(); for (int i = 0; i < myResultsFeed.Entries.Count; i++) { Console.WriteLine(myResultsFeed.Entries[i].Title.Text); } Console.WriteLine(); } /// <summary> /// Helper method to create either single-instance or recurring events. /// For simplicity, some values that might normally be passed as parameters /// (such as author name, email, etc.) are hard-coded. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="entryTitle">Title of the event to create.</param> /// <param name="recurData">Recurrence value for the event, or null for /// single-instance events.</param> /// <returns>The newly-created EventEntry on the calendar.</returns> static EventEntry CreateEvent(CalendarService service, String entryTitle, String recurData) { EventEntry entry = new EventEntry(); // Set the title and content of the entry. entry.Title.Text = entryTitle; entry.Content.Content = "Meet for a quick lesson."; // Set a location for the event. Where eventLocation = new Where(); eventLocation.ValueString = "South Tennis Courts"; entry.Locations.Add(eventLocation); // If a recurrence was requested, add it. Otherwise, set the // time (the current date and time) and duration (30 minutes) // of the event. if (recurData == null) { When eventTime = new When(); eventTime.StartTime = DateTime.Now; eventTime.EndTime = eventTime.StartTime.AddMinutes(30); entry.Times.Add(eventTime); } else { Recurrence recurrence = new Recurrence(); recurrence.Value = recurData; entry.Recurrence = recurrence; } // Send the request and receive the response: Uri postUri = new Uri(feedUri); AtomEntry insertedEntry = service.Insert(postUri, entry); return (EventEntry)insertedEntry; } /// <summary> /// Creates a single-instance event on a calendar. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="entryTitle">Title of the event to create.</param> /// <returns>The newly-created EventEntry on the calendar.</returns> static EventEntry CreateSingleEvent(CalendarService service, String entryTitle) { return CreateEvent(service, entryTitle, null); } /// <summary> /// Creates a recurring event on a calendar. In this example, the event /// occurs every Tuesday from May 1, 2007 through September 4, 2007. Note /// that we are using iCal (RFC 2445) syntax; see http://www.ietf.org/rfc/rfc2445.txt /// for more information. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="entryTitle">Title of the event to create.</param> /// <returns>The newly-created EventEntry on the calendar.</returns> static EventEntry CreateRecurringEvent(CalendarService service, String entryTitle) { String recurData = "DTSTART;VALUE=DATE:20070501\r\n" + "DTEND;VALUE=DATE:20070502\r\n" + "RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n"; return CreateEvent(service, entryTitle, recurData); } /// <summary> /// Updates the title of an existing calendar event. /// </summary> /// <param name="entry">The event to update.</param> /// <param name="newTitle">The new title for this event.</param> /// <returns>The updated EventEntry object.</returns> static EventEntry UpdateTitle(EventEntry entry, String newTitle) { entry.Title.Text = newTitle; return (EventEntry)entry.Update(); } /// <summary> /// Adds a reminder to a calendar event. /// </summary> /// <param name="entry">The event to update.</param> /// <param name="numMinutes">Reminder time, in minutes.</param> /// <returns>The updated EventEntry object.</returns> static EventEntry AddReminder(EventEntry entry, int numMinutes) { Reminder reminder = new Reminder(); reminder.Minutes = numMinutes; entry.Reminder = reminder; return (EventEntry)entry.Update(); } /// <summary> /// Adds an extended property to a calendar event. /// </summary> /// <param name="entry">The event to update.</param> /// <returns>The updated EventEntry object.</returns> static EventEntry AddExtendedProperty(EventEntry entry) { ExtendedProperty property = new ExtendedProperty(); property.Name = "http://www.example.com/schemas/2005#mycal.id"; property.Value = "1234"; entry.ExtensionElements.Add(property); return (EventEntry)entry.Update(); } /// <summary> /// Retrieves and prints the access control lists of all /// of the authenticated user's calendars. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> static void RetrieveAcls(CalendarService service) { FeedQuery query = new FeedQuery(); query.Uri = new Uri("http://www.google.com/calendar/feeds/default"); AtomFeed calFeed = service.Query(query); Console.WriteLine(); Console.WriteLine("Sharing permissions for your calendars:"); // Retrieve the meta-feed of all calendars. foreach (AtomEntry calendarEntry in calFeed.Entries) { Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text); AtomLink link = calendarEntry.Links.FindService( AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, null); // For each calendar, retrieve its ACL feed. if (link != null) { AclFeed feed = service.Query(new AclQuery(link.HRef.ToString())); foreach (AclEntry aclEntry in feed.Entries) { Console.WriteLine("\tScope: Type={0} ({1})", aclEntry.Scope.Type, aclEntry.Scope.Value); Console.WriteLine("\tRole: {0}", aclEntry.Role.Value); } } } } /// <summary> /// Shares a calendar with the specified user. Note that this method /// will not run by default. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="aclFeedUri">the ACL feed URI of the calendar being shared.</param> /// <param name="userEmail">The email address of the user with whom to share.</param> /// <param name="role">The role of the user with whom to share.</param> /// <returns>The AclEntry returned by the server.</returns> static AclEntry AddAccessControl(CalendarService service, string aclFeedUri, string userEmail, AclRole role) { AclEntry entry = new AclEntry(); entry.Scope = new AclScope(); entry.Scope.Type = AclScope.SCOPE_USER; entry.Scope.Value = userEmail; entry.Role = role; Uri aclUri = new Uri("http://www.google.com/calendar/feeds/gdata.ops.test@gmail.com/acl/full"); AclEntry insertedEntry = service.Insert(aclUri, entry); Console.WriteLine("Added user {0}", insertedEntry.Scope.Value); return insertedEntry; } /// <summary> /// Updates a user to have new access permissions over a calendar. /// Note that this method will not run by default. /// </summary> /// <param name="entry">An existing AclEntry representing sharing permissions.</param> /// <param name="newRole">The new role (access permissions) for the user.</param> /// <returns>The updated AclEntry.</returns> static AclEntry UpdateEntry(AclEntry entry, AclRole newRole) { entry.Role = newRole; AclEntry updatedEntry = entry.Update() as AclEntry; Console.WriteLine("Updated {0} to have role {1}", updatedEntry.Scope.Value, entry.Role.Value); return updatedEntry; } /// <summary> /// Deletes a user from a calendar's access control list, preventing /// that user from accessing the calendar. Note that this method will /// not run by default. /// </summary> /// <param name="entry">An existing AclEntry representing sharing permissions.</param> static void DeleteEntry(AclEntry entry) { entry.Delete(); } /// <summary> /// Runs the methods above to demonstrate usage of the .NET /// client library. The methods that add, update, or remove /// users on access control lists will not run by default. /// </summary> static void RunSample() { CalendarService service = new CalendarService("exampleCo-exampleApp-1"); service.setUserCredentials(userName, userPassword); // Demonstrate retrieving a list of the user's calendars. PrintUserCalendars(service); // Demonstrate various feed queries. PrintAllEvents(service); FullTextQuery(service, "Tennis"); DateRangeQuery(service, new DateTime(2007, 1, 5), new DateTime(2007, 1, 7)); // Demonstrate creating a single-occurrence event. EventEntry singleEvent = CreateSingleEvent(service, "Tennis with Mike"); Console.WriteLine("Successfully created event {0}", singleEvent.Title.Text); // Demonstrate creating a recurring event. AtomEntry recurringEvent = CreateRecurringEvent(service, "Tennis with Dan"); Console.WriteLine("Successfully created recurring event {0}", recurringEvent.Title.Text); // Demonstrate updating the event's text. singleEvent = UpdateTitle(singleEvent, "Important meeting"); Console.WriteLine("Event's new title is {0}", singleEvent.Title.Text); // Demonstrate adding a reminder. Note that this will only work on a primary // calendar. singleEvent = AddReminder(singleEvent, 15); Console.WriteLine("Set a {0}-minute reminder for the event.", singleEvent.Reminder.Minutes); // Demonstrate adding an extended property. AddExtendedProperty(singleEvent); // Demonstrate deleting the item. singleEvent.Delete(); // Demonstrate retrieving access control lists for all calendars. RetrieveAcls(service); } static void Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Usage: gcal_demo <username> <password> <feedUri>"); } else { userName = args[0]; userPassword = args[1]; feedUri = args[2]; RunSample(); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.AppEngine.V1.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedAuthorizedCertificatesClientSnippets { /// <summary>Snippet for ListAuthorizedCertificates</summary> public void ListAuthorizedCertificatesRequestObject() { // Snippet: ListAuthorizedCertificates(ListAuthorizedCertificatesRequest, CallSettings) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = AuthorizedCertificatesClient.Create(); // Initialize request argument(s) ListAuthorizedCertificatesRequest request = new ListAuthorizedCertificatesRequest { Parent = "", View = AuthorizedCertificateView.BasicCertificate, }; // Make the request PagedEnumerable<ListAuthorizedCertificatesResponse, AuthorizedCertificate> response = authorizedCertificatesClient.ListAuthorizedCertificates(request); // Iterate over all response items, lazily performing RPCs as required foreach (AuthorizedCertificate item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAuthorizedCertificatesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AuthorizedCertificate item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AuthorizedCertificate> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AuthorizedCertificate item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAuthorizedCertificatesAsync</summary> public async Task ListAuthorizedCertificatesRequestObjectAsync() { // Snippet: ListAuthorizedCertificatesAsync(ListAuthorizedCertificatesRequest, CallSettings) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = await AuthorizedCertificatesClient.CreateAsync(); // Initialize request argument(s) ListAuthorizedCertificatesRequest request = new ListAuthorizedCertificatesRequest { Parent = "", View = AuthorizedCertificateView.BasicCertificate, }; // Make the request PagedAsyncEnumerable<ListAuthorizedCertificatesResponse, AuthorizedCertificate> response = authorizedCertificatesClient.ListAuthorizedCertificatesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AuthorizedCertificate item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAuthorizedCertificatesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AuthorizedCertificate item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AuthorizedCertificate> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AuthorizedCertificate item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetAuthorizedCertificate</summary> public void GetAuthorizedCertificateRequestObject() { // Snippet: GetAuthorizedCertificate(GetAuthorizedCertificateRequest, CallSettings) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = AuthorizedCertificatesClient.Create(); // Initialize request argument(s) GetAuthorizedCertificateRequest request = new GetAuthorizedCertificateRequest { Name = "", View = AuthorizedCertificateView.BasicCertificate, }; // Make the request AuthorizedCertificate response = authorizedCertificatesClient.GetAuthorizedCertificate(request); // End snippet } /// <summary>Snippet for GetAuthorizedCertificateAsync</summary> public async Task GetAuthorizedCertificateRequestObjectAsync() { // Snippet: GetAuthorizedCertificateAsync(GetAuthorizedCertificateRequest, CallSettings) // Additional: GetAuthorizedCertificateAsync(GetAuthorizedCertificateRequest, CancellationToken) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = await AuthorizedCertificatesClient.CreateAsync(); // Initialize request argument(s) GetAuthorizedCertificateRequest request = new GetAuthorizedCertificateRequest { Name = "", View = AuthorizedCertificateView.BasicCertificate, }; // Make the request AuthorizedCertificate response = await authorizedCertificatesClient.GetAuthorizedCertificateAsync(request); // End snippet } /// <summary>Snippet for CreateAuthorizedCertificate</summary> public void CreateAuthorizedCertificateRequestObject() { // Snippet: CreateAuthorizedCertificate(CreateAuthorizedCertificateRequest, CallSettings) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = AuthorizedCertificatesClient.Create(); // Initialize request argument(s) CreateAuthorizedCertificateRequest request = new CreateAuthorizedCertificateRequest { Parent = "", Certificate = new AuthorizedCertificate(), }; // Make the request AuthorizedCertificate response = authorizedCertificatesClient.CreateAuthorizedCertificate(request); // End snippet } /// <summary>Snippet for CreateAuthorizedCertificateAsync</summary> public async Task CreateAuthorizedCertificateRequestObjectAsync() { // Snippet: CreateAuthorizedCertificateAsync(CreateAuthorizedCertificateRequest, CallSettings) // Additional: CreateAuthorizedCertificateAsync(CreateAuthorizedCertificateRequest, CancellationToken) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = await AuthorizedCertificatesClient.CreateAsync(); // Initialize request argument(s) CreateAuthorizedCertificateRequest request = new CreateAuthorizedCertificateRequest { Parent = "", Certificate = new AuthorizedCertificate(), }; // Make the request AuthorizedCertificate response = await authorizedCertificatesClient.CreateAuthorizedCertificateAsync(request); // End snippet } /// <summary>Snippet for UpdateAuthorizedCertificate</summary> public void UpdateAuthorizedCertificateRequestObject() { // Snippet: UpdateAuthorizedCertificate(UpdateAuthorizedCertificateRequest, CallSettings) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = AuthorizedCertificatesClient.Create(); // Initialize request argument(s) UpdateAuthorizedCertificateRequest request = new UpdateAuthorizedCertificateRequest { Name = "", Certificate = new AuthorizedCertificate(), UpdateMask = new FieldMask(), }; // Make the request AuthorizedCertificate response = authorizedCertificatesClient.UpdateAuthorizedCertificate(request); // End snippet } /// <summary>Snippet for UpdateAuthorizedCertificateAsync</summary> public async Task UpdateAuthorizedCertificateRequestObjectAsync() { // Snippet: UpdateAuthorizedCertificateAsync(UpdateAuthorizedCertificateRequest, CallSettings) // Additional: UpdateAuthorizedCertificateAsync(UpdateAuthorizedCertificateRequest, CancellationToken) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = await AuthorizedCertificatesClient.CreateAsync(); // Initialize request argument(s) UpdateAuthorizedCertificateRequest request = new UpdateAuthorizedCertificateRequest { Name = "", Certificate = new AuthorizedCertificate(), UpdateMask = new FieldMask(), }; // Make the request AuthorizedCertificate response = await authorizedCertificatesClient.UpdateAuthorizedCertificateAsync(request); // End snippet } /// <summary>Snippet for DeleteAuthorizedCertificate</summary> public void DeleteAuthorizedCertificateRequestObject() { // Snippet: DeleteAuthorizedCertificate(DeleteAuthorizedCertificateRequest, CallSettings) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = AuthorizedCertificatesClient.Create(); // Initialize request argument(s) DeleteAuthorizedCertificateRequest request = new DeleteAuthorizedCertificateRequest { Name = "", }; // Make the request authorizedCertificatesClient.DeleteAuthorizedCertificate(request); // End snippet } /// <summary>Snippet for DeleteAuthorizedCertificateAsync</summary> public async Task DeleteAuthorizedCertificateRequestObjectAsync() { // Snippet: DeleteAuthorizedCertificateAsync(DeleteAuthorizedCertificateRequest, CallSettings) // Additional: DeleteAuthorizedCertificateAsync(DeleteAuthorizedCertificateRequest, CancellationToken) // Create client AuthorizedCertificatesClient authorizedCertificatesClient = await AuthorizedCertificatesClient.CreateAsync(); // Initialize request argument(s) DeleteAuthorizedCertificateRequest request = new DeleteAuthorizedCertificateRequest { Name = "", }; // Make the request await authorizedCertificatesClient.DeleteAuthorizedCertificateAsync(request); // End snippet } } }
using System; using System.Runtime.InteropServices; using System.Security; using System.IO; using BulletSharp.Math; namespace BulletSharp { public class StridingMeshInterface : IDisposable // abstract { internal IntPtr _native; internal StridingMeshInterface(IntPtr native) { _native = native; } public unsafe UnmanagedMemoryStream GetIndexStream(int subpart = 0) { IntPtr vertexBase, indexBase; int numVerts, numFaces; PhyScalarType vertsType, indicesType; int vertexStride, indexStride; btStridingMeshInterface_getLockedReadOnlyVertexIndexBase2(_native, out vertexBase, out numVerts, out vertsType, out vertexStride, out indexBase, out indexStride, out numFaces, out indicesType, subpart); int length = numFaces * indexStride; return new UnmanagedMemoryStream((byte*)indexBase.ToPointer(), length, length, FileAccess.ReadWrite); } public unsafe UnmanagedMemoryStream GetVertexStream(int subpart = 0) { IntPtr vertexBase, indexBase; int numVerts, numFaces; PhyScalarType vertsType, indicesType; int vertexStride, indexStride; btStridingMeshInterface_getLockedReadOnlyVertexIndexBase2(_native, out vertexBase, out numVerts, out vertsType, out vertexStride, out indexBase, out indexStride, out numFaces, out indicesType, subpart); int length = numVerts * vertexStride; return new UnmanagedMemoryStream((byte*)vertexBase.ToPointer(), length, length, FileAccess.ReadWrite); } public void CalculateAabbBruteForce(out Vector3 aabbMin, out Vector3 aabbMax) { btStridingMeshInterface_calculateAabbBruteForce(_native, out aabbMin, out aabbMax); } public int CalculateSerializeBufferSize() { return btStridingMeshInterface_calculateSerializeBufferSize(_native); } public void GetLockedReadOnlyVertexIndexBase(out IntPtr vertexBase, out int numVerts, out PhyScalarType type, out int stride, out IntPtr indexbase, out int indexStride, int numFaces, out PhyScalarType indicesType, int subpart = 0) { btStridingMeshInterface_getLockedReadOnlyVertexIndexBase2(_native, out vertexBase, out numVerts, out type, out stride, out indexbase, out indexStride, out numFaces, out indicesType, subpart); } public void GetLockedVertexIndexBase(out IntPtr vertexBase, out int numVerts, out PhyScalarType type, out int stride, out IntPtr indexbase, out int indexStride, int numFaces, out PhyScalarType indicesType, int subpart = 0) { btStridingMeshInterface_getLockedVertexIndexBase2(_native, out vertexBase, out numVerts, out type, out stride, out indexbase, out indexStride, out numFaces, out indicesType, subpart); } public void GetPremadeAabb(out Vector3 aabbMin, out Vector3 aabbMax) { btStridingMeshInterface_getPremadeAabb(_native, out aabbMin, out aabbMax); } public void InternalProcessAllTriangles(InternalTriangleIndexCallback callback, Vector3 aabbMin, Vector3 aabbMax) { btStridingMeshInterface_InternalProcessAllTriangles(_native, callback._native, ref aabbMin, ref aabbMax); } public void PreallocateIndices(int numIndices) { btStridingMeshInterface_preallocateIndices(_native, numIndices); } public void PreallocateVertices(int numVerts) { btStridingMeshInterface_preallocateVertices(_native, numVerts); } public string Serialize(IntPtr dataBuffer, Serializer serializer) { return Marshal.PtrToStringAnsi(btStridingMeshInterface_serialize(_native, dataBuffer, serializer._native)); } public void SetPremadeAabb(ref Vector3 aabbMin, ref Vector3 aabbMax) { btStridingMeshInterface_setPremadeAabb(_native, ref aabbMin, ref aabbMax); } public void UnLockReadOnlyVertexBase(int subpart) { btStridingMeshInterface_unLockReadOnlyVertexBase(_native, subpart); } public void UnLockVertexBase(int subpart) { btStridingMeshInterface_unLockVertexBase(_native, subpart); } public bool HasPremadeAabb { get { return btStridingMeshInterface_hasPremadeAabb(_native); } } public int NumSubParts { get { return btStridingMeshInterface_getNumSubParts(_native); } } public Vector3 Scaling { get { Vector3 value; btStridingMeshInterface_getScaling(_native, out value); return value; } set { btStridingMeshInterface_setScaling(_native, ref value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btStridingMeshInterface_delete(_native); _native = IntPtr.Zero; } } ~StridingMeshInterface() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_calculateAabbBruteForce(IntPtr obj, [Out] out Vector3 aabbMin, [Out] out Vector3 aabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btStridingMeshInterface_calculateSerializeBufferSize(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_getLockedReadOnlyVertexIndexBase(IntPtr obj, [Out] out IntPtr vertexbase, [Out] out int numverts, [Out] out PhyScalarType type, [Out] out int stride, [Out] out IntPtr indexbase, [Out] out int indexstride, [Out] out int numfaces, [Out] out PhyScalarType indicestype); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_getLockedReadOnlyVertexIndexBase2(IntPtr obj, [Out] out IntPtr vertexbase, [Out] out int numverts, [Out] out PhyScalarType type, [Out] out int stride, [Out] out IntPtr indexbase, [Out] out int indexstride, [Out] out int numfaces, [Out] out PhyScalarType indicestype, int subpart); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_getLockedVertexIndexBase(IntPtr obj, [Out] out IntPtr vertexbase, [Out] out int numverts, [Out] out PhyScalarType type, [Out] out int stride, [Out] out IntPtr indexbase, [Out] out int indexstride, [Out] out int numfaces, [Out] out PhyScalarType indicestype); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_getLockedVertexIndexBase2(IntPtr obj, [Out] out IntPtr vertexbase, [Out] out int numverts, [Out] out PhyScalarType type, [Out] out int stride, [Out] out IntPtr indexbase, [Out] out int indexstride, [Out] out int numfaces, [Out] out PhyScalarType indicestype, int subpart); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btStridingMeshInterface_getNumSubParts(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_getPremadeAabb(IntPtr obj, [Out] out Vector3 aabbMin, [Out] out Vector3 aabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_getScaling(IntPtr obj, [Out] out Vector3 scaling); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btStridingMeshInterface_hasPremadeAabb(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_InternalProcessAllTriangles(IntPtr obj, IntPtr callback, [In] ref Vector3 aabbMin, [In] ref Vector3 aabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_preallocateIndices(IntPtr obj, int numindices); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_preallocateVertices(IntPtr obj, int numverts); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btStridingMeshInterface_serialize(IntPtr obj, IntPtr dataBuffer, IntPtr serializer); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_setPremadeAabb(IntPtr obj, [In] ref Vector3 aabbMin, [In] ref Vector3 aabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_setScaling(IntPtr obj, [In] ref Vector3 scaling); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_unLockReadOnlyVertexBase(IntPtr obj, int subpart); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_unLockVertexBase(IntPtr obj, int subpart); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStridingMeshInterface_delete(IntPtr obj); } [StructLayout(LayoutKind.Sequential)] internal struct MeshPartData { public IntPtr Vertices3F; public IntPtr Vertices3D; public IntPtr Indices32; public IntPtr Indices16; public IntPtr Indices8; public IntPtr Indices16_2; public int NumTriangles; public int NumVertices; public static int Offset(string fieldName) { return Marshal.OffsetOf(typeof(MeshPartData), fieldName).ToInt32(); } } [StructLayout(LayoutKind.Sequential)] internal struct StridingMeshInterfaceData { public IntPtr MeshPartsPtr; public Vector3FloatData Scaling; public int NumMeshParts; public int Padding; public static int Offset(string fieldName) { return Marshal.OffsetOf(typeof(StridingMeshInterfaceData), fieldName).ToInt32(); } } }
/* * 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 log4net; using OpenMetaverse; using OpenSim.Framework; using Animation = OpenSim.Framework.Animation; namespace OpenSim.Region.Framework.Scenes.Animation { [Serializable] public class AnimationSet { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private OpenSim.Framework.Animation m_implicitDefaultAnimation = new OpenSim.Framework.Animation(); private OpenSim.Framework.Animation m_defaultAnimation = new OpenSim.Framework.Animation(); private List<OpenSim.Framework.Animation> m_animations = new List<OpenSim.Framework.Animation>(); public OpenSim.Framework.Animation DefaultAnimation { get { return m_defaultAnimation; } } public OpenSim.Framework.Animation ImplicitDefaultAnimation { get { return m_implicitDefaultAnimation; } } public AnimationSet() { ResetDefaultAnimation(); } public bool HasAnimation(UUID animID) { if (m_defaultAnimation.AnimID == animID) return true; for (int i = 0; i < m_animations.Count; ++i) { if (m_animations[i].AnimID == animID) return true; } return false; } public bool Add(UUID animID, int sequenceNum, UUID objectID) { lock (m_animations) { if (!HasAnimation(animID)) { m_animations.Add(new OpenSim.Framework.Animation(animID, sequenceNum, objectID)); return true; } } return false; } /// <summary> /// Remove the specified animation /// </summary> /// <param name='animID'></param> /// <param name='allowNoDefault'> /// If true, then the default animation can be entirely removed. /// If false, then removing the default animation will reset it to the simulator default (currently STAND). /// </param> public bool Remove(UUID animID, bool allowNoDefault) { lock (m_animations) { if (m_defaultAnimation.AnimID == animID) { if (allowNoDefault) m_defaultAnimation = new OpenSim.Framework.Animation(UUID.Zero, 1, UUID.Zero); else ResetDefaultAnimation(); } else if (HasAnimation(animID)) { for (int i = 0; i < m_animations.Count; i++) { if (m_animations[i].AnimID == animID) { m_animations.RemoveAt(i); return true; } } } } return false; } public void Clear() { ResetDefaultAnimation(); m_animations.Clear(); } /// <summary> /// The default animation is reserved for "main" animations /// that are mutually exclusive, e.g. flying and sitting. /// </summary> public bool SetDefaultAnimation(UUID animID, int sequenceNum, UUID objectID) { if (m_defaultAnimation.AnimID != animID) { m_defaultAnimation = new OpenSim.Framework.Animation(animID, sequenceNum, objectID); m_implicitDefaultAnimation = m_defaultAnimation; return true; } return false; } // Called from serialization only public void SetImplicitDefaultAnimation(UUID animID, int sequenceNum, UUID objectID) { m_implicitDefaultAnimation = new OpenSim.Framework.Animation(animID, sequenceNum, objectID); } protected bool ResetDefaultAnimation() { return TrySetDefaultAnimation("STAND", 1, UUID.Zero); } /// <summary> /// Set the animation as the default animation if it's known /// </summary> public bool TrySetDefaultAnimation(string anim, int sequenceNum, UUID objectID) { // m_log.DebugFormat( // "[ANIMATION SET]: Setting default animation {0}, sequence number {1}, object id {2}", // anim, sequenceNum, objectID); if (DefaultAvatarAnimations.AnimsUUID.ContainsKey(anim)) { return SetDefaultAnimation(DefaultAvatarAnimations.AnimsUUID[anim], sequenceNum, objectID); } return false; } public void GetArrays(out UUID[] animIDs, out int[] sequenceNums, out UUID[] objectIDs) { lock (m_animations) { int defaultSize = 0; if (m_defaultAnimation.AnimID != UUID.Zero) defaultSize++; animIDs = new UUID[m_animations.Count + defaultSize]; sequenceNums = new int[m_animations.Count + defaultSize]; objectIDs = new UUID[m_animations.Count + defaultSize]; if (m_defaultAnimation.AnimID != UUID.Zero) { animIDs[0] = m_defaultAnimation.AnimID; sequenceNums[0] = m_defaultAnimation.SequenceNum; objectIDs[0] = m_defaultAnimation.ObjectID; } for (int i = 0; i < m_animations.Count; ++i) { animIDs[i + defaultSize] = m_animations[i].AnimID; sequenceNums[i + defaultSize] = m_animations[i].SequenceNum; objectIDs[i + defaultSize] = m_animations[i].ObjectID; } } } public OpenSim.Framework.Animation[] ToArray() { OpenSim.Framework.Animation[] theArray = new OpenSim.Framework.Animation[m_animations.Count]; uint i = 0; try { foreach (OpenSim.Framework.Animation anim in m_animations) theArray[i++] = anim; } catch { /* S%^t happens. Ignore. */ } return theArray; } public void FromArray(OpenSim.Framework.Animation[] theArray) { foreach (OpenSim.Framework.Animation anim in theArray) m_animations.Add(anim); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsModelFlattening { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for AutoRestResourceFlatteningTestService. /// </summary> public static partial class AutoRestResourceFlatteningTestServiceExtensions { /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> public static void PutArray(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IList<Resource> resourceArray = default(System.Collections.Generic.IList<Resource>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutArrayAsync(resourceArray), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutArrayAsync(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IList<Resource> resourceArray = default(System.Collections.Generic.IList<Resource>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutArrayWithHttpMessagesAsync(resourceArray, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.Collections.Generic.IList<FlattenedProduct> GetArray(this IAutoRestResourceFlatteningTestService operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetArrayAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<FlattenedProduct>> GetArrayAsync(this IAutoRestResourceFlatteningTestService operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetArrayWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> public static void PutDictionary(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IDictionary<string, FlattenedProduct> resourceDictionary = default(System.Collections.Generic.IDictionary<string, FlattenedProduct>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutDictionaryAsync(resourceDictionary), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IDictionary<string, FlattenedProduct> resourceDictionary = default(System.Collections.Generic.IDictionary<string, FlattenedProduct>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutDictionaryWithHttpMessagesAsync(resourceDictionary, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.Collections.Generic.IDictionary<string, FlattenedProduct> GetDictionary(this IAutoRestResourceFlatteningTestService operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetDictionaryAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IDictionary<string, FlattenedProduct>> GetDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetDictionaryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutResourceCollectionAsync(resourceComplexObject), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ResourceCollection GetResourceCollection(this IAutoRestResourceFlatteningTestService operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetResourceCollectionAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ResourceCollection> GetResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetResourceCollectionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put Simple Product with client flattening true on the model /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> public static SimpleProduct PutSimpleProduct(this IAutoRestResourceFlatteningTestService operations, SimpleProduct simpleBodyProduct = default(SimpleProduct)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutSimpleProductAsync(simpleBodyProduct), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put Simple Product with client flattening true on the model /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SimpleProduct> PutSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, SimpleProduct simpleBodyProduct = default(SimpleProduct), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PutSimpleProductWithHttpMessagesAsync(simpleBodyProduct, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put Flattened Simple Product with client flattening true on the parameter /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> public static SimpleProduct PostFlattenedSimpleProduct(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PostFlattenedSimpleProductAsync(productId, maxProductDisplayName, description, genericValue, odatavalue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put Flattened Simple Product with client flattening true on the parameter /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SimpleProduct> PostFlattenedSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostFlattenedSimpleProductWithHttpMessagesAsync(productId, maxProductDisplayName, description, genericValue, odatavalue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put Simple Product with client flattening true on the model /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> public static SimpleProduct PutSimpleProductWithGrouping(this IAutoRestResourceFlatteningTestService operations, FlattenParameterGroup flattenParameterGroup) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutSimpleProductWithGroupingAsync(flattenParameterGroup), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put Simple Product with client flattening true on the model /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SimpleProduct> PutSimpleProductWithGroupingAsync(this IAutoRestResourceFlatteningTestService operations, FlattenParameterGroup flattenParameterGroup, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PutSimpleProductWithGroupingWithHttpMessagesAsync(flattenParameterGroup, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B02_Continent (editable child object).<br/> /// This is a generated base class of <see cref="B02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B03_SubContinentObjects"/> of type <see cref="B03_SubContinentColl"/> (1:M relation to <see cref="B04_SubContinent"/>)<br/> /// This class is an item of <see cref="B01_ContinentColl"/> collection. /// </remarks> [Serializable] public partial class B02_Continent : BusinessBase<B02_Continent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continent ID"); /// <summary> /// Gets the Continent ID. /// </summary> /// <value>The Continent ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continent Name"); /// <summary> /// Gets or sets the Continent Name. /// </summary> /// <value>The Continent Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } set { SetProperty(Continent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_Child> B03_Continent_SingleObjectProperty = RegisterProperty<B03_Continent_Child>(p => p.B03_Continent_SingleObject, "B03 Continent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the B03 Continent Single Object ("parent load" child property). /// </summary> /// <value>The B03 Continent Single Object.</value> public B03_Continent_Child B03_Continent_SingleObject { get { return GetProperty(B03_Continent_SingleObjectProperty); } private set { LoadProperty(B03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_ReChild> B03_Continent_ASingleObjectProperty = RegisterProperty<B03_Continent_ReChild>(p => p.B03_Continent_ASingleObject, "B03 Continent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the B03 Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The B03 Continent ASingle Object.</value> public B03_Continent_ReChild B03_Continent_ASingleObject { get { return GetProperty(B03_Continent_ASingleObjectProperty); } private set { LoadProperty(B03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<B03_SubContinentColl> B03_SubContinentObjectsProperty = RegisterProperty<B03_SubContinentColl>(p => p.B03_SubContinentObjects, "B03 SubContinent Objects", RelationshipTypes.Child); /// <summary> /// Gets the B03 Sub Continent Objects ("parent load" child property). /// </summary> /// <value>The B03 Sub Continent Objects.</value> public B03_SubContinentColl B03_SubContinentObjects { get { return GetProperty(B03_SubContinentObjectsProperty); } private set { LoadProperty(B03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B02_Continent"/> object. /// </summary> /// <returns>A reference to the created <see cref="B02_Continent"/> object.</returns> internal static B02_Continent NewB02_Continent() { return DataPortal.CreateChild<B02_Continent>(); } /// <summary> /// Factory method. Loads a <see cref="B02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B02_Continent"/> object.</returns> internal static B02_Continent GetB02_Continent(SafeDataReader dr) { B02_Continent obj = new B02_Continent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(B03_SubContinentObjectsProperty, B03_SubContinentColl.NewB03_SubContinentColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B02_Continent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B02_Continent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(B03_Continent_SingleObjectProperty, DataPortal.CreateChild<B03_Continent_Child>()); LoadProperty(B03_Continent_ASingleObjectProperty, DataPortal.CreateChild<B03_Continent_ReChild>()); LoadProperty(B03_SubContinentObjectsProperty, DataPortal.CreateChild<B03_SubContinentColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> internal void FetchChildren(SafeDataReader dr) { dr.NextResult(); while (dr.Read()) { var child = B03_Continent_Child.GetB03_Continent_Child(dr); var obj = ((B01_ContinentColl)Parent).FindB02_ContinentByParentProperties(child.continent_ID1); obj.LoadProperty(B03_Continent_SingleObjectProperty, child); } dr.NextResult(); while (dr.Read()) { var child = B03_Continent_ReChild.GetB03_Continent_ReChild(dr); var obj = ((B01_ContinentColl)Parent).FindB02_ContinentByParentProperties(child.continent_ID2); obj.LoadProperty(B03_Continent_ASingleObjectProperty, child); } dr.NextResult(); var b03_SubContinentColl = B03_SubContinentColl.GetB03_SubContinentColl(dr); b03_SubContinentColl.LoadItems((B01_ContinentColl)Parent); dr.NextResult(); while (dr.Read()) { var child = B05_SubContinent_Child.GetB05_SubContinent_Child(dr); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B05_SubContinent_ReChild.GetB05_SubContinent_ReChild(dr); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID2); obj.LoadChild(child); } dr.NextResult(); var b05_CountryColl = B05_CountryColl.GetB05_CountryColl(dr); b05_CountryColl.LoadItems(b03_SubContinentColl); dr.NextResult(); while (dr.Read()) { var child = B07_Country_Child.GetB07_Country_Child(dr); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B07_Country_ReChild.GetB07_Country_ReChild(dr); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID2); obj.LoadChild(child); } dr.NextResult(); var b07_RegionColl = B07_RegionColl.GetB07_RegionColl(dr); b07_RegionColl.LoadItems(b05_CountryColl); dr.NextResult(); while (dr.Read()) { var child = B09_Region_Child.GetB09_Region_Child(dr); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B09_Region_ReChild.GetB09_Region_ReChild(dr); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID2); obj.LoadChild(child); } dr.NextResult(); var b09_CityColl = B09_CityColl.GetB09_CityColl(dr); b09_CityColl.LoadItems(b07_RegionColl); dr.NextResult(); while (dr.Read()) { var child = B11_City_Child.GetB11_City_Child(dr); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B11_City_ReChild.GetB11_City_ReChild(dr); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID2); obj.LoadChild(child); } dr.NextResult(); var b11_CityRoadColl = B11_CityRoadColl.GetB11_CityRoadColl(dr); b11_CityRoadColl.LoadItems(b09_CityColl); } /// <summary> /// Inserts a new <see cref="B02_Continent"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert() { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IB02_ContinentDal>(); using (BypassPropertyChecks) { int continent_ID = -1; dal.Insert( out continent_ID, Continent_Name ); LoadProperty(Continent_IDProperty, continent_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="B02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IB02_ContinentDal>(); using (BypassPropertyChecks) { dal.Update( Continent_ID, Continent_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="B02_Continent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IB02_ContinentDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Continent_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using UnityEngine; public class GeomUtils { public static void test() { float ti; int times = 2; Boolean temp; int i; // Moller-Trumbore method ti = Time.realtimeSinceStartup; for (i = 0; i < times; i++) { temp = rayIntersectsTriangleMT(new Vector3(2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(0, 10, 10), new Vector3(10, 0, 10), true); if (i == 0) D.Log ("==> [true, ff=true] = " + temp); temp = rayIntersectsTriangleMT(new Vector3(2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10), true); if (i == 0) D.Log ("==> [true, ff=false] = " + temp); temp = rayIntersectsTriangleMT(new Vector3(-2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10), true); if (i == 0) D.Log ("==> [false] = " + temp); temp = rayIntersectsTriangleMT(new Vector3(-2, 2, 10), new Vector3(10, 0, 10), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10), true); if (i == 0) D.Log ("==> [false] = " + temp); temp = rayIntersectsTriangleMT(new Vector3(-492.3f, 375.0f, 1.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(-553.8f, 250.0f, 0.0f), new Vector3(-615.4f, 375.0f, 0.0f), new Vector3(-492.3f, 375.0f, 0.0f), true); if (i == 0) D.Log ("==> [true] = " + temp); temp = rayIntersectsTriangleMT(new Vector3(-492.3f, 375.0f, 1.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(-553.8f, 250.0f, 0.0f), new Vector3(-615.4f, 375.0f, 0.0f), new Vector3(-492.3f, 375.0f, 0.0f), true); if (i == 0) D.Log ("==> [false] = " + temp); } D.Log("[MT] Time for " + times + " calls: " + (Time.realtimeSinceStartup - ti) + "s"); // Segura-Feito method method ti = Time.realtimeSinceStartup; for (i = 0; i < times; i++) { temp = rayIntersectsTriangleSF(new Vector3(2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(0, 10, 10), new Vector3(10, 0, 10)); if (i == 0) D.Log ("==> [true, hit ccw] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10)); if (i == 0) D.Log ("==> [true, hit cw] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(-2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10)); if (i == 0) D.Log ("==> [false] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(-2, 2, 10), new Vector3(10, 0, 10), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10)); if (i == 0) D.Log ("==> [false] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(-492.3f, 375.0f, 1.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(-553.8f, 250.0f, 0.0f), new Vector3(-615.4f, 375.0f, 0.0f), new Vector3(-492.3f, 375.0f, 0.0f)); if (i == 0) D.Log ("==> [true] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(-492.3f, 375.0f, 1.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(-553.8f, 250.0f, 0.0f), new Vector3(-615.4f, 375.0f, 0.0f), new Vector3(-492.3f, 375.0f, 0.0f)); if (i == 0) D.Log ("==> [false] = " + temp); } D.Log("[SF] Time for " + times + " calls: " + (Time.realtimeSinceStartup - ti) + "s"); // Segura-Feito method method with precalculation ti = Time.realtimeSinceStartup; Vector3 v1xv2 = Vector3.Cross(new Vector3(0, 0, 10) - new Vector3(-2, -2, 0), new Vector3(10, 0, 10)- new Vector3(-2, -2, 0)); Vector3 v2xv3 = Vector3.Cross(new Vector3(10, 0, 10)- new Vector3(-2, -2, 0), new Vector3(0, 10, 10)- new Vector3(-2, -2, 0)); Vector3 v3xv1 = Vector3.Cross(new Vector3(0, 10, 10)- new Vector3(-2, -2, 0), new Vector3(0, 0, 10)- new Vector3(-2, -2, 0)); for (i = 0; i < times; i++) { temp = rayIntersectsTriangleSF_precalculated(new Vector3(2, 2, 0), new Vector3(0, 0, 20), new Vector3(0, 0, 10), new Vector3(0, 10, 10), new Vector3(10, 0, 10)); if (i == 0) D.Log ("==> [true, hit ccw] = " + temp); temp = rayIntersectsTriangleSF_precalculated(new Vector3(2, 2, 0), new Vector3(0, 0, 20), v1xv2, v2xv3, v3xv1); if (i == 0) D.Log ("==> [true, hit cw] = " + temp); temp = rayIntersectsTriangleSF_precalculated(new Vector3(-2, 2, 0), new Vector3(0, 0, 20), v1xv2, v2xv3, v3xv1); if (i == 0) D.Log ("==> [false] = " + temp); temp = rayIntersectsTriangleSF_precalculated(new Vector3(-2, 2, 10), new Vector3(10, 0, 10), v1xv2, v2xv3, v3xv1); if (i == 0) D.Log ("==> [false] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(-492.3f, 375.0f, 1.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(-553.8f, 250.0f, 0.0f), new Vector3(-615.4f, 375.0f, 0.0f), new Vector3(-492.3f, 375.0f, 0.0f)); if (i == 0) D.Log ("==> [true] = " + temp); temp = rayIntersectsTriangleSF(new Vector3(-492.3f, 375.0f, 1.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(-553.8f, 250.0f, 0.0f), new Vector3(-615.4f, 375.0f, 0.0f), new Vector3(-492.3f, 375.0f, 0.0f)); if (i == 0) D.Log ("==> [false] = " + temp); } D.Log("[SF PRECALC] Time for " + times + " calls: " + (Time.realtimeSinceStartup - ti) + "s"); //D.Log("Intersect 3 ==> " + rayIntersectsTriangle(new Vector3(2, 2, 100), new Vector3(0, 0, -200), new Vector3(-1000, -1000, 10), new Vector3(1000, -1000, 10), new Vector3(0, 500, 10))); //D.Log("Intersect 4 ==> " + rayIntersectsTriangle(new Vector3(2, 2, 100), new Vector3(0, 0, -200), new Vector3(-1000, -1000, 10), new Vector3(0, 500, 10), new Vector3(1000, -1000, 10))); //D.Log("Intersect 3 ==> " + segmentIntersectsTriangle(new Vector3(2, 2, 0), new Vector3(2, 2, 20), new Vector3(0, 0, 10), new Vector3(0, 10, 10), new Vector3(10, 0, 10))); //D.Log("Intersect 4 ==> " + segmentIntersectsTriangle(new Vector3(2, 2, 0), new Vector3(2, 2, 20), new Vector3(0, 0, 10), new Vector3(10, 0, 10), new Vector3(0, 10, 10))); } public static bool rayIntersectsTriangleMT(Vector3 __origin, Vector3 __direction, Vector3 __v1, Vector3 __v2, Vector3 __v3, bool __allowSegmentOnly) { // Moller-Trumbore method // http://www.hugi.scene.org/online/coding/hugi%2025%20-%20coding%20corner%20graphics,%20sound%20&%20synchronization%20ken%20ray-triangle%20intersection%20tests%20for%20dummies.htm // Returns: float u, float v, float t, bool intersect, bool frontfacing float eps = 0.000000001f; // eps is the machine fpu epsilon (precision), or a very small number :) Vector3 e2 = __v3 - __v1; // second edge Vector3 e1 = __v2 - __v1; // first edge Vector3 r = Vector3.Cross(__direction, e2); // (d X e2) is used two times in the formula so we store it in an appropriate vector Vector3 s = __origin - __v1; // translated ray origin float a = Vector3.Dot(e1, r); // a=(d X e2)*e1 Vector3 q = Vector3.Cross(s, e1); float u = Vector3.Dot(s, r); //bool frontfacing = true; float v; if (a > eps) { // Front facing triangle... if ((u < 0) || (u > a)) { //D.Log ("u = " + 0 + ", v = " + 0 + ", t = " + 0 + ", intersect = false, frontfacing = " + frontfacing); return false; } v = Vector3.Dot(__direction, q); if ((v < 0) || (u+v > a)) { //D.Log ("u = " + 0 + ", v = " + 0 + ", t = " + 0 + ", intersect = false, frontfacing = " + frontfacing); return false; } } else if (a < -eps) { // Back facing triangle... //frontfacing = false; if ((u > 0) || (u < a)) { //D.Log ("u = " + 0 + ", v = " + 0 + ", t = " + 0 + ", intersect = false, frontfacing = " + frontfacing); return false; } v = Vector3.Dot(__direction, q); if ((v > 0) || (u+v < a)) { //D.Log ("u = " + 0 + ", v = " + 0 + ", t = " + 0 + ", intersect = false, frontfacing = " + frontfacing); return false; } } else { // Ray parallel to triangle plane //D.Log ("u = " + 0 + ", v = " + 0 + ", t = " + 0 + ", intersect = false, frontfacing = false [PARALLEL]"); return false; } float f = 1f / a; // slow division* float t = f * Vector3.Dot(e2, q); //u = u * f; //v = v * f; //D.Log ("u = " + u + ", v = " + v + ", t = " + t + ", intersect = true, frontfacing = " + frontfacing); return t > 0 && (!__allowSegmentOnly || t <= 1); //return true; } public static bool rayIntersectsTriangleSF_old(Vector3 __origin, Vector3 __direction, Vector3 __v1, Vector3 __v2, Vector3 __v3) { // Segura-Feito method /* __v1 -= __origin; __v2 -= __origin; __v3 -= __origin; Vector3 tmp = Vector3.Cross(__direction, __v1); float i = Mathf.Sign(Vector3.Dot(__v3, tmp)); if (i<=0) return false; i = Mathf.Sign(Vector3.Dot(__v2, tmp)); if (i<=0) return false; i = Mathf.Sign(Vector3.Dot(__v3, Vector3.Cross(__direction, __v2))); if (i<=0) return false; */ float i = Mathf.Sign(Vector3.Dot(__direction, Vector3.Cross(__v1 - __origin, __v2 - __origin))); if (i<=0) return false; i = Mathf.Sign(Vector3.Dot(__direction, Vector3.Cross(__v2 - __origin, __v3 - __origin))); if (i<=0) return false; i = Mathf.Sign(Vector3.Dot(__direction, Vector3.Cross(__v3 - __origin, __v1 - __origin))); if (i<=0) return false; return true; } public static bool rayIntersectsTriangleSF(Vector3 __origin, Vector3 __direction, Vector3 __v1, Vector3 __v2, Vector3 __v3) { return rayIntersectsTriangleSF_precalculated(__origin, __direction, Vector3.Cross(__v1 - __origin, __v2 - __origin), Vector3.Cross(__v2 - __origin, __v3 - __origin), Vector3.Cross(__v3 - __origin, __v1 - __origin)); } public static bool rayIntersectsTriangleSF_precalculated(Vector3 __origin, Vector3 __direction, Vector3 __v1xv2, Vector3 __v2xv3, Vector3 __v3xv1) { if (Mathf.Sign(Vector3.Dot(__direction, __v1xv2)) <= 0) return false; if (Mathf.Sign(Vector3.Dot(__direction, __v2xv3)) <= 0) return false; if (Mathf.Sign(Vector3.Dot(__direction, __v3xv1)) <= 0) return false; return true; } public static bool rayIntersectsTriangleSF2(Vector3 __start, Vector3 __end, Vector3 __v1, Vector3 __v2, Vector3 __v3, bool __someBool) { // http://www.hugi.scene.org/online/coding/hugi%2025%20-%20coding%20corner%20graphics,%20sound%20&%20synchronization%20ken%20ray-triangle%20intersection%20tests%20for%20dummies.htm // http://iason.zcu.cz/wscg2001/Papers_2001/R75.pdf __end += __start; //D.Log (" ==> " + areaSign(__start, __end, __v1, __v3)); //D.Log (" ==> " + areaSign(__start, __end, __v2, __v3)); //D.Log (" ==> " + areaSign(__start, __end, __v1, __v2)); if (areaSign(__start, __end, __v1, __v3) <= 0) return false; if (areaSign(__start, __end, __v2, __v3) <= 0) return false; if (areaSign(__start, __end, __v1, __v2) <= 0) return false; return true; } public static float areaSign(Vector3 rs, Vector3 re, Vector3 v1, Vector3 v2) { return Mathf.Sign(v2.z * (re.x * v1.y - v1.x * re.y) + v2.y * (v1.z * re.x - re.z * v1.x) + v2.x * (v1.y * re.z - re.y * v1.z)); //return Mathf.Sign(Vector3.Dot(re, Vector3.Cross(v1, v2))); } /* public bool rayIntersectsTriangle(Vector3 __origin, Vector3 __direction, Vector3 __v1, Vector3 __v2, Vector3 __v3) { __v1 -= __origin; __v2 -= __origin; __v3 -= __origin; Vector3 tmp = Vector3.Cross(__direction, __v1); D.Log (" ==> " + Mathf.Sign(Vector3.Dot(__v3, tmp))); D.Log (" ==> " + Mathf.Sign(Vector3.Dot(__v2, tmp))); D.Log (" ==> " + Mathf.Sign(Vector3.Dot(__v3, Vector3.Cross(__direction, __v2)))); float i = Mathf.Sign(Vector3.Dot(__v3, tmp)); if (i<=0) return false; i = Mathf.Sign(Vector3.Dot(__v2, tmp)); if (i<=0) return false; i = Mathf.Sign(Vector3.Dot(__v3, Vector3.Cross(__direction, __v2))); if (i<=0) return false; return true; } */ }
namespace Modules.Acl { using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading; using Internal; /// <summary> /// A Group. /// </summary> /// /// <remarks> /// <para> /// Used to represent any organisational structure / user on which an /// arbitrary set of properties can be attached, and for which a set /// of access permissions can be defined. /// </para> /// /// <para> /// Groups follow a graphing structure, allowing a group to have /// multiple parents and multiple children. /// </para> /// /// <para> /// It is recommended that you create extended types of group for which /// the properties get set using the <see cref="IPropertyObject"/> /// setters and getters. /// </para> /// </remarks> [DataContract] public sealed class Group : IPrincipal, IPropertyObject, IEquatable<Group> { #region Fields /// <summary> /// The name of the <see cref="Name"/> property. /// </summary> /// /// <remarks> /// This is needed for guards on the setter methods. /// </remarks> private const string NameProperty = "name"; /// <summary> /// The _properties object for this instance. Allows dynamic /// volume of properties to be set on the object. /// </summary> [DataMember] private readonly PropertyObject _properties; private AccessControl _api; /// <summary> /// The _hashcode for this instance. /// </summary> private int? _hashcode; #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Group"/> class. /// </summary> /// /// <param name="api">The AccessControl api</param> /// <param name="name">The name of the group.</param> /// /// <exception cref="System.ArgumentException"> /// Argument 'name' must not be null, whitespace only, or empty. /// </exception> /// /// <remarks> /// The name must be unique. /// </remarks> internal Group(AccessControl api, string name) { _api = api; if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException( "Argument 'name' must not be null, whitespace only, or empty."); } Name = name; // Holds the dynamic properties of group. _properties = new PropertyObject(); } #endregion Constructors #region Properties /// <summary> /// Gets the API to the <see cref="AccessControl"/> instance that /// this group belongs to. /// </summary> public AccessControl Api { get { LazyInitializer.EnsureInitialized(ref _api, () => { return AccessControl.Get(ApiIdentifier); }); return _api; } } /// <summary> /// Gets the identifier of the <see cref="AccessControl"/> API /// instance to which this belongs. /// </summary> [DataMember] public string ApiIdentifier { get; private set; } /// <summary> /// Gets the name of the group. /// </summary> [DataMember] public string Name { get; private set; } #endregion Properties #region Methods /// <summary> /// Determines if the given two group names are considered equal. /// </summary> /// /// <param name="groupName">Name of the group.</param> /// <param name="otherGroupName">Name of the other group.</param> /// /// <exception cref="System.ArgumentException"> /// <para> /// Argument 'groupName' must not be empty whitespace only or empty. /// </para> /// OR /// <para> /// Argument 'otherGroupName' must not be empty whitespace only or empty. /// </para> /// </exception> /// /// <returns> /// <c>true</c> if and only if both the group names are considered /// equal, else <c>false</c>. /// </returns> public static bool NamesEqual(string groupName, string otherGroupName) { if (string.IsNullOrWhiteSpace(groupName)) { throw new ArgumentException( "Argument 'groupName' must not be empty whitespace only or empty."); } if (string.IsNullOrWhiteSpace(otherGroupName)) { throw new ArgumentException( "Argument 'otherGroupName' must not be empty whitespace only or empty."); } return groupName.Equals(otherGroupName, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Determines whether the specified <see cref="Group" />, is /// equal to this instance. /// </summary> /// /// <param name="other"> /// The <see cref="Group" /> to compare with this instance. /// </param> /// /// <returns> /// <c>true</c> if the specified <see cref="Group" /> is equal /// to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(Group other) { return other != null && NamesEqual(Name, other.Name); } /// <summary> /// Determines whether the specified <see cref="System.Object" />, is /// equal to this instance. /// </summary> /// /// <param name="obj"> /// The <see cref="System.Object" /> to compare with this instance. /// </param> /// /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal /// to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return Equals(obj as Group); } /// <summary> /// Returns the boolean-valued property with the given name. /// Returns the given default value if the property is undefined /// or is not an boolean value. /// </summary> /// /// <param name="key">The name of the property.</param> /// /// <param name="defaultValue"> /// The value to use if no value is found. /// </param> /// /// <returns> /// The value or the default value if no value was found. /// </returns> public bool GetBool(string key, bool defaultValue) { return _properties.GetBool(key, defaultValue); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// /// <returns> /// A hash code for this instance, suitable for use in hashing /// algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { // Hashcode is purely on name of group. if (_hashcode == null) { _hashcode = Name.GetHashCode(); } return _hashcode.Value; } /// <summary> /// Returns the integer-valued property with the given name. /// Returns the given default value if the property is undefined /// or is not an integer value. /// </summary> /// /// <param name="key"> /// The name of the property. /// </param> /// <param name="defaultValue"> /// The value to use if no value is found. /// </param> /// /// <returns> /// The value or the default value if no value was found. /// </returns> public int GetInt(string key, int defaultValue) { return _properties.GetInt(key, defaultValue); } /// <summary> /// Returns the properties with the given names. /// </summary> /// /// <param name="keys">The names of the properties to retrieve.</param> /// /// <returns> /// The properties with the given names. /// </returns> /// /// <remarks> /// The result is an an array whose elements correspond to the /// elements of the given property name array. Each element is /// <c>null</c> or an instance of one of the following classes: /// <c>String</c>, <c>Integer</c>, or <c>Boolean</c>. The returned /// array elements are index as per the order for the <c>keys</c>. /// </remarks> public object[] GetProperties(params string[] keys) { return _properties.GetProperties(keys); } /// <summary> /// Returns a dictionary with all the properties for this group. /// If the group has no properties then an empty dictionary is /// returned. /// </summary> /// /// <returns> /// A dictionary with all the properties for the group. /// </returns> /// /// <remarks> /// <para> /// The dictionary returned by calls to this method is readonly, /// however structural changes made to this properties objects are /// reflected in the returned dictionary. Any attempt to structurally /// modify the returned dictionary will result in an exception being /// thrown. /// </para> /// /// <para> /// If you need a dictionary that can be modified then construct a new /// Dictionary from a call to this method /// <c>new Dictionary&lt;string, object&gt;(properties.Get())</c>, /// this new dictionary will not reflect structurally changes made to /// this properties. /// </para> /// </remarks> public IDictionary<string, object> GetProperties() { return _properties.GetProperties(); } /// <summary> /// Returns the property with the given name. The result is an /// instance of one of the following classes: <c>String</c>, /// <c>Integer</c> or <c>Boolean</c>; <c>null</c> if the property /// is undefined. /// </summary> /// /// <param name="key"> /// The name of the property. /// </param> /// /// <returns> /// The property with the given name. /// </returns> public object GetProperty(string key) { return _properties.GetProperty(key); } /// <summary> /// Returns the string-valued property with the given name. /// Returns the given default value if the property is undefined /// or is not an string value. /// </summary> /// /// <param name="key">The name of the property.</param> /// <param name="defaultValue"> /// The value to use if no value is found. /// </param> /// /// <returns> /// The value or the default value if no value was found. /// </returns> public string GetString(string key, string defaultValue) { return _properties.GetString(key, defaultValue); } /// <summary> /// Sets the boolean-valued property with the given name. /// </summary> /// /// <param name="key">The name of the property.</param> /// <param name="value">The value.</param> /// /// <returns> /// The current instance in order to provide a fluent inteface. /// </returns> /// /// <remarks> /// <para> /// If a value is <c>null</c>, the new value of the /// property is considered to be undefined. /// </para> /// <para> /// This method changes resources; these changes will be reported /// in a subsequent resource change event, including an indication /// that this marker has been modified. /// </para> /// </remarks> public IPropertyObject SetBool(string key, bool? value) { CheckKeySetPreconditions(key); _properties.SetBool(key, value); OnPropertiesChanged(); return this; } /// <summary> /// Sets the integer-valued property with the given name. /// </summary> /// /// <param name="key">The name of the property.</param> /// <param name="value">The value.</param> /// /// <returns> /// The current instance in order to provide a fluent inteface. /// </returns> /// /// <remarks> /// <para> /// If a value is <c>null</c>, the new value of the /// property is considered to be undefined. /// </para> /// </remarks> public IPropertyObject SetInt(string key, int? value) { CheckKeySetPreconditions(key); _properties.SetInt(key, value); OnPropertiesChanged(); return this; } /// <summary> /// Sets this properties to those of the argument properties. /// </summary> /// /// <param name="properties">The properties to add.</param> /// /// <returns> /// The current instance in order to provide a fluent inteface. /// </returns> public IPropertyObject SetProperties(IPropertyObject properties) { _properties.SetProperties(properties); OnPropertiesChanged(); return this; } /// <summary> /// Sets the string-valued property with the given name. /// </summary> /// /// <param name="key">The name of the property.</param> /// <param name="value">The value.</param> /// <returns> /// The current instance in order to provide a fluent inteface. /// </returns> /// <remarks> /// <para> /// As properties are intended to be light weight in nature there is /// an upper limit of 5.0 KB (5120 Bytes) for string values, this /// upper bound allows for large comments to be added but still /// enforcing the light weight nature of properties. /// </para> /// <para> /// If a value is <c>null</c>, the new value of the /// property is considered to be undefined. /// </para> /// <para> /// This method changes resources; these changes will be reported /// in a subsequent resource change event, including an indication /// that this marker has been modified. /// </para> /// </remarks> public IPropertyObject SetString(string key, string value) { CheckKeySetPreconditions(key); _properties.SetString(key, value); OnPropertiesChanged(); return this; } /// <summary> /// Checks the key "property" to ensure it meets the preconditions. /// </summary> /// /// <param name="key">The key.</param> /// /// <exception cref="System.ArgumentException"> /// Argument 'key' is invalid. 'Name' property cannot be changed. /// </exception> private void CheckKeySetPreconditions(string key) { if (NameProperty.Equals(key, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException( "Argument 'key' is invalid. 'Name' property cannot be changed."); } } private void OnPropertiesChanged() { _api.Events.OnGroupPropChanged(this); } #endregion Methods } }
using System; using System.Collections.Generic; using System.Data; using System.Web; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Services; using umbraco.BusinessLogic; using umbraco.DataLayer; using Umbraco.Core; using Umbraco.Core.Security; namespace umbraco.BasePages { /// <summary> /// umbraco.BasePages.BasePage is the default page type for the umbraco backend. /// The basepage keeps track of the current user and the page context. But does not /// Restrict access to the page itself. /// The keep the page secure, the umbracoEnsuredPage class should be used instead /// </summary> [Obsolete("This class has been superceded by Umbraco.Web.UI.Pages.BasePage")] public class BasePage : System.Web.UI.Page { private User _user; private bool _userisValidated = false; private ClientTools _clientTools; // ticks per minute 600,000,000 private const long TicksPrMinute = 600000000; private static readonly int UmbracoTimeOutInMinutes = GlobalSettings.TimeOutInMinutes; /// <summary> /// The path to the umbraco root folder /// </summary> protected string UmbracoPath = SystemDirectories.Umbraco; /// <summary> /// The current user ID /// </summary> protected int uid = 0; /// <summary> /// The page timeout in seconds. /// </summary> protected long timeout = 0; /// <summary> /// Gets the SQL helper. /// </summary> /// <value>The SQL helper.</value> protected static ISqlHelper SqlHelper { get { return BusinessLogic.Application.SqlHelper; } } /// <summary> /// Returns the current ApplicationContext /// </summary> public ApplicationContext ApplicationContext { get { return ApplicationContext.Current; } } /// <summary> /// Returns a ServiceContext /// </summary> public ServiceContext Services { get { return ApplicationContext.Services; } } /// <summary> /// Returns a DatabaseContext /// </summary> public DatabaseContext DatabaseContext { get { return ApplicationContext.DatabaseContext; } } /// <summary> /// Returns the current BasePage for the current request. /// This assumes that the current page is a BasePage, otherwise, returns null; /// </summary> [Obsolete("Should use the Umbraco.Web.UmbracoContext.Current singleton instead to access common methods and properties")] public static BasePage Current { get { var page = HttpContext.Current.CurrentHandler as BasePage; if (page != null) return page; //the current handler is not BasePage but people might be expecting this to be the case if they // are using this singleton accesor... which is legacy code now and shouldn't be used. When people // start using Umbraco.Web.UI.Pages.BasePage then this will not be the case! So, we'll just return a // new instance of BasePage as a hack to make it work. if (HttpContext.Current.Items["umbraco.BasePages.BasePage"] == null) { HttpContext.Current.Items["umbraco.BasePages.BasePage"] = new BasePage(); } return (BasePage)HttpContext.Current.Items["umbraco.BasePages.BasePage"]; } } private UrlHelper _url; /// <summary> /// Returns a UrlHelper /// </summary> /// <remarks> /// This URL helper is created without any route data and an empty request context /// </remarks> public UrlHelper Url { get { return _url ?? (_url = new UrlHelper(new RequestContext(new HttpContextWrapper(Context), new RouteData()))); } } /// <summary> /// Returns a refernce of an instance of ClientTools for access to the pages client API /// </summary> public ClientTools ClientTools { get { if (_clientTools == null) _clientTools = new ClientTools(this); return _clientTools; } } [Obsolete("Use ClientTools instead")] public void RefreshPage(int Seconds) { ClientTools.RefreshAdmin(Seconds); } private void ValidateUser() { if ((umbracoUserContextID != "")) { uid = GetUserId(umbracoUserContextID); timeout = GetTimeout(umbracoUserContextID); if (timeout > DateTime.Now.Ticks) { _user = BusinessLogic.User.GetUser(uid); // Check for console access if (_user.Disabled || (_user.NoConsole && GlobalSettings.RequestIsInUmbracoApplication(HttpContext.Current) && !GlobalSettings.RequestIsLiveEditRedirector(HttpContext.Current))) { throw new ArgumentException("You have no priviledges to the umbraco console. Please contact your administrator"); } else { _userisValidated = true; UpdateLogin(); } } else { throw new ArgumentException("User has timed out!!"); } } else { throw new InvalidOperationException("The user has no umbraco contextid - try logging in"); } } /// <summary> /// Gets the user id. /// </summary> /// <param name="umbracoUserContextID">The umbraco user context ID.</param> /// <returns></returns> //[Obsolete("Use Umbraco.Web.Security.WebSecurity.GetUserId instead")] public static int GetUserId(string umbracoUserContextID) { //need to parse to guid Guid gid; if (!Guid.TryParse(umbracoUserContextID, out gid)) { return -1; } var id = ApplicationContext.Current.ApplicationCache.GetCacheItem<int?>( CacheKeys.UserContextCacheKey + umbracoUserContextID, new TimeSpan(0, UmbracoTimeOutInMinutes / 10, 0), () => SqlHelper.ExecuteScalar<int?>( "select userID from umbracoUserLogins where contextID = @contextId", SqlHelper.CreateParameter("@contextId", gid))); if (id == null) return -1; return id.Value; } // Added by NH to use with webservices authentications /// <summary> /// Validates the user context ID. /// </summary> /// <param name="currentUmbracoUserContextID">The umbraco user context ID.</param> /// <returns></returns> //[Obsolete("Use Umbraco.Web.Security.WebSecurity.ValidateUserContextId instead")] public static bool ValidateUserContextID(string currentUmbracoUserContextID) { if (!currentUmbracoUserContextID.IsNullOrWhiteSpace()) { var uid = GetUserId(currentUmbracoUserContextID); var timeout = GetTimeout(currentUmbracoUserContextID); if (timeout > DateTime.Now.Ticks) { return true; } var user = BusinessLogic.User.GetUser(uid); //TODO: We don't actually log anyone out here, not sure why we're logging ?? LogHelper.Info<BasePage>("User {0} (Id:{1}) logged out", () => user.Name, () => user.Id); } return false; } internal static long GetTimeout(string umbracoUserContextId) { return ApplicationContext.Current.ApplicationCache.GetCacheItem( CacheKeys.UserContextTimeoutCacheKey + umbracoUserContextId, new TimeSpan(0, UmbracoTimeOutInMinutes / 10, 0), () => GetTimeout(true)); } //[Obsolete("Use Umbraco.Web.Security.WebSecurity.GetTimeout instead")] public static long GetTimeout(bool bypassCache) { if (UmbracoSettings.KeepUserLoggedIn) RenewLoginTimeout(); if (bypassCache) { return SqlHelper.ExecuteScalar<long>("select timeout from umbracoUserLogins where contextId=@contextId", SqlHelper.CreateParameter("@contextId", new Guid(umbracoUserContextID)) ); } else return GetTimeout(umbracoUserContextID); } // Changed to public by NH to help with webservice authentication /// <summary> /// Gets or sets the umbraco user context ID. /// </summary> /// <value>The umbraco user context ID.</value> //[Obsolete("Use Umbraco.Web.Security.WebSecurity.UmbracoUserContextId instead")] public static string umbracoUserContextID { get { var authTicket = HttpContext.Current.GetUmbracoAuthTicket(); if (authTicket == null) { return ""; } var identity = authTicket.CreateUmbracoIdentity(); if (identity == null) { HttpContext.Current.UmbracoLogout(); return ""; } return identity.UserContextId; } set { if (value.IsNullOrWhiteSpace()) { HttpContext.Current.UmbracoLogout(); } else { var uid = GetUserId(value); if (uid == -1) { HttpContext.Current.UmbracoLogout(); } else { var user = BusinessLogic.User.GetUser(uid); HttpContext.Current.CreateUmbracoAuthTicket( new UserData { Id = uid, AllowedApplications = user.Applications.Select(x => x.alias).ToArray(), Culture = ui.Culture(user), RealName = user.Name, Roles = new string[] {user.UserType.Alias}, StartContentNode = user.StartNodeId, StartMediaNode = user.StartMediaId, UserContextId = value, Username = user.LoginName }); } } } } /// <summary> /// Clears the login. /// </summary> public void ClearLogin() { DeleteLogin(); umbracoUserContextID = ""; } private void DeleteLogin() { // Added try-catch in case login doesn't exist in the database // Either due to old cookie or running multiple sessions on localhost with different port number try { SqlHelper.ExecuteNonQuery( "DELETE FROM umbracoUserLogins WHERE contextId = @contextId", SqlHelper.CreateParameter("@contextId", umbracoUserContextID)); } catch (Exception ex) { LogHelper.Error<BasePage>(string.Format("Login with contextId {0} didn't exist in the database", umbracoUserContextID), ex); } } private void UpdateLogin() { // only call update if more than 1/10 of the timeout has passed if (timeout - (((TicksPrMinute * UmbracoTimeOutInMinutes) * 0.8)) < DateTime.Now.Ticks) SqlHelper.ExecuteNonQuery( "UPDATE umbracoUserLogins SET timeout = @timeout WHERE contextId = @contextId", SqlHelper.CreateParameter("@timeout", DateTime.Now.Ticks + (TicksPrMinute * UmbracoTimeOutInMinutes)), SqlHelper.CreateParameter("@contextId", umbracoUserContextID)); } //[Obsolete("Use Umbraco.Web.Security.WebSecurity.RenewLoginTimeout instead")] public static void RenewLoginTimeout() { // only call update if more than 1/10 of the timeout has passed SqlHelper.ExecuteNonQuery( "UPDATE umbracoUserLogins SET timeout = @timeout WHERE contextId = @contextId", SqlHelper.CreateParameter("@timeout", DateTime.Now.Ticks + (TicksPrMinute * UmbracoTimeOutInMinutes)), SqlHelper.CreateParameter("@contextId", umbracoUserContextID)); } /// <summary> /// Logs a user in. /// </summary> /// <param name="u">The user</param> //[Obsolete("Use Umbraco.Web.Security.WebSecurity.PerformLogin instead")] public static void doLogin(User u) { Guid retVal = Guid.NewGuid(); SqlHelper.ExecuteNonQuery( "insert into umbracoUserLogins (contextID, userID, timeout) values (@contextId,'" + u.Id + "','" + (DateTime.Now.Ticks + (TicksPrMinute * UmbracoTimeOutInMinutes)).ToString() + "') ", SqlHelper.CreateParameter("@contextId", retVal)); umbracoUserContextID = retVal.ToString(); LogHelper.Info<BasePage>("User {0} (Id: {1}) logged in", () => u.Name, () => u.Id); } /// <summary> /// Gets the user. /// </summary> /// <returns></returns> [Obsolete("Use UmbracoUser property instead.")] public User getUser() { return UmbracoUser; } /// <summary> /// Gets the user. /// </summary> /// <value></value> public User UmbracoUser { get { if (!_userisValidated) ValidateUser(); return _user; } } /// <summary> /// Ensures the page context. /// </summary> public void ensureContext() { ValidateUser(); } [Obsolete("Use ClientTools instead")] public void speechBubble(speechBubbleIcon i, string header, string body) { ClientTools.ShowSpeechBubble(i, header, body); } //[Obsolete("Use ClientTools instead")] //public void reloadParentNode() //{ // ClientTools.ReloadParentNode(true); //} /// <summary> /// a collection of available speechbubble icons /// </summary> [Obsolete("This has been superceded by Umbraco.Web.UI.SpeechBubbleIcon but that requires the use of the Umbraco.Web.UI.Pages.BasePage or Umbraco.Web.UI.Pages.EnsuredPage objects")] public enum speechBubbleIcon { /// <summary> /// Save icon /// </summary> save, /// <summary> /// Info icon /// </summary> info, /// <summary> /// Error icon /// </summary> error, /// <summary> /// Success icon /// </summary> success, /// <summary> /// Warning icon /// </summary> warning } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Request.IsSecureConnection && GlobalSettings.UseSSL) { string serverName = HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]); Response.Redirect(string.Format("https://{0}{1}", serverName, Request.FilePath)); } } /// <summary> /// Override client target. /// </summary> [Obsolete("This is no longer supported")] public bool OverrideClientTarget = false; } }
#nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Scriban.Helpers { [DebuggerTypeProxy(typeof(InlineList<>.DebugListView)), DebuggerDisplay("Count = {Count}")] internal struct InlineList<T> : IEnumerable<T> { private const int DefaultCapacity = 4; public int Count; public T[] Items; public InlineList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); Count = 0; Items = capacity == 0 ? Array.Empty<T>() : new T[capacity]; } public int Capacity { get => Items?.Length ?? 0; set { Ensure(); if (value <= Items.Length) return; EnsureCapacity(value); } } public static InlineList<T> Create() { return new InlineList<T>(0); } public static InlineList<T> Create(int capacity) { return new InlineList<T>(capacity); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Ensure() { if (Items == null) Items = Array.Empty<T>(); } public bool IsReadOnly => false; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (Count > 0) { Array.Clear(Items, 0, Count); Count = 0; } } public InlineList<T> Clone() { var items = (T[])Items?.Clone(); return new InlineList<T>() { Count = Count, Items = items }; } public bool Contains(T item) { return Count > 0 && IndexOf(item) >= 0; } public void CopyTo(T[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if (Count > 0) { System.Array.Copy(Items, 0, array, arrayIndex, Count); } } public T[] ToArray() { var array = new T[Count]; CopyTo(array, 0); return array; } public void Reset() { Clear(); Count = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T child) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } Items[Count++] = child; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddByRef(in T child) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } Items[Count++] = child; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Insert(int index, T item) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(Items, index, Items, index + 1, Count - index); } Items[index] = item; Count++; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T InsertReturnRef(int index, T item) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(Items, index, Items, index + 1, Count - index); } ref var refItem = ref Items[index]; refItem = item; Count++; return ref refItem; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void InsertByRef(int index, in T item) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(Items, index, Items, index + 1, Count - index); } Items[index] = item; Count++; } public bool Remove(T element) { var index = IndexOf(element); if (index >= 0) { RemoveAt(index); return true; } return false; } public int IndexOf(T element) { return Array.IndexOf(Items, element, 0, Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T RemoveAt(int index) { if (index < 0 || index >= Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); Count--; // previous children var item = Items[index]; if (index < Count) { Array.Copy(Items, index + 1, Items, index, Count - index); } Items[Count] = default(T); return item; } public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); return Items[index]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { if ((uint)index >= (uint)Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); Items[index] = value; } } private void EnsureCapacity(int min) { if (Items.Length < min) { int num = (Items.Length == 0) ? DefaultCapacity : (Items.Length * 2); if (num < min) { num = min; } Array.Resize(ref Items, num); } } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<T> { private readonly InlineList<T> list; private int index; private T current; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(InlineList<T> list) { this.list = list; index = 0; current = default(T); } public T Current => current; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() { if (index < list.Count) { current = list[index]; index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { index = list.Count + 1; current = default(T); return false; } void IEnumerator.Reset() { index = 0; current = default(T); } } internal class DebugListView { private InlineList<T> _collection; public DebugListView(InlineList<T> collection) { this._collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { var array = new T[this._collection.Count]; for (int i = 0; i < array.Length; i++) { array[i] = _collection[i]; } return array; } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Umbraco.Core.Xml; namespace Umbraco.Core { /// <summary> /// Extension methods for xml objects /// </summary> internal static class XmlExtensions { /// <summary> /// Saves the xml document async /// </summary> /// <param name="xdoc"></param> /// <param name="filename"></param> /// <returns></returns> public static async Task SaveAsync(this XmlDocument xdoc, string filename) { if (xdoc.DocumentElement == null) throw new XmlException("Cannot save xml document, there is no root element"); using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize: 4096, useAsync: true)) using (var xmlWriter = XmlWriter.Create(fs, new XmlWriterSettings { Async = true, Encoding = Encoding.UTF8, Indent = true })) { //NOTE: There are no nice methods to write it async, only flushing it async. We // could implement this ourselves but it'd be a very manual process. xdoc.WriteTo(xmlWriter); await xmlWriter.FlushAsync().ConfigureAwait(false); } } public static bool HasAttribute(this XmlAttributeCollection attributes, string attributeName) { return attributes.Cast<XmlAttribute>().Any(x => x.Name == attributeName); } /// <summary> /// Selects a list of XmlNode matching an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The list of XmlNode matching the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNodeList SelectNodes(this XmlNode source, string expression, IEnumerable<XPathVariable> variables) { var av = variables == null ? null : variables.ToArray(); return SelectNodes(source, expression, av); } /// <summary> /// Selects a list of XmlNode matching an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The list of XmlNode matching the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, IEnumerable<XPathVariable> variables) { var av = variables == null ? null : variables.ToArray(); return SelectNodes(source, expression, av); } /// <summary> /// Selects a list of XmlNode matching an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The list of XmlNode matching the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNodeList SelectNodes(this XmlNode source, string expression, params XPathVariable[] variables) { if (variables == null || variables.Length == 0 || variables[0] == null) return source.SelectNodes(expression); var iterator = source.CreateNavigator().Select(expression, variables); return XmlNodeListFactory.CreateNodeList(iterator); } /// <summary> /// Selects a list of XmlNode matching an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The list of XmlNode matching the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, params XPathVariable[] variables) { if (variables == null || variables.Length == 0 || variables[0] == null) return source.SelectNodes(expression); var iterator = source.CreateNavigator().Select(expression, variables); return XmlNodeListFactory.CreateNodeList(iterator); } /// <summary> /// Selects the first XmlNode that matches an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The first XmlNode that matches the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNode SelectSingleNode(this XmlNode source, string expression, IEnumerable<XPathVariable> variables) { var av = variables == null ? null : variables.ToArray(); return SelectSingleNode(source, expression, av); } /// <summary> /// Selects the first XmlNode that matches an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The first XmlNode that matches the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNode SelectSingleNode(this XmlNode source, XPathExpression expression, IEnumerable<XPathVariable> variables) { var av = variables == null ? null : variables.ToArray(); return SelectSingleNode(source, expression, av); } /// <summary> /// Selects the first XmlNode that matches an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The first XmlNode that matches the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNode SelectSingleNode(this XmlNode source, string expression, params XPathVariable[] variables) { if (variables == null || variables.Length == 0 || variables[0] == null) return source.SelectSingleNode(expression); return SelectNodes(source, expression, variables).Cast<XmlNode>().FirstOrDefault(); } /// <summary> /// Selects the first XmlNode that matches an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The first XmlNode that matches the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNode SelectSingleNode(this XmlNode source, XPathExpression expression, params XPathVariable[] variables) { if (variables == null || variables.Length == 0 || variables[0] == null) return source.SelectSingleNode(expression); return SelectNodes(source, expression, variables).Cast<XmlNode>().FirstOrDefault(); } /// <summary> /// Converts from an XDocument to an XmlDocument /// </summary> /// <param name="xDocument"></param> /// <returns></returns> public static XmlDocument ToXmlDocument(this XDocument xDocument) { var xmlDocument = new XmlDocument(); using (var xmlReader = xDocument.CreateReader()) { xmlDocument.Load(xmlReader); } return xmlDocument; } /// <summary> /// Converts from an XmlDocument to an XDocument /// </summary> /// <param name="xmlDocument"></param> /// <returns></returns> public static XDocument ToXDocument(this XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader); } } ///// <summary> ///// Converts from an XElement to an XmlElement ///// </summary> ///// <param name="xElement"></param> ///// <returns></returns> //public static XmlNode ToXmlElement(this XContainer xElement) //{ // var xmlDocument = new XmlDocument(); // using (var xmlReader = xElement.CreateReader()) // { // xmlDocument.Load(xmlReader); // } // return xmlDocument.DocumentElement; //} /// <summary> /// Converts from an XmlElement to an XElement /// </summary> /// <param name="xmlElement"></param> /// <returns></returns> public static XElement ToXElement(this XmlNode xmlElement) { using (var nodeReader = new XmlNodeReader(xmlElement)) { nodeReader.MoveToContent(); return XElement.Load(nodeReader); } } public static T AttributeValue<T>(this XElement xml, string attributeName) { if (xml == null) throw new ArgumentNullException("xml"); if (xml.HasAttributes == false) return default(T); if (xml.Attribute(attributeName) == null) return default(T); var val = xml.Attribute(attributeName).Value; var result = val.TryConvertTo<T>(); if (result.Success) return result.Result; return default(T); } public static T AttributeValue<T>(this XmlNode xml, string attributeName) { if (xml == null) throw new ArgumentNullException("xml"); if (xml.Attributes == null) return default(T); if (xml.Attributes[attributeName] == null) return default(T); var val = xml.Attributes[attributeName].Value; var result = val.TryConvertTo<T>(); if (result.Success) return result.Result; return default(T); } public static XElement GetXElement(this XmlNode node) { XDocument xDoc = new XDocument(); using (XmlWriter xmlWriter = xDoc.CreateWriter()) node.WriteTo(xmlWriter); return xDoc.Root; } public static XmlNode GetXmlNode(this XContainer element) { using (XmlReader xmlReader = element.CreateReader()) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlReader); return xmlDoc.FirstChild; } } public static XmlNode GetXmlNode(this XContainer element, XmlDocument xmlDoc) { using (XmlReader xmlReader = element.CreateReader()) { xmlDoc.Load(xmlReader); return xmlDoc.DocumentElement; } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An ocean (for example, the Pacific). /// </summary> public class OceanBodyOfWater_Core : TypeCore, IBodyOfWater { public OceanBodyOfWater_Core() { this._TypeId = 188; this._Id = "OceanBodyOfWater"; this._Schema_Org_Url = "http://schema.org/OceanBodyOfWater"; string label = ""; GetLabel(out label, "OceanBodyOfWater", typeof(OceanBodyOfWater_Core)); this._Label = label; this._Ancestors = new int[]{266,206,146,40}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{40}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // This script function is called before a client connection // is accepted. Returning "" will accept the connection, // anything else will be sent back as an error to the client. // All the connect args are passed also to onConnectRequest // function GameConnection::onConnectRequest( %client, %netAddress, %name ) { echo("Connect request from: " @ %netAddress); if($Server::PlayerCount >= $pref::Server::MaxPlayers) return "CR_SERVERFULL"; return ""; } //----------------------------------------------------------------------------- // This script function is the first called on a client accept // function GameConnection::onConnect( %client, %name ) { // Send down the connection error info, the client is // responsible for displaying this message if a connection // error occures. messageClient(%client,'MsgConnectionError',"",$Pref::Server::ConnectionError); // Send mission information to the client sendLoadInfoToClient( %client ); // Simulated client lag for testing... // %client.setSimulatedNetParams(0.1, 30); // Get the client's unique id: // %authInfo = %client.getAuthInfo(); // %client.guid = getField( %authInfo, 3 ); %client.guid = 0; addToServerGuidList( %client.guid ); // Set admin status if (%client.getAddress() $= "local") { %client.isAdmin = true; %client.isSuperAdmin = true; } else { %client.isAdmin = false; %client.isSuperAdmin = false; } // Save client preferences on the connection object for later use. %client.gender = "Male"; %client.armor = "Light"; %client.race = "Human"; %client.skin = addTaggedString( "base" ); %client.setPlayerName(%name); %client.score = 0; // echo("CADD: " @ %client @ " " @ %client.getAddress()); // Inform the client of all the other clients %count = ClientGroup.getCount(); for (%cl = 0; %cl < %count; %cl++) { %other = ClientGroup.getObject(%cl); if ((%other != %client)) { // These should be "silent" versions of these messages... messageClient(%client, 'MsgClientJoin', "", %other.playerName, %other, %other.sendGuid, %other.score, %other.isAIControlled(), %other.isAdmin, %other.isSuperAdmin); } } // Inform the client we've joined up messageClient(%client, 'MsgClientJoin', 'Welcome to a Torque application %1.', %client.playerName, %client, %client.sendGuid, %client.score, %client.isAiControlled(), %client.isAdmin, %client.isSuperAdmin); // Inform all the other clients of the new guy messageAllExcept(%client, -1, 'MsgClientJoin', '\c1%1 joined the game.', %client.playerName, %client, %client.sendGuid, %client.score, %client.isAiControlled(), %client.isAdmin, %client.isSuperAdmin); // If the mission is running, go ahead download it to the client if ($missionRunning) { %client.loadMission(); } else if ($Server::LoadFailMsg !$= "") { messageClient(%client, 'MsgLoadFailed', $Server::LoadFailMsg); } $Server::PlayerCount++; } //----------------------------------------------------------------------------- // A player's name could be obtained from the auth server, but for // now we use the one passed from the client. // %realName = getField( %authInfo, 0 ); // function GameConnection::setPlayerName(%client,%name) { %client.sendGuid = 0; // Minimum length requirements %name = trim( strToPlayerName( %name ) ); if ( strlen( %name ) < 3 ) %name = "Poser"; // Make sure the alias is unique, we'll hit something eventually if (!isNameUnique(%name)) { %isUnique = false; for (%suffix = 1; !%isUnique; %suffix++) { %nameTry = %name @ "." @ %suffix; %isUnique = isNameUnique(%nameTry); } %name = %nameTry; } // Tag the name with the "smurf" color: %client.nameBase = %name; %client.playerName = addTaggedString("\cp\c8" @ %name @ "\co"); } function isNameUnique(%name) { %count = ClientGroup.getCount(); for ( %i = 0; %i < %count; %i++ ) { %test = ClientGroup.getObject( %i ); %rawName = stripChars( detag( getTaggedString( %test.playerName ) ), "\cp\co\c6\c7\c8\c9" ); if ( strcmp( %name, %rawName ) == 0 ) return false; } return true; } //----------------------------------------------------------------------------- // This function is called when a client drops for any reason // function GameConnection::onDrop(%client, %reason) { %client.onClientLeaveGame(); removeFromServerGuidList( %client.guid ); messageAllExcept(%client, -1, 'MsgClientDrop', '\c1%1 has left the game.', %client.playerName, %client); removeTaggedString(%client.playerName); echo("CDROP: " @ %client @ " " @ %client.getAddress()); $Server::PlayerCount--; // Reset the server if everyone has left the game if( $Server::PlayerCount == 0 && $Server::Dedicated) schedule(0, 0, "resetServerDefaults"); } //----------------------------------------------------------------------------- function GameConnection::startMission(%this) { // Inform the client the mission starting commandToClient(%this, 'MissionStart', $missionSequence); } function GameConnection::endMission(%this) { // Inform the client the mission is done. Note that if this is // called as part of the server destruction routine, the client will // actually never see this comment since the client connection will // be destroyed before another round of command processing occurs. // In this case, the client will only see the disconnect from the server // and should manually trigger a mission cleanup. commandToClient(%this, 'MissionEnd', $missionSequence); } //-------------------------------------------------------------------------- // Sync the clock on the client. function GameConnection::syncClock(%client, %time) { commandToClient(%client, 'syncClock', %time); } //-------------------------------------------------------------------------- // Update all the clients with the new score function GameConnection::incScore(%this,%delta) { %this.score += %delta; messageAll('MsgClientScoreChanged', "", %this.score, %this); }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using System.Text; using Encog.App.Analyst.Missing; using Encog.App.Analyst.Script; using Encog.App.Analyst.Script.ML; using Encog.App.Analyst.Script.Normalize; using Encog.App.Analyst.Script.Process; using Encog.App.Analyst.Script.Prop; using Encog.App.Analyst.Script.Segregate; using Encog.App.Analyst.Script.Task; using Encog.App.Generate; using Encog.ML.Factory; using Encog.ML.Prg; using Encog.ML.Prg.Ext; using Encog.Neural.NEAT; using Encog.Util.Arrayutil; using Encog.Util.CSV; using Encog.Util.File; namespace Encog.App.Analyst.Wizard { /// <summary> /// The Encog Analyst Wizard can be used to create Encog Analyst script files /// from a CSV file. This class is typically used by the Encog Workbench, but it /// can easily be used from any program to create a starting point for an Encog /// Analyst Script. /// Several items must be provided to the wizard. /// Desired Machine Learning Method: This is the machine learning method that you /// would like the wizard to use. This might be a neural network, SVM or other /// supported method. /// Normalization Range: This is the range that the data should be normalized /// into. Some machine learning methods perform better with different ranges. The /// two ranges supported by the wizard are -1 to 1 and 0 to 1. /// Goal: What are we trying to accomplish. Is this a classification, regression /// or autoassociation problem. /// </summary> public class AnalystWizard { /// <summary> /// The default training percent. /// </summary> public const int DefaultTrainPercent = 75; /// <summary> /// The default evaluation percent. /// </summary> public const int DefaultEvalPercent = 25; /// <summary> /// The default training error. /// </summary> public const double DefaultTrainError = 0.05d; /// <summary> /// The raw file. /// </summary> public const String FileRaw = "FILE_RAW"; /// <summary> /// The normalized file. /// </summary> public const String FileNormalize = "FILE_NORMALIZE"; /// <summary> /// The randomized file. /// </summary> public const String FileRandom = "FILE_RANDOMIZE"; /// <summary> /// The training file. /// </summary> public const String FileTrain = "FILE_TRAIN"; /// <summary> /// The evaluation file. /// </summary> public const String FileEval = "FILE_EVAL"; /// <summary> /// The eval file normalization file. /// </summary> public const String FileEvalNorm = "FILE_EVAL_NORM"; /// <summary> /// The training set. /// </summary> public const String FileTrainset = "FILE_TRAINSET"; /// <summary> /// The machine learning file. /// </summary> public const String FileMl = "FILE_ML"; /// <summary> /// The output file. /// </summary> public const String FileOutput = "FILE_OUTPUT"; /// <summary> /// The balanced file. /// </summary> public const String FileBalance = "FILE_BALANCE"; /// <summary> /// The clustered file. /// </summary> public const String FileCluster = "FILE_CLUSTER"; /// <summary> /// The code file. /// </summary> public const String FileCode = "FILE_CODE"; /// <summary> /// The preprocess file. /// </summary> public const String FilePre = "FILE_PROCESSED"; /// <summary> /// The analyst. /// </summary> private readonly EncogAnalyst _analyst; /// <summary> /// The analyst script. /// </summary> private readonly AnalystScript _script; /// <summary> /// Should code data be embedded. /// </summary> private bool _codeEmbedData; /// <summary> /// The target language for code generation. /// </summary> private TargetLanguage _codeTargetLanguage = TargetLanguage.NoGeneration; /// <summary> /// Are we using single-field(direct) classification. /// </summary> private bool _directClassification; /// <summary> /// The balance filename. /// </summary> private String _filenameBalance; /// <summary> /// The cluster filename. /// </summary> private String _filenameCluster; /// <summary> /// The code filename. /// </summary> private string _filenameCode; /// <summary> /// The evaluation filename. /// </summary> private String _filenameEval; /// <summary> /// The normalization eval file name. /// </summary> private String _filenameEvalNorm; /// <summary> /// The machine learning file name. /// </summary> private String _filenameMl; /// <summary> /// The normalized filename. /// </summary> private String _filenameNorm; /// <summary> /// The output filename. /// </summary> private String _filenameOutput; /// <summary> /// The process filename. /// </summary> private string _filenameProcess; /// <summary> /// The random file name. /// </summary> private String _filenameRandom; /// <summary> /// The raw filename. /// </summary> private String _filenameRaw; /// <summary> /// The training filename. /// </summary> private String _filenameTrain; /// <summary> /// The training set filename. /// </summary> private String _filenameTrainSet; /// <summary> /// The format in use. /// </summary> private AnalystFileFormat _format; /// <summary> /// The analyst goal. /// </summary> private AnalystGoal _goal; /// <summary> /// Should the target field be included int he input, if we are doing /// time-series. /// </summary> private bool _includeTargetField; /// <summary> /// The size of the lag window, if we are doing time-series. /// </summary> private int _lagWindowSize; /// <summary> /// The size of the lead window, if we are doing time-series. /// </summary> private int _leadWindowSize; /// <summary> /// The machine learning method that we will be using. /// </summary> private WizardMethodType _methodType; /// <summary> /// How to handle missing values. /// </summary> private IHandleMissingValues _missing; /// <summary> /// Should we preprocess. /// </summary> private bool _preprocess; /// <summary> /// The normalization range. /// </summary> private NormalizeRange _range; /// <summary> /// The target field, or null to detect. /// </summary> private AnalystField _targetField; /// <summary> /// True if the balance command should be generated. /// </summary> private bool _taskBalance; /// <summary> /// True if the cluster command should be generated. /// </summary> private bool _taskCluster; /// <summary> /// True if the normalize command should be generated. /// </summary> private bool _taskNormalize; /// <summary> /// True if the randomize command should be generated. /// </summary> private bool _taskRandomize; /// <summary> /// True if the segregate command should be generated. /// </summary> private bool _taskSegregate; /// <summary> /// True if we are doing time-series. /// </summary> private bool _timeSeries; /// <summary> /// Construct the analyst wizard. /// </summary> /// <param name="theAnalyst">The analyst to use.</param> public AnalystWizard(EncogAnalyst theAnalyst) { _directClassification = false; _taskSegregate = true; _taskRandomize = true; _taskNormalize = true; _taskBalance = false; _taskCluster = true; _range = NormalizeRange.NegOne2One; _analyst = theAnalyst; _script = _analyst.Script; _methodType = WizardMethodType.FeedForward; TargetFieldName = ""; _goal = AnalystGoal.Classification; _leadWindowSize = 0; _lagWindowSize = 0; _includeTargetField = false; _missing = new DiscardMissing(); MaxError = DefaultTrainError; NaiveBayes = false; } /// <summary> /// The number of evidence segments to use when mapping continuous values to Bayes. /// </summary> public int EvidenceSegements { get; set; } public bool NaiveBayes { get; set; } /// <summary> /// The maximum allowed training error. /// </summary> public double MaxError { get; set; } /// <summary> /// The String name of the target field. /// </summary> public String TargetFieldName { get; set; } /// <summary> /// Set the goal. /// </summary> public AnalystGoal Goal { get { return _goal; } set { _goal = value; } } /// <value>the lagWindowSize to set</value> public int LagWindowSize { get { return _lagWindowSize; } set { _lagWindowSize = value; } } /// <value>the leadWindowSize to set</value> public int LeadWindowSize { get { return _leadWindowSize; } set { _leadWindowSize = value; } } /// <value>the methodType to set</value> public WizardMethodType MethodType { get { return _methodType; } set { _methodType = value; } } /// <value>the range to set</value> public NormalizeRange Range { get { return _range; } set { _range = value; } } /// <summary> /// Set the target field. /// </summary> /// <value>The target field.</value> public AnalystField TargetField { get { return _targetField; } set { _targetField = value; } } /// <value>the includeTargetField to set</value> public bool IncludeTargetField { get { return _includeTargetField; } set { _includeTargetField = value; } } /// <value>the taskBalance to set</value> public bool TaskBalance { get { return _taskBalance; } set { _taskBalance = value; } } /// <value>the taskCluster to set</value> public bool TaskCluster { get { return _taskCluster; } set { _taskCluster = value; } } /// <value>the taskNormalize to set</value> public bool TaskNormalize { get { return _taskNormalize; } set { _taskNormalize = value; } } /// <value>the taskRandomize to set</value> public bool TaskRandomize { get { return _taskRandomize; } set { _taskRandomize = value; } } /// <value>the taskSegregate to set</value> public bool TaskSegregate { get { return _taskSegregate; } set { _taskSegregate = value; } } /// <summary> /// How should missing values be handled. /// </summary> public IHandleMissingValues Missing { get { return _missing; } set { _missing = value; } } /// <summary> /// The target language for code generation. /// </summary> public TargetLanguage CodeTargetLanguage { get { return _codeTargetLanguage; } set { _codeTargetLanguage = value; } } /// <summary> /// Should code data be embedded. /// </summary> public bool CodeEmbedData { get { return _codeEmbedData; } set { _codeEmbedData = value; } } /// <summary> /// Should we preprocess. /// </summary> public bool Preprocess { get { return _preprocess; } set { _preprocess = value; } } /// <summary> /// Create a "set" command to add to a task. /// </summary> /// <param name="setTarget">The target.</param> /// <param name="setSource">The source.</param> /// <returns>The "set" command.</returns> private static String CreateSet(String setTarget, String setSource) { var result = new StringBuilder(); result.Append("set "); result.Append(ScriptProperties.ToDots(setTarget)); result.Append("=\""); result.Append(setSource); result.Append("\""); return result.ToString(); } /// <summary> /// Determine the type of classification used. /// </summary> private void DetermineClassification() { _directClassification = false; if ((_methodType == WizardMethodType.SVM) || (_methodType == WizardMethodType.SOM) || (_methodType == WizardMethodType.PNN)) { _directClassification = true; } } /// <summary> /// Determine the target field. /// </summary> private void DetermineTargetField() { IList<AnalystField> fields = _script.Normalize.NormalizedFields; if (string.IsNullOrEmpty(TargetFieldName)) { bool success = false; if (Goal == AnalystGoal.Classification) { // first try to the last classify field foreach (AnalystField field in fields) { DataField df = _script.FindDataField(field.Name); if (field.Action.IsClassify() && df.Class) { TargetField = field; success = true; } } } else { // otherwise, just return the last regression field foreach (AnalystField field in fields) { DataField df = _script.FindDataField(field.Name); if (!df.Class && (df.Real || df.Integer)) { TargetField = field; success = true; } } } if (!success) { throw new AnalystError( "Can't determine target field automatically, " + "please specify one.\nThis can also happen if you " + "specified the wrong file format."); } } else { TargetField = _script.FindAnalystField(TargetFieldName); if (TargetField == null) { throw new AnalystError("Invalid target field: " + TargetFieldName); } } _script.Properties.SetProperty( ScriptProperties.DataConfigGoal, _goal); if (!_timeSeries && _taskBalance) { _script.Properties.SetProperty( ScriptProperties.BalanceConfigBalanceField, TargetField.Name); DataField field = _analyst.Script.FindDataField( _targetField.Name); if ((field != null) && field.Class) { int countPer = field.MinClassCount; _script.Properties.SetProperty( ScriptProperties.BalanceConfigCountPer, countPer); } } // determine output field if (_methodType != WizardMethodType.BayesianNetwork) { // now that the target field has been determined, set the analyst fields AnalystField af = null; foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields) { if ((field.Action != NormalizationAction.Ignore) && field == _targetField) { if ((af == null) || (af.TimeSlice < field.TimeSlice)) { af = field; } } } if (af != null) { af.Output = (true); } } // set the clusters count if (_taskCluster) { if ((TargetField == null) || (_goal != AnalystGoal.Classification)) { _script.Properties.SetProperty( ScriptProperties.ClusterConfigClusters, 2); } else { DataField tf = _script.FindDataField(TargetField.Name); _script.Properties.SetProperty( ScriptProperties.ClusterConfigClusters, tf.ClassMembers.Count); } } } /// <summary> /// Expand the time-series fields. /// </summary> private void ExpandTimeSlices() { IList<AnalystField> oldList = _script.Normalize.NormalizedFields; IList<AnalystField> newList = new List<AnalystField>(); // generate the inputs foreach the new list foreach (AnalystField field in oldList) { if (!field.Ignored) { if (_includeTargetField || field.Input) { for (int i = 0; i < _lagWindowSize; i++) { var newField = new AnalystField(field) {TimeSlice = -i, Output = false}; newList.Add(newField); } } } else { newList.Add(field); } } // generate the outputs foreach the new list foreach (AnalystField field in oldList) { if (!field.Ignored) { if (field.Output) { for (int i = 1; i <= _leadWindowSize; i++) { var newField = new AnalystField(field) {TimeSlice = i}; newList.Add(newField); } } } } // generate the ignores foreach the new list foreach (AnalystField field in oldList) { if (field.Ignored) { newList.Add(field); } } // swap back in oldList.Clear(); foreach (AnalystField item in oldList) { oldList.Add(item); } } /// <summary> /// Generate a feed forward machine learning method. /// </summary> /// <param name="inputColumns">The input column count.</param> private void GenerateFeedForward(int inputColumns) { var hidden = (int) ((inputColumns)*1.5d); _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeFeedforward); if (_range == NormalizeRange.NegOne2One) { _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, "?:B->TANH->" + hidden + ":B->TANH->?"); } else { _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, "?:B->SIGMOID->" + hidden + ":B->SIGMOID->?"); } _script.Properties.SetProperty(ScriptProperties.MlTrainType, "rprop"); _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate a Bayesian network machine learning method. /// </summary> /// <param name="inputColumns">The input column count.</param> /// <param name="outputColumns">The output column count.</param> private void GenerateBayesian(int inputColumns, int outputColumns) { int segment = EvidenceSegements; if (!_targetField.Classify) { throw new AnalystError("Bayesian networks cannot be used for regression."); } var a = new StringBuilder(); foreach (DataField field in _analyst.Script.Fields) { a.Append("P("); a.Append(field.Name); // handle actual class members if (field.ClassMembers.Count > 0) { a.Append("["); bool first = true; foreach (AnalystClassItem item in field.ClassMembers) { if (!first) { a.Append(","); } a.Append(item.Code); first = false; } // append a "fake" member, if there is only one if (field.ClassMembers.Count == 1) { a.Append(",Other0"); } a.Append("]"); } else { a.Append("["); // handle ranges double size = Math.Abs(field.Max - field.Min); double per = size/segment; if (size < EncogFramework.DefaultDoubleEqual) { double low = field.Min - 0.0001; double hi = field.Min + 0.0001; a.Append("BELOW: " + (low - 100) + " to " + hi + ","); a.Append("Type0: " + low + " to " + hi + ","); a.Append("ABOVE: " + hi + " to " + (hi + 100)); } else { bool first = true; for (int i = 0; i < segment; i++) { if (!first) { a.Append(","); } double low = field.Min + (per*i); double hi = i == (segment - 1) ? (field.Max) : (low + per); a.Append("Type"); a.Append(i); a.Append(":"); a.Append(CSVFormat.EgFormat.Format(low, 16)); a.Append(" to "); a.Append(CSVFormat.EgFormat.Format(hi, 16)); first = false; } } a.Append("]"); } a.Append(") "); } var q = new StringBuilder(); q.Append("P("); q.Append(_targetField.Name); q.Append("|"); bool first2 = true; foreach (DataField field in _analyst.Script.Fields) { if (!field.Name.Equals(_targetField.Name)) { if (!first2) { q.Append(","); } q.Append(field.Name); first2 = false; } } q.Append(")"); _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeBayesian); _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, a.ToString()); _script.Properties.SetProperty( ScriptProperties.MLConfigQuery, q.ToString()); _script.Properties.SetProperty(ScriptProperties.MlTrainType, "bayesian"); if (NaiveBayes) { _script.Properties.SetProperty( ScriptProperties.MlTrainArguments, "maxParents=1,estimator=simple,search=none,init=naive"); } else { _script.Properties.SetProperty( ScriptProperties.MlTrainArguments, "maxParents=1,estimator=simple,search=k2,init=naive"); } _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate a NEAT population method. /// </summary> /// <param name="inputColumns">The input column count.</param> /// <param name="outputColumns">The output column count.</param> private void GenerateNEAT(int inputColumns, int outputColumns) { _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeNEAT); _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, "cycles=" + NEATPopulation.DefaultCycles); _script.Properties.SetProperty(ScriptProperties.MlTrainType, MLTrainFactory.TypeNEATGA); _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate a EPL population method. /// </summary> /// <param name="inputColumns">The input column count.</param> /// <param name="outputColumns">The output column count.</param> private void generateEPL(int inputColumns, int outputColumns) { _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeEPL); String vars = ""; if (inputColumns > 26) { throw new EncogError("More than 26 input variables is not supported for EPL."); } else if (inputColumns <= 3) { var temp = new StringBuilder(); for (int i = 0; i < inputColumns; i++) { if (temp.Length > 0) { temp.Append(','); } temp.Append((char) ('x' + i)); } vars = temp.ToString(); } else { var temp = new StringBuilder(); for (int i = 0; i < inputColumns; i++) { if (temp.Length > 0) { temp.Append(','); } temp.Append((char) ('a' + i)); } vars = temp.ToString(); } _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, "cycles=" + NEATPopulation.DefaultCycles + ",vars=\"" + vars + "\""); _script.Properties.SetProperty(ScriptProperties.MlTrainType, MLTrainFactory.TypeEPLGA); _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); // add in the opcodes var context = new EncogProgramContext(); if (Goal == AnalystGoal.Regression) { StandardExtensions.CreateNumericOperators(context); } else { StandardExtensions.CreateNumericOperators(context); StandardExtensions.CreateBooleanOperators(context); } foreach (IProgramExtensionTemplate temp in context.Functions.OpCodes) { _script.Opcodes.Add(new ScriptOpcode(temp)); } } /// <summary> /// Generate a PNN machine learning method. /// </summary> /// <param name="inputColumns">The number of input columns.</param> /// <param name="outputColumns">The number of ideal columns.</param> private void GeneratePNN(int inputColumns, int outputColumns) { var arch = new StringBuilder(); arch.Append("?->"); if (_goal == AnalystGoal.Classification) { arch.Append("C"); } else { arch.Append("R"); } arch.Append("(kernel=gaussian)->"); arch.Append(_targetField.Classes.Count); _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypePNN); _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, arch.ToString()); _script.Properties.SetProperty(ScriptProperties.MlTrainType, MLTrainFactory.TypePNN); _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate filenames. /// </summary> /// <param name="rawFile">The raw filename.</param> private void GenerateFilenames(FileInfo rawFile) { if (_preprocess) { _filenameProcess = FileUtil.AddFilenameBase(rawFile, "_process").Name; } _filenameRaw = rawFile.Name; _filenameNorm = FileUtil.AddFilenameBase(rawFile, "_norm").Name; _filenameRandom = FileUtil.AddFilenameBase(rawFile, "_random").Name; _filenameTrain = FileUtil.AddFilenameBase(rawFile, "_train").Name; _filenameEval = FileUtil.AddFilenameBase(rawFile, "_eval").Name; _filenameEvalNorm = FileUtil.AddFilenameBase(rawFile, "_eval_norm").Name; _filenameTrainSet = FileUtil.ForceExtension(_filenameTrain, "egb"); _filenameMl = FileUtil.ForceExtension(_filenameTrain, "eg"); _filenameOutput = FileUtil.AddFilenameBase(rawFile, "_output").Name; _filenameBalance = FileUtil.AddFilenameBase(rawFile, "_balance").Name; _filenameCluster = FileUtil.AddFilenameBase(rawFile, "_cluster").Name; _filenameCode = FileUtil.ForceExtension( FileUtil.AddFilenameBase(rawFile, "_code").Name, EncogCodeGeneration.GetExtension(_codeTargetLanguage)); ScriptProperties p = _script.Properties; p.SetFilename(FileRaw, _filenameRaw); if (_taskNormalize) { p.SetFilename(FileNormalize, _filenameNorm); } if (_taskRandomize) { p.SetFilename(FileRandom, _filenameRandom); } if (_taskCluster) { p.SetFilename(FileCluster, _filenameCluster); } if (_taskSegregate) { p.SetFilename(FileTrain, _filenameTrain); p.SetFilename(FileEval, _filenameEval); p.SetFilename(FileEvalNorm, _filenameEvalNorm); } if (_taskBalance) { p.SetFilename(FileBalance, _filenameBalance); } if (_codeTargetLanguage != TargetLanguage.NoGeneration) { p.SetFilename(FileCode, _filenameCode); } p.SetFilename(FileTrainset, _filenameTrainSet); p.SetFilename(FileMl, _filenameMl); p.SetFilename(FileOutput, _filenameOutput); } /// <summary> /// Generate the generate task. /// </summary> private void GenerateGenerate() { DetermineTargetField(); if (_targetField == null) { throw new AnalystError( "Failed to find normalized version of target field: " + _targetField); } int inputColumns = _script.Normalize .CalculateInputColumns(); int idealColumns = _script.Normalize .CalculateOutputColumns(); switch (_methodType) { case WizardMethodType.FeedForward: GenerateFeedForward(inputColumns); break; case WizardMethodType.SVM: GenerateSVM(); break; case WizardMethodType.RBF: GenerateRBF(inputColumns, idealColumns); break; case WizardMethodType.SOM: GenerateSOM(); break; case WizardMethodType.PNN: GeneratePNN(inputColumns, idealColumns); break; case WizardMethodType.BayesianNetwork: GenerateBayesian(inputColumns, idealColumns); break; case WizardMethodType.NEAT: GenerateNEAT(inputColumns, idealColumns); break; case WizardMethodType.EPL: generateEPL(inputColumns, idealColumns); break; default: throw new AnalystError("Unknown method type"); } } /// <summary> /// Generate the normalized fields. /// </summary> private void GenerateNormalizedFields() { IList<AnalystField> norm = _script.Normalize.NormalizedFields; norm.Clear(); DataField[] dataFields = _script.Fields; for (int i = 0; i < _script.Fields.Length; i++) { DataField f = dataFields[i]; NormalizationAction action; bool isLast = i == _script.Fields.Length - 1; if (_methodType == WizardMethodType.BayesianNetwork) { AnalystField af; if (f.Class) { af = new AnalystField(f.Name, NormalizationAction.SingleField, 0, 0); } else { af = new AnalystField(f.Name, NormalizationAction.PassThrough, 0, 0); } norm.Add(af); } else if ((f.Integer || f.Real) && !f.Class) { action = NormalizationAction.Normalize; AnalystField af = _range == NormalizeRange.NegOne2One ? new AnalystField(f.Name, action, 1, -1) : new AnalystField(f.Name, action, 1, 0); norm.Add(af); af.ActualHigh = f.Max; af.ActualLow = f.Min; } else if (f.Class) { if (isLast && _directClassification) { action = NormalizationAction.SingleField; } else if (f.ClassMembers.Count > 2) { action = NormalizationAction.Equilateral; } else { action = NormalizationAction.OneOf; } norm.Add(_range == NormalizeRange.NegOne2One ? new AnalystField(f.Name, action, 1, -1) : new AnalystField(f.Name, action, 1, 0)); } else { action = NormalizationAction.Ignore; norm.Add(new AnalystField(action, f.Name)); } } _script.Normalize.Init(_script); } /// <summary> /// Generate a RBF machine learning method. /// </summary> /// <param name="inputColumns">The number of input columns.</param> /// <param name="outputColumns">The number of output columns.</param> private void GenerateRBF(int inputColumns, int outputColumns) { var hidden = (int) ((inputColumns)*1.5d); _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeRbfnetwork); _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, "?->GAUSSIAN(c=" + hidden + ")->?"); _script.Properties.SetProperty( ScriptProperties.MlTrainType, outputColumns > 1 ? "rprop" : "svd"); _script.Properties.SetProperty(ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate the segregate task. /// </summary> private void GenerateSegregate() { if (_taskSegregate) { var array = new AnalystSegregateTarget[2]; array[0] = new AnalystSegregateTarget(FileTrain, DefaultTrainPercent); array[1] = new AnalystSegregateTarget(FileEval, DefaultEvalPercent); _script.Segregate.SegregateTargets = array; } else { var array = new AnalystSegregateTarget[0]; _script.Segregate.SegregateTargets = array; } } /// <summary> /// Generate the settings. /// </summary> private void GenerateSettings() { // starting point string target = FileRaw; _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceRawFile, target); // randomize if (!_timeSeries && _taskRandomize) { _script.Properties.SetProperty( ScriptProperties.RandomizeConfigSourceFile, FileRaw); target = FileRandom; _script.Properties.SetProperty( ScriptProperties.RandomizeConfigTargetFile, target); } // balance if (!_timeSeries && _taskBalance) { _script.Properties.SetProperty( ScriptProperties.BalanceConfigSourceFile, target); target = FileBalance; _script.Properties.SetProperty( ScriptProperties.BalanceConfigTargetFile, target); } // segregate if (_taskSegregate) { _script.Properties.SetProperty( ScriptProperties.SegregateConfigSourceFile, target); target = FileTrain; } // normalize if (_taskNormalize) { _script.Properties.SetProperty( ScriptProperties.NormalizeConfigSourceFile, target); target = FileNormalize; _script.Properties.SetProperty( ScriptProperties.NormalizeConfigTargetFile, target); _script.Normalize.MissingValues = _missing; } string evalSource = _taskSegregate ? FileEval : target; // cluster if (_taskCluster) { _script.Properties.SetProperty( ScriptProperties.ClusterConfigSourceFile, evalSource); _script.Properties.SetProperty( ScriptProperties.ClusterConfigTargetFile, FileCluster); _script.Properties.SetProperty( ScriptProperties.ClusterConfigType, "kmeans"); } // generate _script.Properties.SetProperty( ScriptProperties.GenerateConfigSourceFile, target); _script.Properties.SetProperty( ScriptProperties.GenerateConfigTargetFile, FileTrainset); // ML _script.Properties.SetProperty( ScriptProperties.MlConfigTrainingFile, FileTrainset); _script.Properties.SetProperty( ScriptProperties.MlConfigMachineLearningFile, FileMl); _script.Properties.SetProperty( ScriptProperties.MlConfigOutputFile, FileOutput); _script.Properties.SetProperty( ScriptProperties.MlConfigEvalFile, evalSource); // other _script.Properties.SetProperty( ScriptProperties.SetupConfigCSVFormat, _format); } /// <summary> /// Generate a SOM machine learning method. /// </summary> private void GenerateSOM() { _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeSOM); _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, "?->" + _targetField.Classes.Count); _script.Properties.SetProperty(ScriptProperties.MlTrainType, MLTrainFactory.TypeSOMNeighborhood); _script.Properties.SetProperty( ScriptProperties.MlTrainArguments, "ITERATIONS=1000,NEIGHBORHOOD=rbf1d,RBF_TYPE=gaussian"); // ScriptProperties.ML_TRAIN_arguments _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate a SVM machine learning method. /// </summary> private void GenerateSVM() { var arch = new StringBuilder(); arch.Append("?->"); arch.Append(_goal == AnalystGoal.Classification ? "C" : "R"); arch.Append("(type=new,kernel=rbf)->?"); _script.Properties.SetProperty( ScriptProperties.MlConfigType, MLMethodFactory.TypeSVM); _script.Properties.SetProperty( ScriptProperties.MlConfigArchitecture, arch.ToString()); _script.Properties.SetProperty(ScriptProperties.MlTrainType, MLTrainFactory.TypeSVMSearch); _script.Properties.SetProperty( ScriptProperties.MlTrainTargetError, MaxError); } /// <summary> /// Generate the tasks. /// </summary> private void GenerateTasks() { var task1 = new AnalystTask(EncogAnalyst.TaskFull); if (!_timeSeries && _taskRandomize) { task1.Lines.Add("randomize"); } if (!_timeSeries && _taskBalance) { task1.Lines.Add("balance"); } if (_taskSegregate) { task1.Lines.Add("segregate"); } if (_taskNormalize) { task1.Lines.Add("normalize"); } task1.Lines.Add("generate"); task1.Lines.Add("create"); task1.Lines.Add("train"); task1.Lines.Add("evaluate"); if (_codeTargetLanguage != TargetLanguage.NoGeneration) { task1.Lines.Add("code"); } var task2 = new AnalystTask("task-generate"); if (!_timeSeries && _taskRandomize) { task2.Lines.Add("randomize"); } if (_taskSegregate) { task2.Lines.Add("segregate"); } if (_taskNormalize) { task2.Lines.Add("normalize"); } task2.Lines.Add("generate"); var task3 = new AnalystTask("task-evaluate-raw"); task3.Lines.Add(CreateSet(ScriptProperties.MlConfigEvalFile, FileEvalNorm)); task3.Lines.Add(CreateSet(ScriptProperties.NormalizeConfigSourceFile, FileEval)); task3.Lines.Add(CreateSet(ScriptProperties.NormalizeConfigTargetFile, FileEvalNorm)); task3.Lines.Add("normalize"); task3.Lines.Add("evaluate-raw"); var task4 = new AnalystTask("task-create"); task4.Lines.Add("create"); var task5 = new AnalystTask("task-train"); task5.Lines.Add("train"); var task6 = new AnalystTask("task-evaluate"); task6.Lines.Add("evaluate"); var task7 = new AnalystTask("task-cluster"); task7.Lines.Add("cluster"); var task8 = new AnalystTask("task-code"); task8.Lines.Add("code"); AnalystTask task9 = null; if (_preprocess) { task9 = new AnalystTask("task-preprocess"); task9.Lines.Add("process"); } _script.AddTask(task1); _script.AddTask(task2); _script.AddTask(task3); _script.AddTask(task4); _script.AddTask(task5); _script.AddTask(task6); _script.AddTask(task7); _script.AddTask(task8); if (task9 != null) { _script.AddTask(task9); } } /// <summary> /// Reanalyze column ranges. /// </summary> public void Reanalyze() { String rawID = _script.Properties.GetPropertyFile( ScriptProperties.HeaderDatasourceRawFile); FileInfo rawFilename = _analyst.Script .ResolveFilename(rawID); _analyst.Analyze( rawFilename, _script.Properties.GetPropertyBoolean( ScriptProperties.SetupConfigInputHeaders), _script.Properties.GetPropertyFormat( ScriptProperties.SetupConfigCSVFormat)); } /// <summary> /// Analyze a file. /// </summary> /// <param name="analyzeFile">The file to analyze.</param> /// <param name="b">True if there are headers.</param> /// <param name="format">The file format.</param> public void Wizard(FileInfo analyzeFile, bool b, AnalystFileFormat format) { _script.BasePath = analyzeFile.DirectoryName; _format = format; _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceSourceHeaders, b); _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceRawFile, analyzeFile); _timeSeries = ((_lagWindowSize > 0) || (_leadWindowSize > 0)); DetermineClassification(); GenerateFilenames(analyzeFile); GenerateSettings(); _analyst.Analyze(analyzeFile, b, format); GenerateNormalizedFields(); GenerateSegregate(); GenerateGenerate(); GenerateTasks(); if (_timeSeries && (_lagWindowSize > 0) && (_leadWindowSize > 0)) { ExpandTimeSlices(); } } /// <summary> /// Analyze a file at the specified URL. /// </summary> /// <param name="url">The URL to analyze.</param> /// <param name="saveFile">The save file.</param> /// <param name="analyzeFile">The Encog analyst file.</param> /// <param name="b">True if there are headers.</param> /// <param name="format">The file format.</param> public void Wizard(Uri url, FileInfo saveFile, FileInfo analyzeFile, bool b, AnalystFileFormat format) { _script.BasePath = saveFile.DirectoryName; _format = format; _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceSourceFile, url); _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceSourceHeaders, b); _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceRawFile, analyzeFile); GenerateFilenames(analyzeFile); GenerateSettings(); _analyst.Download(); Wizard(analyzeFile, b, format); } public void WizardRealTime(IList<SourceElement> sourceData, FileInfo csvFile, int backwardWindow, int forwardWindow, PredictionType prediction, String predictField) { Preprocess = true; _script.BasePath = csvFile.DirectoryName; _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceSourceHeaders, true); _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceRawFile, csvFile); _script.Properties.SetProperty( ScriptProperties.SetupConfigInputHeaders, true); LagWindowSize = backwardWindow; LeadWindowSize = 1; _timeSeries = true; _format = AnalystFileFormat.DecpntComma; MethodType = WizardMethodType.FeedForward; _includeTargetField = false; TargetFieldName = "prediction"; Missing = new DiscardMissing(); Goal = AnalystGoal.Regression; Range = NormalizeRange.NegOne2One; TaskNormalize = true; TaskRandomize = false; TaskSegregate = true; TaskBalance = false; TaskCluster = false; MaxError = 0.05; CodeEmbedData = true; DetermineClassification(); GenerateFilenames(csvFile); GenerateSettings(); GenerateSourceData(sourceData); GenerateNormalizedFields(); // if there is a time field, then ignore it AnalystField timeField = _script.FindAnalystField("time"); if (timeField != null) { timeField.Action = NormalizationAction.Ignore; } GenerateSegregate(); GenerateGenerate(); GenerateProcess(backwardWindow, forwardWindow, prediction, predictField); GenerateCode(); // override raw_file to be the processed file _script.Properties.SetProperty( ScriptProperties.HeaderDatasourceRawFile, FilePre); GenerateTasks(); if (_timeSeries && (_lagWindowSize > 0) && (_leadWindowSize > 0)) { ExpandTimeSlices(); } } private void GenerateSourceData(IList<SourceElement> sourceData) { var fields = new DataField[sourceData.Count + 1]; int index = 0; foreach (SourceElement element in sourceData) { var df = new DataField(element.Name); df.Source = element.Source; df.Integer = false; df.Class = false; df.Max = 100000; df.Mean = 0; df.Min = -100000; df.StandardDeviation = 0; fields[index++] = df; } // now add the prediction var df2 = new DataField("prediction"); df2.Source = "prediction"; df2.Integer = false; df2.Class = false; df2.Max = 100000; df2.Min = -100000; df2.Mean = 0; df2.StandardDeviation = 0; fields[index++] = df2; _script.Fields = fields; } private void GenerateProcess(int backwardWindow, int forwardWindow, PredictionType prediction, String predictField) { _script.Properties.SetProperty( ScriptProperties.PROCESS_CONFIG_BACKWARD_SIZE, backwardWindow); _script.Properties.SetProperty( ScriptProperties.PROCESS_CONFIG_FORWARD_SIZE, forwardWindow); IList<ProcessField> fields = _script.Process.Fields; fields.Clear(); foreach (DataField df in _script.Fields) { if (string.Compare(df.Name, "prediction", true) == 0) { continue; } var command = new StringBuilder(); if (string.Compare(df.Name, "time", true) == 0) { command.Append("cint(field(\""); command.Append(df.Name); command.Append("\",0"); command.Append("))"); fields.Add(new ProcessField(df.Name, command.ToString())); } else { command.Append("cfloat(field(\""); command.Append(df.Name); command.Append("\",0"); command.Append("))"); fields.Add(new ProcessField(df.Name, command.ToString())); } } var c = new StringBuilder(); switch (prediction) { case PredictionType.fieldmax: c.Append("fieldmax(\""); c.Append(predictField); c.Append("\","); c.Append(-forwardWindow); c.Append(","); c.Append(-1); c.Append(")"); break; case PredictionType.fieldmaxpip: c.Append("fieldmaxpip(\""); c.Append(predictField); c.Append("\","); c.Append(-forwardWindow); c.Append(","); c.Append(-1); c.Append(")"); break; } fields.Add(new ProcessField("prediction", c.ToString())); } private void GenerateCode() { _script.Properties.SetProperty( ScriptProperties.CODE_CONFIG_EMBED_DATA, _codeEmbedData); _script.Properties.SetProperty( ScriptProperties.CODE_CONFIG_TARGET_LANGUAGE, _codeTargetLanguage); _script.Properties.SetProperty( ScriptProperties.CODE_CONFIG_TARGET_FILE, FileCode); } } }
// Inflater.cs // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 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. using System; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// Inflater is used to decompress data that has been compressed according /// to the "deflate" standard described in rfc1950. /// /// The usage is as following. First you have to set some input with /// <code>setInput()</code>, then inflate() it. If inflate doesn't /// inflate any bytes there may be three reasons: /// <ul> /// <li>needsInput() returns true because the input buffer is empty. /// You have to provide more input with <code>setInput()</code>. /// NOTE: needsInput() also returns true when, the stream is finished. /// </li> /// <li>needsDictionary() returns true, you have to provide a preset /// dictionary with <code>setDictionary()</code>.</li> /// <li>finished() returns true, the inflater has finished.</li> /// </ul> /// Once the first output byte is produced, a dictionary will not be /// needed at a later stage. /// /// author of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class Inflater { /// <summary> /// Copy lengths for literal codes 257..285 /// </summary> private static int[] CPLENS = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; /// <summary> /// Extra bits for literal codes 257..285 /// </summary> private static int[] CPLEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; /// <summary> /// Copy offsets for distance codes 0..29 /// </summary> private static int[] CPDIST = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; /// <summary> /// Extra bits for distance codes /// </summary> private static int[] CPDEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; /// <summary> /// This are the state in which the inflater can be. /// </summary> private const int DECODE_HEADER = 0; private const int DECODE_DICT = 1; private const int DECODE_BLOCKS = 2; private const int DECODE_STORED_LEN1 = 3; private const int DECODE_STORED_LEN2 = 4; private const int DECODE_STORED = 5; private const int DECODE_DYN_HEADER = 6; private const int DECODE_HUFFMAN = 7; private const int DECODE_HUFFMAN_LENBITS = 8; private const int DECODE_HUFFMAN_DIST = 9; private const int DECODE_HUFFMAN_DISTBITS = 10; private const int DECODE_CHKSUM = 11; private const int FINISHED = 12; /// <summary> /// This variable contains the current state. /// </summary> private int mode; /// <summary> /// The adler checksum of the dictionary or of the decompressed /// stream, as it is written in the header resp. footer of the /// compressed stream. /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM. /// </summary> private int readAdler; /// <summary> /// The number of bits needed to complete the current state. This /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM, /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS. /// </summary> private int neededBits; private int repLength, repDist; private int uncomprLen; /// <summary> /// True, if the last block flag was set in the last block of the /// inflated stream. This means that the stream ends after the /// current block. /// </summary> private bool isLastBlock; /// <summary> /// The total number of inflated bytes. /// </summary> private int totalOut; /// <summary> /// The total number of bytes set with setInput(). This is not the /// value returned by getTotalIn(), since this also includes the /// unprocessed input. /// </summary> private int totalIn; /// <summary> /// This variable stores the nowrap flag that was given to the constructor. /// True means, that the inflated stream doesn't contain a header nor the /// checksum in the footer. /// </summary> private bool nowrap; private StreamManipulator input; private OutputWindow outputWindow; private InflaterDynHeader dynHeader; private InflaterHuffmanTree litlenTree, distTree; private Adler32 adler; /// <summary> /// Creates a new inflater. /// </summary> public Inflater() : this(false) { } /// <summary> /// Creates a new inflater. /// </summary> /// <param name="nowrap"> /// true if no header and checksum field appears in the /// stream. This is used for GZIPed input. For compatibility with /// Sun JDK you should provide one byte of input more than needed in /// this case. /// </param> public Inflater(bool nowrap) { this.nowrap = nowrap; this.adler = new Adler32(); input = new StreamManipulator(); outputWindow = new OutputWindow(); mode = nowrap ? DECODE_BLOCKS : DECODE_HEADER; } /// <summary> /// Resets the inflater so that a new stream can be decompressed. All /// pending input and output will be discarded. /// </summary> public void Reset() { mode = nowrap ? DECODE_BLOCKS : DECODE_HEADER; totalIn = totalOut = 0; input.Reset(); outputWindow.Reset(); dynHeader = null; litlenTree = null; distTree = null; isLastBlock = false; adler.Reset(); } /// <summary> /// Decodes the deflate header. /// </summary> /// <returns> /// false if more input is needed. /// </returns> /// <exception cref="System.FormatException"> /// if header is invalid. /// </exception> private bool DecodeHeader() { int header = input.PeekBits(16); if (header < 0) { return false; } input.DropBits(16); /* The header is written in "wrong" byte order */ header = ((header << 8) | (header >> 8)) & 0xffff; if (header % 31 != 0) { throw new FormatException("Header checksum illegal"); } if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) { throw new FormatException("Compression Method unknown"); } /* Maximum size of the backwards window in bits. * We currently ignore this, but we could use it to make the * inflater window more space efficient. On the other hand the * full window (15 bits) is needed most times, anyway. int max_wbits = ((header & 0x7000) >> 12) + 8; */ if ((header & 0x0020) == 0) { // Dictionary flag? mode = DECODE_BLOCKS; } else { mode = DECODE_DICT; neededBits = 32; } return true; } /// <summary> /// Decodes the dictionary checksum after the deflate header. /// </summary> /// <returns> /// false if more input is needed. /// </returns> private bool DecodeDict() { while (neededBits > 0) { int dictByte = input.PeekBits(8); if (dictByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | dictByte; neededBits -= 8; } return false; } /// <summary> /// Decodes the huffman encoded symbols in the input stream. /// </summary> /// <returns> /// false if more input is needed, true if output window is /// full or the current block ends. /// </returns> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> private bool DecodeHuffman() { int free = outputWindow.GetFreeSpace(); while (free >= 258) { int symbol; switch (mode) { case DECODE_HUFFMAN: /* This is the inner loop so it is optimized a bit */ while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) { outputWindow.Write(symbol); if (--free < 258) { return true; } } if (symbol < 257) { if (symbol < 0) { return false; } else { /* symbol == 256: end of block */ distTree = null; litlenTree = null; mode = DECODE_BLOCKS; return true; } } try { repLength = CPLENS[symbol - 257]; neededBits = CPLEXT[symbol - 257]; } catch (Exception) { throw new FormatException("Illegal rep length code"); } goto case DECODE_HUFFMAN_LENBITS;/* fall through */ case DECODE_HUFFMAN_LENBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_LENBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repLength += i; } mode = DECODE_HUFFMAN_DIST; goto case DECODE_HUFFMAN_DIST;/* fall through */ case DECODE_HUFFMAN_DIST: symbol = distTree.GetSymbol(input); if (symbol < 0) { return false; } try { repDist = CPDIST[symbol]; neededBits = CPDEXT[symbol]; } catch (Exception) { throw new FormatException("Illegal rep dist code"); } goto case DECODE_HUFFMAN_DISTBITS;/* fall through */ case DECODE_HUFFMAN_DISTBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_DISTBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repDist += i; } outputWindow.Repeat(repLength, repDist); free -= repLength; mode = DECODE_HUFFMAN; break; default: throw new FormatException(); } } return true; } /// <summary> /// Decodes the adler checksum after the deflate stream. /// </summary> /// <returns> /// false if more input is needed. /// </returns> /// <exception cref="System.FormatException"> /// DataFormatException, if checksum doesn't match. /// </exception> private bool DecodeChksum() { while (neededBits > 0) { int chkByte = input.PeekBits(8); if (chkByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | chkByte; neededBits -= 8; } if ((int) adler.Value != readAdler) { throw new FormatException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler); } mode = FINISHED; return false; } /// <summary> /// Decodes the deflated stream. /// </summary> /// <returns> /// false if more input is needed, or if finished. /// </returns> /// <exception cref="System.FormatException"> /// DataFormatException, if deflated stream is invalid. /// </exception> private bool Decode() { switch (mode) { case DECODE_HEADER: return DecodeHeader(); case DECODE_DICT: return DecodeDict(); case DECODE_CHKSUM: return DecodeChksum(); case DECODE_BLOCKS: if (isLastBlock) { if (nowrap) { mode = FINISHED; return false; } else { input.SkipToByteBoundary(); neededBits = 32; mode = DECODE_CHKSUM; return true; } } int type = input.PeekBits(3); if (type < 0) { return false; } input.DropBits(3); if ((type & 1) != 0) { isLastBlock = true; } switch (type >> 1) { case DeflaterConstants.STORED_BLOCK: input.SkipToByteBoundary(); mode = DECODE_STORED_LEN1; break; case DeflaterConstants.STATIC_TREES: litlenTree = InflaterHuffmanTree.defLitLenTree; distTree = InflaterHuffmanTree.defDistTree; mode = DECODE_HUFFMAN; break; case DeflaterConstants.DYN_TREES: dynHeader = new InflaterDynHeader(); mode = DECODE_DYN_HEADER; break; default: throw new FormatException("Unknown block type "+type); } return true; case DECODE_STORED_LEN1: { if ((uncomprLen = input.PeekBits(16)) < 0) { return false; } input.DropBits(16); mode = DECODE_STORED_LEN2; } goto case DECODE_STORED_LEN2; /* fall through */ case DECODE_STORED_LEN2: { int nlen = input.PeekBits(16); if (nlen < 0) { return false; } input.DropBits(16); if (nlen != (uncomprLen ^ 0xffff)) { throw new FormatException("broken uncompressed block"); } mode = DECODE_STORED; } goto case DECODE_STORED;/* fall through */ case DECODE_STORED: { int more = outputWindow.CopyStored(input, uncomprLen); uncomprLen -= more; if (uncomprLen == 0) { mode = DECODE_BLOCKS; return true; } return !input.IsNeedingInput; } case DECODE_DYN_HEADER: if (!dynHeader.Decode(input)) { return false; } litlenTree = dynHeader.BuildLitLenTree(); distTree = dynHeader.BuildDistTree(); mode = DECODE_HUFFMAN; goto case DECODE_HUFFMAN; /* fall through */ case DECODE_HUFFMAN: case DECODE_HUFFMAN_LENBITS: case DECODE_HUFFMAN_DIST: case DECODE_HUFFMAN_DISTBITS: return DecodeHuffman(); case FINISHED: return false; default: throw new FormatException(); } } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if no dictionary is needed. /// </exception> /// <exception cref="System.ArgumentException"> /// if the dictionary checksum is wrong. /// </exception> public void SetDictionary(byte[] buffer) { SetDictionary(buffer, 0, buffer.Length); } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// the dictionary. /// </param> /// <param name="off"> /// the offset into buffer where the dictionary starts. /// </param> /// <param name="len"> /// the length of the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if no dictionary is needed. /// </exception> /// <exception cref="System.ArgumentException"> /// if the dictionary checksum is wrong. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// if the off and/or len are wrong. /// </exception> public void SetDictionary(byte[] buffer, int off, int len) { if (!IsNeedingDictionary) { throw new InvalidOperationException(); } adler.Update(buffer, off, len); if ((int) adler.Value != readAdler) { throw new ArgumentException("Wrong adler checksum"); } adler.Reset(); outputWindow.CopyDict(buffer, off, len); mode = DECODE_BLOCKS; } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buf"> /// the input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if no input is needed. /// </exception> public void SetInput(byte[] buf) { SetInput(buf, 0, buf.Length); } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buf"> /// the input. /// </param> /// <param name="off"> /// the offset into buffer where the input starts. /// </param> /// <param name="len"> /// the length of the input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if no input is needed. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// if the off and/or len are wrong. /// </exception> public void SetInput(byte[] buf, int off, int len) { input.SetInput(buf, off, len); totalIn += len; } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether needsDictionary(), /// needsInput() or finished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name = "buf"> /// the output buffer. /// </param> /// <returns> /// the number of bytes written to the buffer, 0 if no further /// output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if buf has length 0. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buf) { return Inflate(buf, 0, buf.Length); } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether needsDictionary(), /// needsInput() or finished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name = "buf"> /// the output buffer. /// </param> /// <param name = "off"> /// the offset into buffer where the output should start. /// </param> /// <param name = "len"> /// the maximum length of the output. /// </param> /// <returns> /// the number of bytes written to the buffer, 0 if no further output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if len is &lt;= 0. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// if the off and/or len are wrong. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buf, int off, int len) { if (len < 0) { throw new ArgumentOutOfRangeException("len < 0"); } // Special case: len may be zero if (len == 0) { return 0; } /* // Check for correct buff, off, len triple if (off < 0 || off + len >= buf.Length) { throw new ArgumentException("off/len outside buf bounds"); }*/ int count = 0; int more; do { if (mode != DECODE_CHKSUM) { /* Don't give away any output, if we are waiting for the * checksum in the input stream. * * With this trick we have always: * needsInput() and not finished() * implies more output can be produced. */ more = outputWindow.CopyOutput(buf, off, len); adler.Update(buf, off, more); off += more; count += more; totalOut += more; len -= more; if (len == 0) { return count; } } } while (Decode() || (outputWindow.GetAvailable() > 0 && mode != DECODE_CHKSUM)); return count; } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method also returns true when the stream is finished. /// </summary> public bool IsNeedingInput { get { return input.IsNeedingInput; } } /// <summary> /// Returns true, if a preset dictionary is needed to inflate the input. /// </summary> public bool IsNeedingDictionary { get { return mode == DECODE_DICT && neededBits == 0; } } /// <summary> /// Returns true, if the inflater has finished. This means, that no /// input is needed and no output can be produced. /// </summary> public bool IsFinished { get { return mode == FINISHED && outputWindow.GetAvailable() == 0; } } /// <summary> /// Gets the adler checksum. This is either the checksum of all /// uncompressed bytes returned by inflate(), or if needsDictionary() /// returns true (and thus no output was yet produced) this is the /// adler checksum of the expected dictionary. /// </summary> /// <returns> /// the adler checksum. /// </returns> public int Adler { get { return IsNeedingDictionary ? readAdler : (int) adler.Value; } } /// <summary> /// Gets the total number of output bytes returned by inflate(). /// </summary> /// <returns> /// the total number of output bytes. /// </returns> public int TotalOut { get { return totalOut; } } /// <summary> /// Gets the total number of processed compressed input bytes. /// </summary> /// <returns> /// the total number of bytes of processed input bytes. /// </returns> public int TotalIn { get { return totalIn - RemainingInput; } } /// <summary> /// Gets the number of unprocessed input. Useful, if the end of the /// stream is reached and you want to further process the bytes after /// the deflate stream. /// </summary> /// <returns> /// the number of bytes of the input which were not processed. /// </returns> public int RemainingInput { get { return input.AvailableBytes; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; namespace System.IO { public sealed partial class DirectoryInfo : FileSystemInfo { [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path; FullPath = PathHelpers.GetFullPathInternal(path); DisplayPath = GetDisplayName(OriginalPath, FullPath); } [System.Security.SecuritySafeCritical] internal DirectoryInfo(String fullPath, String originalPath) { Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = originalPath ?? Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } public override String Name { get { // DisplayPath is dir name for coreclr Debug.Assert(GetDirName(FullPath) == DisplayPath || DisplayPath == "."); return DisplayPath; } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { string s = FullPath; // FullPath might end in either "parent\child" or "parent\child", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. if (!PathHelpers.IsRoot(s)) { s = PathHelpers.TrimEndingDirectorySeparator(s); } string parentName = Path.GetDirectoryName(s); return parentName != null ? new DirectoryInfo(parentName, null) : null; } } [System.Security.SecuritySafeCritical] public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path); } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path) { Contract.Requires(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); String newDirs = Path.Combine(FullPath, path); String fullPath = Path.GetFullPath(newDirs); if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.GetComparison())) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), "path"); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } [System.Security.SecurityCritical] public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). [SecurityCritical] public FileInfo[] GetFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); return EnumerableHelpers.ToArray(enumerable); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { String rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(String destDirName) { if (destDirName == null) throw new ArgumentNullException("destDirName"); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName"); Contract.EndContractBlock(); String fullDestDirName = PathHelpers.GetFullPathInternal(destDirName); if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar) fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString; String fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; if (PathInternal.IsDirectoryTooLong(fullSourcePath)) throw new PathTooLongException(SR.IO_PathTooLong); if (PathInternal.IsDirectoryTooLong(fullDestDirName)) throw new PathTooLongException(SR.IO_PathTooLong); StringComparison pathComparison = PathInternal.GetComparison(); if (String.Equals(fullSourcePath, fullDestDirName, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (!String.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); FileSystem.Current.MoveDirectory(FullPath, fullDestDirName); FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); // Flush any cached information about the directory. Invalidate(); } [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } // Returns the fully qualified path public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath, String fullPath) { Debug.Assert(originalPath != null); Debug.Assert(fullPath != null); return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ? "." : GetDirName(fullPath); } private static String GetDirName(String fullPath) { Debug.Assert(fullPath != null); return PathHelpers.IsRoot(fullPath) ? fullPath : Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath)); } } }
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; namespace FluentAssert { [DebuggerNonUserCode] [DebuggerStepThrough] public class TestWhenClause<T> { private readonly T _actionContainer; private readonly IWhenActionWrapper _actionUnderTest; private readonly IList<IParameterActionWrapper> _parameterActions = new List<IParameterActionWrapper>(); internal TestWhenClause(T actionContainer, IWhenActionWrapper actionUnderTest) { _actionContainer = actionContainer; _actionUnderTest = actionUnderTest; } public TestExpectClause<T> Expect(Action dependencyAction) { return new TestExpectClause<T>(_actionContainer, _actionUnderTest, _parameterActions) .Expect(dependencyAction); } public TestShouldClause<T> Should(Action<T> assertion) { return new TestShouldClause<T>(_actionContainer, _actionUnderTest, _parameterActions) .Should(assertion); } public TestShouldClause<T> Should(Action assertion) { return new TestShouldClause<T>(_actionContainer, _actionUnderTest, _parameterActions) .Should(assertion); } public TestShouldClause<T> ShouldThrowException<TExceptionType>() where TExceptionType : Exception { return new TestShouldClause<T>(_actionContainer, _actionUnderTest, _parameterActions) .ShouldThrowException<TExceptionType>(); } public TestShouldClause<T> ShouldThrowException<TExceptionType>(string message) where TExceptionType : Exception { return new TestShouldClause<T>(_actionContainer, _actionUnderTest, _parameterActions) .ShouldThrowException<TExceptionType>(message); } public TestWhenClause<T> With(Action<T> parameterAction) { _parameterActions.Add(new ParameterActionWrapper<T>(_actionContainer, parameterAction)); return this; } public TestWhenClause<T> With(Action parameterAction) { _parameterActions.Add(new ParameterActionWrapper(parameterAction)); return this; } } [DebuggerNonUserCode] [DebuggerStepThrough] public class TestWhenClause<T, TContext> { private readonly T _actionContainer; private readonly IWhenActionWrapper _actionUnderTest; private readonly TContext _context; private readonly IList<IParameterActionWrapper> _parameterActions = new List<IParameterActionWrapper>(); internal TestWhenClause(T actionContainer, IWhenActionWrapper actionUnderTest, TContext context) { _actionContainer = actionContainer; _actionUnderTest = actionUnderTest; _context = context; } public TestExpectClause<T, TContext> Expect(Action dependencyAction) { return new TestExpectClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .Expect(dependencyAction); } public TestShouldClause<T, TContext> Should<TBaseContext>(Action<T, TBaseContext> assertion) where TBaseContext : class { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .Should(assertion); } public TestShouldClause<T, TContext> Should(Action<T, TContext> assertion) { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .Should(assertion); } public TestShouldClause<T, TContext> Should(Action<TContext> assertion) { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .Should(assertion); } public TestShouldClause<T, TContext> Should(Action<T> assertion) { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .Should(assertion); } public TestShouldClause<T, TContext> Should(Action assertion) { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .Should(assertion); } public TestShouldClause<T, TContext> ShouldThrowException<TExceptionType>() where TExceptionType : Exception { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .ShouldThrowException<TExceptionType>(); } public TestShouldClause<T, TContext> ShouldThrowException<TExceptionType>(string message) where TExceptionType : Exception { return new TestShouldClause<T, TContext>(_actionContainer, _actionUnderTest, _parameterActions, _context) .ShouldThrowException<TExceptionType>(message); } public TestWhenClause<T, TContext> With<TBaseContext>(Action<T, TBaseContext> parameterAction) where TBaseContext : class { var baseContext = _context as TBaseContext; if (baseContext == null) { throw new InvalidCastException(typeof(TContext).Name + " must inherit from " + typeof(TBaseContext) + " in order to call " + parameterAction.Method.Name); } _parameterActions.Add(new ParameterActionWrapper<T, TBaseContext>(_actionContainer, baseContext, parameterAction)); return this; } public TestWhenClause<T, TContext> With(Action<T, TContext> parameterAction) { _parameterActions.Add(new ParameterActionWrapper<T, TContext>(_actionContainer, _context, parameterAction)); return this; } public TestWhenClause<T, TContext> With(Action<TContext> parameterAction) { _parameterActions.Add(new ParameterActionWrapper<TContext>(_context, parameterAction)); return this; } public TestWhenClause<T, TContext> With(Action<T> parameterAction) { _parameterActions.Add(new ParameterActionWrapper<T>(_actionContainer, parameterAction)); return this; } public TestWhenClause<T, TContext> With(Action parameterAction) { _parameterActions.Add(new ParameterActionWrapper(parameterAction)); return this; } } }
using System; using System.Globalization; using System.IO; namespace XSerializer { internal class JsonWriter : IDisposable { private readonly TextWriter _primaryWriter; private readonly IJsonSerializeOperationInfo _info; private bool _encryptWrites; private StringWriter _encryptingStringWriter; private TextWriter _currentWriter; public JsonWriter(TextWriter writer, IJsonSerializeOperationInfo info) { _primaryWriter = writer; _currentWriter = _primaryWriter; _info = info; } public bool EncryptWrites { get { return _encryptWrites; } set { if (value == _encryptWrites) { return; } Flush(); _encryptWrites = value; if (_encryptWrites) { // We're starting an encrypt session _encryptingStringWriter = new StringWriter(); _currentWriter = _encryptingStringWriter; } else { var plainText = _encryptingStringWriter.GetStringBuilder().ToString(); _encryptingStringWriter = null; _currentWriter = _primaryWriter; // We're ending an encrypt session - encrypt if a mechanism exists. if (_info.EncryptionMechanism != null) { var encryptedValue = _info.EncryptionMechanism.Encrypt( plainText, _info.EncryptKey, _info.SerializationState); WriteValue(encryptedValue); } else { // No encryption mechanism exists - just write the plain text. _currentWriter.Write(plainText); } } } } public void WriteValue(string value) { if (value == null) { WriteNull(); } else { _currentWriter.Write('"'); _currentWriter.Write(Escape(value)); _currentWriter.Write('"'); } } public void WriteValue(DateTime value) { _currentWriter.Write('"'); _currentWriter.Write(value.ToString("O", CultureInfo.InvariantCulture)); _currentWriter.Write('"'); } public void WriteValue(DateTimeOffset value) { _currentWriter.Write('"'); _currentWriter.Write(value.ToString("O", CultureInfo.InvariantCulture)); _currentWriter.Write('"'); } public void WriteValue(TimeSpan value) { _currentWriter.Write('"'); _currentWriter.Write(value.ToString("c", CultureInfo.InvariantCulture)); _currentWriter.Write('"'); } public void WriteValue(Guid value) { _currentWriter.Write('"'); _currentWriter.Write(value.ToString("D")); _currentWriter.Write('"'); } public void WriteValue(double value) { _currentWriter.Write(value); } public void WriteValue(float value) { _currentWriter.Write(value); } public void WriteValue(decimal value) { _currentWriter.Write(value); } public void WriteValue(int value) { _currentWriter.Write(value); } public void WriteValue(long value) { _currentWriter.Write(value); } public void WriteValue(uint value) { _currentWriter.Write(value); } public void WriteValue(ulong value) { _currentWriter.Write(value); } public void WriteValue(bool value) { _currentWriter.Write(value ? "true" : "false"); } public void WriteNull() { _currentWriter.Write("null"); } public void WriteOpenObject() { _currentWriter.Write('{'); } public void WriteCloseObject() { _currentWriter.Write('}'); } public void WriteNameValueSeparator() { _currentWriter.Write(':'); } public void WriteItemSeparator() { _currentWriter.Write(','); } public void WriteOpenArray() { _currentWriter.Write('['); } public void WriteCloseArray() { _currentWriter.Write(']'); } public void Flush() { _currentWriter.Flush(); } public void Dispose() { // TODO: Something? } private static string Escape(string value) { int flags = 0; // ReSharper disable once ForCanBeConvertedToForeach for (int i = 0; i < value.Length; i++) { switch (value[i]) { case '\\': flags |= 0x01; break; case '"': flags |= 0x02; break; case '/': flags |= 0x04; break; case '\b': flags |= 0x08; break; case '\f': flags |= 0x10; break; case '\n': flags |= 0x20; break; case '\r': flags |= 0x40; break; case '\t': flags |= 0x80; break; } } if (flags == 0) { return value; } if ((flags & 0x01) == 0x01) { value = value.Replace(@"\", @"\\"); } if ((flags & 0x02) == 0x02) { value = value.Replace(@"""", @"\"""); } if ((flags & 0x04) == 0x04) { value = value.Replace("/", @"\/"); } if ((flags & 0x08) == 0x08) { value = value.Replace("\b", @"\b"); } if ((flags & 0x10) == 0x10) { value = value.Replace("\f", @"\f"); } if ((flags & 0x20) == 0x20) { value = value.Replace("\n", @"\n"); } if ((flags & 0x40) == 0x40) { value = value.Replace("\r", @"\r"); } if ((flags & 0x80) == 0x80) { value = value.Replace("\t", @"\t"); } return value; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DeviceRequest. /// </summary> public partial class DeviceRequest : BaseRequest, IDeviceRequest { /// <summary> /// Constructs a new DeviceRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DeviceRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Device using POST. /// </summary> /// <param name="deviceToCreate">The Device to create.</param> /// <returns>The created Device.</returns> public System.Threading.Tasks.Task<Device> CreateAsync(Device deviceToCreate) { return this.CreateAsync(deviceToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Device using POST. /// </summary> /// <param name="deviceToCreate">The Device to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Device.</returns> public async System.Threading.Tasks.Task<Device> CreateAsync(Device deviceToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Device>(deviceToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Device. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Device. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Device>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Device. /// </summary> /// <returns>The Device.</returns> public System.Threading.Tasks.Task<Device> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Device. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Device.</returns> public async System.Threading.Tasks.Task<Device> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Device>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Device using PATCH. /// </summary> /// <param name="deviceToUpdate">The Device to update.</param> /// <returns>The updated Device.</returns> public System.Threading.Tasks.Task<Device> UpdateAsync(Device deviceToUpdate) { return this.UpdateAsync(deviceToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Device using PATCH. /// </summary> /// <param name="deviceToUpdate">The Device to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Device.</returns> public async System.Threading.Tasks.Task<Device> UpdateAsync(Device deviceToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Device>(deviceToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Expand(Expression<Func<Device, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Select(Expression<Func<Device, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="deviceToInitialize">The <see cref="Device"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Device deviceToInitialize) { if (deviceToInitialize != null && deviceToInitialize.AdditionalData != null) { if (deviceToInitialize.RegisteredOwners != null && deviceToInitialize.RegisteredOwners.CurrentPage != null) { deviceToInitialize.RegisteredOwners.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("registeredOwners@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.RegisteredOwners.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (deviceToInitialize.RegisteredUsers != null && deviceToInitialize.RegisteredUsers.CurrentPage != null) { deviceToInitialize.RegisteredUsers.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("registeredUsers@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.RegisteredUsers.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Audio; using Discord.WebSocket; using SagiriBot.Extensions; using SagiriBot.Objects.Databases.Audio; using SagiriBot.Objects.Databases.Settings; using SagiriBot.Objects.Logger; namespace SagiriBot.Objects.Audio { public class AudioPlayer { public event Func<IGuild, string, Exception, Task> Exception; public event Func<IGuild, Severity, string, Task> Log; private readonly IUser _currentUser; private readonly IVoiceChannel _voiceChannel; private readonly IGuild _guild; private readonly List<ISong> _songQueue; private readonly CancellationTokenSource _cancelToken; private readonly BlockingCollection<Task> _importantTasks; private readonly int _blockSize = (int)Math.Round((decimal)1536 / 8 * 10 * 2m); private IUserMessage _lastMessage { get; set; } private ITextChannel _messageChannel { get; set; } private IAudioClient _audioClient; private float _volume { get; set; } private float _currentVolume { get; set; } private ISong _firstSong => _songQueue.ToList().FirstOrDefault(); private PlayerStatus _status { get; set; } = PlayerStatus.Playing; private int _skipThreshold => Math.Max(1, (int)Math.Ceiling((_voiceChannel as SocketVoiceChannel).Users.Count(x => !x.IsBot) * new SettingsContext(_guild.Id).GetSkipThreshold())); private Color _color => new SettingsContext(_guild.Id).GetEmbedColor(); private bool _playExited { get; set; } public AudioPlayer(SocketVoiceChannel voiceChannel, SocketGuild guild, ITextChannel messageChannel, IUser currentUser, float initialVolume) { this._voiceChannel = voiceChannel; this._volume = initialVolume; this._guild = guild; this._currentUser = currentUser; this._cancelToken = new CancellationTokenSource(); this._songQueue = new List<ISong>(); this._importantTasks = new BlockingCollection<Task>(); this._messageChannel = messageChannel as ITextChannel; Task.Run(() => connectAsync()); } public void AddSong(ISong song) => _songQueue.Add(song); public void SetMessageChannel(ITextChannel messageChannel) => _messageChannel = messageChannel; public bool AddSkip(IUser user, out int needed) { needed = 0; if (_firstSong.Skips.Contains(user.Id)) return false; _firstSong.Skips.Add(user.Id); needed = Math.Max(_skipThreshold - _firstSong.Skips.Count, 0); return true; } public void ChangeVolume(float newVolume) { _volume = newVolume; Task.Run(() => changeVolumeSlowly(newVolume)); } public bool ChangeStatus(PlayerStatus status) { if (_status == status) return false; _status = status; return true; } public void Shuffle() { List<ISong> songs = new List<ISong>(_songQueue.Skip(1)); songs.Shuffle(); _songQueue.RemoveRange(1, songs.Count); _songQueue.InsertRange(1, songs); } public void ClearQueue() => _songQueue.RemoveRange(1, _songQueue.Count-1); public void PlaceSongAtTop(ISong song) => _songQueue.Insert(1, song); public PlayerStatus GetStatus() => _status; public IEnumerable<ISong> GetSongQueue() => _songQueue.ToList(); public ISong GetCurrentSong() => _firstSong; public int GetVolume() => (int)Math.Floor(_currentVolume*100); private async Task connectAsync() { try { _audioClient = await _voiceChannel.ConnectAsync(_config => { _config.Connected += _handleConnected; _config.Disconnected += _handleDisconnected; }); } catch (Exception e) { await Exception(_guild, "Error occured while trying to connect", e); } } private async Task disconnectAsync() { try { await _audioClient.StopAsync(); } catch (Exception e) { await Exception(_guild, "Error occured while trying to disconnect", e); } while (_importantTasks.Any(x => !x.IsCompleted)) await Task.Delay(100); } private Task _handleConnected() { Task.Run(() => _play(_cancelToken.Token)); return Task.CompletedTask; } private Task _handleDisconnected(Exception _exception) { Task.Run(() => disconnectAsync().ConfigureAwait(true)); return Task.CompletedTask; } private async Task _enqueueNewSong(BaseSong _song = null) { try { if (_songQueue.Count <= 1) { if (!AutoplaylistManager.DatabaseExists(_guild.Id)) return; using (var _context = new AutoplaylistContext(_guild.Id)) { if (_context.GetCurrentPlaylists().Count() == 0) return; await Log(_guild, Severity.Info, "Trying to queue new song"); _context.Database.EnsureCreated(); var _urls = _context.GetSongUrls().ToArray(); if (_urls.Count() < 1) return; var _url = _urls[new Random().Next(0, _urls.Count()-1)]; var _newSong = new DownloadableSong(_url, _currentUser) as ISongResult; if (!_newSong.Viable) { _context.AgnosticRemoveSong(_url); _context.SaveChanges(); await Log(_guild, Severity.Info, "Could not queue song!"); } else { await (_newSong as ISong).DecodeToFile().ConfigureAwait(true); _songQueue.Add(_newSong as ISong); await Log(_guild, Severity.Info, $"Queued {_newSong.Title}"); } } } else { await _songQueue.Skip(1).First().DecodeToFile().ConfigureAwait(true); } } catch (Exception e) { await Exception(_guild, "Exception occured while trying to enqueue a new song!",e); } } private async Task _play(CancellationToken _token) { do { if (this._songQueue.Count > 0) { AudioOutStream _stream = null; CancellationTokenSource _skipToken = new CancellationTokenSource(); ISong _currentSong = _firstSong; Task _skipManager = null; try { _currentVolume = 0f; _status = PlayerStatus.Playing; _currentSong.Playing = true; try { _skipManager = skipManager(_skipToken.Token); } catch{} _stream = _audioClient.CreatePCMStream(AudioApplication.Music, bufferMillis: 500); if (!_currentSong.Playable && !_currentSong.Decoding) await _currentSong.DecodeToFile(); while (!_currentSong.Playable) await Task.Delay(100); await SendNotification(); _currentSong.NearEnd += _enqueueNewSong; while (_currentSong.File == null) await Task.Delay(100); var _fileStream = _currentSong.File; byte[] _buffer = new byte[_blockSize]; bool _first = true; bool _loweringVolume = false; bool _paused = false; while (true) { if (_token.IsCancellationRequested) break; var _read = await _fileStream.ReadAsync(_buffer, 0, _blockSize); if (_read == 0) break; if (_first) { await Task.Run(() => changeVolumeSlowly(_volume, true).ConfigureAwait(true)); _currentSong.StartTimer(); _first = false; } if (_status == PlayerStatus.Stopped) { if (!_loweringVolume) { _loweringVolume = true; await Task.Run(() => changeVolumeSlowly(0f, true).ConfigureAwait(true)); } if (this._currentVolume < 0.01f) break; } while (_paused && _status == PlayerStatus.Paused && this._currentVolume < 0.01f) await Task.Delay(100); if (_status == PlayerStatus.Paused && !_paused) { await Task.Run(() => changeVolumeSlowly(0f, true).ConfigureAwait(true)); _paused = true; _currentSong.Pause(); } if (_status != PlayerStatus.Paused && _paused) { await Task.Run(() => changeVolumeSlowly(_volume, true).ConfigureAwait(true)); _paused = false; _currentSong.Resume(); } if (_read != _blockSize) await Task.Run(() => changeVolumeSlowly(0f, true).ConfigureAwait(true)); _buffer = AdjustVolume(_buffer, _currentVolume); await _stream.WriteAsync(_buffer, 0, _read); } _fileStream.Close(); _fileStream.Dispose(); _skipToken?.Cancel(); } catch (OperationCanceledException) { } catch (Exception e) { await Exception(_guild, "Error occured while playing", e); } finally { if (_stream != null) { await _stream.FlushAsync(); while (_changingVolume) await Task.Delay(10); _stream?.Clear(); _stream?.Dispose(); _stream = null; } _currentSong.NearEnd -= _enqueueNewSong; await _currentSong?.Dispose(); _songQueue.RemoveAt(0); } } else { await _enqueueNewSong(); await Task.Delay(500); } } while(!_token.IsCancellationRequested); _playExited = true; } private async Task skipManager(CancellationToken _token) { do { if (_firstSong.Skips.Count >= _skipThreshold && (_voiceChannel as SocketVoiceChannel).Users.Where(x => !x.IsBot).Count() > 0) { _status = PlayerStatus.Stopped; } await Task.Delay(1000); } while(!_token.IsCancellationRequested); } private async Task SendNotification() { if (_lastMessage != null) { var messages = await _messageChannel.GetMessagesAsync(_lastMessage.Id, Direction.After).Flatten(); if (messages.Count() > 5) { await _lastMessage.DeleteAsync(); _lastMessage = await _messageChannel.SendMessageAsync("", embed: ConstructNotificationEmbed()); } else if (_lastMessage.Channel.Id != _messageChannel.Id) { try { await _lastMessage.DeleteAsync(); } catch (Exception e) { await Exception(_guild, "Exception occured while trying to delete last message!",e); } _lastMessage = await _messageChannel.SendMessageAsync("", embed: ConstructNotificationEmbed()); } else { try { await _lastMessage.ModifyAsync(x => { x.Embed = ConstructNotificationEmbed(); }); } catch (Exception e) { await Exception(_guild, "Exception occured while trying to modify the last message!",e); try { await _lastMessage.DeleteAsync(); } catch (Exception ein) { await SagiriBot.Logger.LogExceptionAsync(ein); } _lastMessage = await _messageChannel.SendMessageAsync("", embed: ConstructNotificationEmbed()); } } } else { _lastMessage = await _messageChannel.SendMessageAsync("", embed: ConstructNotificationEmbed()); } } private Embed ConstructNotificationEmbed() { var _currentSong = GetCurrentSong(); return new EmbedBuilder() .WithColor(_color) .WithTitle($"Now Playing in {_voiceChannel.Name}") .WithDescription($"[{_currentSong.Title}]({_currentSong.Url})"); } private bool _changingVolume { get; set; } private async Task changeVolumeSlowly(float _targetVolume, bool _important = false) { if (_important) while (_changingVolume) await Task.Delay(100); _changingVolume = true; bool greater; decimal diff; if (_currentVolume > _targetVolume) { diff = (decimal)_currentVolume - (decimal)_targetVolume; greater = false; } else { diff = (decimal)_targetVolume - (decimal)_currentVolume; greater = true; } // This should happen in 1 Second, tops var diff_final = diff / 100m; var count = 0; while (count <= 100) { if (greater) { if (_currentVolume > _targetVolume) { _currentVolume = _targetVolume; break; } _currentVolume += (float)diff_final; } else { if (_currentVolume < _targetVolume) { _currentVolume = _targetVolume; break; } _currentVolume -= (float)diff_final; } count++; await Task.Delay(10); } _currentVolume = _targetVolume; _changingVolume = false; } private unsafe static byte[] AdjustVolume(byte[] audioSamples, float volume) { Contract.Requires(audioSamples != null); Contract.Requires(audioSamples.Length % 2 == 0); Contract.Requires(volume >= 0f && volume <= 1f); Contract.Assert(BitConverter.IsLittleEndian); if (Math.Abs(volume - 1f) < 0.0001f) return audioSamples; // 16-bit precision for the multiplication int volumeFixed = (int)Math.Round(volume * 65536d); int count = audioSamples.Length / 2; fixed (byte* srcBytes = audioSamples) { short* src = (short*)srcBytes; for (int i = count; i != 0; i--, src++) *src = (short)(((*src) * volumeFixed) >> 16); } return audioSamples; } public async Task Dispose() { await Log(_guild, Severity.Normal, "Cancelling the play task..."); _cancelToken.Cancel(); while (!_playExited) await Task.Delay(100); await Log(_guild, Severity.Normal, "Disconnecting..."); await disconnectAsync().ConfigureAwait(true); await Log(_guild, Severity.Normal, "Deleteing last message..."); await _lastMessage.DeleteAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file contains the IDN functions and implementation. // // This allows encoding of non-ASCII domain names in a "punycode" form, // for example: // // \u5B89\u5BA4\u5948\u7F8E\u6075-with-SUPER-MONKEYS // // is encoded as: // // xn---with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n // // Additional options are provided to allow unassigned IDN characters and // to validate according to the Std3ASCII Rules (like DNS names). // // There are also rules regarding bidirectionality of text and the length // of segments. // // For additional rules see also: // RFC 3490 - Internationalizing Domain Names in Applications (IDNA) // RFC 3491 - Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN) // RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA) using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace System.Globalization { // IdnMapping class used to map names to Punycode public sealed partial class IdnMapping { private bool _allowUnassigned; private bool _useStd3AsciiRules; public IdnMapping() { } public bool AllowUnassigned { get { return _allowUnassigned; } set { _allowUnassigned = value; } } public bool UseStd3AsciiRules { get { return _useStd3AsciiRules; } set { _useStd3AsciiRules = value; } } // Gets ASCII (Punycode) version of the string public string GetAscii(string unicode) { return GetAscii(unicode, 0); } public string GetAscii(string unicode, int index) { if (unicode == null) throw new ArgumentNullException(nameof(unicode)); return GetAscii(unicode, index, unicode.Length - index); } public string GetAscii(string unicode, int index, int count) { if (unicode == null) throw new ArgumentNullException(nameof(unicode)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > unicode.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); if (index > unicode.Length - count) throw new ArgumentOutOfRangeException(nameof(unicode), SR.ArgumentOutOfRange_IndexCountBuffer); if (count == 0) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); } if (unicode[index + count - 1] == 0) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, index + count - 1), nameof(unicode)); } if (GlobalizationMode.Invariant) { return GetAsciiInvariant(unicode, index, count); } unsafe { fixed (char* pUnicode = unicode) { return GetAsciiCore(unicode, pUnicode + index, count); } } } // Gets Unicode version of the string. Normalized and limited to IDNA characters. public string GetUnicode(string ascii) { return GetUnicode(ascii, 0); } public string GetUnicode(string ascii, int index) { if (ascii == null) throw new ArgumentNullException(nameof(ascii)); return GetUnicode(ascii, index, ascii.Length - index); } public string GetUnicode(string ascii, int index, int count) { if (ascii == null) throw new ArgumentNullException(nameof(ascii)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > ascii.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); if (index > ascii.Length - count) throw new ArgumentOutOfRangeException(nameof(ascii), SR.ArgumentOutOfRange_IndexCountBuffer); // This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ. // The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null. // The Win32 APIs fail on an embedded null, but not on a terminating null. if (count > 0 && ascii[index + count - 1] == (char)0) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); if (GlobalizationMode.Invariant) { return GetUnicodeInvariant(ascii, index, count); } unsafe { fixed (char* pAscii = ascii) { return GetUnicodeCore(ascii, pAscii + index, count); } } } public override bool Equals(object obj) { IdnMapping that = obj as IdnMapping; return that != null && _allowUnassigned == that._allowUnassigned && _useStd3AsciiRules == that._useStd3AsciiRules; } public override int GetHashCode() { return (_allowUnassigned ? 100 : 200) + (_useStd3AsciiRules ? 1000 : 2000); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static unsafe string GetStringForOutput(string originalString, char* input, int inputLength, char* output, int outputLength) { return originalString.Length == inputLength && new ReadOnlySpan<char>(input, inputLength).SequenceEqual(new ReadOnlySpan<char>(output, outputLength)) ? originalString : new string(output, 0, outputLength); } // // Invariant implementation // private const char c_delimiter = '-'; private const string c_strAcePrefix = "xn--"; private const int c_labelLimit = 63; // Not including dots private const int c_defaultNameLimit = 255; // Including dots private const int c_initialN = 0x80; private const int c_maxint = 0x7ffffff; private const int c_initialBias = 72; private const int c_punycodeBase = 36; private const int c_tmin = 1; private const int c_tmax = 26; private const int c_skew = 38; private const int c_damp = 700; // Legal "dot" separators (i.e: . in www.microsoft.com) private static char[] c_Dots = { '.', '\u3002', '\uFF0E', '\uFF61' }; private string GetAsciiInvariant(string unicode, int index, int count) { if (index > 0 || count < unicode.Length) { unicode = unicode.Substring(index, count); } // Check for ASCII only string, which will be unchanged if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, true)) { return unicode; } // Cannot be null terminated (normalization won't help us with this one, and // may have returned false before checking the whole string above) Debug.Assert(count >= 1, "[IdnMapping.GetAscii] Expected 0 length strings to fail before now."); if (unicode[unicode.Length - 1] <= 0x1f) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, unicode.Length - 1), nameof(unicode)); } // Have to correctly IDNA normalize the string and Unassigned flags bool bHasLastDot = (unicode.Length > 0) && IsDot(unicode[unicode.Length - 1]); // Make sure we didn't normalize away something after a last dot if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1])) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); } // May need to check Std3 rules again for non-ascii if (UseStd3AsciiRules) { ValidateStd3AndAscii(unicode, true, false); } // Go ahead and encode it return PunycodeEncode(unicode); } // See if we're only ASCII static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii) { // If its empty, then its too small if (unicode.Length == 0) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); int iLastDot = -1; // Loop the whole string for (int i = 0; i < unicode.Length; i++) { // Aren't allowing control chars (or 7f, but idn tables catch that, they don't catch \0 at end though) if (unicode[i] <= 0x1f) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, i ), nameof(unicode)); } // If its Unicode or a control character, return false (non-ascii) if (bCheckAscii && unicode[i] >= 0x7f) return false; // Check for dots if (IsDot(unicode[i])) { // Can't have 2 dots in a row if (i == iLastDot + 1) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // If its too far between dots then fail if (i - iLastDot > c_labelLimit + 1) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // If validating Std3, then char before dot can't be - char if (bUseStd3 && i > 0) ValidateStd3(unicode[i - 1], true); // Remember where the last dot is iLastDot = i; continue; } // If necessary, make sure its a valid std3 character if (bUseStd3) { ValidateStd3(unicode[i], (i == iLastDot + 1)); } } // If we never had a dot, then we need to be shorter than the label limit if (iLastDot == -1 && unicode.Length > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // Need to validate entire string length, 1 shorter if last char wasn't a dot if (unicode.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)), nameof(unicode)); // If last char wasn't a dot we need to check for trailing - if (bUseStd3 && !IsDot(unicode[unicode.Length - 1])) ValidateStd3(unicode[unicode.Length - 1], true); return true; } /* PunycodeEncode() converts Unicode to Punycode. The input */ /* is represented as an array of Unicode code points (not code */ /* units; surrogate pairs are not allowed), and the output */ /* will be represented as an array of ASCII code points. The */ /* output string is *not* null-terminated; it will contain */ /* zeros if and only if the input contains zeros. (Of course */ /* the caller can leave room for a terminator and add one if */ /* needed.) The input_length is the number of code points in */ /* the input. The output_length is an in/out argument: the */ /* caller passes in the maximum number of code points that it */ /* can receive, and on successful return it will contain the */ /* number of code points actually output. The case_flags array */ /* holds input_length boolean values, where nonzero suggests that */ /* the corresponding Unicode character be forced to uppercase */ /* after being decoded (if possible), and zero suggests that */ /* it be forced to lowercase (if possible). ASCII code points */ /* are encoded literally, except that ASCII letters are forced */ /* to uppercase or lowercase according to the corresponding */ /* uppercase flags. If case_flags is a null pointer then ASCII */ /* letters are left as they are, and other code points are */ /* treated as if their uppercase flags were zero. The return */ /* value can be any of the punycode_status values defined above */ /* except punycode_bad_input; if not punycode_success, then */ /* output_size and output might contain garbage. */ static string PunycodeEncode(string unicode) { // 0 length strings aren't allowed if (unicode.Length == 0) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); StringBuilder output = new StringBuilder(unicode.Length); int iNextDot = 0; int iAfterLastDot = 0; int iOutputAfterLastDot = 0; // Find the next dot while (iNextDot < unicode.Length) { // Find end of this segment iNextDot = unicode.IndexOfAny(c_Dots, iAfterLastDot); Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); if (iNextDot < 0) iNextDot = unicode.Length; // Only allowed to have empty . section at end (www.microsoft.com.) if (iNextDot == iAfterLastDot) { // Only allowed to have empty sections as trailing . if (iNextDot != unicode.Length) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // Last dot, stop break; } // We'll need an Ace prefix output.Append(c_strAcePrefix); // Everything resets every segment. bool bRightToLeft = false; // Check for RTL. If right-to-left, then 1st & last chars must be RTL BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iAfterLastDot); if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic) { // It has to be right to left. bRightToLeft = true; // Check last char int iTest = iNextDot - 1; if (char.IsLowSurrogate(unicode, iTest)) { iTest--; } eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iTest); if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic) { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode)); } } // Handle the basic code points int basicCount; int numProcessed = 0; // Num code points that have been processed so far (this segment) for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization Debug.Assert(char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount); // If we're RTL, we can't have LTR chars if (bRightToLeft && testBidi == BidiCategory.LeftToRight) { // Oops, throw error throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode)); } // If we're not RTL we can't have RTL chars if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft || testBidi == BidiCategory.RightToLeftArabic)) { // Oops, throw error throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode)); } // If its basic then add it if (Basic(unicode[basicCount])) { output.Append(EncodeBasic(unicode[basicCount])); numProcessed++; } // If its a surrogate, skip the next since our bidi category tester doesn't handle it. else if (char.IsSurrogatePair(unicode, basicCount)) basicCount++; } int numBasicCodePoints = numProcessed; // number of basic code points // Stop if we ONLY had basic code points if (numBasicCodePoints == iNextDot - iAfterLastDot) { // Get rid of xn-- and this segments done output.Remove(iOutputAfterLastDot, c_strAcePrefix.Length); } else { // If it has some non-basic code points the input cannot start with xn-- if (unicode.Length - iAfterLastDot >= c_strAcePrefix.Length && unicode.Substring(iAfterLastDot, c_strAcePrefix.Length).Equals( c_strAcePrefix, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(unicode)); // Need to do ACE encoding int numSurrogatePairs = 0; // number of surrogate pairs so far // Add a delimiter (-) if we had any basic code points (between basic and encoded pieces) if (numBasicCodePoints > 0) { output.Append(c_delimiter); } // Initialize the state int n = c_initialN; int delta = 0; int bias = c_initialBias; // Main loop while (numProcessed < (iNextDot - iAfterLastDot)) { /* All non-basic code points < n have been */ /* handled already. Find the next larger one: */ int j; int m; int test = 0; for (m = c_maxint, j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1) { test = char.ConvertToUtf32(unicode, j); if (test >= n && test < m) m = test; } /* Increase delta enough to advance the decoder's */ /* <n,i> state to <m,0>, but guard against overflow: */ delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1)); Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); n = m; for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) { // Make sure we're aware of surrogates test = char.ConvertToUtf32(unicode, j); // Adjust for character position (only the chars in our string already, some // haven't been processed. if (test < n) { delta++; Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); } if (test == n) { // Represent delta as a generalized variable-length integer: int q, k; for (q = delta, k = c_punycodeBase; ; k += c_punycodeBase) { int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias; if (q < t) break; Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_encode]Expected c_punycodeBase (36) to be != t"); output.Append(EncodeDigit(t + (q - t) % (c_punycodeBase - t))); q = (q - t) / (c_punycodeBase - t); } output.Append(EncodeDigit(q)); bias = Adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints); delta = 0; numProcessed++; if (IsSupplementary(m)) { numProcessed++; numSurrogatePairs++; } } } ++delta; ++n; Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); } } // Make sure its not too big if (output.Length - iOutputAfterLastDot > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode)); // Done with this segment, add dot if necessary if (iNextDot != unicode.Length) output.Append('.'); iAfterLastDot = iNextDot + 1; iOutputAfterLastDot = output.Length; } // Throw if we're too long if (output.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), nameof(unicode)); // Return our output string return output.ToString(); } // Is it a dot? // are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or // U+FF61 (halfwidth ideographic full stop). // Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization private static bool IsDot(char c) { return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61'; } private static bool IsSupplementary(int cTest) { return cTest >= 0x10000; } private static bool Basic(uint cp) { // Is it in ASCII range? return cp < 0x80; } // Validate Std3 rules for a character private static void ValidateStd3(char c, bool bNextToDot) { // Check for illegal characters if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed (c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) || (c == '-' && bNextToDot)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadStd3, c), nameof(c)); } private string GetUnicodeInvariant(string ascii, int index, int count) { if (index > 0 || count < ascii.Length) { // We're only using part of the string ascii = ascii.Substring(index, count); } // Convert Punycode to Unicode string strUnicode = PunycodeDecode(ascii); // Output name MUST obey IDNA rules & round trip (casing differences are allowed) if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii)); return strUnicode; } /* PunycodeDecode() converts Punycode to Unicode. The input is */ /* represented as an array of ASCII code points, and the output */ /* will be represented as an array of Unicode code points. The */ /* input_length is the number of code points in the input. The */ /* output_length is an in/out argument: the caller passes in */ /* the maximum number of code points that it can receive, and */ /* on successful return it will contain the actual number of */ /* code points output. The case_flags array needs room for at */ /* least output_length values, or it can be a null pointer if the */ /* case information is not needed. A nonzero flag suggests that */ /* the corresponding Unicode character be forced to uppercase */ /* by the caller (if possible), while zero suggests that it be */ /* forced to lowercase (if possible). ASCII code points are */ /* output already in the proper case, but their flags will be set */ /* appropriately so that applying the flags would be harmless. */ /* The return value can be any of the punycode_status values */ /* defined above; if not punycode_success, then output_length, */ /* output, and case_flags might contain garbage. On success, the */ /* decoder will never need to write an output_length greater than */ /* input_length, because of how the encoding is defined. */ private static string PunycodeDecode(string ascii) { // 0 length strings aren't allowed if (ascii.Length == 0) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // Throw if we're too long if (ascii.Length > c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii)); // output stringbuilder StringBuilder output = new StringBuilder(ascii.Length); // Dot searching int iNextDot = 0; int iAfterLastDot = 0; int iOutputAfterLastDot = 0; while (iNextDot < ascii.Length) { // Find end of this segment iNextDot = ascii.IndexOf('.', iAfterLastDot); if (iNextDot < 0 || iNextDot > ascii.Length) iNextDot = ascii.Length; // Only allowed to have empty . section at end (www.microsoft.com.) if (iNextDot == iAfterLastDot) { // Only allowed to have empty sections as trailing . if (iNextDot != ascii.Length) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // Last dot, stop break; } // In either case it can't be bigger than segment size if (iNextDot - iAfterLastDot > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // See if this section's ASCII or ACE if (ascii.Length < c_strAcePrefix.Length + iAfterLastDot || string.Compare(ascii, iAfterLastDot, c_strAcePrefix, 0, c_strAcePrefix.Length, StringComparison.OrdinalIgnoreCase) != 0) { // Its ASCII, copy it output.Append(ascii, iAfterLastDot, iNextDot - iAfterLastDot); } else { // Not ASCII, bump up iAfterLastDot to be after ACE Prefix iAfterLastDot += c_strAcePrefix.Length; // Get number of basic code points (where delimiter is) // numBasicCodePoints < 0 if there're no basic code points int iTemp = ascii.LastIndexOf(c_delimiter, iNextDot - 1); // Trailing - not allowed if (iTemp == iNextDot - 1) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); int numBasicCodePoints; if (iTemp <= iAfterLastDot) numBasicCodePoints = 0; else { numBasicCodePoints = iTemp - iAfterLastDot; // Copy all the basic code points, making sure they're all in the allowed range, // and losing the casing for all of them. for (int copyAscii = iAfterLastDot; copyAscii < iAfterLastDot + numBasicCodePoints; copyAscii++) { // Make sure we don't allow unicode in the ascii part if (ascii[copyAscii] > 0x7f) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); // When appending make sure they get lower cased output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ? ascii[copyAscii] - 'A' + 'a' : ascii[copyAscii])); } } // Get ready for main loop. Start at beginning if we didn't have any // basic code points, otherwise start after the -. // asciiIndex will be next character to read from ascii int asciiIndex = iAfterLastDot + (numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0); // initialize our state int n = c_initialN; int bias = c_initialBias; int i = 0; int w, k; // no Supplementary characters yet int numSurrogatePairs = 0; // Main loop, read rest of ascii while (asciiIndex < iNextDot) { /* Decode a generalized variable-length integer into delta, */ /* which gets added to i. The overflow checking is easier */ /* if we increase i as we go, then subtract off its starting */ /* value at the end to obtain delta. */ int oldi = i; for (w = 1, k = c_punycodeBase; ; k += c_punycodeBase) { // Check to make sure we aren't overrunning our ascii string if (asciiIndex >= iNextDot) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); // decode the digit from the next char int digit = DecodeDigit(ascii[asciiIndex++]); Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0"); if (digit > (c_maxint - i) / w) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); i += (int)(digit * w); int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias; if (digit < t) break; Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != c_punycodeBase (36)"); if (w > c_maxint / (c_punycodeBase - t)) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); w *= (c_punycodeBase - t); } bias = Adapt(i - oldi, (output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0); /* i was supposed to wrap around from output.Length to 0, */ /* incrementing n each time, so we'll fix that now: */ Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0, "[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment"); if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > c_maxint - n) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1)); i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1); // Make sure n is legal if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF)) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); // insert n at position i of the output: Really tricky if we have surrogates int iUseInsertLocation; string strTemp = char.ConvertFromUtf32(n); // If we have supplimentary characters if (numSurrogatePairs > 0) { // Hard way, we have supplimentary characters int iCount; for (iCount = i, iUseInsertLocation = iOutputAfterLastDot; iCount > 0; iCount--, iUseInsertLocation++) { // If its a surrogate, we have to go one more if (iUseInsertLocation >= output.Length) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); if (char.IsSurrogate(output[iUseInsertLocation])) iUseInsertLocation++; } } else { // No Supplementary chars yet, just add i iUseInsertLocation = iOutputAfterLastDot + i; } // Insert it output.Insert(iUseInsertLocation, strTemp); // If it was a surrogate increment our counter if (IsSupplementary(n)) numSurrogatePairs++; // Index gets updated i++; } // Do BIDI testing bool bRightToLeft = false; // Check for RTL. If right-to-left, then 1st & last chars must be RTL BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output, iOutputAfterLastDot); if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic) { // It has to be right to left. bRightToLeft = true; } // Check the rest of them to make sure RTL/LTR is consistent for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++) { // This might happen if we run into a pair if (char.IsLowSurrogate(output[iTest])) continue; // Check to see if its LTR eBidi = CharUnicodeInfo.GetBidiCategory(output, iTest); if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) || (!bRightToLeft && (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic))) throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii)); } // Its also a requirement that the last one be RTL if 1st is RTL if (bRightToLeft && eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic) { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii)); } } // See if this label was too long if (iNextDot - iAfterLastDot > c_labelLimit) throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii)); // Done with this segment, add dot if necessary if (iNextDot != ascii.Length) output.Append('.'); iAfterLastDot = iNextDot + 1; iOutputAfterLastDot = output.Length; } // Throw if we're too long if (output.Length > c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)) throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii)); // Return our output string return output.ToString(); } // DecodeDigit(cp) returns the numeric value of a basic code */ // point (for use in representing integers) in the range 0 to */ // c_punycodeBase-1, or <0 if cp is does not represent a value. */ private static int DecodeDigit(char cp) { if (cp >= '0' && cp <= '9') return cp - '0' + 26; // Two flavors for case differences if (cp >= 'a' && cp <= 'z') return cp - 'a'; if (cp >= 'A' && cp <= 'Z') return cp - 'A'; // Expected 0-9, A-Z or a-z, everything else is illegal throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(cp)); } private static int Adapt(int delta, int numpoints, bool firsttime) { uint k; delta = firsttime ? delta / c_damp : delta / 2; Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints."); delta += delta / numpoints; for (k = 0; delta > ((c_punycodeBase - c_tmin) * c_tmax) / 2; k += c_punycodeBase) { delta /= c_punycodeBase - c_tmin; } Debug.Assert(delta + c_skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew."); return (int)(k + (c_punycodeBase - c_tmin + 1) * delta / (delta + c_skew)); } /* EncodeBasic(bcp,flag) forces a basic code point to lowercase */ /* if flag is false, uppercase if flag is true, and returns */ /* the resulting code point. The code point is unchanged if it */ /* is caseless. The behavior is undefined if bcp is not a basic */ /* code point. */ static char EncodeBasic(char bcp) { if (HasUpperCaseFlag(bcp)) bcp += (char)('a' - 'A'); return bcp; } // Return whether a punycode code point is flagged as being upper case. private static bool HasUpperCaseFlag(char punychar) { return (punychar >= 'A' && punychar <= 'Z'); } /* EncodeDigit(d,flag) returns the basic code point whose value */ /* (when used for representing integers) is d, which needs to be in */ /* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */ /* true, in which case the uppercase form is used. */ private static char EncodeDigit(int d) { Debug.Assert(d >= 0 && d < c_punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase"); // 26-35 map to ASCII 0-9 if (d > 25) return (char)(d - 26 + '0'); // 0-25 map to a-z or A-Z return (char)(d + 'a'); } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class PostDecrementAssignTests : IncDecAssignTests { [Theory] [PerCompilationType(nameof(Int16sAndDecrements))] [PerCompilationType(nameof(NullableInt16sAndDecrements))] [PerCompilationType(nameof(UInt16sAndDecrements))] [PerCompilationType(nameof(NullableUInt16sAndDecrements))] [PerCompilationType(nameof(Int32sAndDecrements))] [PerCompilationType(nameof(NullableInt32sAndDecrements))] [PerCompilationType(nameof(UInt32sAndDecrements))] [PerCompilationType(nameof(NullableUInt32sAndDecrements))] [PerCompilationType(nameof(Int64sAndDecrements))] [PerCompilationType(nameof(NullableInt64sAndDecrements))] [PerCompilationType(nameof(UInt64sAndDecrements))] [PerCompilationType(nameof(NullableUInt64sAndDecrements))] [PerCompilationType(nameof(DecimalsAndDecrements))] [PerCompilationType(nameof(NullableDecimalsAndDecrements))] [PerCompilationType(nameof(SinglesAndDecrements))] [PerCompilationType(nameof(NullableSinglesAndDecrements))] [PerCompilationType(nameof(DoublesAndDecrements))] [PerCompilationType(nameof(NullableDoublesAndDecrements))] public void ReturnsCorrectValues(Type type, object value, object _, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PostDecrementAssign(variable) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(Int16sAndDecrements))] [PerCompilationType(nameof(NullableInt16sAndDecrements))] [PerCompilationType(nameof(UInt16sAndDecrements))] [PerCompilationType(nameof(NullableUInt16sAndDecrements))] [PerCompilationType(nameof(Int32sAndDecrements))] [PerCompilationType(nameof(NullableInt32sAndDecrements))] [PerCompilationType(nameof(UInt32sAndDecrements))] [PerCompilationType(nameof(NullableUInt32sAndDecrements))] [PerCompilationType(nameof(Int64sAndDecrements))] [PerCompilationType(nameof(NullableInt64sAndDecrements))] [PerCompilationType(nameof(UInt64sAndDecrements))] [PerCompilationType(nameof(NullableUInt64sAndDecrements))] [PerCompilationType(nameof(DecimalsAndDecrements))] [PerCompilationType(nameof(NullableDecimalsAndDecrements))] [PerCompilationType(nameof(SinglesAndDecrements))] [PerCompilationType(nameof(NullableSinglesAndDecrements))] [PerCompilationType(nameof(DoublesAndDecrements))] [PerCompilationType(nameof(NullableDoublesAndDecrements))] public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); LabelTarget target = Expression.Label(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PostDecrementAssign(variable), Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void SingleNanToNan(bool useInterpreter) { TestPropertyClass<float> instance = new TestPropertyClass<float>(); instance.TestInstance = float.NaN; Assert.True(float.IsNaN( Expression.Lambda<Func<float>>( Expression.PostDecrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<float>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(float.IsNaN(instance.TestInstance)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DoubleNanToNan(bool useInterpreter) { TestPropertyClass<double> instance = new TestPropertyClass<double>(); instance.TestInstance = double.NaN; Assert.True(double.IsNaN( Expression.Lambda<Func<double>>( Expression.PostDecrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<double>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(double.IsNaN(instance.TestInstance)); } [Theory] [PerCompilationType(nameof(DecrementOverflowingValues))] public void OverflowingValuesThrow(object value, bool useInterpreter) { ParameterExpression variable = Expression.Variable(value.GetType()); Action overflow = Expression.Lambda<Action>( Expression.Block( typeof(void), new[] { variable }, Expression.Assign(variable, Expression.Constant(value)), Expression.PostDecrementAssign(variable) ) ).Compile(useInterpreter); Assert.Throws<OverflowException>(overflow); } [Theory] [MemberData(nameof(UnincrementableAndUndecrementableTypes))] public void InvalidOperandType(Type type) { ParameterExpression variable = Expression.Variable(type); Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable)); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectResult(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")) ); Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectAssign(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); LabelTarget target = Expression.Label(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(string))) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Fact] public void IncorrectMethodType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"); Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable, method)); } [Fact] public void IncorrectMethodParameterCount() { Expression variable = Expression.Variable(typeof(string)); MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals"); Assert.Throws<ArgumentException>("method", () => Expression.PostDecrementAssign(variable, method)); } [Fact] public void IncorrectMethodReturnType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString"); Assert.Throws<ArgumentException>(null, () => Expression.PostDecrementAssign(variable, method)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StaticMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<double>.TestStatic = 2.0; Assert.Equal( 2.0, Expression.Lambda<Func<double>>( Expression.PostDecrementAssign( Expression.Property(null, typeof(TestPropertyClass<double>), "TestStatic") ) ).Compile(useInterpreter)() ); Assert.Equal(1.0, TestPropertyClass<double>.TestStatic); } [Theory] [ClassData(typeof(CompilationTypes))] public void InstanceMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<int> instance = new TestPropertyClass<int>(); instance.TestInstance = 2; Assert.Equal( 2, Expression.Lambda<Func<int>>( Expression.PostDecrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<int>), "TestInstance" ) ) ).Compile(useInterpreter)() ); Assert.Equal(1, instance.TestInstance); } [Theory] [ClassData(typeof(CompilationTypes))] public void ArrayAccessCorrect(bool useInterpreter) { int[] array = new int[1]; array[0] = 2; Assert.Equal( 2, Expression.Lambda<Func<int>>( Expression.PostDecrementAssign( Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0)) ) ).Compile(useInterpreter)() ); Assert.Equal(1, array[0]); } [Fact] public void CanReduce() { ParameterExpression variable = Expression.Variable(typeof(int)); UnaryExpression op = Expression.PostDecrementAssign(variable); Assert.True(op.CanReduce); Assert.NotSame(op, op.ReduceAndCheck()); } [Fact] public void NullOperand() { Assert.Throws<ArgumentNullException>("expression", () => Expression.PostDecrementAssign(null)); } [Fact] public void UnwritableOperand() { Assert.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(Expression.Constant(1))); } [Fact] public void UnreadableOperand() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(value)); } [Fact] public void UpdateSameOperandSameNode() { UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int))); Assert.Same(op, op.Update(op.Operand)); Assert.Same(op, NoOpVisitor.Instance.Visit(op)); } [Fact] public void UpdateDiffOperandDiffNode() { UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int))); Assert.NotSame(op, op.Update(Expression.Variable(typeof(int)))); } [Fact] public void ToStringTest() { UnaryExpression e = Expression.PostDecrementAssign(Expression.Parameter(typeof(int), "x")); Assert.Equal("x--", e.ToString()); } } }
// // - NamespaceUri.cs - // // Copyright 2005, 2006, 2010, 2012 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Carbonfrost.Commons.Shared.Runtime; namespace Carbonfrost.Commons.Shared { [TypeConverter(typeof(NamespaceUriConverter))] public sealed class NamespaceUri : IEquatable<NamespaceUri>, IFormattable, IObjectReference { private static readonly Dictionary<string, NamespaceUri> namespaces = new Dictionary<string, NamespaceUri>(); private readonly Dictionary<string, QualifiedName> names = new Dictionary<string, QualifiedName>(); private readonly int hashCodeCache; private readonly string namespaceUri; static readonly Regex TAG_DATE_PATTERN = new Regex( @"^\d{4}(-\d{2}(-\d{2})?)?$", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); private static readonly NamespaceUri xml = new NamespaceUri(XmlPrefixNamespace); private static readonly NamespaceUri xmlns = new NamespaceUri(XmlnsPrefixNamespace); private static readonly NamespaceUri defaultNamespace = new NamespaceUri(); internal const string XmlnsPrefixNamespace = "http://www.w3.org/2000/xmlns/"; // $NON-NLS-1 internal const string XmlPrefixNamespace = "http://www.w3.org/XML/1998/namespace"; // $NON-NLS-1 private static readonly int xmlnsPrefixNamespaceLength = XmlnsPrefixNamespace.Length; private static readonly int xmlPrefixNamespaceLength = XmlPrefixNamespace.Length; // Properties. public static NamespaceUri Default { get { return defaultNamespace; } } public bool IsDefault { get { return object.ReferenceEquals(this, NamespaceUri.Default); } } public string NamespaceName { get { return this.namespaceUri; } } public static NamespaceUri Xml { get { return xml; } } public static NamespaceUri Xmlns { get { return xmlns; } } // Constructors. private NamespaceUri() : this(String.Empty) { } internal NamespaceUri(string namespaceName) { // N.B. Argument checking done upstream this.namespaceUri = string.Intern(namespaceName); unchecked { this.hashCodeCache = 1000000009 * namespaceName.GetHashCode(); } } public static NamespaceUri Create(string namespaceName) { if (namespaceName == null) throw new ArgumentNullException("namespaceName"); if (namespaceName.Length == 0) throw Failure.EmptyString("namespaceName"); return Parse(namespaceName); } public static NamespaceUri Create(Uri uri) { if (uri == null) throw new ArgumentNullException("uri"); // $NON-NLS-1 return Parse(uri.ToString()); } public static bool TryParse(string text, out NamespaceUri value) { value = _TryParse(text, true); return value != null; } public static NamespaceUri Parse(string text) { return _TryParse(text, true); } internal static NamespaceUri _TryParse(string text, bool throwOnError) { if (text == null) { if (throwOnError) throw new ArgumentNullException("text"); // $NON-NLS-1 else return null; } if (text.Length == 0) return NamespaceUri.Default; NamespaceUri result = null; if (namespaces.TryGetValue(text, out result)) return result; else { // It may be the case that one of the static members is in use int count = text.Length; if ((count == NamespaceUri.xmlnsPrefixNamespaceLength) && (string.CompareOrdinal( text, XmlnsPrefixNamespace) == 0)) { return Xmlns; } if ((count == NamespaceUri.xmlPrefixNamespaceLength) && (string.CompareOrdinal( text, XmlPrefixNamespace) == 0)) { return Xml; } result = new NamespaceUri(text); namespaces.Add(text, result); return result; } } public QualifiedName GetName(string localName) { QualifiedName.VerifyLocalName("localName", localName); QualifiedName result = null; if (this.names.TryGetValue(localName, out result)) { return result; } else { result = new QualifiedName(this, localName);; this.names.Add(localName, result); return result; } } // Operators. public static QualifiedName operator +(NamespaceUri ns, string localName) { return (ns ?? NamespaceUri.Default).GetName(localName); } public static bool operator ==(NamespaceUri left, NamespaceUri right) { return object.ReferenceEquals(left, right); } [CLSCompliant(false)] public static implicit operator NamespaceUri(string namespaceName) { if (namespaceName == null) { return null; } return Parse(namespaceName); } public static bool operator !=(NamespaceUri left, NamespaceUri right) { return !object.ReferenceEquals(left, right); } // 'object' overrides. public override int GetHashCode() { return this.hashCodeCache; } public override bool Equals(object obj) { return Equals(obj as NamespaceUri); } public override string ToString() { return this.namespaceUri; } // 'IFormattable' implementation. public string ToString(string format, IFormatProvider formatProvider = null) { if (string.IsNullOrEmpty(format)) format = "G"; if (format.Length > 1) throw new FormatException(); switch (char.ToLowerInvariant(format[0])) { case 'g': case 'f': return this.NamespaceName; case 'b': return string.Concat("{", this.NamespaceName, "}"); case 't': return CreateTagUri(); default: throw new FormatException(); } } private string CreateTagUri() { Uri u; if (Uri.TryCreate(this.NamespaceName, UriKind.Absolute, out u)) { string hostName = u.Host; string[] split = u.PathAndQuery.Split(new char[] { '/' }, 3); string date = split[1]; string rest = "/" + split.ElementAtOrDefault(2); if ((u.Scheme == "http" || u.Scheme == "https") && TAG_DATE_PATTERN.IsMatch(date)) return string.Format("tag:{0},{1}:{2}", hostName, date, rest); } throw RuntimeFailure.CannotBuildTagUri(); } // 'IEquatable' implementation. public bool Equals(NamespaceUri other) { if (object.ReferenceEquals(this, other)) return true; else return string.Compare(other.namespaceUri, this.namespaceUri, StringComparison.Ordinal) == 0; } // `IObjectReference' implementation object IObjectReference.GetRealObject(StreamingContext context) { return NamespaceUri.Create(this.NamespaceName); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesAnalyzer, Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesAnalyzer, Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesFixer>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class SealMethodsThatSatisfyPrivateInterfacesFixerTests { [Fact] public async Task TestCSharp_OverriddenMethodChangedToSealedAsync() { await VerifyCS.VerifyCodeFixAsync( @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public class C : B, IFace { public override void [|M|]() { } }", @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public class C : B, IFace { public sealed override void M() { } }"); } [Fact] public async Task TestCSharp_VirtualMethodChangedToNotVirtualAsync() { await VerifyCS.VerifyCodeFixAsync( @"internal interface IFace { void M(); } public class C : IFace { public virtual void [|M|]() { } }", @"internal interface IFace { void M(); } public class C : IFace { public void M() { } }"); } [Fact] public async Task TestCSharp_AbstractMethodChangedToNotAbstractAsync() { await VerifyCS.VerifyCodeFixAsync( @"internal interface IFace { void M(); } public abstract class C : IFace { public abstract void [|M|](); }", @"internal interface IFace { void M(); } public abstract class C : IFace { public void M() { } }"); } [Fact] public async Task TestCSharp_ContainingTypeChangedToSealedAsync() { await new VerifyCS.Test { TestState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public class C : B, IFace { public override void [|M|]() { } }", }, }, FixedState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public sealed class C : B, IFace { public override void M() { } }", }, }, CodeActionIndex = 1, CodeActionEquivalenceKey = "MakeDeclaringTypeSealed", }.RunAsync(); } [Fact] public async Task TestCSharp_ContainingTypeChangedToInternalAsync() { await new VerifyCS.Test { TestState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public class C : B, IFace { public override void [|M|]() { } }", }, }, FixedState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } internal class C : B, IFace { public override void M() { } }", }, }, CodeActionIndex = 2, CodeActionEquivalenceKey = "MakeDeclaringTypeInternal", }.RunAsync(); } [Fact] public async Task TestCSharp_AbstractContainingTypeChangedToInternalAsync() { await new VerifyCS.Test { TestState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public abstract class C : B, IFace { public override void [|M|]() { } }", }, }, FixedState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } internal abstract class C : B, IFace { public override void M() { } }", }, }, CodeActionIndex = 1, // sealed option is not available because class is abstract CodeActionEquivalenceKey = "MakeDeclaringTypeInternal", }.RunAsync(); } [Fact] public async Task TestCSharp_ImplicitOverride_ContainingTypeChangedToSealedAsync() { await VerifyCS.VerifyCodeFixAsync( @"internal interface IFace { void M(); } public class B { public virtual void M() { } } public class [|C|] : B, IFace { }", @"internal interface IFace { void M(); } public class B { public virtual void M() { } } public sealed class C : B, IFace { }"); } [Fact] public async Task TestCSharp_ImplicitOverride_ContainingTypeChangedToInternalAsync() { await new VerifyCS.Test { TestState = { Sources = { @"internal interface IFace { void M(); } public class B { public virtual void M() { } } public class [|C|] : B, IFace { }", }, }, FixedState = { Sources = { @"internal interface IFace { void M(); } public class B { public virtual void M() { } } internal class C : B, IFace { }", }, }, CodeActionIndex = 1, CodeActionEquivalenceKey = "MakeDeclaringTypeInternal", }.RunAsync(); } [Fact] public async Task TestCSharp_ImplicitOverride_AbstractContainingTypeChangedToInternalAsync() { await new VerifyCS.Test { TestState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public abstract class [|C|] : B, IFace { }", }, }, FixedState = { Sources = { @"internal interface IFace { void M(); } public abstract class B { public abstract void M(); } internal abstract class C : B, IFace { }", }, }, CodeActionIndex = 0, // sealed option is not available because type is abstract CodeActionEquivalenceKey = "MakeDeclaringTypeInternal", }.RunAsync(); } [Fact] public async Task TestBasic_OverriddenMethodChangedToSealedAsync() { await VerifyVB.VerifyCodeFixAsync( @"Friend Interface IFace Sub M() End Interface Public MustInherit Class B Public MustOverride Sub M() End Class Public Class C Inherits B Implements IFace Public Overrides Sub [|M|]() Implements IFace.M End Sub End Class", @"Friend Interface IFace Sub M() End Interface Public MustInherit Class B Public MustOverride Sub M() End Class Public Class C Inherits B Implements IFace Public NotOverridable Overrides Sub M() Implements IFace.M End Sub End Class"); } [Fact] public async Task TestBasic_VirtualMethodChangedToNotVirtualAsync() { await VerifyVB.VerifyCodeFixAsync( @"Friend Interface IFace Sub M() End Interface Public Class C Implements IFace Public Overridable Sub [|M|]() Implements IFace.M End Sub End Class", @"Friend Interface IFace Sub M() End Interface Public Class C Implements IFace Public Sub M() Implements IFace.M End Sub End Class"); } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2285")] public async Task TestBasic_AbstractMethodChangedToNotAbstractAsync() { await VerifyVB.VerifyCodeFixAsync( @"Friend Interface IFace Sub M() End Interface Public MustInherit Class C Implements IFace Public MustOverride Sub [|M|]() Implements IFace.M End Class", @"Friend Interface IFace Sub M() End Interface Public MustInherit Class C Implements IFace Public Sub M() Implements IFace.M End Sub End Class"); } } }
#region Header // Revit API .NET Labs // // Copyright (C) 2007-2021 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software // for any purpose and without fee is hereby granted, provided // that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Linq; using WinForms = System.Windows.Forms; using System.Windows.Media.Imaging; // for ribbon, requires references to PresentationCore and WindowsBase .NET assemblies using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Architecture; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Events; using DocumentSavingEventArgs = Autodesk.Revit.DB.Events.DocumentSavingEventArgs; #endregion // Namespaces namespace XtraCs { #region SampleAccessibilityCheck public class SampleAccessibilityCheck : IExternalCommandAvailability { public bool IsCommandAvailable( UIApplication applicationData, CategorySet selectedCategories ) { // Allow button click if there is // no active selection if( selectedCategories.IsEmpty ) return true; // Allow button click if there is // at least one wall selected foreach( Category c in selectedCategories ) { if( c.Id.IntegerValue == (int) BuiltInCategory.OST_Walls ) return true; } return false; } } #endregion // SampleAccessibilityCheck #region Lab6_1_HelloWorldExternalApplication /// <summary> /// A minimal external application saying hello. /// Explain the concept of an external application and its minimal interface. /// Explore how to create a manifest file for an external application. /// </summary> public class Lab6_1_HelloWorldExternalApplication : IExternalApplication { /// <summary> /// This method will run automatically when Revit start up. /// It shows a message box. Initiative task can be done in this function. /// </summary> public Result OnStartup( UIControlledApplication a ) { LabUtils.InfoMsg( "Hello World from an external application in C#." ); return Result.Succeeded; } public Result OnShutdown( UIControlledApplication a ) { return Result.Succeeded; } } #endregion // Lab6_1_HelloWorldExternalApplication #region Lab6_2_Ribbon /// <summary> /// Add various controls to the Revit ribbon. /// </summary> public class Lab6_2_Ribbon : IExternalApplication { public Result OnStartup( UIControlledApplication a ) { try { CreateRibbonItems( a ); } catch( Exception ex ) { LabUtils.InfoMsg( ex.Message ); return Result.Failed; } return Result.Succeeded; } public Result OnShutdown( UIControlledApplication a ) { return Result.Succeeded; } /// <summary> /// Starting at the given directory, search upwards for /// a subdirectory with the given target name located /// in some parent directory. /// </summary> /// <param name="path">Starting directory, e.g. GetDirectoryName( GetExecutingAssembly().Location ).</param> /// <param name="target">Target subdirectory name, e.g. "Images".</param> /// <returns>The full path of the target directory if found, else null.</returns> string FindFolderInParents( string path, string target ) { Debug.Assert( Directory.Exists( path ), "expected an existing directory to start search in" ); string s; do { s = Path.Combine( path, target ); if( Directory.Exists( s ) ) { return s; } path = Path.GetDirectoryName( path ); } while( null != path ); return null; } void CreateRibbonItems( UIControlledApplication a ) { // get the path of our dll string addInPath = GetType().Assembly.Location; string imgDir = FindFolderInParents( Path.GetDirectoryName( addInPath ), "Images" ); const string panelName = "Lab 6 Panel"; const string cmd1 = "XtraCs.Lab1_1_HelloWorld"; const string name1 = "HelloWorld"; const string text1 = "Hello World"; const string tooltip1 = "Run Lab1_1_HelloWorld command"; const string img1 = "ImgHelloWorld.png"; const string img31 = "ImgHelloWorldSmall.png"; const string cmd2 = "XtraCs.Lab1_2_CommandArguments"; const string name2 = "CommandArguments"; const string text2 = "Command Arguments"; const string tooltip2 = "Run Lab1_2_CommandArguments command"; const string img2 = "ImgCommandArguments.png"; const string img32 = "ImgCommandArgumentsSmall.png"; const string name3 = "Lab1Commands"; const string text3 = "Lab 1 Commands"; const string tooltip3 = "Run a Lab 1 command"; const string img33 = "ImgCommandSmall.png"; // create a Ribbon Panel RibbonPanel panel = a.CreateRibbonPanel( panelName ); // add a button for Lab1's Hello World command PushButtonData pbd = new PushButtonData( name1, text1, addInPath, cmd1 ); PushButton pb1 = panel.AddItem( pbd ) as PushButton; pb1.ToolTip = tooltip1; pb1.LargeImage = new BitmapImage( new Uri( Path.Combine( imgDir, img1 ) ) ); // add a vertical separation line in the panel panel.AddSeparator(); // prepare data for creating stackable buttons PushButtonData pbd1 = new PushButtonData( name1 + " 2", text1, addInPath, cmd1 ); pbd1.ToolTip = tooltip1; pbd1.Image = new BitmapImage( new Uri( Path.Combine( imgDir, img31 ) ) ); PushButtonData pbd2 = new PushButtonData( name2, text2, addInPath, cmd2 ); pbd2.ToolTip = tooltip2; pbd2.Image = new BitmapImage( new Uri( Path.Combine( imgDir, img32 ) ) ); PulldownButtonData pbd3 = new PulldownButtonData( name3, text3 ); pbd3.ToolTip = tooltip3; pbd3.Image = new BitmapImage( new Uri( Path.Combine( imgDir, img33 ) ) ); // add stackable buttons IList<RibbonItem> ribbonItems = panel.AddStackedItems( pbd1, pbd2, pbd3 ); // add two push buttons as sub-items of the Lab 1 commands PulldownButton pb3 = ribbonItems[2] as PulldownButton; pbd = new PushButtonData( name1, text1, addInPath, cmd1 ); PushButton pb3_1 = pb3.AddPushButton( pbd ); pb3_1.ToolTip = tooltip1; pb3_1.LargeImage = new BitmapImage( new Uri( Path.Combine( imgDir, img1 ) ) ); pbd = new PushButtonData( name2, text2, addInPath, cmd2 ); PushButton pb3_2 = pb3.AddPushButton( pbd ); pb3_2.ToolTip = tooltip2; pb3_2.LargeImage = new BitmapImage( new Uri( Path.Combine( imgDir, img2 ) ) ); } } #endregion // Lab6_2_Ribbon #region Lab6_3_PreventSaveEvent /// <summary> /// This external application subscribes to, handles, /// and unsubscribes from the document saving event. /// Using the event mechnism pre-event features, some actions can be prevented. /// This sample displays a message dialog to let the user decide whether to save changes to the document. /// Note: The document must have been already saved to disk prior to running this application. /// </summary> public class Lab6_3_PreventSaveEvent : IExternalApplication { public Result OnStartup( UIControlledApplication a ) { try { // subscribe to the DocumentSaving event: a.ControlledApplication.DocumentSaving += new EventHandler<DocumentSavingEventArgs>( a_DocumentSaving ); } catch( Exception ex ) { LabUtils.InfoMsg( ex.Message ); return Result.Failed; } return Result.Succeeded; } public Result OnShutdown( UIControlledApplication a ) { // remove the event subscription: a.ControlledApplication.DocumentSaving -= new EventHandler<DocumentSavingEventArgs>( a_DocumentSaving ); return Result.Succeeded; } // Show a message to decide whether to save the document. void a_DocumentSaving( object obj, DocumentSavingEventArgs args ) { // Ask whether to prevent from saving: bool cancel = args.Cancellable && LabUtils.QuestionMsg( "Saving event handler was triggered.\r\n" + "Using the pre-event mechanism, we can cancel the save.\r\n" + "Continue saving the document?" ); //args.Cancel = cancel; // 2011 if( cancel ) { args.Cancel(); } // 2012 } } #endregion //Lab6_3_PreventSaveEvent #region Lab6_4_DismissDialog /// <summary> /// This external application subscribes to, handles, /// and unsubscribe from the dialog box showing event. /// Its can dismiss the "Family already exists" dialog when /// reloading an already loaded family, and overwrite the existing version. /// It dismisses message box by simulating a click on the "Yes" button. /// In addition, it can dismiss the property dialog. /// </summary> public class Lab6_4_DismissDialog : IExternalApplication { public Result OnStartup( UIControlledApplication a ) { a.DialogBoxShowing += new EventHandler<DialogBoxShowingEventArgs>( DismissDialog ); return Result.Succeeded; } public Result OnShutdown( UIControlledApplication a ) { a.DialogBoxShowing -= new EventHandler<DialogBoxShowingEventArgs>( DismissDialog ); return Result.Succeeded; } void DismissDialog( object sender, DialogBoxShowingEventArgs e ) { TaskDialogShowingEventArgs te = e as TaskDialogShowingEventArgs; if( te != null ) { if( te.DialogId == "TaskDialog_Family_Already_Exists" ) { // In this task dialog, 1001 maps to the first button, // which is the "override the existing version" int iReturn = 1001; // Set OverrideResult argument to 1001 mimic clicking the first button. e.OverrideResult( iReturn ); // 1002 maps the second button in this dialog. // DialogResult.Cancel maps to the cancel button. } } else { MessageBoxShowingEventArgs msgArgs = e as MessageBoxShowingEventArgs; if( null != msgArgs ) // this is a message box { //e.OverrideResult( (int) WinForms.DialogResult.Yes ); //Debug.Print( "Dialog id is {0}\r\nMessage is {1}", // msgArgs.HelpId, msgArgs.Message ); // Revit 2016 e.OverrideResult( (int) WinForms.DialogResult.Yes ); Debug.Print( "Dialog id is {0}\r\nMessage is {1}", msgArgs.DialogId, msgArgs.Message ); // Revit 2017 } else // this is some other dialog, for example, element property dialog. { // Use the HelpId to identify the dialog. //if( e.HelpId == 1002 ) // Element property dialog's HelpId is 1002 in Revit 2016 and earlier if( e.DialogId.Equals( "1002" ) ) // What is the corresponding Element property dialog DialogId? { e.OverrideResult( (int) WinForms.DialogResult.No ); Debug.Print( "We just dismissed the element property dialog " + "and set the return value to No." ); } } } } } #endregion //Lab6_4_DismissDialog #region Lab6_5_RibbonExplorer /// <summary> /// List the contents of the Revit ribbon in the Visual Studio debug output window. /// </summary> [Transaction( TransactionMode.ReadOnly )] public class Lab6_5_RibbonExplorer : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; List<RibbonPanel> panels = app.GetRibbonPanels(); foreach( RibbonPanel panel in panels ) { Debug.Print( panel.Name ); IList<RibbonItem> items = panel.GetItems(); foreach( RibbonItem item in items ) { RibbonItemType t = item.ItemType; if( RibbonItemType.PushButton == t ) { PushButton b = item as PushButton; Debug.Print( " {0} : {1}", item.ItemText, b.Name ); } else { Debug.Assert( RibbonItemType.PulldownButton == t, "expected pulldown button" ); PulldownButton b = item as PulldownButton; Debug.Print( " {0} : {1}", item.ItemText, b.Name ); foreach( RibbonItem item2 in b.GetItems() ) { Debug.Assert( RibbonItemType.PushButton == item2.ItemType, "expected push button in pulldown menu" ); Debug.Print( " {0} : {1}", item2.ItemText, ( (PushButton) item2 ).Name ); } } } } return Result.Failed; } } #endregion // Lab6_5_RibbonExplorer }
/* ==================================================================== 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.SS.Formula { using System; using System.Collections.Generic; using System.IO; using System.Text; using NUnit.Framework; using NPOI.HSSF.Model; using NPOI.HSSF.UserModel; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.SS.Util; using TestCases.HSSF.UserModel; /** * Tests {@link NPOI.SS.Formula.EvaluationCache}. Makes sure that where possible (previously calculated) cached * values are used. Also Checks that changing cell values causes the correct (minimal) Set of * dependent cached values to be Cleared. * * @author Josh Micich */ [TestFixture] public class TestEvaluationCache { private class FormulaCellCacheEntryComparer : IComparer<ICacheEntry> { private Dictionary<ICacheEntry, IEvaluationCell> _formulaCellsByCacheEntry; public FormulaCellCacheEntryComparer(Dictionary<ICacheEntry, IEvaluationCell> formulaCellsByCacheEntry) { _formulaCellsByCacheEntry = formulaCellsByCacheEntry; } private IEvaluationCell GetCell(ICacheEntry a) { return _formulaCellsByCacheEntry[a]; } public int Compare(ICacheEntry oa, ICacheEntry ob) { IEvaluationCell a = GetCell(oa); IEvaluationCell b = GetCell(ob); int cmp; cmp = a.RowIndex - b.RowIndex; if (cmp != 0) { return cmp; } cmp = a.ColumnIndex - b.ColumnIndex; if (cmp != 0) { return cmp; } if (a.Sheet == b.Sheet) { return 0; } throw new Exception("Incomplete code - don't know how to order sheets"); } } private class EvalListener : EvaluationListener { private List<String> _logList; private HSSFWorkbook _book; private Dictionary<ICacheEntry, IEvaluationCell> _formulaCellsByCacheEntry; private Dictionary<ICacheEntry, Loc> _plainCellLocsByCacheEntry; public EvalListener(HSSFWorkbook wb) { _book = wb; _logList = new List<String>(); _formulaCellsByCacheEntry = new Dictionary<ICacheEntry, IEvaluationCell>(); _plainCellLocsByCacheEntry = new Dictionary<ICacheEntry, Loc>(); } public override void OnCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result) { Log("hit", rowIndex, columnIndex, result); } public override void OnReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { Loc loc = new Loc(0, sheetIndex, rowIndex, columnIndex); if (!_plainCellLocsByCacheEntry.ContainsKey(entry)) _plainCellLocsByCacheEntry.Add(entry, loc); else _plainCellLocsByCacheEntry[entry] = loc; Log("value", rowIndex, columnIndex, entry.GetValue()); } public override void OnStartEvaluate(IEvaluationCell cell, ICacheEntry entry) { if (!_formulaCellsByCacheEntry.ContainsKey(entry)) _formulaCellsByCacheEntry.Add(entry, cell); else _formulaCellsByCacheEntry[entry] = cell; ICell hc = _book.GetSheetAt(0).GetRow(cell.RowIndex).GetCell(cell.ColumnIndex); Log("start", cell.RowIndex, cell.ColumnIndex, FormulaExtractor.GetPtgs(hc)); } public override void OnEndEvaluate(ICacheEntry entry, ValueEval result) { IEvaluationCell cell = _formulaCellsByCacheEntry[(entry)]; Log("end", cell.RowIndex, cell.ColumnIndex, result); } public override void OnClearCachedValue(ICacheEntry entry) { int rowIndex; int columnIndex; IEvaluationCell cell = _formulaCellsByCacheEntry.ContainsKey(entry) ? _formulaCellsByCacheEntry[entry] : null; if (cell == null) { Loc loc = _plainCellLocsByCacheEntry.ContainsKey(entry) ? _plainCellLocsByCacheEntry[entry] : null; if (loc == null) { throw new InvalidOperationException("can't find cell or location"); } rowIndex = loc.RowIndex; columnIndex = loc.ColumnIndex; } else { rowIndex = cell.RowIndex; columnIndex = cell.ColumnIndex; } Log("clear", rowIndex, columnIndex, entry.GetValue()); } public override void SortDependentCachedValues(ICacheEntry[] entries) { Array.Sort(entries, new FormulaCellCacheEntryComparer(_formulaCellsByCacheEntry)); } public override void OnClearDependentCachedValue(ICacheEntry entry, int depth) { IEvaluationCell cell = _formulaCellsByCacheEntry.ContainsKey(entry) ? _formulaCellsByCacheEntry[(entry)] : null; Log("clear" + depth, cell.RowIndex, cell.ColumnIndex, entry.GetValue()); } public override void OnChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, IEvaluationCell cell, ICacheEntry entry) { Log("changeFromBlank", rowIndex, columnIndex, entry.GetValue()); if (entry.GetValue() == null) { // hack to tell the difference between formula and plain value // perhaps the API could be improved: onChangeFromBlankToValue, onChangeFromBlankToFormula if (!_formulaCellsByCacheEntry.ContainsKey(entry)) _formulaCellsByCacheEntry.Add(entry, cell); else _formulaCellsByCacheEntry[entry] = cell; } else { Loc loc = new Loc(0, sheetIndex, rowIndex, columnIndex); if (!_plainCellLocsByCacheEntry.ContainsKey(entry)) _plainCellLocsByCacheEntry.Add(entry, loc); else _plainCellLocsByCacheEntry[entry] = loc; } } private void Log(String tag, int rowIndex, int columnIndex, Object value) { StringBuilder sb = new StringBuilder(64); sb.Append(tag).Append(' '); sb.Append(new CellReference(rowIndex, columnIndex, false, false).FormatAsString()); if (value != null) { sb.Append(' ').Append(FormatValue(value)); } _logList.Add(sb.ToString()); } private String FormatValue(Object value) { if (value is Ptg[]) { Ptg[] ptgs = (Ptg[])value; return HSSFFormulaParser.ToFormulaString(_book, ptgs); } if (value is NumberEval) { NumberEval ne = (NumberEval)value; return ne.StringValue; } if (value is StringEval) { StringEval se = (StringEval)value; return "'" + se.StringValue + "'"; } if (value is BoolEval) { BoolEval be = (BoolEval)value; return be.StringValue; } if (value == BlankEval.instance) { return "#BLANK#"; } if (value is ErrorEval) { ErrorEval ee = (ErrorEval)value; return ErrorEval.GetText(ee.ErrorCode); } throw new ArgumentException("Unexpected value class (" + value.GetType().Name + ")"); } public String[] GetAndClearLog() { String[] result = _logList.ToArray(); _logList.Clear(); return result; } } /** * Wrapper class to manage repetitive tasks from this Test, * * Note - this class does a little bit more than just plain Set-up of data. The method * {@link WorkbookEvaluator#ClearCachedResultValue(HSSFSheet, int, int)} is called whenever a * cell value is Changed. * */ private class MySheet { private ISheet _sheet; private WorkbookEvaluator _Evaluator; private HSSFWorkbook _wb; private EvalListener _EvalListener; public MySheet() { _wb = new HSSFWorkbook(); _EvalListener = new EvalListener(_wb); _Evaluator = WorkbookEvaluatorTestHelper.CreateEvaluator(_wb, _EvalListener); _sheet = _wb.CreateSheet("Sheet1"); } private static IEvaluationCell WrapCell(ICell cell) { return HSSFEvaluationTestHelper.WrapCell(cell); } public void SetCellValue(String cellRefText, double value) { ICell cell = GetOrCreateCell(cellRefText); // be sure to blank cell, in case it is currently a formula cell.SetCellType(CellType.Blank); // otherwise this line will only Set the formula cached result; cell.SetCellValue(value); _Evaluator.NotifyUpdateCell(WrapCell(cell)); } public void ClearCell(String cellRefText) { ICell cell = GetOrCreateCell(cellRefText); cell.SetCellType(CellType.Blank); _Evaluator.NotifyUpdateCell(WrapCell(cell)); } public void SetCellFormula(String cellRefText, String formulaText) { ICell cell = GetOrCreateCell(cellRefText); cell.CellFormula = formulaText; _Evaluator.NotifyUpdateCell(WrapCell(cell)); } private ICell GetOrCreateCell(String cellRefText) { CellReference cr = new CellReference(cellRefText); int rowIndex = cr.Row; IRow row = _sheet.GetRow(rowIndex); if (row == null) { row = _sheet.CreateRow(rowIndex); } int cellIndex = cr.Col; ICell cell = row.GetCell(cellIndex); if (cell == null) { cell = row.CreateCell(cellIndex); } return cell; } public ValueEval EvaluateCell(String cellRefText) { return _Evaluator.Evaluate(WrapCell(GetOrCreateCell(cellRefText))); } public String[] GetAndClearLog() { return _EvalListener.GetAndClearLog(); } public void ClearAllCachedResultValues() { _Evaluator.ClearAllCachedResultValues(); } } private static MySheet CreateMediumComplex() { MySheet ms = new MySheet(); // plain data in D1:F3 ms.SetCellValue("D1", 12); ms.SetCellValue("E1", 13); ms.SetCellValue("D2", 14); ms.SetCellValue("E2", 15); ms.SetCellValue("D3", 16); ms.SetCellValue("E3", 17); ms.SetCellFormula("C1", "SUM(D1:E2)"); ms.SetCellFormula("C2", "SUM(D2:E3)"); ms.SetCellFormula("C3", "SUM(D3:E4)"); ms.SetCellFormula("B1", "C2-C1"); ms.SetCellFormula("B2", "B3*C1-C2"); ms.SetCellValue("B3", 2); ms.SetCellFormula("A1", "MAX(B1:B2)"); ms.SetCellFormula("A2", "MIN(B3,D2:F2)"); ms.SetCellFormula("A3", "B3*C3"); // clear all the logging from the above Initialisation ms.GetAndClearLog(); ms.ClearAllCachedResultValues(); return ms; } [Test] public void TestMediumComplex() { MySheet ms = CreateMediumComplex(); // completely fresh Evaluation ConfirmEvaluate(ms, "A1", 46); ConfirmLog(ms, new String[] { "start A1 MAX(B1:B2)", "start B1 C2-C1", "start C2 SUM(D2:E3)", "value D2 14", "value E2 15", "value D3 16", "value E3 17", "end C2 62", "start C1 SUM(D1:E2)", "value D1 12", "value E1 13", "hit D2 14", "hit E2 15", "end C1 54", "end B1 8", "start B2 B3*C1-C2", "value B3 2", "hit C1 54", "hit C2 62", "end B2 46", "end A1 46", }); // simple cache hit - immediate re-Evaluation with no Changes ConfirmEvaluate(ms, "A1", 46); ConfirmLog(ms, new String[] { "hit A1 46", }); // change a low level cell ms.SetCellValue("D1", 10); ConfirmLog(ms, new String[] { "clear D1 10", "clear1 C1 54", "clear2 B1 8", "clear3 A1 46", "clear2 B2 46", }); ConfirmEvaluate(ms, "A1", 42); ConfirmLog(ms, new String[] { "start A1 MAX(B1:B2)", "start B1 C2-C1", "hit C2 62", "start C1 SUM(D1:E2)", "hit D1 10", "hit E1 13", "hit D2 14", "hit E2 15", "end C1 52", "end B1 10", "start B2 B3*C1-C2", "hit B3 2", "hit C1 52", "hit C2 62", "end B2 42", "end A1 42", }); // Reset and try changing an intermediate value ms = CreateMediumComplex(); ConfirmEvaluate(ms, "A1", 46); ms.GetAndClearLog(); ms.SetCellValue("B3", 3); // B3 is in the middle of the dependency tree ConfirmLog(ms, new String[] { "clear B3 3", "clear1 B2 46", "clear2 A1 46", }); ConfirmEvaluate(ms, "A1", 100); ConfirmLog(ms, new String[] { "start A1 MAX(B1:B2)", "hit B1 8", "start B2 B3*C1-C2", "hit B3 3", "hit C1 54", "hit C2 62", "end B2 100", "end A1 100", }); } [Test] public void TestMediumComplexWithDependencyChange() { // Changing an intermediate formula MySheet ms = CreateMediumComplex(); ConfirmEvaluate(ms, "A1", 46); ms.GetAndClearLog(); ms.SetCellFormula("B2", "B3*C2-C3"); // used to be "B3*C1-C2" ConfirmLog(ms, new String[] { "clear B2 46", "clear1 A1 46", }); ConfirmEvaluate(ms, "A1", 91); ConfirmLog(ms, new String[] { "start A1 MAX(B1:B2)", "hit B1 8", "start B2 B3*C2-C3", "hit B3 2", "hit C2 62", "start C3 SUM(D3:E4)", "hit D3 16", "hit E3 17", // "value D4 #BLANK#", "value E4 #BLANK#", "end C3 33", "end B2 91", "end A1 91", }); //---------------- // Note - From now on the demonstrated POI behaviour is not optimal //---------------- // Now change a value that should no longer affect B2 ms.SetCellValue("D1", 11); ConfirmLog(ms, new String[] { "clear D1 11", "clear1 C1 54", // note there is no "Clear2 B2 91" here because B2 doesn't depend on C1 anymore "clear2 B1 8", "clear3 A1 91", }); ConfirmEvaluate(ms, "B2", 91); ConfirmLog(ms, new String[] { "hit B2 91", // further Confirmation that B2 was not cleared due to changing D1 above }); // things should be back to normal now ms.SetCellValue("D1", 11); ConfirmLog(ms, new String[] { }); ConfirmEvaluate(ms, "B2", 91); ConfirmLog(ms, new String[] { "hit B2 91", }); } /** * verifies that when updating a plain cell, depending (formula) cell cached values are cleared * only when the plain cell's value actually changes */ [Test] public void TestRedundantUpdate() { MySheet ms = new MySheet(); ms.SetCellValue("B1", 12); ms.SetCellValue("C1", 13); ms.SetCellFormula("A1", "B1+C1"); // Evaluate twice to confirm caching looks OK ms.EvaluateCell("A1"); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 25); ConfirmLog(ms, new String[] { "hit A1 25", }); // Make redundant update, and check re-Evaluation ms.SetCellValue("B1", 12); // value didn't change ConfirmLog(ms, new String[] { }); ConfirmEvaluate(ms, "A1", 25); ConfirmLog(ms, new String[] { "hit A1 25", }); ms.SetCellValue("B1", 11); // value changing ConfirmLog(ms, new String[] { "clear B1 11", "clear1 A1 25", // expect consuming formula cached result to Get Cleared }); ConfirmEvaluate(ms, "A1", 24); ConfirmLog(ms, new String[] { "start A1 B1+C1", "hit B1 11", "hit C1 13", "end A1 24", }); } /** * Changing any input to a formula may cause the formula to 'use' a different Set of cells. * Functions like INDEX and OFFSET make this effect obvious, with functions like MATCH * and VLOOKUP the effect can be subtle. The presence of error values can also produce this * effect in almost every function and operator. */ [Test] public void TestSimpleWithDependencyChange() { MySheet ms = new MySheet(); ms.SetCellFormula("A1", "INDEX(C1:E1,1,B1)"); ms.SetCellValue("B1", 1); ms.SetCellValue("C1", 17); ms.SetCellValue("D1", 18); ms.SetCellValue("E1", 19); ms.ClearAllCachedResultValues(); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 17); ConfirmLog(ms, new String[] { "start A1 INDEX(C1:E1,1,B1)", "value B1 1", "value C1 17", "end A1 17", }); ms.SetCellValue("B1", 2); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 18); ConfirmLog(ms, new String[] { "start A1 INDEX(C1:E1,1,B1)", "hit B1 2", "value D1 18", "end A1 18", }); // change C1. Note - last time A1 Evaluated C1 was not used ms.SetCellValue("C1", 15); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 18); ConfirmLog(ms, new String[] { "hit A1 18", }); // but A1 still uses D1, so if it Changes... ms.SetCellValue("D1", 25); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 25); ConfirmLog(ms, new String[] { "start A1 INDEX(C1:E1,1,B1)", "hit B1 2", "hit D1 25", "end A1 25", }); } [Test] public void TestBlankCells() { MySheet ms = new MySheet(); ms.SetCellFormula("A1", "sum(B1:D4,B5:E6)"); ms.SetCellValue("B1", 12); ms.ClearAllCachedResultValues(); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 12); ConfirmLog(ms, new String[] { "start A1 SUM(B1:D4,B5:E6)", "value B1 12", "end A1 12", }); ms.SetCellValue("B6", 2); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 14); ConfirmLog(ms, new String[] { "start A1 SUM(B1:D4,B5:E6)", "hit B1 12", "hit B6 2", "end A1 14", }); ms.SetCellValue("E4", 2); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 14); ConfirmLog(ms, new String[] { "hit A1 14", }); ms.SetCellValue("D1", 1); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 15); ConfirmLog(ms, new String[] { "start A1 SUM(B1:D4,B5:E6)", "hit B1 12", "hit D1 1", "hit B6 2", "end A1 15", }); } /** * Make sure that when blank cells are Changed to value/formula cells, any dependent formulas * have their cached results Cleared. */ [Test] public void TestBlankCellChangedToValueCell_bug46053() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet = wb.CreateSheet("Sheet1"); IRow row = sheet.CreateRow(0); ICell cellA1 = row.CreateCell(0); ICell cellB1 = row.CreateCell(1); HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); cellA1.CellFormula = "B1+2.2"; cellB1.SetCellValue(1.5); fe.NotifyUpdateCell(cellA1); fe.NotifyUpdateCell(cellB1); CellValue cv; cv = fe.Evaluate(cellA1); Assert.AreEqual(3.7, cv.NumberValue, 0.0); cellB1.SetCellType(CellType.Blank); fe.NotifyUpdateCell(cellB1); cv = fe.Evaluate(cellA1); // B1 was used to Evaluate A1 Assert.AreEqual(2.2, cv.NumberValue, 0.0); cellB1.SetCellValue(0.4); // changing B1, so A1 cached result should be Cleared fe.NotifyUpdateCell(cellB1); cv = fe.Evaluate(cellA1); if (cv.NumberValue == 2.2) { // looks like left-over cached result from before change to B1 throw new AssertionException("Identified bug 46053"); } Assert.AreEqual(2.6, cv.NumberValue, 0.0); } /** * same use-case as the Test for bug 46053, but Checking trace values too */ [Test] public void TestBlankCellChangedToValueCell() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); MySheet ms = new MySheet(); ms.SetCellFormula("A1", "B1+2.2"); ms.SetCellValue("B1", 1.5); ms.ClearAllCachedResultValues(); ms.ClearCell("B1"); ms.GetAndClearLog(); ConfirmEvaluate(ms, "A1", 2.2); ConfirmLog(ms, new String[] { "start A1 B1+2.2", "end A1 2.2", }); ms.SetCellValue("B1", 0.4); ConfirmLog(ms, new String[] { "changeFromBlank B1 0.4", "clear A1", }); ConfirmEvaluate(ms, "A1", 2.6); ConfirmLog(ms, new String[] { "start A1 B1+2.2", "hit B1 0.4", "end A1 2.6", }); } private static void ConfirmEvaluate(MySheet ms, String cellRefText, double expectedValue) { ValueEval v = ms.EvaluateCell(cellRefText); Assert.AreEqual(typeof(NumberEval), v.GetType()); Assert.AreEqual(expectedValue, ((NumberEval)v).NumberValue, 0.0); } private static void ConfirmLog(MySheet ms, String[] expectedLog) { String[] actualLog = ms.GetAndClearLog(); int endIx = actualLog.Length; if (endIx != expectedLog.Length) { System.Console.Error.WriteLine("Log lengths mismatch"); dumpCompare(System.Console.Error, expectedLog, actualLog); throw new AssertionException("Log lengths mismatch"); } for (int i = 0; i < endIx; i++) { if (!actualLog[i].Equals(expectedLog[i])) { String msg = "Log entry mismatch at index " + i; System.Console.Error.WriteLine(msg); dumpCompare(System.Console.Error, expectedLog, actualLog); throw new AssertionException(msg); } } } private static void dumpCompare(TextWriter ps, String[] expectedLog, String[] actualLog) { int max = Math.Max(actualLog.Length, expectedLog.Length); ps.WriteLine("Index\tExpected\tActual"); for (int i = 0; i < max; i++) { ps.Write(i + "\t"); printItem(ps, expectedLog, i); ps.Write("\t"); printItem(ps, actualLog, i); ps.WriteLine(); } ps.WriteLine(); debugPrint(ps, actualLog); } private static void printItem(TextWriter ps, String[] ss, int index) { if (index < ss.Length) { ps.Write(ss[index]); } } private static void debugPrint(TextWriter ps, String[] log) { for (int i = 0; i < log.Length; i++) { ps.WriteLine('"' + log[i] + "\","); } } private static void TestPlainValueCache(HSSFWorkbook wb, int numberOfSheets) { IRow row; ICell cell; //create summary sheet ISheet summary = wb.CreateSheet("summary"); wb.SetActiveSheet(wb.GetSheetIndex(summary)); //formula referring all sheets Created below row = summary.CreateRow(0); ICell summaryCell = row.CreateCell(0); summaryCell.CellFormula=("SUM(A2:A" + (numberOfSheets + 2) + ")"); //create sheets with cells having (different) numbers // and add a row to summary for (int i = 1; i < numberOfSheets; i++) { ISheet sheet = wb.CreateSheet("new" + i); row = sheet.CreateRow(0); cell = row.CreateCell(0); cell.SetCellValue(i); row = summary.CreateRow(i); cell = row.CreateCell(0); cell.CellFormula=("new" + i + "!A1"); } //calculate IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator(); Evaluator.EvaluateFormulaCell(summaryCell); } [Test] public void TestPlainValueCache() { HSSFWorkbook wb = new HSSFWorkbook(); int numberOfSheets = 4098; // Bug 51448 reported that Evaluation Cache got messed up After 256 sheets IRow row; ICell cell; //create summary sheet ISheet summary = wb.CreateSheet("summary"); wb.SetActiveSheet(wb.GetSheetIndex(summary)); //formula referring all sheets Created below row = summary.CreateRow(0); ICell summaryCell = row.CreateCell(0); summaryCell.CellFormula = "SUM(A2:A" + (numberOfSheets + 2) + ")"; //create sheets with cells having (different) numbers // and add a row to summary for (int i = 1; i < numberOfSheets; i++) { ISheet sheet = wb.CreateSheet("new" + i); row = sheet.CreateRow(0); cell = row.CreateCell(0); cell.SetCellValue(i); row = summary.CreateRow(i); cell = row.CreateCell(0); cell.CellFormula = "new" + i + "!A1"; } //calculate IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator(); Evaluator.EvaluateFormulaCell(summaryCell); Assert.AreEqual(8394753.0, summaryCell.NumericCellValue); } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this 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, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using System; using System.Reflection; using System.Reflection.Emit; using System.Diagnostics; public sealed class Plus : BinaryOp{ private Object metaData = null; internal Plus(Context context, AST operand1, AST operand2) : base(context, operand1, operand2, JSToken.Plus){ } public Plus() : base(null, null, null, JSToken.Plus){ } internal override Object Evaluate(){ return this.EvaluatePlus(this.operand1.Evaluate(), this.operand2.Evaluate()); } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif public Object EvaluatePlus(Object v1, Object v2){ if (v1 is Int32 && v2 is Int32) return Plus.DoOp((Int32)v1, (Int32)v2); else if (v1 is Double && v2 is Double) return Plus.DoOp((Double)v1, (Double)v2); else return this.EvaluatePlus2(v1, v2); } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif private Object EvaluatePlus2(Object v1, Object v2){ IConvertible ic1 = Convert.GetIConvertible(v1); IConvertible ic2 = Convert.GetIConvertible(v2); TypeCode t1 = Convert.GetTypeCode(v1, ic1); TypeCode t2 = Convert.GetTypeCode(v2, ic2); switch (t1){ case TypeCode.Empty: return Plus.DoOp(v1, v2); case TypeCode.DBNull: switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return 0; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: return ic2.ToInt32(null); case TypeCode.UInt32: return ic2.ToUInt32(null); case TypeCode.Int64: return ic2.ToInt64(null); case TypeCode.UInt64: return ic2.ToUInt64(null); case TypeCode.Single: case TypeCode.Double: return ic2.ToDouble(null); case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: return "null" + ic2.ToString(null); } break; case TypeCode.Char: {int val = ic1.ToInt32(null); switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return val; case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: return ((IConvertible)Plus.DoOp(val, ic2.ToInt32(null))).ToChar(null); case TypeCode.UInt32: case TypeCode.Int64: return ((IConvertible)Plus.DoOp((long)val, ic2.ToInt64(null))).ToChar(null); case TypeCode.UInt64: return ((IConvertible)Plus.DoOp((ulong)val, ic2.ToUInt64(null))).ToChar(null); case TypeCode.Single: case TypeCode.Double: checked {return (char)(int)(Convert.CheckIfDoubleIsInteger((double)Plus.DoOp((double)val, ic2.ToDouble(null))));} case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: return Plus.DoOp(v1, v2); case TypeCode.Char: case TypeCode.String: return ic1.ToString(null) + ic2.ToString(null); } break;} case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: {int val = ic1.ToInt32(null); switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return val; case TypeCode.Char: return ((IConvertible)Plus.DoOp(val, ic2.ToInt32(null))).ToChar(null); case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: return Plus.DoOp(val, ic2.ToInt32(null)); case TypeCode.UInt32: case TypeCode.Int64: return Plus.DoOp((long)val, ic2.ToInt64(null)); case TypeCode.UInt64: if (val >= 0) return Plus.DoOp((ulong)val, ic2.ToUInt64(null)); else return Plus.DoOp((double)val, ic2.ToDouble(null)); case TypeCode.Single: case TypeCode.Double: return Plus.DoOp((double)val, ic2.ToDouble(null)); case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: return Convert.ToString(v1) + ic2.ToString(null); } break;} case TypeCode.UInt32: {uint val = ic1.ToUInt32(null); switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return val; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: int val2 = ic2.ToInt32(null); if (val2 >= 0) return Plus.DoOp(val, (uint)val2); else return Plus.DoOp((long)val, (long)val2); case TypeCode.Int64: return Plus.DoOp((long)val, ic2.ToInt64(null)); case TypeCode.Char: return ((IConvertible)Plus.DoOp(val, ic2.ToUInt32(null))).ToChar(null); case TypeCode.Boolean: case TypeCode.UInt16: case TypeCode.UInt32: return Plus.DoOp(val, ic2.ToUInt32(null)); case TypeCode.UInt64: return Plus.DoOp((ulong)val, ic2.ToUInt64(null)); case TypeCode.Single: case TypeCode.Double: return Plus.DoOp((double)val, ic2.ToDouble(null)); case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: return Convert.ToString(v1) + ic2.ToString(null); } break;} case TypeCode.Int64: {long val = ic1.ToInt64(null); switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return val; case TypeCode.Char: return ((IConvertible)Plus.DoOp(val, ic2.ToInt64(null))).ToChar(null); case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: return Plus.DoOp(val, ic2.ToInt64(null)); case TypeCode.UInt64: if (val >= 0) return Plus.DoOp((ulong)val, ic2.ToUInt64(null)); else return Plus.DoOp((double)val, ic2.ToDouble(null)); case TypeCode.Single: case TypeCode.Double: return Plus.DoOp((double)val, ic2.ToDouble(null)); case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: return Convert.ToString(v1) + ic2.ToString(null); } break;} case TypeCode.UInt64: {ulong val = ic1.ToUInt64(null); switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return val; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: long val2 = ic2.ToInt64(null); if (val2 >= 0) return Plus.DoOp(val, (ulong)val2); else return Plus.DoOp((double)val, (double)val2); case TypeCode.Char: return ((IConvertible)Plus.DoOp(val, ic2.ToUInt64(null))).ToChar(null); case TypeCode.UInt16: case TypeCode.Boolean: case TypeCode.UInt32: case TypeCode.UInt64: return Plus.DoOp(val, ic2.ToUInt64(null)); case TypeCode.Single: case TypeCode.Double: return Plus.DoOp((double)val, ic2.ToDouble(null)); case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: return Convert.ToString(v1) + ic2.ToString(null); } break;} case TypeCode.Single: case TypeCode.Double:{ double d = ic1.ToDouble(null); switch (t2){ case TypeCode.Empty: return Double.NaN; case TypeCode.DBNull: return ic1.ToDouble(null); case TypeCode.Char: return System.Convert.ToChar(System.Convert.ToInt32((d + (double)ic2.ToInt32(null)))); case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: return d + (double)ic2.ToInt32(null); case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: return d + ic2.ToDouble(null); case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: return new ConcatString(Convert.ToString(d), ic2.ToString(null)); } break;} case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: break; case TypeCode.String: switch (t2){ case TypeCode.Object: break; case TypeCode.String: if (v1 is ConcatString) return new ConcatString((ConcatString)v1, ic2.ToString(null)); else return new ConcatString(ic1.ToString(null), ic2.ToString(null)); default: if (v1 is ConcatString) return new ConcatString((ConcatString)v1, Convert.ToString(v2)); else return new ConcatString(ic1.ToString(null), Convert.ToString(v2)); } break; } MethodInfo oper = this.GetOperator(v1 == null ? Typeob.Empty : v1.GetType(), v2 == null ? Typeob.Empty : v2.GetType()); if (oper != null) return oper.Invoke(null, (BindingFlags)0, JSBinder.ob, new Object[]{v1, v2}, null); else return Plus.DoOp(v1, v2); } private new MethodInfo GetOperator(IReflect ir1, IReflect ir2){ Type t1 = ir1 is Type ? (Type)ir1 : Typeob.Object; Type t2 = ir2 is Type ? (Type)ir2 : Typeob.Object; if (this.type1 == t1 && this.type2 == t2) return this.operatorMeth; if (t1 == Typeob.String || t2 == Typeob.String || ((Convert.IsPrimitiveNumericType(t1) || Typeob.JSObject.IsAssignableFrom(t1)) && (Convert.IsPrimitiveNumericType(t2) || Typeob.JSObject.IsAssignableFrom(t2)))){ this.operatorMeth = null; this.type1 = t1; this.type2 = t2; return null; } return base.GetOperator(t1, t2); } private static Object DoOp(double x, double y){ return x + y; } private static Object DoOp(int x, int y){ int r = x + y; // If the result is on the same side of x as y is to 0, no overflow occured. if ((r < x) == (y < 0)) return r; return ((double)x) + (double)y; } private static Object DoOp(long x, long y){ // If the result is on the same side of x as y is to 0, no overflow occured. long r = x + y; if ((r < x) == (y < 0)) return r; return ((double)x) + (double)y; } private static Object DoOp(uint x, uint y){ uint r = x + y; if (r >= x) // Since y >= 0, no overflow occured if r >= x. return r; return ((double)x) + (double)y; } private static Object DoOp(ulong x, ulong y){ ulong r = x + y; if (r >= x) // Since y >= 0, no overflow occured if r >= x. return r; return ((double)x) + (double)y; } public static Object DoOp(Object v1, Object v2){ IConvertible ic1 = Convert.GetIConvertible(v1); IConvertible ic2 = Convert.GetIConvertible(v2); v1 = Convert.ToPrimitive(v1, PreferredType.Either, ref ic1); v2 = Convert.ToPrimitive(v2, PreferredType.Either, ref ic2); TypeCode t1 = Convert.GetTypeCode(v1, ic1); TypeCode t2 = Convert.GetTypeCode(v2, ic2); if (t1 == TypeCode.String) if (v1 is ConcatString) return new ConcatString((ConcatString)v1, Convert.ToString(v2, ic2)); else return new ConcatString(ic1.ToString(null), Convert.ToString(v2, ic2)); else if (t2 == TypeCode.String) return Convert.ToString(v1, ic1) + ic2.ToString(null); else if (t1 == TypeCode.Char && t2 == TypeCode.Char) return ic1.ToString(null) + ic2.ToString(null); else if ((t1 == TypeCode.Char && (Convert.IsPrimitiveNumericTypeCode(t2) || t2 == TypeCode.Boolean)) || (t2 == TypeCode.Char && (Convert.IsPrimitiveNumericTypeCode(t1) || t1 == TypeCode.Boolean))) return (char)(int)Runtime.DoubleToInt64(Convert.ToNumber(v1, ic1) + Convert.ToNumber(v2, ic2)); else return Convert.ToNumber(v1, ic1) + Convert.ToNumber(v2, ic2); } internal override IReflect InferType(JSField inference_target){ Debug.Assert(Globals.TypeRefs.InReferenceContext(this.type1)); Debug.Assert(Globals.TypeRefs.InReferenceContext(this.type2)); MethodInfo oper; if (this.type1 == null || inference_target != null) oper = this.GetOperator(this.operand1.InferType(inference_target), this.operand2.InferType(inference_target)); else oper = this.GetOperator(this.type1, this.type2); if (oper != null){ this.metaData = oper; return oper.ReturnType; } if (this.type1 == Typeob.String || this.type2 == Typeob.String) return Typeob.String; else if (this.type1 == Typeob.Char && this.type2 == Typeob.Char) return Typeob.String; else if (Convert.IsPrimitiveNumericTypeFitForDouble(this.type1)){ if (this.type2 == Typeob.Char) return Typeob.Char; else if (Convert.IsPrimitiveNumericTypeFitForDouble(this.type2)) return Typeob.Double; else return Typeob.Object; }else if (Convert.IsPrimitiveNumericTypeFitForDouble(this.type2)){ if (this.type1 == Typeob.Char) return Typeob.Char; else if (Convert.IsPrimitiveNumericTypeFitForDouble(this.type1)) return Typeob.Double; else return Typeob.Object; }else if (this.type1 == Typeob.Boolean && this.type2 == Typeob.Char) return Typeob.Char; else if (this.type1 == Typeob.Char && this.type2 == Typeob.Boolean) return Typeob.Char; else return Typeob.Object; } internal override void TranslateToIL(ILGenerator il, Type rtype){ Type type = Convert.ToType(this.InferType(null)); if (this.metaData == null){ Type rt = Typeob.Object; if (rtype == Typeob.Double) rt = rtype; else if (this.type1 == Typeob.Char && this.type2 == Typeob.Char) rt = Typeob.String; else if (Convert.IsPrimitiveNumericType(rtype) && Convert.IsPromotableTo(this.type1, rtype) && Convert.IsPromotableTo(this.type2, rtype)) rt = rtype; else if (this.type1 != Typeob.String && this.type2 != Typeob.String) //Both will be converted to numbers rt = Typeob.Double; //Won't get here unless InferType returned Typeob.Double. else rt = Typeob.String; if (rt == Typeob.SByte || rt == Typeob.Int16) rt = Typeob.Int32; else if (rt == Typeob.Byte || rt == Typeob.UInt16 || rt == Typeob.Char) rt = Typeob.UInt32; if (rt == Typeob.String){ if (this.operand1 is Plus && this.type1 == rt){ Plus op1 = (Plus)this.operand1; if (op1.operand1 is Plus && op1.type1 == rt){ Plus op11 = (Plus)op1.operand1; if (op11.operand1 is Plus && op11.type1 == rt){ int len = op1.TranslateToILArrayOfStrings(il, 1); il.Emit(OpCodes.Dup); ConstantWrapper.TranslateToILInt(il, len-1); this.operand2.TranslateToIL(il, rt); il.Emit(OpCodes.Stelem_Ref); il.Emit(OpCodes.Call, CompilerGlobals.stringConcatArrMethod); Convert.Emit(this, il, rt, rtype); return; } Plus.TranslateToStringWithSpecialCaseForNull(il, op11.operand1); Plus.TranslateToStringWithSpecialCaseForNull(il, op11.operand2); Plus.TranslateToStringWithSpecialCaseForNull(il, op1.operand2); Plus.TranslateToStringWithSpecialCaseForNull(il, this.operand2); il.Emit(OpCodes.Call, CompilerGlobals.stringConcat4Method); Convert.Emit(this, il, rt, rtype); return; } Plus.TranslateToStringWithSpecialCaseForNull(il, op1.operand1); Plus.TranslateToStringWithSpecialCaseForNull(il, op1.operand2); Plus.TranslateToStringWithSpecialCaseForNull(il, this.operand2); il.Emit(OpCodes.Call, CompilerGlobals.stringConcat3Method); Convert.Emit(this, il, rt, rtype); return; } Plus.TranslateToStringWithSpecialCaseForNull(il, this.operand1); Plus.TranslateToStringWithSpecialCaseForNull(il, this.operand2); il.Emit(OpCodes.Call, CompilerGlobals.stringConcat2Method); Convert.Emit(this, il, rt, rtype); return; } this.operand1.TranslateToIL(il, rt); this.operand2.TranslateToIL(il, rt); if (rt == Typeob.Object){ il.Emit(OpCodes.Call, CompilerGlobals.plusDoOpMethod); }else if (rt == Typeob.Double || rt == Typeob.Single) il.Emit(OpCodes.Add); else if (rt == Typeob.Int32 || rt == Typeob.Int64) il.Emit(OpCodes.Add_Ovf); else il.Emit(OpCodes.Add_Ovf_Un); if (type == Typeob.Char){ Convert.Emit(this, il, rt, Typeob.Char); Convert.Emit(this, il, Typeob.Char, rtype); } else Convert.Emit(this, il, rt, rtype); return; } if (this.metaData is MethodInfo){ MethodInfo oper = (MethodInfo)this.metaData; ParameterInfo[] pars = oper.GetParameters(); this.operand1.TranslateToIL(il, pars[0].ParameterType); this.operand2.TranslateToIL(il, pars[1].ParameterType); il.Emit(OpCodes.Call, oper); Convert.Emit(this, il, oper.ReturnType, rtype); return; } //Getting here is just too bad. We do not know until the code runs whether or not to call an overloaded operator method. //Compile operands to objects and devolve the decision making to run time thunks //Also get here when dealing with Int64 and UInt64. These cannot always be converted to doubles. The late-bound code checks for this. il.Emit(OpCodes.Ldloc, (LocalBuilder)this.metaData); this.operand1.TranslateToIL(il, Typeob.Object); this.operand2.TranslateToIL(il, Typeob.Object); il.Emit(OpCodes.Callvirt, CompilerGlobals.evaluatePlusMethod); Convert.Emit(this, il, Typeob.Object, rtype); } private int TranslateToILArrayOfStrings(ILGenerator il, int n){ int len = n+2; if (this.operand1 is Plus && this.type1 == Typeob.String) len = ((Plus)this.operand1).TranslateToILArrayOfStrings(il, n+1); else{ ConstantWrapper.TranslateToILInt(il, len); il.Emit(OpCodes.Newarr, Typeob.String); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldc_I4_0); Plus.TranslateToStringWithSpecialCaseForNull(il, this.operand1); il.Emit(OpCodes.Stelem_Ref); } il.Emit(OpCodes.Dup); ConstantWrapper.TranslateToILInt(il, len-1-n); Plus.TranslateToStringWithSpecialCaseForNull(il, this.operand2); il.Emit(OpCodes.Stelem_Ref); return len; } internal override void TranslateToILInitializer(ILGenerator il){ IReflect rtype = this.InferType(null); this.operand1.TranslateToILInitializer(il); this.operand2.TranslateToILInitializer(il); if (rtype != Typeob.Object) return; this.metaData = il.DeclareLocal(Typeob.Plus); il.Emit(OpCodes.Newobj, CompilerGlobals.plusConstructor); il.Emit(OpCodes.Stloc, (LocalBuilder)this.metaData); } private static void TranslateToStringWithSpecialCaseForNull(ILGenerator il, AST operand){ ConstantWrapper cw = operand as ConstantWrapper; if (cw != null){ if (cw.value is DBNull) il.Emit(OpCodes.Ldstr, "null"); else if (cw.value == Empty.Value) il.Emit(OpCodes.Ldstr, "undefined"); else cw.TranslateToIL(il, Typeob.String); }else operand.TranslateToIL(il, Typeob.String); } } }
// // AudioFile.cs: // // Authors: // Miguel de Icaza (miguel@novell.com) // // Copyright 2009 Novell, Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using OSStatus = System.Int32; using AudioFileID = System.IntPtr; namespace MonoMac.AudioToolbox { public enum AudioFileType { AIFF = 0x41494646, // AIFF AIFC = 0x41494643, // AIFC WAVE = 0x57415645, // WAVE SoundDesigner2 = 0x53643266, // Sd2f Next = 0x4e655854, // NeXT MP3 = 0x4d504733, // MPG3 MP2 = 0x4d504732, // MPG2 MP1 = 0x4d504731, // MPG1 AC3 = 0x61632d33, // ac-3 AAC_ADTS = 0x61647473, // adts MPEG4 = 0x6d703466, // mp4f M4A = 0x6d346166, // m4af CAF = 0x63616666, // caff ThreeGP = 0x33677070, // 3gpp ThreeGP2 = 0x33677032, // 3gp2 AMR = 0x616d7266, // amrf } enum AudioFileError { Unspecified = 0x7768743f, // wht? UnsupportedFileType = 0x7479703f, // typ? UnsupportedDataFormat = 0x666d743f, // fmt? UnsupportedProperty = 0x7074793f, // pty? BadPropertySize = 0x2173697a, // !siz Permissions = 0x70726d3f, // prm? NotOptimized = 0x6f70746d, // optm InvalidChunk = 0x63686b3f, // chk? DoesNotAllow64BitDataSize = 0x6f66663f, // off? InvalidPacketOffset = 0x70636b3f, // pck? InvalidFile = 0x6474613f, // dta? FileNotOpen = -38, EndOfFile = -39, FileNotFound = -43, FilePosition = -40, } [Flags] public enum AudioFilePermission { Read = 0x01, Write = 0x02, ReadWrite = 0x03 } [Flags] public enum AudioFileFlags { EraseFlags = 1, DontPageAlignAudioData = 2 } public enum AudioFileProperty { FileFormat = 0x66666d74, DataFormat = 0x64666d74, IsOptimized = 0x6f70746d, MagicCookieData = 0x6d676963, AudioDataByteCount = 0x62636e74, AudioDataPacketCount = 0x70636e74, MaximumPacketSize = 0x70737a65, DataOffset = 0x646f6666, ChannelLayout = 0x636d6170, DeferSizeUpdates = 0x64737a75, DataFormatName = 0x666e6d65, MarkerList = 0x6d6b6c73, RegionList = 0x72676c73, PacketToFrame = 0x706b6672, FrameToPacket = 0x6672706b, PacketToByte = 0x706b6279, ByteToPacket = 0x6279706b, ChunkIDs = 0x63686964, InfoDictionary = 0x696e666f, PacketTableInfo = 0x706e666f, FormatList = 0x666c7374, PacketSizeUpperBound = 0x706b7562, ReserveDuration = 0x72737276, EstimatedDuration = 0x65647572, BitRate = 0x62726174, ID3Tag = 0x69643374, } public enum AudioFileLoopDirection { NoLooping = 0, Forward = 1, ForwardAndBackward = 2, Backward = 3 } [StructLayout(LayoutKind.Sequential)] struct AudioFramePacketTranslation { public long Frame; public long Packet; public int FrameOffsetInPacket; } [StructLayout(LayoutKind.Sequential)] struct AudioBytePacketTranslation { public long Byte; public long Packet; public int ByteOffsetInPacket; public uint Flags; }; [StructLayout(LayoutKind.Sequential)] struct AudioFileSmpteTime { public sbyte Hours; public byte Minutes; public byte Seconds; public byte Frames; public uint SubFrameSampleOffset; } [StructLayout(LayoutKind.Sequential)] struct AudioFileMarker { public double FramePosition; public IntPtr Name_cfstringref; public int MarkerID; public AudioFileSmpteTime SmpteTime; public uint Type; public ushort Reserved; public ushort Channel; public string Name { get { return CFString.FetchString (Name_cfstringref); } } } [StructLayout(LayoutKind.Sequential)] struct AudioFileMarkerList { public uint SmpteTimeType; public uint NumberMarkers; public AudioFileMarker Markers; // this is a variable length array of mNumberMarkers elements public static int RecordsThatFitIn (int n) { unsafe { if (n <= sizeof (AudioFileMarker)) return 0; n -= 8; return n / sizeof (AudioFileMarker); } } public static int SizeForMarkers (int markers) { unsafe { return 8 + markers * sizeof (AudioFileMarker); } } } [StructLayout(LayoutKind.Sequential)] struct AudioFileRegion { public uint RegionID; public IntPtr Name_cfstringref; public uint Flags; public int Count; public AudioFileMarker Markers; // this is a variable length array of mNumberMarkers elements } [StructLayout(LayoutKind.Sequential)] struct AudioFileRegionList { public uint SmpteTimeType; public int Count; public AudioFileRegion Regions; // this is a variable length array of mNumberRegions elements } public class AudioFile : IDisposable { internal protected IntPtr handle; protected internal AudioFile (bool x) { // This ctor is used by AudioSource that will set the handle later. } internal AudioFile (IntPtr handle) { this.handle = handle; } ~AudioFile () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileClose (AudioFileID handle); protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ AudioFileClose (handle); handle = IntPtr.Zero; } } public long Length { get { return GetLong (AudioFileProperty.AudioDataByteCount); } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileCreateWithURL (IntPtr cfurlref_infile, AudioFileType inFileType, ref AudioStreamBasicDescription inFormat, AudioFileFlags inFlags, out AudioFileID file_id); public static AudioFile Create (string url, AudioFileType fileType, AudioStreamBasicDescription format, AudioFileFlags inFlags) { if (url == null) throw new ArgumentNullException ("url"); using (CFUrl cfurl = CFUrl.FromUrlString (url, null)) return Create (cfurl, fileType, format, inFlags); } public static AudioFile Create (CFUrl url, AudioFileType fileType, AudioStreamBasicDescription format, AudioFileFlags inFlags) { if (url == null) throw new ArgumentNullException ("url"); IntPtr h; if (AudioFileCreateWithURL (url.Handle, fileType, ref format, inFlags, out h) == 0) return new AudioFile (h); return null; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileOpenURL (IntPtr cfurlref_infile, byte permissions, AudioFileType fileTypeHint, out IntPtr file_id); public static AudioFile OpenRead (string url, AudioFileType fileTypeHint) { return Open (url, AudioFilePermission.Read, fileTypeHint); } public static AudioFile Open (string url, AudioFilePermission permissions, AudioFileType fileTypeHint) { if (url == null) throw new ArgumentNullException ("url"); using (CFUrl cfurl = CFUrl.FromUrlString (url, null)) return Open (cfurl, permissions, fileTypeHint); } public static AudioFile Open (CFUrl url, AudioFilePermission permissions, AudioFileType fileTypeHint) { if (url == null) throw new ArgumentNullException ("url"); IntPtr h; if (AudioFileOpenURL (url.Handle, (byte) permissions, fileTypeHint, out h) == 0) return new AudioFile (h); return null; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileOptimize (AudioFileID handle); public bool Optimize () { return AudioFileOptimize (handle) == 0; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileReadBytes (AudioFileID inAudioFile, bool useCache, long startingByte, ref int numBytes, IntPtr outBuffer); public int Read (long startingByte, byte [] buffer, int offset, int count, bool useCache) { if (offset < 0) throw new ArgumentException ("offset", "<0"); if (count < 0) throw new ArgumentException ("count", "<0"); if (startingByte < 0) throw new ArgumentException ("startingByte", "<0"); int len = buffer.Length; if (offset > len) throw new ArgumentException ("destination offset is beyond array size"); // reordered to avoid possible integer overflow if (offset > len - count) throw new ArgumentException ("Reading would overrun buffer"); unsafe { fixed (byte *p = &buffer [offset]){ if (AudioFileReadBytes (handle, useCache, startingByte, ref count, (IntPtr) p) == 0) return count; else return -1; } } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileWriteBytes (AudioFileID audioFile, bool useCache, long startingByte, ref int numBytes, IntPtr buffer); public int Write (long startingByte, byte [] buffer, int offset, int count, bool useCache) { if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); if (offset > buffer.Length - count) throw new ArgumentException ("Reading would overrun buffer"); unsafe { fixed (byte *p = &buffer [offset]){ if (AudioFileWriteBytes (handle, useCache, startingByte, ref count, (IntPtr) p) == 0) return count; else return -1; } } } public int Write (long startingByte, byte [] buffer, int offset, int count, bool useCache, out int errorCode) { if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); if (offset > buffer.Length - count) throw new ArgumentException ("Reading would overrun buffer"); unsafe { fixed (byte *p = &buffer [offset]){ errorCode = AudioFileWriteBytes (handle, useCache, startingByte, ref count, (IntPtr) p); if (errorCode == 0) return count; else return -1; } } } [DllImport (Constants.AudioToolboxLibrary)] unsafe extern static OSStatus AudioFileReadPacketData ( AudioFileID audioFile, bool useCache, ref int numBytes, IntPtr *ptr_outPacketDescriptions, long inStartingPacket, ref int numPackets, IntPtr outBuffer); [DllImport (Constants.AudioToolboxLibrary)] unsafe extern static OSStatus AudioFileReadPackets ( AudioFileID audioFile, bool useCache, ref int numBytes, IntPtr *ptr_outPacketDescriptions, long inStartingPacket, ref int numPackets, IntPtr outBuffer); public AudioStreamPacketDescription [] ReadPacketData (long inStartingPacket, int nPackets, byte [] buffer) { if (buffer == null) throw new ArgumentNullException ("buffer"); return RealReadPacketData (false, inStartingPacket, nPackets, buffer, 0, buffer.Length); } public AudioStreamPacketDescription [] ReadPacketData (bool useCache, long inStartingPacket, int nPackets, byte [] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentException ("offset", "<0"); if (count < 0) throw new ArgumentException ("count", "<0"); int len = buffer.Length; if (offset > len) throw new ArgumentException ("destination offset is beyond array size"); // reordered to avoid possible integer overflow if (offset > len - count) throw new ArgumentException ("Reading would overrun buffer"); return RealReadPacketData (useCache, inStartingPacket, nPackets, buffer, offset, count); } static internal AudioStreamPacketDescription [] PacketDescriptionFrom (int nPackets, IntPtr b) { if (b == IntPtr.Zero) return new AudioStreamPacketDescription [0]; var ret = new AudioStreamPacketDescription [nPackets]; int p = 0; for (int i = 0; i < nPackets; i++){ ret [i].StartOffset = Marshal.ReadInt64 (b, p); ret [i].VariableFramesInPacket = Marshal.ReadInt32 (b, p+8); ret [i].DataByteSize = Marshal.ReadInt32 (b, p+12); p += 16; } return ret; } unsafe AudioStreamPacketDescription [] RealReadPacketData (bool useCache, long inStartingPacket, int nPackets, byte [] buffer, int offset, int count) { // sizeof (AudioStreamPacketDescription) == 16 var b = Marshal.AllocHGlobal (16 * nPackets); try { fixed (byte *bop = &buffer [offset]){ var r = AudioFileReadPacketData (handle, useCache, ref count, &b, inStartingPacket, ref nPackets, (IntPtr) bop); if (r != 0) return null; } var ret = PacketDescriptionFrom (nPackets, b); return ret; } finally { Marshal.FreeHGlobal (b); } } public AudioStreamPacketDescription [] ReadFixedPackets (long inStartingPacket, int nPackets, byte [] buffer) { if (buffer == null) throw new ArgumentNullException ("buffer"); return RealReadFixedPackets (false, inStartingPacket, nPackets, buffer, 0, buffer.Length); } public AudioStreamPacketDescription [] ReadFixedPackets (bool useCache, long inStartingPacket, int nPackets, byte [] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentException ("offset", "<0"); if (count < 0) throw new ArgumentException ("count", "<0"); int len = buffer.Length; if (offset > len) throw new ArgumentException ("destination offset is beyond array size"); // reordered to avoid possible integer overflow if (offset > len - count) throw new ArgumentException ("Reading would overrun buffer"); return RealReadFixedPackets (useCache, inStartingPacket, nPackets, buffer, offset, count); } unsafe AudioStreamPacketDescription [] RealReadFixedPackets (bool useCache, long inStartingPacket, int nPackets, byte [] buffer, int offset, int count) { // 16 == sizeof (AudioStreamPacketDescription) var b = Marshal.AllocHGlobal (16* nPackets); try { fixed (byte *bop = &buffer [offset]){ var r = AudioFileReadPacketData (handle, useCache, ref count, &b, inStartingPacket, ref nPackets, (IntPtr) bop); if (r != 0) return null; } var ret = new AudioStreamPacketDescription [nPackets]; int p = 0; for (int i = 0; i < nPackets; i++){ ret [i].StartOffset = Marshal.ReadInt64 (b, p); ret [i].VariableFramesInPacket = Marshal.ReadInt32 (b, p+8); ret [i].DataByteSize = Marshal.ReadInt32 (b, p+12); p += 16; } return ret; } finally { Marshal.FreeHGlobal (b); } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileWritePackets ( AudioFileID audioFile, bool useCache, int inNumBytes, AudioStreamPacketDescription [] inPacketDescriptions, long inStartingPacket, ref int numPackets, IntPtr buffer); unsafe public int WritePackets (bool useCache, long inStartingPacket, AudioStreamPacketDescription [] inPacketDescriptions, IntPtr buffer, int count) { if (inPacketDescriptions == null) throw new ArgumentNullException ("inPacketDescriptions"); if (buffer == IntPtr.Zero) throw new ArgumentNullException ("buffer"); int nPackets = inPacketDescriptions.Length; if (AudioFileWritePackets (handle, useCache, count, inPacketDescriptions, inStartingPacket, ref nPackets, buffer) == 0) return nPackets; return -1; } unsafe public int WritePackets (bool useCache, long startingPacket, AudioStreamPacketDescription [] packetDescriptions, byte [] buffer, int offset, int count) { if (packetDescriptions == null) throw new ArgumentNullException ("inPacketDescriptions"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); if (offset > buffer.Length - count) throw new ArgumentException ("Reading would overrun buffer"); int nPackets = packetDescriptions.Length; fixed (byte *bop = &buffer [offset]){ if (AudioFileWritePackets (handle, useCache, count, packetDescriptions, startingPacket, ref nPackets, (IntPtr) bop) == 0) return nPackets; return -1; } } unsafe public int WritePackets (bool useCache, long inStartingPacket, AudioStreamPacketDescription [] inPacketDescriptions, IntPtr buffer, int count, out int errorCode) { if (inPacketDescriptions == null) throw new ArgumentNullException ("inPacketDescriptions"); if (buffer == IntPtr.Zero) throw new ArgumentNullException ("buffer"); int nPackets = inPacketDescriptions.Length; errorCode = AudioFileWritePackets (handle, useCache, count, inPacketDescriptions, inStartingPacket, ref nPackets, buffer); if (errorCode == 0) return nPackets; return -1; } unsafe public int WritePackets (bool useCache, long startingPacket, AudioStreamPacketDescription [] packetDescriptions, byte [] buffer, int offset, int count, out int errorCode) { if (packetDescriptions == null) throw new ArgumentNullException ("inPacketDescriptions"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); if (offset > buffer.Length - count) throw new ArgumentException ("Reading would overrun buffer"); int nPackets = packetDescriptions.Length; fixed (byte *bop = &buffer [offset]){ errorCode = AudioFileWritePackets (handle, useCache, count, packetDescriptions, startingPacket, ref nPackets, (IntPtr) bop); if (errorCode == 0) return nPackets; return -1; } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileCountUserData (AudioFileID handle, uint userData, out int count); public int CountUserData (uint userData) { int count; if (AudioFileCountUserData (handle, userData, out count) == 0) return count; return -1; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileGetUserDataSize (AudioFileID audioFile, uint userDataID, int index, out int userDataSize); public int GetUserDataSize (uint userDataId, int index) { int ds; if (AudioFileGetUserDataSize (handle, userDataId, index, out ds) == 0) return -1; return ds; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileGetUserData (AudioFileID audioFile, int userDataID, int index, ref int userDataSize, IntPtr userData); public int GetUserData (int userDataID, int index, ref int size, IntPtr userData) { return AudioFileGetUserData (handle, userDataID, index, ref size, userData); } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileSetUserData (AudioFileID inAudioFile, int userDataID, int index, int userDataSize, IntPtr userData); public int SetUserData (int userDataId, int index, int userDataSize, IntPtr userData) { return AudioFileSetUserData (handle, userDataId, index, userDataSize, userData); } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileRemoveUserData (AudioFileID audioFile, int userDataID, int index); public int RemoveUserData (int userDataId, int index) { return AudioFileRemoveUserData (handle, userDataId, index); } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileGetPropertyInfo (AudioFileID audioFile, AudioFileProperty propertyID, out int outDataSize, out int isWritable); public bool GetPropertyInfo (AudioFileProperty property, out int size, out int writable) { return AudioFileGetPropertyInfo (handle, property, out size, out writable) == 0; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileGetProperty (AudioFileID audioFile, AudioFileProperty property, ref int dataSize, IntPtr outdata); public bool GetProperty (AudioFileProperty property, ref int dataSize, IntPtr outdata) { return AudioFileGetProperty (handle, property, ref dataSize, outdata) == 0; } public IntPtr GetProperty (AudioFileProperty property, out int size) { int writable; var r = AudioFileGetPropertyInfo (handle, property, out size, out writable); if (r != 0) return IntPtr.Zero; var buffer = Marshal.AllocHGlobal (size); if (buffer == IntPtr.Zero) return IntPtr.Zero; r = AudioFileGetProperty (handle, property, ref size, buffer); if (r == 0) return buffer; Marshal.FreeHGlobal (buffer); return IntPtr.Zero; } T GetProperty<T> (AudioFileProperty property) { int size, writable; if (AudioFileGetPropertyInfo (handle, property, out size, out writable) != 0) return default (T); var buffer = Marshal.AllocHGlobal (size); if (buffer == IntPtr.Zero) return default(T); try { var r = AudioFileGetProperty (handle, property, ref size, buffer); if (r == 0) return (T) Marshal.PtrToStructure (buffer, typeof (T)); return default(T); } finally { Marshal.FreeHGlobal (buffer); } } int GetInt (AudioFileProperty property) { unsafe { int val = 0; int size = 4; if (AudioFileGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } double GetDouble (AudioFileProperty property) { unsafe { double val = 0; int size = 8; if (AudioFileGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } long GetLong (AudioFileProperty property) { unsafe { long val = 0; int size = 8; if (AudioFileGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileSetProperty (AudioFileID audioFile, AudioFileProperty property, int dataSize, IntPtr propertyData); public bool SetProperty (AudioFileProperty property, int dataSize, IntPtr propertyData) { return AudioFileSetProperty (handle, property, dataSize, propertyData) == 0; } void SetInt (AudioFileProperty property, int value) { unsafe { AudioFileSetProperty (handle, property, 4, (IntPtr) (&value)); } } public AudioFileType FileType { get { return (AudioFileType) GetInt (AudioFileProperty.FileFormat); } } public AudioStreamBasicDescription StreamBasicDescription { get { return GetProperty<AudioStreamBasicDescription> (AudioFileProperty.DataFormat); } } // TODO: kAudioFilePropertyFormatList public bool IsOptimized { get { return GetInt (AudioFileProperty.IsOptimized) == 1; } } public byte [] MagicCookie { get { int size; var h = GetProperty (AudioFileProperty.MagicCookieData, out size); if (h == IntPtr.Zero) return new byte [0]; byte [] cookie = new byte [size]; for (int i = 0; i < cookie.Length; i++) cookie [i] = Marshal.ReadByte (h, i); Marshal.FreeHGlobal (h); return cookie; } set { if (value == null) throw new ArgumentNullException ("value"); unsafe { fixed (byte *bp = &value [0]){ SetProperty (AudioFileProperty.MagicCookieData, value.Length, (IntPtr) bp); } } } } public long DataPacketCount { get { return GetLong (AudioFileProperty.AudioDataPacketCount); } } public int MaximumPacketSize { get { return GetInt (AudioFileProperty.MaximumPacketSize); } } public long DataOffset { get { return GetLong (AudioFileProperty.DataOffset); } } unsafe static float ReadFloat (IntPtr p, int offset) { float f; var pf = &f; byte *pb = (byte *) pf; byte *src = ((byte *)p) + offset; pb [0] = src [0]; pb [1] = src [1]; pb [2] = src [2]; pb [3] = src [3]; return f; } unsafe static void WriteFloat (IntPtr p, int offset, float f) { var pf = &f; byte *pb = (byte *) pf; byte *dest = ((byte *)p) + offset; dest [0] = pb [0]; dest [1] = pb [1]; dest [2] = pb [2]; dest [3] = pb [3]; } static internal AudioChannelLayout AudioChannelLayoutFromHandle (IntPtr h) { var layout = new AudioChannelLayout (); layout.AudioTag = (AudioChannelLayoutTag) Marshal.ReadInt32 (h, 0); layout.Bitmap = Marshal.ReadInt32 (h, 4); layout.Channels = new AudioChannelDescription [Marshal.ReadInt32 (h, 8)]; int p = 12; for (int i = 0; i < layout.Channels.Length; i++){ var desc = new AudioChannelDescription (); desc.Label = (AudioChannelLabel) Marshal.ReadInt32 (h, p); desc.Flags = (AudioChannelFlags) Marshal.ReadInt32 (h, p+4); desc.Coords = new float [3]; desc.Coords [0] = ReadFloat (h, p+8); desc.Coords [1] = ReadFloat (h, p+12); desc.Coords [2] = ReadFloat (h, p+16); layout.Channels [i] = desc; p += 20; } return layout; } static internal IntPtr AudioChannelLayoutToBlock (AudioChannelLayout layout, out int size) { if (layout == null) throw new ArgumentNullException ("layout"); if (layout.Channels == null) throw new ArgumentNullException ("layout.Channels"); size = 12 + layout.Channels.Length * 20; IntPtr buffer = Marshal.AllocHGlobal (size); int p; Marshal.WriteInt32 (buffer, 0, (int) layout.AudioTag); Marshal.WriteInt32 (buffer, 4, layout.Bitmap); Marshal.WriteInt32 (buffer, 8, layout.Channels.Length); p = 12; foreach (var desc in layout.Channels){ Marshal.WriteInt32 (buffer, p, (int) desc.Label); Marshal.WriteInt32 (buffer, p + 4, (int) desc.Flags); WriteFloat (buffer, p + 8, desc.Coords [0]); WriteFloat (buffer, p + 12, desc.Coords [1]); WriteFloat (buffer, p + 16, desc.Coords [2]); p += 20; } return buffer; } public AudioChannelLayout ChannelLayout { get { int size; var h = GetProperty (AudioFileProperty.ChannelLayout, out size); if (h == IntPtr.Zero) return null; var layout = AudioChannelLayoutFromHandle (h); Marshal.FreeHGlobal (h); return layout; } } public bool DeferSizeUpdates { get { return GetInt (AudioFileProperty.DeferSizeUpdates) == 1; } set { SetInt (AudioFileProperty.DeferSizeUpdates, value ? 1 : 0); } } public int BitRate { get { return GetInt (AudioFileProperty.BitRate); } } public double EstimatedDuration { get { return GetDouble (AudioFileProperty.EstimatedDuration); } } public int PacketSizeUpperBound { get { return GetInt (AudioFileProperty.PacketSizeUpperBound); } } public long PacketToFrame (long packet) { AudioFramePacketTranslation buffer; buffer.Packet = packet; unsafe { AudioFramePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileGetProperty (handle, AudioFileProperty.PacketToFrame, ref size, (IntPtr) p) == 0) return buffer.Frame; return -1; } } public long FrameToPacket (long frame, out int frameOffsetInPacket) { AudioFramePacketTranslation buffer; buffer.Frame = frame; unsafe { AudioFramePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileGetProperty (handle, AudioFileProperty.FrameToPacket, ref size, (IntPtr) p) == 0){ frameOffsetInPacket = buffer.FrameOffsetInPacket; return buffer.Packet; } frameOffsetInPacket = 0; return -1; } } public long PacketToByte (long packet, out bool isEstimate) { AudioBytePacketTranslation buffer; buffer.Packet = packet; unsafe { AudioBytePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileGetProperty (handle, AudioFileProperty.PacketToByte, ref size, (IntPtr) p) == 0){ isEstimate = (buffer.Flags & 1) == 1; return buffer.Byte; } isEstimate = false; return -1; } } public long ByteToPacket (long byteval, out int byteOffsetInPacket, out bool isEstimate) { AudioBytePacketTranslation buffer; buffer.Byte = byteval; unsafe { AudioBytePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileGetProperty (handle, AudioFileProperty.ByteToPacket, ref size, (IntPtr) p) == 0){ isEstimate = (buffer.Flags & 1) == 1; byteOffsetInPacket = buffer.ByteOffsetInPacket; return buffer.Packet; } byteOffsetInPacket = 0; isEstimate = false; return -1; } } // MarkerList = 0x6d6b6c73, // RegionList = 0x72676c73, // ChunkIDs = 0x63686964, // InfoDictionary = 0x696e666f, // PacketTableInfo = 0x706e666f, // FormatList = 0x666c7374, // ReserveDuration = 0x72737276, // EstimatedDuration = 0x65647572, // ID3Tag = 0x69643374, // } delegate int ReadProc (IntPtr clientData, long position, int requestCount, IntPtr buffer, out int actualCount); delegate int WriteProc (IntPtr clientData, long position, int requestCount, IntPtr buffer, out int actualCount); delegate long GetSizeProc (IntPtr clientData); delegate int SetSizeProc (IntPtr clientData, long size); public abstract class AudioSource : AudioFile { static ReadProc dRead; static WriteProc dWrite; static GetSizeProc dGetSize; static SetSizeProc dSetSize; GCHandle gch; static AudioSource () { dRead = SourceRead; dWrite = SourceWrite; dGetSize = SourceGetSize; dSetSize = SourceSetSize; } [MonoPInvokeCallback(typeof(ReadProc))] static int SourceRead (IntPtr clientData, long inPosition, int requestCount, IntPtr buffer, out int actualCount) { GCHandle handle = GCHandle.FromIntPtr (clientData); var audioSource = handle.Target as AudioSource; return audioSource.Read (inPosition, requestCount, buffer, out actualCount) ? 0 : 1; } public abstract bool Read (long position, int requestCount, IntPtr buffer, out int actualCount); [MonoPInvokeCallback(typeof(WriteProc))] static int SourceWrite (IntPtr clientData, long position, int requestCount, IntPtr buffer, out int actualCount) { GCHandle handle = GCHandle.FromIntPtr (clientData); var audioSource = handle.Target as AudioSource; return audioSource.Write (position, requestCount, buffer, out actualCount) ? 0 : 1; } public abstract bool Write (long position, int requestCount, IntPtr buffer, out int actualCount); [MonoPInvokeCallback(typeof(GetSizeProc))] static long SourceGetSize (IntPtr clientData) { GCHandle handle = GCHandle.FromIntPtr (clientData); var audioSource = handle.Target as AudioSource; return audioSource.Size; } [MonoPInvokeCallback(typeof(SetSizeProc))] static int SourceSetSize (IntPtr clientData, long size) { GCHandle handle = GCHandle.FromIntPtr (clientData); var audioSource = handle.Target as AudioSource; audioSource.Size = size; return 0; } public abstract long Size { get; set; } protected override void Dispose (bool disposing) { base.Dispose (disposing); if (gch.IsAllocated) gch.Free (); } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileInitializeWithCallbacks ( IntPtr inClientData, ReadProc inReadFunc, WriteProc inWriteFunc, GetSizeProc inGetSizeFunc, SetSizeProc inSetSizeFunc, AudioFileType inFileType, ref AudioStreamBasicDescription format, uint flags, out IntPtr id); public AudioSource (AudioFileType inFileType, AudioStreamBasicDescription format) : base (true) { Initialize (inFileType, format); } public AudioSource () : base (true) { } protected void Initialize (AudioFileType inFileType, AudioStreamBasicDescription format) { IntPtr h; gch = GCHandle.Alloc (this); var code = AudioFileInitializeWithCallbacks (GCHandle.ToIntPtr (gch), dRead, dWrite, dGetSize, dSetSize, inFileType, ref format, 0, out h); if (code == 0){ handle = h; return; } throw new Exception (String.Format ("Unable to create AudioSource, code: 0x{0:x}", code)); } [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileOpenWithCallbacks ( IntPtr inClientData, ReadProc inReadFunc, WriteProc inWriteFunc, GetSizeProc inGetSizeFunc, SetSizeProc inSetSizeFunc, AudioFileType inFileTypeHint, out IntPtr outAudioFile); public AudioSource (AudioFileType fileTypeHint) : base (true) { Open (fileTypeHint); } protected void Open (AudioFileType fileTypeHint) { IntPtr h; gch = GCHandle.Alloc (this); var code = AudioFileOpenWithCallbacks (GCHandle.ToIntPtr (gch), dRead, dWrite, dGetSize, dSetSize, fileTypeHint, out h); if (code == 0){ handle = h; return; } throw new Exception (String.Format ("Unable to create AudioSource, code: 0x{0:x}", code)); } } }
// 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 Infrastructure.Common; using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; using Xunit; using System.Collections.Generic; using System.Text; public class Tcp_ClientCredentialTypeCertificateCanonicalNameTests : ConditionalWcfTest { // We set up three endpoints on the Bridge (server) side, each with a different certificate: // Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address - is bound to a cert where CN=localhost // Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address - is bound to a cert where CN=domainname // Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address - is bound to a cert with a fqdn, e.g., CN=domainname.example.com // // When tests are run, a /p:BridgeHost=<name> is specified; if none is specified, then "localhost" is used // Hence, we are only able to determine at runtime whether a particular endpoint presented by the Bridge is going // to pass a variation or fail a variation. [WcfFact] [Condition(nameof(Root_Certificate_Installed))] [OuterLoop] public static void Certificate_With_CanonicalName_Localhost_Address_EchoString() { var localhostEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address); var endpointAddress = new EndpointAddress(localhostEndpointUri); bool shouldCallSucceed = string.Compare(localhostEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", localhostEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (Exception exception) when (exception is CommunicationException || exception is MessageSecurityException) { if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException")) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed))] [OuterLoop] public static void Certificate_With_CanonicalName_DomainName_Address_EchoString() { var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address); var endpointAddress = new EndpointAddress(domainNameEndpointUri); // We check that: // 1. The Bridge's reported hostname does not contain a '.' (which means we're hitting the FQDN) // 2. The Bridge's reported hostname is not "localhost" (which means we're hitting localhost) // If both these conditions are true, expect the test to pass. Otherwise, it should fail bool shouldCallSucceed = domainNameEndpointUri.Host.IndexOf('.') == -1 && string.Compare(domainNameEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) != 0; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", domainNameEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", domainNameEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (Exception exception) when (exception is CommunicationException || exception is MessageSecurityException) { if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException")) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", domainNameEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", domainNameEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed))] [OuterLoop] public static void Certificate_With_CanonicalName_Fqdn_Address_EchoString() { bool shouldCallSucceed = false; var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address); // Get just the hostname part of the domainName Uri var domainNameHost = domainNameEndpointUri.Host.Split('.')[0]; var fqdnEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address); var endpointAddress = new EndpointAddress(fqdnEndpointUri); // If the Bridge's reported FQDN is the same as the Bridge's reported hostname, // it means that there the bridge is set up on a network where FQDNs aren't used, only hostnames. // Since our pass/fail detection logic on whether or not this is an FQDN depends on whether the host name has a '.', we don't test this case if (string.Compare(domainNameHost, fqdnEndpointUri.Host, StringComparison.OrdinalIgnoreCase) != 0) { shouldCallSucceed = fqdnEndpointUri.Host.IndexOf('.') > -1; } string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", fqdnEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (MessageSecurityException exception) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } }
// 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.Reflection; using System.Resources; using System.Runtime.CompilerServices; #if !NET_NATIVE namespace System.Xml.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Xml; using System.Xml.Serialization.Configuration; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Security; using System.Text.RegularExpressions; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Xml.Extensions; internal class CodeGenerator { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method does validation only without any user input")] internal static bool IsValidLanguageIndependentIdentifier(string ident) { return System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(ident); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method does validation only without any user input")] internal static void ValidateIdentifiers(System.CodeDom.CodeObject e) { System.CodeDom.Compiler.CodeGenerator.ValidateIdentifiers(e); } internal static BindingFlags InstancePublicBindingFlags = BindingFlags.Instance | BindingFlags.Public; internal static BindingFlags InstanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; internal static BindingFlags StaticBindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; internal static MethodAttributes PublicMethodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig; internal static MethodAttributes PublicOverrideMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig; internal static MethodAttributes ProtectedOverrideMethodAttributes = MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig; internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig; internal static Type[] EmptyTypeArray = new Type[] { }; private TypeBuilder _typeBuilder; private MethodBuilder _methodBuilder; private ILGenerator _ilGen; private Dictionary<string, ArgBuilder> _argList; private LocalScope _currentScope; // Stores a queue of free locals available in the context of the method, keyed by // type and name of the local private Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> _freeLocals; private Stack _blockStack; private Label _methodEndLabel; internal CodeGenerator(TypeBuilder typeBuilder) { System.Diagnostics.Debug.Assert(typeBuilder != null); _typeBuilder = typeBuilder; } internal static bool IsNullableGenericType(Type type) { return type.Name == "Nullable`1"; } internal static void AssertHasInterface(Type type, Type iType) { #if DEBUG Debug.Assert(iType.GetTypeInfo().IsInterface); foreach (Type iFace in type.GetInterfaces()) { if (iFace == iType) return; } Debug.Assert(false); #endif } internal void BeginMethod(Type returnType, string methodName, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes) { _methodBuilder = _typeBuilder.DefineMethod(methodName, methodAttributes, returnType, argTypes); _ilGen = _methodBuilder.GetILGenerator(); InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static); } internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes) { #if DEBUG methodBuilderInfo.Validate(returnType, argTypes, methodAttributes); #endif _methodBuilder = methodBuilderInfo.MethodBuilder; _ilGen = _methodBuilder.GetILGenerator(); InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static); } private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) { _methodEndLabel = _ilGen.DefineLabel(); this.retLabel = _ilGen.DefineLabel(); _blockStack = new Stack(); _whileStack = new Stack(); _currentScope = new LocalScope(); _freeLocals = new Dictionary<Tuple<Type, string>, Queue<LocalBuilder>>(); _argList = new Dictionary<string, ArgBuilder>(); // this ptr is arg 0 for non static, assuming ref type (not value type) if (!isStatic) _argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType)); for (int i = 0; i < argTypes.Length; i++) { ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]); _argList.Add(arg.Name, arg); _methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name); } } internal MethodBuilder EndMethod() { MarkLabel(_methodEndLabel); Ret(); MethodBuilder retVal = null; retVal = _methodBuilder; _methodBuilder = null; _ilGen = null; _freeLocals = null; _blockStack = null; _whileStack = null; _argList = null; _currentScope = null; retLocal = null; return retVal; } internal MethodBuilder MethodBuilder { get { return _methodBuilder; } } internal ArgBuilder GetArg(string name) { System.Diagnostics.Debug.Assert(_argList != null && _argList.ContainsKey(name)); return (ArgBuilder)_argList[name]; } internal LocalBuilder GetLocal(string name) { System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name)); return _currentScope[name]; } internal LocalBuilder retLocal; internal Label retLabel; internal LocalBuilder ReturnLocal { get { if (retLocal == null) retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret"); return retLocal; } } internal Label ReturnLabel { get { return retLabel; } } private Dictionary<Type, LocalBuilder> _tmpLocals = new Dictionary<Type, LocalBuilder>(); internal LocalBuilder GetTempLocal(Type type) { LocalBuilder localTmp; if (!_tmpLocals.TryGetValue(type, out localTmp)) { localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count); _tmpLocals.Add(type, localTmp); } return localTmp; } internal Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; else if (var is LocalBuilder) return ((LocalBuilder)var).LocalType; else return var.GetType(); } internal object GetVariable(string name) { object var; if (TryGetVariable(name, out var)) return var; System.Diagnostics.Debug.Assert(false); return null; } internal bool TryGetVariable(string name, out object variable) { LocalBuilder loc; if (_currentScope != null && _currentScope.TryGetValue(name, out loc)) { variable = loc; return true; } ArgBuilder arg; if (_argList != null && _argList.TryGetValue(name, out arg)) { variable = arg; return true; } int val; if (Int32.TryParse(name, out val)) { variable = val; return true; } variable = null; return false; } internal void EnterScope() { LocalScope newScope = new LocalScope(_currentScope); _currentScope = newScope; } internal void ExitScope() { Debug.Assert(_currentScope.parent != null); _currentScope.AddToFreeLocals(_freeLocals); _currentScope = _currentScope.parent; } private bool TryDequeueLocal(Type type, string name, out LocalBuilder local) { // This method can only be called between BeginMethod and EndMethod (i.e. // while we are emitting code for a method Debug.Assert(_freeLocals != null); Queue<LocalBuilder> freeLocalQueue; Tuple<Type, string> key = new Tuple<Type, string>(type, name); if (_freeLocals.TryGetValue(key, out freeLocalQueue)) { local = freeLocalQueue.Dequeue(); // If the queue is empty, remove this key from the dictionary // of free locals if (freeLocalQueue.Count == 0) { _freeLocals.Remove(key); } return true; } local = null; return false; } internal LocalBuilder DeclareLocal(Type type, string name) { Debug.Assert(!_currentScope.ContainsKey(name)); LocalBuilder local; if (!TryDequeueLocal(type, name, out local)) { local = _ilGen.DeclareLocal(type, false); } _currentScope[name] = local; return local; } internal LocalBuilder DeclareOrGetLocal(Type type, string name) { LocalBuilder local; if (!_currentScope.TryGetValue(name, out local)) local = DeclareLocal(type, name); else Debug.Assert(local.LocalType == type); return local; } internal object For(LocalBuilder local, object start, object end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); if (forState.Index != null) { Load(start); Stloc(forState.Index); Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); _blockStack.Push(forState); return forState; } internal void EndFor() { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; Debug.Assert(forState != null); if (forState.Index != null) { Ldloc(forState.Index); Ldc(1); Add(); Stloc(forState.Index); MarkLabel(forState.TestLabel); Ldloc(forState.Index); Load(forState.End); Type varType = GetVariableType(forState.End); if (varType.IsArray) { Ldlen(); } else { #if DEBUG CodeGenerator.AssertHasInterface(varType, typeof(ICollection)); #endif MethodInfo ICollection_get_Count = typeof(ICollection).GetMethod( "get_Count", CodeGenerator.InstanceBindingFlags, CodeGenerator.EmptyTypeArray ); Call(ICollection_get_Count); } Blt(forState.BeginLabel); } else Br(forState.BeginLabel); } internal void If() { InternalIf(false); } internal void IfNot() { InternalIf(true); } private static OpCode[] s_branchCodes = new OpCode[] { OpCodes.Bge, OpCodes.Bne_Un, OpCodes.Bgt, OpCodes.Ble, OpCodes.Beq, OpCodes.Blt, }; private OpCode GetBranchCode(Cmp cmp) { return s_branchCodes[(int)cmp]; } internal void If(Cmp cmpOp) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void If(object value1, Cmp cmpOp, object value2) { Load(value1); Load(value2); If(cmpOp); } internal void Else() { IfState ifState = PopIfState(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; _blockStack.Push(ifState); } internal void EndIf() { IfState ifState = PopIfState(); if (!ifState.ElseBegin.Equals(ifState.EndIf)) MarkLabel(ifState.ElseBegin); MarkLabel(ifState.EndIf); } private Stack _leaveLabels = new Stack(); internal void BeginExceptionBlock() { _leaveLabels.Push(DefineLabel()); _ilGen.BeginExceptionBlock(); } internal void BeginCatchBlock(Type exception) { _ilGen.BeginCatchBlock(exception); } internal void EndExceptionBlock() { _ilGen.EndExceptionBlock(); _ilGen.MarkLabel((Label)_leaveLabels.Pop()); } internal void Leave() { _ilGen.Emit(OpCodes.Leave, (Label)_leaveLabels.Peek()); } internal void Call(MethodInfo methodInfo) { Debug.Assert(methodInfo != null); if (methodInfo.IsVirtual && !methodInfo.DeclaringType.GetTypeInfo().IsValueType) _ilGen.Emit(OpCodes.Callvirt, methodInfo); else _ilGen.Emit(OpCodes.Call, methodInfo); } internal void Call(ConstructorInfo ctor) { Debug.Assert(ctor != null); _ilGen.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { Debug.Assert(constructorInfo != null); _ilGen.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { _ilGen.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); _ilGen.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { Type objType = GetVariableType(obj).GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) { Ldelema(objType); Ldobj(objType); } else Ldelem(objType); } internal void StoreArrayElement(object obj, object arrayIndex, object value) { Type arrayType = GetVariableType(obj); if (arrayType == typeof(Array)) { Load(obj); Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) })); } else { Type objType = arrayType.GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) Ldelema(objType); Load(value); ConvertValue(GetVariableType(value), objType); if (IsStruct(objType)) Stobj(objType); else Stelem(objType); } } private static bool IsStruct(Type objType) { return objType.GetTypeInfo().IsValueType && !objType.GetTypeInfo().IsPrimitive; } internal Type LoadMember(object obj, MemberInfo memberInfo) { if (GetVariableType(obj).GetTypeInfo().IsValueType) LoadAddress(obj); else Load(obj); return LoadMember(memberInfo); } private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter) { // we only invoke this when the propertyInfo does not have a GET or SET method on it Type currentType = propertyInfo.DeclaringType.GetTypeInfo().BaseType; PropertyInfo currentProperty; string propertyName = propertyInfo.Name; MethodInfo result = null; while (currentType != null) { currentProperty = currentType.GetProperty(propertyName); if (currentProperty != null) { if (isGetter) { result = currentProperty.GetMethod; } else { result = currentProperty.SetMethod; } if (result != null) { // we found the GetMethod/SetMethod on the type closest to the current declaring type break; } } // keep looking at the base type like compiler does currentType = currentType.GetTypeInfo().BaseType; } return result; } internal Type LoadMember(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); } else { _ilGen.Emit(OpCodes.Ldfld, fieldInfo); } } else { System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo); PropertyInfo property = (PropertyInfo)memberInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) { getMethod = GetPropertyMethodFromBaseType(property, true); } System.Diagnostics.Debug.Assert(getMethod != null); Call(getMethod); } } return memberType; } internal Type LoadMemberAddress(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { _ilGen.Emit(OpCodes.Ldsflda, fieldInfo); } else { _ilGen.Emit(OpCodes.Ldflda, fieldInfo); } } else { System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo); PropertyInfo property = (PropertyInfo)memberInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) { getMethod = GetPropertyMethodFromBaseType(property, true); } System.Diagnostics.Debug.Assert(getMethod != null); Call(getMethod); LocalBuilder tmpLoc = GetTempLocal(memberType); Stloc(tmpLoc); Ldloca(tmpLoc); } } return memberType; } internal void StoreMember(MemberInfo memberInfo) { if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { _ilGen.Emit(OpCodes.Stsfld, fieldInfo); } else { _ilGen.Emit(OpCodes.Stfld, fieldInfo); } } else { System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo); PropertyInfo property = (PropertyInfo)memberInfo; if (property != null) { MethodInfo setMethod = property.SetMethod; if (setMethod == null) { setMethod = GetPropertyMethodFromBaseType(property, false); } System.Diagnostics.Debug.Assert(setMethod != null); Call(setMethod); } } } internal void Load(object obj) { if (obj == null) _ilGen.Emit(OpCodes.Ldnull); else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) Ldloc((LocalBuilder)obj); else Ldc(obj); } internal void LoadAddress(object obj) { if (obj is ArgBuilder) LdargAddress((ArgBuilder)obj); else if (obj is LocalBuilder) LdlocAddress((LocalBuilder)obj); else Load(obj); } internal void ConvertAddress(Type source, Type target) { InternalConvert(source, target, true); } internal void ConvertValue(Type source, Type target) { InternalConvert(source, target, false); } internal void Castclass(Type target) { _ilGen.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { _ilGen.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { _ilGen.Emit(OpCodes.Unbox, type); } private static OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Ldind_I1,//Boolean = 3, OpCodes.Ldind_I2,//Char = 4, OpCodes.Ldind_I1,//SByte = 5, OpCodes.Ldind_U1,//Byte = 6, OpCodes.Ldind_I2,//Int16 = 7, OpCodes.Ldind_U2,//UInt16 = 8, OpCodes.Ldind_I4,//Int32 = 9, OpCodes.Ldind_U4,//UInt32 = 10, OpCodes.Ldind_I8,//Int64 = 11, OpCodes.Ldind_I8,//UInt64 = 12, OpCodes.Ldind_R4,//Single = 13, OpCodes.Ldind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Ldind_Ref,//String = 18, }; private OpCode GetLdindOpCode(TypeCode typeCode) { return s_ldindOpCodes[(int)typeCode]; } internal void Ldobj(Type type) { OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { _ilGen.Emit(opCode); } else { _ilGen.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { _ilGen.Emit(OpCodes.Stobj, type); } internal void Ceq() { _ilGen.Emit(OpCodes.Ceq); } internal void Clt() { _ilGen.Emit(OpCodes.Clt); } internal void Cne() { Ceq(); Ldc(0); Ceq(); } internal void Ble(Label label) { _ilGen.Emit(OpCodes.Ble, label); } internal void Throw() { _ilGen.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { _ilGen.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) { Type valueType = o.GetType(); if (o is Type) { Ldtoken((Type)o); Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })); } else if (valueType.GetTypeInfo().IsEnum) { Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null)); } else { switch (valueType.GetTypeCode()) { case TypeCode.Boolean: Ldc((bool)o); break; case TypeCode.Char: Debug.Assert(false, "Char is not a valid schema primitive and should be treated as int in DataContract"); throw new NotSupportedException(SR.XmlInvalidCharSchemaPrimitive); case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture)); break; case TypeCode.Int32: Ldc((int)o); break; case TypeCode.UInt32: Ldc((int)(uint)o); break; case TypeCode.UInt64: Ldc((long)(ulong)o); break; case TypeCode.Int64: Ldc((long)o); break; case TypeCode.Single: Ldc((float)o); break; case TypeCode.Double: Ldc((double)o); break; case TypeCode.String: Ldstr((string)o); break; case TypeCode.Decimal: ConstructorInfo Decimal_ctor = typeof(Decimal).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Int32), typeof(Int32), typeof(Int32), typeof(Boolean), typeof(Byte) } ); int[] bits = Decimal.GetBits((decimal)o); Ldc(bits[0]); // digit Ldc(bits[1]); // digit Ldc(bits[2]); // digit Ldc((bits[3] & 0x80000000) == 0x80000000); // sign Ldc((Byte)((bits[3] >> 16) & 0xFF)); // decimal location New(Decimal_ctor); break; case TypeCode.DateTime: ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Int64) } ); Ldc(((DateTime)o).Ticks); // ticks New(DateTime_ctor); break; case TypeCode.Object: case TypeCode.Empty: case TypeCode.DBNull: default: Debug.Assert(false, "UnknownConstantType"); throw new NotSupportedException(SR.Format(SR.UnknownConstantType, valueType.GetTypeInfo().AssemblyQualifiedName)); } } } internal void Ldc(bool boolVar) { if (boolVar) { _ilGen.Emit(OpCodes.Ldc_I4_1); } else { _ilGen.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { switch (intVar) { case -1: _ilGen.Emit(OpCodes.Ldc_I4_M1); break; case 0: _ilGen.Emit(OpCodes.Ldc_I4_0); break; case 1: _ilGen.Emit(OpCodes.Ldc_I4_1); break; case 2: _ilGen.Emit(OpCodes.Ldc_I4_2); break; case 3: _ilGen.Emit(OpCodes.Ldc_I4_3); break; case 4: _ilGen.Emit(OpCodes.Ldc_I4_4); break; case 5: _ilGen.Emit(OpCodes.Ldc_I4_5); break; case 6: _ilGen.Emit(OpCodes.Ldc_I4_6); break; case 7: _ilGen.Emit(OpCodes.Ldc_I4_7); break; case 8: _ilGen.Emit(OpCodes.Ldc_I4_8); break; default: _ilGen.Emit(OpCodes.Ldc_I4, intVar); break; } } internal void Ldc(long l) { _ilGen.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { _ilGen.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { _ilGen.Emit(OpCodes.Ldc_R8, d); } internal void Ldstr(string strVar) { if (strVar == null) _ilGen.Emit(OpCodes.Ldnull); else _ilGen.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) { if (localBuilder.LocalType.GetTypeInfo().IsValueType) Ldloca(localBuilder); else Ldloc(localBuilder); } internal void Ldloc(LocalBuilder localBuilder) { _ilGen.Emit(OpCodes.Ldloc, localBuilder); } internal void Ldloc(string name) { Debug.Assert(_currentScope.ContainsKey(name)); LocalBuilder local = _currentScope[name]; Ldloc(local); } internal void Stloc(Type type, string name) { LocalBuilder local = null; if (!_currentScope.TryGetValue(name, out local)) { local = DeclareLocal(type, name); } Debug.Assert(local.LocalType == type); Stloc(local); } internal void Stloc(LocalBuilder local) { _ilGen.Emit(OpCodes.Stloc, local); } internal void Ldloc(Type type, string name) { Debug.Assert(_currentScope.ContainsKey(name)); LocalBuilder local = _currentScope[name]; Debug.Assert(local.LocalType == type); Ldloc(local); } internal void Ldloca(LocalBuilder localBuilder) { _ilGen.Emit(OpCodes.Ldloca, localBuilder); } internal void LdargAddress(ArgBuilder argBuilder) { if (argBuilder.ArgType.GetTypeInfo().IsValueType) Ldarga(argBuilder); else Ldarg(argBuilder); } internal void Ldarg(string arg) { Ldarg(GetArg(arg)); } internal void Ldarg(ArgBuilder arg) { Ldarg(arg.Index); } internal void Ldarg(int slot) { switch (slot) { case 0: _ilGen.Emit(OpCodes.Ldarg_0); break; case 1: _ilGen.Emit(OpCodes.Ldarg_1); break; case 2: _ilGen.Emit(OpCodes.Ldarg_2); break; case 3: _ilGen.Emit(OpCodes.Ldarg_3); break; default: if (slot <= 255) _ilGen.Emit(OpCodes.Ldarg_S, slot); else _ilGen.Emit(OpCodes.Ldarg, slot); break; } } internal void Ldarga(ArgBuilder argBuilder) { Ldarga(argBuilder.Index); } internal void Ldarga(int slot) { if (slot <= 255) _ilGen.Emit(OpCodes.Ldarga_S, slot); else _ilGen.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { _ilGen.Emit(OpCodes.Ldlen); _ilGen.Emit(OpCodes.Conv_I4); } private static OpCode[] s_ldelemOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Ldelem_Ref,//Object = 1, OpCodes.Ldelem_Ref,//DBNull = 2, OpCodes.Ldelem_I1,//Boolean = 3, OpCodes.Ldelem_I2,//Char = 4, OpCodes.Ldelem_I1,//SByte = 5, OpCodes.Ldelem_U1,//Byte = 6, OpCodes.Ldelem_I2,//Int16 = 7, OpCodes.Ldelem_U2,//UInt16 = 8, OpCodes.Ldelem_I4,//Int32 = 9, OpCodes.Ldelem_U4,//UInt32 = 10, OpCodes.Ldelem_I8,//Int64 = 11, OpCodes.Ldelem_I8,//UInt64 = 12, OpCodes.Ldelem_R4,//Single = 13, OpCodes.Ldelem_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Ldelem_Ref,//String = 18, }; private OpCode GetLdelemOpCode(TypeCode typeCode) { return s_ldelemOpCodes[(int)typeCode]; } internal void Ldelem(Type arrayElementType) { if (arrayElementType.GetTypeInfo().IsEnum) { Ldelem(Enum.GetUnderlyingType(arrayElementType)); } else { OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode()); Debug.Assert(!opCode.Equals(OpCodes.Nop)); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.GetTypeInfo().AssemblyQualifiedName)); _ilGen.Emit(opCode); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; _ilGen.Emit(opCode, arrayElementType); } private static OpCode[] s_stelemOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Stelem_Ref,//Object = 1, OpCodes.Stelem_Ref,//DBNull = 2, OpCodes.Stelem_I1,//Boolean = 3, OpCodes.Stelem_I2,//Char = 4, OpCodes.Stelem_I1,//SByte = 5, OpCodes.Stelem_I1,//Byte = 6, OpCodes.Stelem_I2,//Int16 = 7, OpCodes.Stelem_I2,//UInt16 = 8, OpCodes.Stelem_I4,//Int32 = 9, OpCodes.Stelem_I4,//UInt32 = 10, OpCodes.Stelem_I8,//Int64 = 11, OpCodes.Stelem_I8,//UInt64 = 12, OpCodes.Stelem_R4,//Single = 13, OpCodes.Stelem_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Stelem_Ref,//String = 18, }; private OpCode GetStelemOpCode(TypeCode typeCode) { return s_stelemOpCodes[(int)typeCode]; } internal void Stelem(Type arrayElementType) { if (arrayElementType.GetTypeInfo().IsEnum) Stelem(Enum.GetUnderlyingType(arrayElementType)); else { OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.GetTypeInfo().AssemblyQualifiedName)); _ilGen.Emit(opCode); } } internal Label DefineLabel() { return _ilGen.DefineLabel(); } internal void MarkLabel(Label label) { _ilGen.MarkLabel(label); } internal void Nop() { _ilGen.Emit(OpCodes.Nop); } internal void Add() { _ilGen.Emit(OpCodes.Add); } internal void Ret() { _ilGen.Emit(OpCodes.Ret); } internal void Br(Label label) { _ilGen.Emit(OpCodes.Br, label); } internal void Br_S(Label label) { _ilGen.Emit(OpCodes.Br_S, label); } internal void Blt(Label label) { _ilGen.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { _ilGen.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { _ilGen.Emit(OpCodes.Brtrue, label); } internal void Pop() { _ilGen.Emit(OpCodes.Pop); } internal void Dup() { _ilGen.Emit(OpCodes.Dup); } private void InternalIf(bool negate) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); if (negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); _blockStack.Push(ifState); } private static OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Conv_I1,//Boolean = 3, OpCodes.Conv_I2,//Char = 4, OpCodes.Conv_I1,//SByte = 5, OpCodes.Conv_U1,//Byte = 6, OpCodes.Conv_I2,//Int16 = 7, OpCodes.Conv_U2,//UInt16 = 8, OpCodes.Conv_I4,//Int32 = 9, OpCodes.Conv_U4,//UInt32 = 10, OpCodes.Conv_I8,//Int64 = 11, OpCodes.Conv_U8,//UInt64 = 12, OpCodes.Conv_R4,//Single = 13, OpCodes.Conv_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Nop,//String = 18, }; private OpCode GetConvOpCode(TypeCode typeCode) { return s_convOpCodes[(int)typeCode]; } private void InternalConvert(Type source, Type target, bool isAddress) { if (target == source) return; if (target.GetTypeInfo().IsValueType) { if (source.GetTypeInfo().IsValueType) { OpCode opCode = GetConvOpCode(target.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) { throw new CodeGeneratorConversionException(source, target, isAddress, "NoConversionPossibleTo"); } else { _ilGen.Emit(opCode); } } else if (source.IsAssignableFrom(target)) { Unbox(target); if (!isAddress) Ldobj(target); } else { throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom"); } } else if (target.IsAssignableFrom(source)) { if (source.GetTypeInfo().IsValueType) { if (isAddress) Ldobj(source); Box(source); } } else if (source.IsAssignableFrom(target)) { Castclass(target); } else if (target.GetTypeInfo().IsInterface || source.GetTypeInfo().IsInterface) { Castclass(target); } else { throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom"); } } private IfState PopIfState() { object stackTop = _blockStack.Pop(); IfState ifState = stackTop as IfState; Debug.Assert(ifState != null); return ifState; } static internal AssemblyBuilder CreateAssemblyBuilder(string name) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = name; assemblyName.Version = new Version(1, 0, 0, 0); return AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); } static internal ModuleBuilder CreateModuleBuilder(AssemblyBuilder assemblyBuilder, string name) { return assemblyBuilder.DefineDynamicModule(name); } static internal TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, string name, TypeAttributes attributes, Type parent, Type[] interfaces) { // parent is nullable if no base class return moduleBuilder.DefineType(TempAssembly.GeneratedAssemblyNamespace + "." + name, attributes, parent, interfaces); } private int _initElseIfStack = -1; private IfState _elseIfState; internal void InitElseIf() { Debug.Assert(_initElseIfStack == -1); _elseIfState = (IfState)_blockStack.Pop(); _initElseIfStack = _blockStack.Count; Br(_elseIfState.EndIf); MarkLabel(_elseIfState.ElseBegin); } private int _initIfStack = -1; internal void InitIf() { Debug.Assert(_initIfStack == -1); _initIfStack = _blockStack.Count; } internal void AndIf(Cmp cmpOp) { if (_initIfStack == _blockStack.Count) { _initIfStack = -1; If(cmpOp); return; } if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; _elseIfState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; } Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1); IfState ifState = (IfState)_blockStack.Peek(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); } internal void AndIf() { if (_initIfStack == _blockStack.Count) { _initIfStack = -1; If(); return; } if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; _elseIfState.ElseBegin = DefineLabel(); Brfalse(_elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; } Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1); IfState ifState = (IfState)_blockStack.Peek(); Brfalse(ifState.ElseBegin); } internal void IsInst(Type type) { _ilGen.Emit(OpCodes.Isinst, type); } internal void Beq(Label label) { _ilGen.Emit(OpCodes.Beq, label); } internal void Bne(Label label) { _ilGen.Emit(OpCodes.Bne_Un, label); } internal void GotoMethodEnd() { //limit to only short forward (127 CIL instruction) //Br_S(this.methodEndLabel); Br(_methodEndLabel); } internal class WhileState { public Label StartLabel; public Label CondLabel; public Label EndLabel; public WhileState(CodeGenerator ilg) { StartLabel = ilg.DefineLabel(); CondLabel = ilg.DefineLabel(); EndLabel = ilg.DefineLabel(); } } // Usage: // WhileBegin() // WhileBreak() // WhileContinue() // WhileBeginCondition() // (bool on stack) // WhileEndCondition() // WhileEnd() private Stack _whileStack; internal void WhileBegin() { WhileState whileState = new WhileState(this); Br(whileState.CondLabel); MarkLabel(whileState.StartLabel); _whileStack.Push(whileState); } internal void WhileEnd() { WhileState whileState = (WhileState)_whileStack.Pop(); MarkLabel(whileState.EndLabel); } internal void WhileBreak() { WhileState whileState = (WhileState)_whileStack.Peek(); Br(whileState.EndLabel); } internal void WhileContinue() { WhileState whileState = (WhileState)_whileStack.Peek(); Br(whileState.CondLabel); } internal void WhileBeginCondition() { WhileState whileState = (WhileState)_whileStack.Peek(); // If there are two MarkLabel ILs consecutively, Labels will converge to one label. // This could cause the code to look different. We insert Nop here specifically // that the While label stands out. Nop(); MarkLabel(whileState.CondLabel); } internal void WhileEndCondition() { WhileState whileState = (WhileState)_whileStack.Peek(); Brtrue(whileState.StartLabel); } } internal class ArgBuilder { internal string Name; internal int Index; internal Type ArgType; internal ArgBuilder(string name, int index, Type argType) { this.Name = name; this.Index = index; this.ArgType = argType; } } internal class ForState { private LocalBuilder _indexVar; private Label _beginLabel; private Label _testLabel; private object _end; internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end) { _indexVar = indexVar; _beginLabel = beginLabel; _testLabel = testLabel; _end = end; } internal LocalBuilder Index { get { return _indexVar; } } internal Label BeginLabel { get { return _beginLabel; } } internal Label TestLabel { get { return _testLabel; } } internal object End { get { return _end; } } } internal enum Cmp : int { LessThan = 0, EqualTo, LessThanOrEqualTo, GreaterThan, NotEqualTo, GreaterThanOrEqualTo } internal class IfState { private Label _elseBegin; private Label _endIf; internal Label EndIf { get { return _endIf; } set { _endIf = value; } } internal Label ElseBegin { get { return _elseBegin; } set { _elseBegin = value; } } } internal class LocalScope { public readonly LocalScope parent; private readonly Dictionary<string, LocalBuilder> _locals; // Root scope public LocalScope() { _locals = new Dictionary<string, LocalBuilder>(); } public LocalScope(LocalScope parent) : this() { this.parent = parent; } public void Add(string key, LocalBuilder value) { _locals.Add(key, value); } public bool ContainsKey(string key) { return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key)); } public bool TryGetValue(string key, out LocalBuilder value) { if (_locals.TryGetValue(key, out value)) { return true; } else if (parent != null) { return parent.TryGetValue(key, out value); } else { value = null; return false; } } public LocalBuilder this[string key] { get { LocalBuilder value; TryGetValue(key, out value); return value; } set { _locals[key] = value; } } public void AddToFreeLocals(Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> freeLocals) { foreach (var item in _locals) { Tuple<Type, string> key = new Tuple<Type, string>(item.Value.LocalType, item.Key); Queue<LocalBuilder> freeLocalQueue; if (freeLocals.TryGetValue(key, out freeLocalQueue)) { // Add to end of the queue so that it will be re-used in // FIFO manner freeLocalQueue.Enqueue(item.Value); } else { freeLocalQueue = new Queue<LocalBuilder>(); freeLocalQueue.Enqueue(item.Value); freeLocals.Add(key, freeLocalQueue); } } } } internal class MethodBuilderInfo { public readonly MethodBuilder MethodBuilder; public readonly Type[] ParameterTypes; public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes) { this.MethodBuilder = methodBuilder; this.ParameterTypes = parameterTypes; } public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes) { #if DEBUG Debug.Assert(this.MethodBuilder.ReturnType == returnType); Debug.Assert(this.MethodBuilder.Attributes == attributes); Debug.Assert(this.ParameterTypes.Length == parameterTypes.Length); for (int i = 0; i < parameterTypes.Length; ++i) { Debug.Assert(this.ParameterTypes[i] == parameterTypes[i]); } #endif } } internal class CodeGeneratorConversionException : Exception { private Type _sourceType; private Type _targetType; private bool _isAddress; private string _reason; public CodeGeneratorConversionException(Type sourceType, Type targetType, bool isAddress, string reason) : base() { _sourceType = sourceType; _targetType = targetType; _isAddress = isAddress; _reason = reason; } } } #endif
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia.Markup.Parsers; using XamlX; using XamlX.Ast; using XamlX.Emit; using XamlX.IL; using XamlX.Transform; using XamlX.Transform.Transformers; using XamlX.TypeSystem; namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers { using XamlParseException = XamlX.XamlParseException; using XamlLoadException = XamlX.XamlLoadException; class AvaloniaXamlIlSelectorTransformer : IXamlAstTransformer { public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node) { if (!(node is XamlAstObjectNode on && on.Type.GetClrType().FullName == "Avalonia.Styling.Style")) return node; var pn = on.Children.OfType<XamlAstXamlPropertyValueNode>() .FirstOrDefault(p => p.Property.GetClrProperty().Name == "Selector"); if (pn == null) return node; if (pn.Values.Count != 1) throw new XamlParseException("Selector property should should have exactly one value", node); if (pn.Values[0] is XamlIlSelectorNode) //Deja vu. I've just been in this place before return node; if (!(pn.Values[0] is XamlAstTextNode tn)) throw new XamlParseException("Selector property should be a text node", node); var selectorType = pn.Property.GetClrProperty().Getter.ReturnType; var initialNode = new XamlIlSelectorInitialNode(node, selectorType); XamlIlSelectorNode Create(IEnumerable<SelectorGrammar.ISyntax> syntax, Func<string, string, XamlAstClrTypeReference> typeResolver) { XamlIlSelectorNode result = initialNode; XamlIlOrSelectorNode results = null; foreach (var i in syntax) { switch (i) { case SelectorGrammar.OfTypeSyntax ofType: result = new XamlIlTypeSelector(result, typeResolver(ofType.Xmlns, ofType.TypeName).Type, true); break; case SelectorGrammar.IsSyntax @is: result = new XamlIlTypeSelector(result, typeResolver(@is.Xmlns, @is.TypeName).Type, false); break; case SelectorGrammar.ClassSyntax @class: result = new XamlIlStringSelector(result, XamlIlStringSelector.SelectorType.Class, @class.Class); break; case SelectorGrammar.NameSyntax name: result = new XamlIlStringSelector(result, XamlIlStringSelector.SelectorType.Name, name.Name); break; case SelectorGrammar.PropertySyntax property: { var type = result?.TargetType; if (type == null) throw new XamlParseException("Property selectors must be applied to a type.", node); var targetProperty = type.GetAllProperties().FirstOrDefault(p => p.Name == property.Property); if (targetProperty == null) throw new XamlParseException($"Cannot find '{property.Property}' on '{type}", node); if (!XamlTransformHelpers.TryGetCorrectlyTypedValue(context, new XamlAstTextNode(node, property.Value, context.Configuration.WellKnownTypes.String), targetProperty.PropertyType, out var typedValue)) throw new XamlParseException( $"Cannot convert '{property.Value}' to '{targetProperty.PropertyType.GetFqn()}", node); result = new XamlIlPropertyEqualsSelector(result, targetProperty, typedValue); break; } case SelectorGrammar.ChildSyntax child: result = new XamlIlCombinatorSelector(result, XamlIlCombinatorSelector.SelectorType.Child); break; case SelectorGrammar.DescendantSyntax descendant: result = new XamlIlCombinatorSelector(result, XamlIlCombinatorSelector.SelectorType.Descendant); break; case SelectorGrammar.TemplateSyntax template: result = new XamlIlCombinatorSelector(result, XamlIlCombinatorSelector.SelectorType.Template); break; case SelectorGrammar.NotSyntax not: result = new XamlIlNotSelector(result, Create(not.Argument, typeResolver)); break; case SelectorGrammar.CommaSyntax comma: if (results == null) results = new XamlIlOrSelectorNode(node, selectorType); results.Add(result); result = initialNode; break; default: throw new XamlParseException($"Unsupported selector grammar '{i.GetType()}'.", node); } } if (results != null && result != null) { results.Add(result); } return results ?? result; } IEnumerable<SelectorGrammar.ISyntax> parsed; try { parsed = SelectorGrammar.Parse(tn.Text); } catch (Exception e) { throw new XamlParseException("Unable to parse selector: " + e.Message, node); } var selector = Create(parsed, (p, n) => TypeReferenceResolver.ResolveType(context, $"{p}:{n}", true, node, true)); pn.Values[0] = selector; return new AvaloniaXamlIlTargetTypeMetadataNode(on, new XamlAstClrTypeReference(selector, selector.TargetType, false), AvaloniaXamlIlTargetTypeMetadataNode.ScopeTypes.Style); } } abstract class XamlIlSelectorNode : XamlAstNode, IXamlAstValueNode, IXamlAstEmitableNode<IXamlILEmitter, XamlILNodeEmitResult> { protected XamlIlSelectorNode Previous { get; } public abstract IXamlType TargetType { get; } public XamlIlSelectorNode(XamlIlSelectorNode previous, IXamlLineInfo info = null, IXamlType selectorType = null) : base(info ?? previous) { Previous = previous; Type = selectorType == null ? previous.Type : new XamlAstClrTypeReference(this, selectorType, false); } public IXamlAstTypeReference Type { get; } public virtual XamlILNodeEmitResult Emit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { if (Previous != null) context.Emit(Previous, codeGen, Type.GetClrType()); DoEmit(context, codeGen); return XamlILNodeEmitResult.Type(0, Type.GetClrType()); } protected abstract void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen); protected void EmitCall(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen, Func<IXamlMethod, bool> method) { var selectors = context.Configuration.TypeSystem.GetType("Avalonia.Styling.Selectors"); var found = selectors.FindMethod(m => m.IsStatic && m.Parameters.Count > 0 && method(m)); codeGen.EmitCall(found); } } class XamlIlSelectorInitialNode : XamlIlSelectorNode { public XamlIlSelectorInitialNode(IXamlLineInfo info, IXamlType selectorType) : base(null, info, selectorType) { } public override IXamlType TargetType => null; protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) => codeGen.Ldnull(); } class XamlIlTypeSelector : XamlIlSelectorNode { public bool Concrete { get; } public XamlIlTypeSelector(XamlIlSelectorNode previous, IXamlType type, bool concrete) : base(previous) { TargetType = type; Concrete = concrete; } public override IXamlType TargetType { get; } protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { var name = Concrete ? "OfType" : "Is"; codeGen.Ldtype(TargetType); EmitCall(context, codeGen, m => m.Name == name && m.Parameters.Count == 2 && m.Parameters[1].FullName == "System.Type"); } } class XamlIlStringSelector : XamlIlSelectorNode { public string String { get; set; } public enum SelectorType { Class, Name } private SelectorType _type; public XamlIlStringSelector(XamlIlSelectorNode previous, SelectorType type, string s) : base(previous) { _type = type; String = s; } public override IXamlType TargetType => Previous?.TargetType; protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { codeGen.Ldstr(String); var name = _type.ToString(); EmitCall(context, codeGen, m => m.Name == name && m.Parameters.Count == 2 && m.Parameters[1].FullName == "System.String"); } } class XamlIlCombinatorSelector : XamlIlSelectorNode { private readonly SelectorType _type; public enum SelectorType { Child, Descendant, Template } public XamlIlCombinatorSelector(XamlIlSelectorNode previous, SelectorType type) : base(previous) { _type = type; } public override IXamlType TargetType => null; protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { var name = _type.ToString(); EmitCall(context, codeGen, m => m.Name == name && m.Parameters.Count == 1); } } class XamlIlNotSelector : XamlIlSelectorNode { public XamlIlSelectorNode Argument { get; } public XamlIlNotSelector(XamlIlSelectorNode previous, XamlIlSelectorNode argument) : base(previous) { Argument = argument; } public override IXamlType TargetType => Previous?.TargetType; protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { context.Emit(Argument, codeGen, Type.GetClrType()); EmitCall(context, codeGen, m => m.Name == "Not" && m.Parameters.Count == 2 && m.Parameters[1].Equals(Type.GetClrType())); } } class XamlIlPropertyEqualsSelector : XamlIlSelectorNode { public XamlIlPropertyEqualsSelector(XamlIlSelectorNode previous, IXamlProperty property, IXamlAstValueNode value) : base(previous) { Property = property; Value = value; } public IXamlProperty Property { get; set; } public IXamlAstValueNode Value { get; set; } public override IXamlType TargetType => Previous?.TargetType; protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { if (!XamlIlAvaloniaPropertyHelper.Emit(context, codeGen, Property)) throw new XamlLoadException( $"{Property.Name} of {(Property.Setter ?? Property.Getter).DeclaringType.GetFqn()} doesn't seem to be an AvaloniaProperty", this); context.Emit(Value, codeGen, context.Configuration.WellKnownTypes.Object); EmitCall(context, codeGen, m => m.Name == "PropertyEquals" && m.Parameters.Count == 3 && m.Parameters[1].FullName == "Avalonia.AvaloniaProperty" && m.Parameters[2].Equals(context.Configuration.WellKnownTypes.Object)); } } class XamlIlOrSelectorNode : XamlIlSelectorNode { List<XamlIlSelectorNode> _selectors = new List<XamlIlSelectorNode>(); public XamlIlOrSelectorNode(IXamlLineInfo info, IXamlType selectorType) : base(null, info, selectorType) { } public void Add(XamlIlSelectorNode node) { _selectors.Add(node); } public override IXamlType TargetType { get { IXamlType result = null; foreach (var selector in _selectors) { if (selector.TargetType == null) { return null; } else if (result == null) { result = selector.TargetType; } else { while (!result.IsAssignableFrom(selector.TargetType)) { result = result.BaseType; } } } return result; } } protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen) { if (_selectors.Count == 0) throw new XamlLoadException("Invalid selector count", this); if (_selectors.Count == 1) { _selectors[0].Emit(context, codeGen); return; } var listType = context.Configuration.TypeSystem.FindType("System.Collections.Generic.List`1") .MakeGenericType(base.Type.GetClrType()); var add = listType.FindMethod("Add", context.Configuration.WellKnownTypes.Void, false, Type.GetClrType()); codeGen .Newobj(listType.FindConstructor()); foreach (var s in _selectors) { codeGen.Dup(); context.Emit(s, codeGen, Type.GetClrType()); codeGen.EmitCall(add, true); } EmitCall(context, codeGen, m => m.Name == "Or" && m.Parameters.Count == 1 && m.Parameters[0].Name.StartsWith("IReadOnlyList")); } } }
/* * 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. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * <keiron@aftexsw.com> to whom the Ant project is very grateful for his * great code. */ using java.io; using java.lang; using java.math; using java.nio; using java.text; using java.util; using java.util.zip; namespace RSUtilities.Compression.BZip2 { /// <summary> /// A simple class the hold and calculate the CRC for sanity checking /// of the data. /// </summary> internal sealed class CRC { internal static readonly int[] crc32Table = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, unchecked((int) 0x9823b6e0), unchecked((int) 0x9ce2ab57), unchecked((int) 0x91a18d8e), unchecked((int) 0x95609039), unchecked((int) 0x8b27c03c), unchecked((int) 0x8fe6dd8b), unchecked((int) 0x82a5fb52), unchecked((int) 0x8664e6e5), unchecked((int) 0xbe2b5b58), unchecked((int) 0xbaea46ef), unchecked((int) 0xb7a96036), unchecked((int) 0xb3687d81), unchecked((int) 0xad2f2d84), unchecked((int) 0xa9ee3033), unchecked((int) 0xa4ad16ea), unchecked((int) 0xa06c0b5d), unchecked((int) 0xd4326d90), unchecked((int) 0xd0f37027), unchecked((int) 0xddb056fe), unchecked((int) 0xd9714b49), unchecked((int) 0xc7361b4c), unchecked((int) 0xc3f706fb), unchecked((int) 0xceb42022), unchecked((int) 0xca753d95), unchecked((int) 0xf23a8028), unchecked((int) 0xf6fb9d9f), unchecked((int) 0xfbb8bb46), unchecked((int) 0xff79a6f1), unchecked((int) 0xe13ef6f4), unchecked((int) 0xe5ffeb43), unchecked((int) 0xe8bccd9a), unchecked((int) 0xec7dd02d), 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, unchecked((int) 0xaca5c697), unchecked((int) 0xa864db20), unchecked((int) 0xa527fdf9), unchecked((int) 0xa1e6e04e), unchecked((int) 0xbfa1b04b), unchecked((int) 0xbb60adfc), unchecked((int) 0xb6238b25), unchecked((int) 0xb2e29692), unchecked((int) 0x8aad2b2f), unchecked((int) 0x8e6c3698), unchecked((int) 0x832f1041), unchecked((int) 0x87ee0df6), unchecked((int) 0x99a95df3), unchecked((int) 0x9d684044), unchecked((int) 0x902b669d), unchecked((int) 0x94ea7b2a), unchecked((int) 0xe0b41de7), unchecked((int) 0xe4750050), unchecked((int) 0xe9362689), unchecked((int) 0xedf73b3e), unchecked((int) 0xf3b06b3b), unchecked((int) 0xf771768c), unchecked((int) 0xfa325055), unchecked((int) 0xfef34de2), unchecked((int) 0xc6bcf05f), unchecked((int) 0xc27dede8), unchecked((int) 0xcf3ecb31), unchecked((int) 0xcbffd686), unchecked((int) 0xd5b88683), unchecked((int) 0xd1799b34), unchecked((int) 0xdc3abded), unchecked((int) 0xd8fba05a), 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, unchecked((int) 0xf12f560e), unchecked((int) 0xf5ee4bb9), unchecked((int) 0xf8ad6d60), unchecked((int) 0xfc6c70d7), unchecked((int) 0xe22b20d2), unchecked((int) 0xe6ea3d65), unchecked((int) 0xeba91bbc), unchecked((int) 0xef68060b), unchecked((int) 0xd727bbb6), unchecked((int) 0xd3e6a601), unchecked((int) 0xdea580d8), unchecked((int) 0xda649d6f), unchecked((int) 0xc423cd6a), unchecked((int) 0xc0e2d0dd), unchecked((int) 0xcda1f604), unchecked((int) 0xc960ebb3), unchecked((int) 0xbd3e8d7e), unchecked((int) 0xb9ff90c9), unchecked((int) 0xb4bcb610), unchecked((int) 0xb07daba7), unchecked((int) 0xae3afba2), unchecked((int) 0xaafbe615), unchecked((int) 0xa7b8c0cc), unchecked((int) 0xa379dd7b), unchecked((int) 0x9b3660c6), unchecked((int) 0x9ff77d71), unchecked((int) 0x92b45ba8), unchecked((int) 0x9675461f), unchecked((int) 0x8832161a), unchecked((int) 0x8cf30bad), unchecked((int) 0x81b02d74), unchecked((int) 0x857130c3), 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, unchecked((int) 0xc5a92679), unchecked((int) 0xc1683bce), unchecked((int) 0xcc2b1d17), unchecked((int) 0xc8ea00a0), unchecked((int) 0xd6ad50a5), unchecked((int) 0xd26c4d12), unchecked((int) 0xdf2f6bcb), unchecked((int) 0xdbee767c), unchecked((int) 0xe3a1cbc1), unchecked((int) 0xe760d676), unchecked((int) 0xea23f0af), unchecked((int) 0xeee2ed18), unchecked((int) 0xf0a5bd1d), unchecked((int) 0xf464a0aa), unchecked((int) 0xf9278673), unchecked((int) 0xfde69bc4), unchecked((int) 0x89b8fd09), unchecked((int) 0x8d79e0be), unchecked((int) 0x803ac667), unchecked((int) 0x84fbdbd0), unchecked((int) 0x9abc8bd5), unchecked((int) 0x9e7d9662), unchecked((int) 0x933eb0bb), unchecked((int) 0x97ffad0c), unchecked((int) 0xafb010b1), unchecked((int) 0xab710d06), unchecked((int) 0xa6322bdf), unchecked((int) 0xa2f33668), unchecked((int) 0xbcb4666d), unchecked((int) 0xb8757bda), unchecked((int) 0xb5365d03), unchecked((int) 0xb1f740b4) }; internal int globalCrc; internal CRC() { InitialiseCRC(); } internal void InitialiseCRC() { globalCrc = unchecked((int) 0xffffffff); } internal int GetFinalCRC() { return ~globalCrc; } internal int GetGlobalCRC() { return globalCrc; } internal void SetGlobalCRC(int newCrc) { globalCrc = newCrc; } internal void UpdateCRC(int inCh) { var temp = (globalCrc >> 24) ^ inCh; if (temp < 0) { temp = 256 + temp; } globalCrc = (globalCrc << 8) ^ crc32Table[temp]; } internal void UpdateCRC(int inCh, int repeat) { var globalCrcShadow = globalCrc; while (repeat-- > 0) { var temp = (globalCrcShadow >> 24) ^ inCh; globalCrcShadow = (globalCrcShadow << 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } globalCrc = globalCrcShadow; } } }
using System; using System.Linq; using System.Collections; using UnityEngine; [AddComponentMenu( "Daikon Forge/Examples/Actionbar/Spell Slot" )] [ExecuteInEditMode] public class SpellSlot : MonoBehaviour { #region Protected serialized fields [SerializeField] protected string spellName = ""; [SerializeField] protected int slotNumber = 0; [SerializeField] protected bool isActionSlot = false; #endregion #region Private non-serialized fields private bool isSpellActive = false; #endregion #region Public properties public bool IsActionSlot { get { return this.isActionSlot; } set { this.isActionSlot = value; refresh(); } } public string Spell { get { return this.spellName; } set { this.spellName = value; refresh(); } } public int SlotNumber { get { return this.slotNumber; } set { this.slotNumber = value; refresh(); } } #endregion #region Unity events void OnEnable() { refresh(); } void Start() { refresh(); } void Update() { if( IsActionSlot && !string.IsNullOrEmpty( Spell ) ) { if( Input.GetKeyDown( (KeyCode)( this.slotNumber + 48 ) ) ) { castSpell(); } } } #endregion #region Event handlers public void onSpellActivated( SpellDefinition spell ) { if( spell.Name != this.Spell ) return; StartCoroutine( showCooldown() ); } void OnDoubleClick() { if( !isSpellActive && !string.IsNullOrEmpty( Spell ) ) { castSpell(); } } #endregion #region Drag and drop void OnDragStart( dfControl source, dfDragEventArgs args ) { if( allowDrag( args ) ) { if( string.IsNullOrEmpty( Spell ) ) { // Indicates that the drag-and-drop operation cannot be performed args.State = dfDragDropState.Denied; } else { // Get the offset that will be used for the drag cursor var sprite = GetComponent<dfControl>().Find( "Icon" ) as dfSprite; var ray = sprite.GetCamera().ScreenPointToRay( Input.mousePosition ); var dragCursorOffset = Vector2.zero; if( !sprite.GetHitPosition( ray, out dragCursorOffset ) ) return; // Set the variables that will be used to render the drag cursor. // The UI library provides all of the drag and drop events necessary // but does not provide a default drag visualization and requires // that the application provide the visualization. We'll do that by // supplying a Texture2D that will be placed at the mouse location // in the OnGUI() method. ActionbarsDragCursor.Show( sprite, Input.mousePosition, dragCursorOffset ); if( IsActionSlot ) { // Visually indicate that they are *moving* the spell rather than // just dragging it into a slot sprite.SpriteName = ""; } // Indicate that the drag and drop operation can continue and set // the user-defined data that will be sent to potential drop targets args.State = dfDragDropState.Dragging; args.Data = this; } // Do not let the OnDragStart event "bubble up" to higher-level controls args.Use(); } } void OnDragEnd( dfControl source, dfDragEventArgs args ) { ActionbarsDragCursor.Hide(); if( !this.isActionSlot ) return; if( args.State == dfDragDropState.CancelledNoTarget ) { Spell = ""; } refresh(); } void OnDragDrop( dfControl source, dfDragEventArgs args ) { if( allowDrop( args ) ) { args.State = dfDragDropState.Dropped; var otherSlot = args.Data as SpellSlot; var temp = this.spellName; this.Spell = otherSlot.Spell; if( otherSlot.IsActionSlot ) { otherSlot.Spell = temp; } } else { args.State = dfDragDropState.Denied; } args.Use(); } private bool allowDrag( dfDragEventArgs args ) { // Do not allow the user to drag and drop empty SpellSlot instances return !isSpellActive && !string.IsNullOrEmpty( spellName ); } private bool allowDrop( dfDragEventArgs args ) { if( isSpellActive ) return false; // Only allow drop if the source is another SpellSlot and // this SpellSlot is assignable var slot = args.Data as SpellSlot; return slot != null && this.IsActionSlot; } #endregion #region Private utility methods private IEnumerator showCooldown() { isSpellActive = true; var assignedSpell = SpellDefinition.FindByName( this.Spell ); var sprite = GetComponent<dfControl>().Find( "CoolDown" ) as dfSprite; sprite.IsVisible = true; var startTime = Time.realtimeSinceStartup; var endTime = startTime + assignedSpell.Recharge; while( Time.realtimeSinceStartup < endTime ) { var elapsed = Time.realtimeSinceStartup - startTime; var lerp = 1f - elapsed / assignedSpell.Recharge; sprite.FillAmount = lerp; yield return null; } sprite.FillAmount = 1f; sprite.IsVisible = false; isSpellActive = false; } private void castSpell() { var view = FindObjectsOfType( typeof( ActionBarViewModel ) ).FirstOrDefault() as ActionBarViewModel; if( view != null ) { view.CastSpell( this.Spell ); } } private void refresh() { var assignedSpell = SpellDefinition.FindByName( this.Spell ); var sprite = GetComponent<dfControl>().Find<dfSprite>( "Icon" ); sprite.SpriteName = assignedSpell != null ? assignedSpell.Icon : ""; var label = GetComponentInChildren<dfButton>(); label.IsVisible = this.IsActionSlot; label.Text = this.slotNumber.ToString(); } #endregion }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using System.Reflection; using System.Text; #if NET_2_0 using System.Collections.Generic; #endif namespace NUnit.Constraints.Constraints { #region CollectionConstraint /// <summary> /// CollectionConstraint is the abstract base class for /// constraints that operate on collections. /// </summary> public abstract class CollectionConstraint : Constraint { /// <summary> /// Construct an empty CollectionConstraint /// </summary> public CollectionConstraint() { } /// <summary> /// Construct a CollectionConstraint /// </summary> /// <param name="arg"></param> public CollectionConstraint(object arg) : base(arg) { } /// <summary> /// Determines whether the specified enumerable is empty. /// </summary> /// <param name="enumerable">The enumerable.</param> /// <returns> /// <c>true</c> if the specified enumerable is empty; otherwise, <c>false</c>. /// </returns> protected static bool IsEmpty( IEnumerable enumerable ) { ICollection collection = enumerable as ICollection; if ( collection != null ) return collection.Count == 0; else return !enumerable.GetEnumerator().MoveNext(); } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; IEnumerable enumerable = actual as IEnumerable; if ( enumerable == null ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); return doMatch( enumerable ); } /// <summary> /// Protected method to be implemented by derived classes /// </summary> /// <param name="collection"></param> /// <returns></returns> protected abstract bool doMatch(IEnumerable collection); } #endregion #region CollectionItemsEqualConstraint /// <summary> /// CollectionItemsEqualConstraint is the abstract base class for all /// collection constraints that apply some notion of item equality /// as a part of their operation. /// </summary> public abstract class CollectionItemsEqualConstraint : CollectionConstraint { private NUnitEqualityComparer comparer = NUnitEqualityComparer.Default; /// <summary> /// Construct an empty CollectionConstraint /// </summary> public CollectionItemsEqualConstraint() { } /// <summary> /// Construct a CollectionConstraint /// </summary> /// <param name="arg"></param> public CollectionItemsEqualConstraint(object arg) : base(arg) { } #region Modifiers /// <summary> /// Flag the constraint to ignore case and return self. /// </summary> public CollectionItemsEqualConstraint IgnoreCase { get { comparer.IgnoreCase = true; return this; } } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using(IComparer comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } #if NET_2_0 /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } /// <summary> /// Flag the constraint to use the supplied Comparison object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(Comparison<T> comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using(IEqualityComparer comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer) { this.comparer.ExternalComparer = EqualityAdapter.For(comparer); return this; } #endif #endregion /// <summary> /// Compares two collection members for equality /// </summary> protected bool ItemsEqual(object x, object y) { return comparer.ObjectsEqual(x, y); } /// <summary> /// Return a new CollectionTally for use in making tests /// </summary> /// <param name="c">The collection to be included in the tally</param> protected CollectionTally Tally(IEnumerable c) { return new CollectionTally(comparer, c); } } #endregion #region EmptyCollectionConstraint /// <summary> /// EmptyCollectionConstraint tests whether a collection is empty. /// </summary> public class EmptyCollectionConstraint : CollectionConstraint { /// <summary> /// Check that the collection is empty /// </summary> /// <param name="collection"></param> /// <returns></returns> protected override bool doMatch(IEnumerable collection) { return IsEmpty( collection ); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write( "<empty>" ); } } #endregion #region UniqueItemsConstraint /// <summary> /// UniqueItemsConstraint tests whether all the items in a /// collection are unique. /// </summary> public class UniqueItemsConstraint : CollectionItemsEqualConstraint { /// <summary> /// Check that all items are unique. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { ArrayList list = new ArrayList(); foreach (object o1 in actual) { foreach( object o2 in list ) if ( ItemsEqual(o1, o2) ) return false; list.Add(o1); } return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write("all items unique"); } } #endregion #region CollectionContainsConstraint /// <summary> /// CollectionContainsConstraint is used to test whether a collection /// contains an expected object as a member. /// </summary> public class CollectionContainsConstraint : CollectionItemsEqualConstraint { private object expected; /// <summary> /// Construct a CollectionContainsConstraint /// </summary> /// <param name="expected"></param> public CollectionContainsConstraint(object expected) : base(expected) { this.expected = expected; this.DisplayName = "contains"; } /// <summary> /// Test whether the expected item is contained in the collection /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { foreach (object obj in actual) if (ItemsEqual(obj, expected)) return true; return false; } /// <summary> /// Write a descripton of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("collection containing"); writer.WriteExpectedValue(expected); } } #endregion #region CollectionEquivalentConstraint /// <summary> /// CollectionEquivalentCOnstraint is used to determine whether two /// collections are equivalent. /// </summary> public class CollectionEquivalentConstraint : CollectionItemsEqualConstraint { private IEnumerable expected; /// <summary> /// Construct a CollectionEquivalentConstraint /// </summary> /// <param name="expected"></param> public CollectionEquivalentConstraint(IEnumerable expected) : base(expected) { this.expected = expected; this.DisplayName = "equivalent"; } /// <summary> /// Test whether two collections are equivalent /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { // This is just an optimization if( expected is ICollection && actual is ICollection ) if( ((ICollection)actual).Count != ((ICollection)expected).Count ) return false; CollectionTally tally = Tally(expected); return tally.TryRemove(actual) && tally.Count == 0; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("equivalent to"); writer.WriteExpectedValue(expected); } } #endregion #region CollectionSubsetConstraint /// <summary> /// CollectionSubsetConstraint is used to determine whether /// one collection is a subset of another /// </summary> public class CollectionSubsetConstraint : CollectionItemsEqualConstraint { private IEnumerable expected; /// <summary> /// Construct a CollectionSubsetConstraint /// </summary> /// <param name="expected">The collection that the actual value is expected to be a subset of</param> public CollectionSubsetConstraint(IEnumerable expected) : base(expected) { this.expected = expected; this.DisplayName = "subsetof"; } /// <summary> /// Test whether the actual collection is a subset of /// the expected collection provided. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { return Tally(expected).TryRemove( actual ); } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate( "subset of" ); writer.WriteExpectedValue(expected); } } #endregion #region CollectionOrderedConstraint /// <summary> /// CollectionOrderedConstraint is used to test whether a collection is ordered. /// </summary> public class CollectionOrderedConstraint : CollectionConstraint { private ComparisonAdapter comparer = ComparisonAdapter.Default; private string comparerName; private string propertyName; private bool descending; /// <summary> /// Construct a CollectionOrderedConstraint /// </summary> public CollectionOrderedConstraint() { this.DisplayName = "ordered"; } ///<summary> /// If used performs a reverse comparison ///</summary> public CollectionOrderedConstraint Descending { get { descending = true; return this; } } /// <summary> /// Modifies the constraint to use an IComparer and returns self. /// </summary> public CollectionOrderedConstraint Using(IComparer comparer) { this.comparer = ComparisonAdapter.For( comparer ); this.comparerName = comparer.GetType().FullName; return this; } #if NET_2_0 /// <summary> /// Modifies the constraint to use an IComparer&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(IComparer<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } /// <summary> /// Modifies the constraint to use a Comparison&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(Comparison<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } #endif /// <summary> /// Modifies the constraint to test ordering by the value of /// a specified property and returns self. /// </summary> public CollectionOrderedConstraint By(string propertyName) { this.propertyName = propertyName; return this; } /// <summary> /// Test whether the collection is ordered /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { object previous = null; int index = 0; foreach(object obj in actual) { object objToCompare = obj; if (obj == null) throw new ArgumentNullException("actual", "Null value at index " + index.ToString()); if (this.propertyName != null) { PropertyInfo prop = obj.GetType().GetProperty(propertyName); objToCompare = prop.GetValue(obj, null); if (objToCompare == null) throw new ArgumentNullException("actual", "Null property value at index " + index.ToString()); } if (previous != null) { //int comparisonResult = comparer.Compare(al[i], al[i + 1]); int comparisonResult = comparer.Compare(previous, objToCompare); if (descending && comparisonResult < 0) return false; if (!descending && comparisonResult > 0) return false; } previous = objToCompare; index++; } return true; } /// <summary> /// Write a description of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { if (propertyName == null) writer.Write("collection ordered"); else { writer.WritePredicate("collection ordered by"); writer.WriteExpectedValue(propertyName); } if (descending) writer.WriteModifier("descending"); } /// <summary> /// Returns the string representation of the constraint. /// </summary> /// <returns></returns> protected override string GetStringRepresentation() { StringBuilder sb = new StringBuilder("<ordered"); if (propertyName != null) sb.Append("by " + propertyName); if (descending) sb.Append(" descending"); if (comparerName != null) sb.Append(" " + comparerName); sb.Append(">"); return sb.ToString(); } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebSharp { //BEGIN INTERFACE public interface IElement { string ElementName { get;} string ToWebOptimizedString (PassonStylesheet PS); //Web Optimized ToString() } //END INTERFACE BEGIN ATTRIBUTESET public enum ButtonT {Button, Reset, Submit} public enum InputT {Text, Password, Radio, Checkbox, Submit, File, Hidden} public enum FormMethodT {GET, POST} public class AttributeSet { protected Dictionary<string, string> attributes = new Dictionary<string, string>(); public List<Styleset> Stylesets = new List<Styleset>(); public List<Style> Styles = new List<Style>(); public AttributeSet() { } public AttributeSet Attrib(string key, string value) { if (key != null && value != null) { attributes [key] = value; } return this; } public AttributeSet Accept(string value) {return Attrib ("accept", value);} public AttributeSet Action(string value) {return Attrib ("action", value);} public AttributeSet Alt(string value) {return Attrib ("alt", value);} public AttributeSet Enctype(MIME M) {return Attrib ("enctype", M.ToString());} public AttributeSet Formaction(string value) {return Attrib ("formaction", value);} public AttributeSet Height(int value) {return Attrib ("height", value.ToString());} public AttributeSet ID(string value) {return Attrib ("id", value);} public AttributeSet Method(FormMethodT value) {return Attrib ("method", value.ToString().ToLower());} public AttributeSet Name(string value) {return Attrib ("name", value);} public AttributeSet Reference(string value) {return Attrib ("href", value);} public AttributeSet Relationship(string value) {return Attrib ("rel", value);} public AttributeSet Source(string value) {return Attrib ("src", value);} public AttributeSet Title(string value) {return Attrib ("title", value);} public AttributeSet InputType(InputT value) {return Attrib ("type", value.ToString().ToLower());} public AttributeSet Value(string value) {return Attrib ("value", value);} public AttributeSet Width(int value) {return Attrib ("width", value.ToString());} public virtual string GetPassonText(PassonStylesheet PS) { return (Stylesets.Count > 0 ? String.Format(" class=\"{0}\"", String.Join(" ", Stylesets.Select(x => PS[x]))) : String.Empty) + (Styles.Count > 0 ? String.Format(" style=\"{0}\"", (Styles.Count > 0 ? String.Join("", Styles) : String.Empty)) : String.Empty) + String.Join ("", attributes.Select((k) => String.Format(" {0}=\"{1}\"", k.Key, k.Value))); //return (Styleset != null ? String.Format(" class=\"{0}\"", PS[Styleset, elementtype]) : String.Empty) + (Styles.Count > 0 ? String.Format(" style=\"{0}\"", String.Join("", Styles)) : String.Empty) + String.Join ("", attributes.Select((k, v) => String.Format(" {0}=\"{1}\"", k, v))); } public override string ToString () { return (Styles.Count > 0 || Stylesets.Count > 0 ? String.Format(" style=\"{0}\"", (Styles.Count > 0 ? String.Join("", Styles) : String.Empty) + (Stylesets.Count > 0 ? String.Join("", Stylesets.SelectMany((k) => k.Select((s) => String.Format("{0}:{1};", s.Key, s.Value)))) : String.Empty)) : String.Empty) + String.Join ("", attributes.Select((k) => String.Format(" {0}=\"{1}\"", k.Key, k.Value))); } } public class AttributeSetA { protected Dictionary<string, string> attributes = new Dictionary<string, string>(); public List<Styleset> Stylesets = new List<Styleset>(); public AttributeStyleset Styleset = new AttributeStyleset(null, null, null, null); public Styleset Link {get {return Styleset.Link;} set {Styleset.Link = value;}} public Styleset Visited {get {return Styleset.Visited;} set {Styleset.Visited = value;}} public Styleset Hover {get {return Styleset.Hover;} set {Styleset.Hover = value;}} public Styleset Active {get {return Styleset.Active;} set {Styleset.Active = value;}} public List<Style> Styles = new List<Style>(); public AttributeSetA () {} public AttributeSetA Attrib(string key, string value) { if (key != null && value != null) { attributes [key] = value; } return this; } public AttributeSetA ID(string value) {return Attrib ("id", value);} public AttributeSetA Reference(string value) {return Attrib ("href", value);} public AttributeSetA Title(string value) {return Attrib ("title", value);} public virtual string GetPassonText(PassonStylesheet PS) { return ((Link != null || Visited != null || Hover != null || Active != null || Stylesets.Count > 0) ? String.Format(" class=\"{0}\"", String.Join(" ", Stylesets.Select(x => PS[x]).Concat(new string[] {PS[Link, Visited, Hover, Active]}))) : String.Empty) + (Styles.Count > 0 ? String.Format(" style=\"{0}\"", (Styles.Count > 0 ? String.Join("", Styles) : String.Empty)) : String.Empty) + String.Join ("", attributes.Select((k) => String.Format(" {0}=\"{1}\"", k.Key, k.Value))); //return (Styleset != null ? String.Format(" class=\"{0}\"", PS[Styleset, elementtype]) : String.Empty) + (Styles.Count > 0 ? String.Format(" style=\"{0}\"", String.Join("", Styles)) : String.Empty) + String.Join ("", attributes.Select((k, v) => String.Format(" {0}=\"{1}\"", k, v))); } public override string ToString () { return (Styles.Count > 0 || Link != null ? String.Format(" style=\"{0}\"", (Styles.Count > 0 ? String.Join("", Styles) : String.Empty) + (Link != null ? String.Join("", Link.Select((k) => String.Format("{0}:{1};", k.Key, k.Value))) : String.Empty)) : String.Empty) + String.Join ("", attributes.Select((k) => String.Format(" {0}=\"{1}\"", k.Key, k.Value))); } } //END ATTRIBUTESET BEGIN ABSTRACTS public class ElementEmpty : IElement { protected string name; public AttributeSet Attributes = new AttributeSet(); public ElementEmpty Accept(string value) {this.Attributes.Accept (value); return this;} public ElementEmpty Action(string value) {this.Attributes.Action (value); return this;} public ElementEmpty Alt(string value) {this.Attributes.Alt (value); return this;} public ElementEmpty Enctype(MIME value) {this.Attributes.Enctype (value); return this;} public ElementEmpty Formaction(string value) {this.Attributes.Formaction (value); return this;} public ElementEmpty Height(int value) {this.Attributes.Height (value); return this;} public ElementEmpty ID(string value) {this.Attributes.ID (value); return this;} public ElementEmpty Method(FormMethodT value) {this.Attributes.Method (value); return this;} public ElementEmpty Name(string value) {this.Attributes.Name (value); return this;} public ElementEmpty Reference(string value) {this.Attributes.Reference (value); return this;} public ElementEmpty Relationship(string value) {this.Attributes.Relationship (value); return this;} public ElementEmpty Source(string value) {this.Attributes.Source (value); return this;} public ElementEmpty Title(string value) {this.Attributes.Title (value); return this;} public ElementEmpty InputType(InputT value) {this.Attributes.InputType (value); return this;} public ElementEmpty Value(string value) {this.Attributes.Value (value); return this;} public ElementEmpty Width(int value) {this.Attributes.Width (value); return this;} public ElementEmpty CustomAttribute(string attr, string value) {this.Attributes.Attrib (attr, value);return this;} public ElementEmpty SetStyleset(Styleset S) {this.Attributes.Stylesets.Clear ();this.Attributes.Stylesets.Add(S); return this;} public ElementEmpty AddStyleset(Styleset S) {this.Attributes.Stylesets.Add(S); return this;} public ElementEmpty AddStyles(params Style[] S) {this.Attributes.Styles.AddRange (S);return this;} public string ElementName { get{return name;} } public ElementEmpty (string name) { this.name = name; } public virtual string ToWebOptimizedString(PassonStylesheet PS) { return String.Format ("<{0}{1}>", this.ElementName, this.Attributes.GetPassonText(PS)); } public override string ToString () { return String.Format ("<{0}{1}>", this.ElementName, this.Attributes.ToString()); } } public class ElementText : IElement { public bool HTMLProtection = true; protected string name; public AttributeSet Attributes = new AttributeSet(); public ElementText EnableProtection () {this.HTMLProtection = true; return this;} public ElementText DisableProtection () {this.HTMLProtection = false; return this;} public ElementText Accept(string value) {this.Attributes.Accept (value); return this;} public ElementText Action(string value) {this.Attributes.Action (value); return this;} public ElementText Alt(string value) {this.Attributes.Alt (value); return this;} public ElementText Enctype(MIME value) {this.Attributes.Enctype (value); return this;} public ElementText Formaction(string value) {this.Attributes.Formaction (value); return this;} public ElementText ID(string value) {this.Attributes.ID (value); return this;} public ElementText Method(FormMethodT value) {this.Attributes.Method (value); return this;} public ElementText Name(string value) {this.Attributes.Name (value); return this;} public ElementText Reference(string value) {this.Attributes.Reference (value); return this;} public ElementText Relationship(string value) {this.Attributes.Relationship (value); return this;} public ElementText Source(string value) {this.Attributes.Source (value); return this;} public ElementText Title(string value) {this.Attributes.Title (value); return this;} public ElementText InputType(InputT value) {this.Attributes.InputType (value); return this;} public ElementText Value(string value) {this.Attributes.Value (value); return this;} public ElementText CustomAttribute(string attr, string value) {this.Attributes.Attrib (attr, value);return this;} public ElementText SetStyleset(Styleset S) {this.Attributes.Stylesets.Clear ();this.Attributes.Stylesets.Add(S); return this;} public ElementText AddStyleset(Styleset S) {this.Attributes.Stylesets.Add(S); return this;} public ElementText AddStyles(params Style[] S) {this.Attributes.Styles.AddRange (S);return this;} public string Text; public string ElementName { get{return name;} } public ElementText (string name, string text) { this.name = name; this.Text = text; } public virtual string ToWebOptimizedString(PassonStylesheet PS) { return String.Format ("<{0}{1}>{2}</{0}>", this.ElementName, this.Attributes.GetPassonText(PS), HTMLProtection ? HttpUtility.HtmlEncode(this.Text) : this.Text); } public override string ToString () { return String.Format ("<{0}{1}>{2}</{0}>", this.ElementName, this.Attributes.ToString(), HTMLProtection ? HttpUtility.HtmlEncode(this.Text) : this.Text); } } public class ElementContainer : List<IElement>, IElement { protected string name; public AttributeSet Attributes = new AttributeSet(); public ElementContainer Accept(string value) {this.Attributes.Accept (value); return this;} public ElementContainer Action(string value) {this.Attributes.Action (value); return this;} public ElementContainer Alt(string value) {this.Attributes.Alt (value); return this;} public ElementContainer Enctype(MIME value) {this.Attributes.Enctype (value); return this;} public ElementContainer Formaction(string value) {this.Attributes.Formaction (value); return this;} public ElementContainer ID(string value) {this.Attributes.ID (value); return this;} public ElementContainer Method(FormMethodT value) {this.Attributes.Method (value); return this;} public ElementContainer Name(string value) {this.Attributes.Name (value); return this;} public ElementContainer Reference(string value) {this.Attributes.Reference (value); return this;} public ElementContainer Relationship(string value) {this.Attributes.Relationship (value); return this;} public ElementContainer Source(string value) {this.Attributes.Source (value); return this;} public ElementContainer Title(string value) {this.Attributes.Title (value); return this;} public ElementContainer InputType(InputT value) {this.Attributes.InputType (value); return this;} public ElementContainer Value(string value) {this.Attributes.Value (value); return this;} public ElementContainer CustomAttribute(string attr, string value) {this.Attributes.Attrib (attr, value);return this;} public ElementContainer SetStyleset(Styleset S) {this.Attributes.Stylesets.Clear ();this.Attributes.Stylesets.Add(S); return this;} public ElementContainer AddStyleset(Styleset S) {this.Attributes.Stylesets.Add(S); return this;} public ElementContainer AddStyles(params Style[] S) {this.Attributes.Styles.AddRange (S);return this;} public string ElementName { get{return name;} } public ElementContainer (string name, params IElement[] contents) : base (contents) { this.name = name; } public void Add(params IElement[] e) { this.AddRange (e); } public virtual string ToWebOptimizedString(PassonStylesheet PS) { return String.Format ("<{0}{1}>{2}</{0}>", this.ElementName, this.Attributes.GetPassonText(PS), String.Join("", this.Select((e) => e.ToWebOptimizedString(PS)))); } public override string ToString () { return String.Format ("<{0}{1}>{2}</{0}>", this.ElementName, this.Attributes.ToString(), String.Join("", this)); } } public class NonformatText : IElement { public string ElementName {get {return String.Empty;}} protected string text; public NonformatText(string text) { this.text = text; } public string ToWebOptimizedString(PassonStylesheet PS) { return text; } public override string ToString () { return text; } } public class AttributeElement : IElement { public AttributeSetA Attributes = new AttributeSetA(); public AttributeElement ID(string value) {Attributes.ID(value); return this;} public AttributeElement Reference(string value) {Attributes.Reference(value);return this;} public AttributeElement Title(string value) {Attributes.Title(value); return this;} public AttributeElement SetStyleset(AttributeStyleset ASET) {this.Attributes.Styleset = ASET; return this;} public AttributeElement AddStyleset(Styleset S) {this.Attributes.Stylesets.Add (S); return this;} public AttributeElement AddStyles(params Style[] S) {this.Attributes.Styles.AddRange (S);return this;} public string ElementName {get {return "a";}} private IElement element; public AttributeElement(IElement element) { this.element = element; } public virtual string ToWebOptimizedString(PassonStylesheet PS) { return String.Format ("<{0}{1}>{2}</{0}>", this.ElementName, this.Attributes.GetPassonText(PS), this.element.ToWebOptimizedString(PS)); } public override string ToString () { return String.Format ("<{0}{1}>{2}</{0}>", this.ElementName, this.Attributes.ToString(), this.element.ToString()); } } public class ButtonElement : ElementText { ButtonT BT; public ButtonElement(string text, ButtonT BT) : base("button", text) { this.BT = BT; } public override string ToWebOptimizedString(PassonStylesheet PS) { return String.Format ("<{0}{1} type=\"{3}\">{2}</{0}>", this.ElementName, this.Attributes.GetPassonText(PS), HttpUtility.HtmlEncode(this.Text), BT.ToString().ToLower()); } public override string ToString () { return String.Format ("<{0}{1} type=\"{3}\">{2}</{0}>", this.ElementName, this.Attributes.ToString(), HttpUtility.HtmlEncode(this.Text), BT.ToString().ToLower()); } } public static class HTML { //END ABSTRACTS BEGIN SPECIALS public static AttributeElement Attribute(IElement IE) {return new AttributeElement (IE);} public static AttributeElement Attribute(string IE) {return new AttributeElement (new NonformatText(IE));} //END SPECIALS BEGIN EMPTIES public static ElementEmpty Breakline () {return new ElementEmpty ("br");} public static ElementEmpty Image(string src) {return new ElementEmpty ("img").Source(src);} public static ElementEmpty Input (InputT type, string name) {return new ElementEmpty ("input").InputType (type).Name (name);} public static ElementEmpty Input (InputT type, string name, string value) {return new ElementEmpty ("input").InputType (type).Name (name).Value (value);} public static ElementEmpty FileInput (string name, string mimeaccept) {return new ElementEmpty ("input").InputType (InputT.File).Name (name).Accept (mimeaccept);} public static ElementEmpty Submit(string name = "Submit") {return new ElementEmpty ("input").InputType (InputT.Submit).Value (name);} //END EMPTIES BEGIN TEXTS public static ElementText Button(ButtonT B, string text) {return new ButtonElement (text, B);} public static ElementText Paragraph(string text) {return new ElementText ("p", text);} public static ElementText Span(string text) {return new ElementText ("span", text);} //END TEXTS BEGIN CONTAINERS public static ElementContainer Divider(params IElement[] contents) {return new ElementContainer ("div", contents);} public static ElementContainer Form(FormMethodT method, params IElement[] contents) { ElementContainer F = new ElementContainer ("form", contents).Method (method); if (method == FormMethodT.POST) {F.Enctype (MIME.MultipartFormData);} return F; } //END CONTAINERS BEGIN STRUCTURES } public class Webpage { public string HTitle; public ElementContainer Body; public List<string> Scripts = new List<string>(); public List<string> ScriptReferences = new List<string>(); protected List<Styleset> preset = new List<Styleset> (); protected List<AttributeStyleset> preaset = new List<AttributeStyleset> (); public Webpage(string title, params IElement[] contents) { this.HTitle = title; this.Body = new ElementContainer("body", contents); } public void Add (IElement element) { Body.Add (element); } public void Add (params IElement[] elements) { Body.AddRange (elements); } public void Preload(params Styleset[] S) { this.preset.AddRange (S); } public void Preload(params AttributeStyleset[] S) { this.preaset.AddRange (S); } public override string ToString () { PassonStylesheet PS = new PassonStylesheet (); preset.ForEach (s => PS.ManualAdd(s)); preaset.ForEach (s => PS.ManualAdd(s)); return String.Format ("<{3}>{4}{5}{6}{7}</{3}><{0}{1}>{2}</{0}>", Body.ElementName, Body.Attributes.GetPassonText(PS), String.Join("", Body.Select((e) => e.ToWebOptimizedString(PS))), "head", String.Format("<title>{0}</title>", this.HTitle), String.Format("<style type=\"text/css\">{0}</style>", String.Join ("\n", PS.GetFormattedSheet ())), String.Join("\n", ScriptReferences.Select(s => String.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", s))), String.Join("\n", Scripts.Select(s => String.Format("<script type=\"text/javascript\">{0}</script>", s))) ); } } //END STRUCTURES }
// ============================================================================ // FileName: NotifierCore.cs // // Description: // SIP Notifier server as described in RFC3265 "Session Initiation Protocol (SIP)-Specific Event Notification". // // Author(s): // Aaron Clauson // // History: // 22 Feb 2010 Aaron Clauson Created. // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2010 Aaron Clauson (aaron@sipsorcery.com), SIPSorcery Ltd, London, UK (www.sipsorcery.com) // 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 Blue Face Ltd. // nor the names of its contributors may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using System.Xml.Serialization; using SIPSorcery.CRM; using SIPSorcery.Persistence; using SIPSorcery.SIP; using SIPSorcery.SIP.App; using SIPSorcery.Sys; using log4net; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.Servers { public class NotifierCore { private const int MAX_NOTIFIER_QUEUE_SIZE = 1000; private const int MAX_NOTIFIER_SLEEP_TIME = 10000; private const string NOTIFIER_THREAD_NAME_PREFIX = "sipnotifier-core"; private const int MIN_SUBSCRIPTION_EXPIRY = 60; private const int MAX_SUBSCRIPTION_EXPIRY = 3600; private static ILog logger = AppState.GetLogger("sipnotifier"); private static string m_wildcardUser = SIPMonitorFilter.WILDCARD; private string m_topLevelAdminID = Customer.TOPLEVEL_ADMIN_ID; private SIPMonitorLogDelegate MonitorLogEvent_External; private SIPTransport m_sipTransport; private SIPAssetGetDelegate<Customer> GetCustomer_External; private GetCanonicalDomainDelegate GetCanonicalDomain_External; private SIPAuthenticateRequestDelegate SIPRequestAuthenticator_External; private SIPAssetPersistor<SIPAccount> m_sipAssetPersistor; private Queue<SIPNonInviteTransaction> m_notifierQueue = new Queue<SIPNonInviteTransaction>(); private AutoResetEvent m_notifierARE = new AutoResetEvent(false); private SIPEndPoint m_outboundProxy; private NotifierSubscriptionsManager m_subscriptionsManager; private bool m_exit; public NotifierCore( SIPMonitorLogDelegate logDelegate, SIPTransport sipTransport, SIPAssetGetDelegate<Customer> getCustomer, SIPAssetGetListDelegate<SIPDialogueAsset> getDialogues, SIPAssetGetByIdDelegate<SIPDialogueAsset> getDialogue, GetCanonicalDomainDelegate getCanonicalDomain, SIPAssetPersistor<SIPAccount> sipAssetPersistor, SIPAssetCountDelegate<SIPRegistrarBinding> getBindingsCount, SIPAuthenticateRequestDelegate sipRequestAuthenticator, SIPEndPoint outboundProxy, ISIPMonitorPublisher publisher) { MonitorLogEvent_External = logDelegate; m_sipTransport = sipTransport; GetCustomer_External = getCustomer; m_sipAssetPersistor = sipAssetPersistor; GetCanonicalDomain_External = getCanonicalDomain; SIPRequestAuthenticator_External = sipRequestAuthenticator; m_outboundProxy = outboundProxy; m_subscriptionsManager = new NotifierSubscriptionsManager(MonitorLogEvent_External, getDialogues, getDialogue, m_sipAssetPersistor, getBindingsCount, m_sipTransport, m_outboundProxy, publisher); ThreadPool.QueueUserWorkItem(delegate { ProcessSubscribeRequest(NOTIFIER_THREAD_NAME_PREFIX + "1"); }); } public void Stop() { m_exit = true; //if (m_subscriptionsManager != null) //{ // m_subscriptionsManager.Stop(); //} } public void AddSubscribeRequest(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest subscribeRequest) { try { if (subscribeRequest.Method != SIPMethodsEnum.SUBSCRIBE) { SIPResponse notSupportedResponse = SIPTransport.GetResponse(subscribeRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, "Subscribe requests only"); m_sipTransport.SendResponse(notSupportedResponse); } else { #region Do as many validation checks as possible on the request before adding it to the queue. if (subscribeRequest.Header.Event.IsNullOrBlank() || !(subscribeRequest.Header.Event.ToLower() == SIPEventPackage.Dialog.ToString().ToLower() || subscribeRequest.Header.Event.ToLower() == SIPEventPackage.Presence.ToString().ToLower())) { SIPResponse badEventResponse = SIPTransport.GetResponse(subscribeRequest, SIPResponseStatusCodesEnum.BadEvent, null); m_sipTransport.SendResponse(badEventResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Warn, "Event type " + subscribeRequest.Header.Event + " not supported for " + subscribeRequest.URI.ToString() + ".", null)); } else if (subscribeRequest.Header.Expires > 0 && subscribeRequest.Header.Expires < MIN_SUBSCRIPTION_EXPIRY) { SIPResponse tooBriefResponse = SIPTransport.GetResponse(subscribeRequest, SIPResponseStatusCodesEnum.IntervalTooBrief, null); tooBriefResponse.Header.MinExpires = MIN_SUBSCRIPTION_EXPIRY; m_sipTransport.SendResponse(tooBriefResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Warn, "Subscribe request was rejected as interval too brief " + subscribeRequest.Header.Expires + ".", null)); } else if (subscribeRequest.Header.Contact == null || subscribeRequest.Header.Contact.Count == 0) { SIPResponse noContactResponse = SIPTransport.GetResponse(subscribeRequest, SIPResponseStatusCodesEnum.BadRequest, "Missing Contact header"); m_sipTransport.SendResponse(noContactResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Warn, "Subscribe request was rejected due to no Contact header.", null)); } #endregion else { if (m_notifierQueue.Count < MAX_NOTIFIER_QUEUE_SIZE) { SIPNonInviteTransaction subscribeTransaction = m_sipTransport.CreateNonInviteTransaction(subscribeRequest, remoteEndPoint, localSIPEndPoint, m_outboundProxy); lock (m_notifierQueue) { m_notifierQueue.Enqueue(subscribeTransaction); } FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeQueued, "Subscribe queued for " + subscribeRequest.Header.To.ToURI.ToString() + ".", null)); } else { logger.Error("Subscribe queue exceeded max queue size " + MAX_NOTIFIER_QUEUE_SIZE + ", overloaded response sent."); SIPResponse overloadedResponse = SIPTransport.GetResponse(subscribeRequest, SIPResponseStatusCodesEnum.TemporarilyUnavailable, "Notifier overloaded, please try again shortly"); m_sipTransport.SendResponse(overloadedResponse); } m_notifierARE.Set(); } } } catch (Exception excp) { logger.Error("Exception AddNotifierRequest (" + remoteEndPoint.ToString() + "). " + excp.Message); } } private void ProcessSubscribeRequest(string threadName) { try { Thread.CurrentThread.Name = threadName; while (!m_exit) { if (m_notifierQueue.Count > 0) { try { SIPNonInviteTransaction subscribeTransaction = null; lock (m_notifierQueue) { subscribeTransaction = m_notifierQueue.Dequeue(); } if (subscribeTransaction != null) { DateTime startTime = DateTime.Now; Subscribe(subscribeTransaction); TimeSpan duration = DateTime.Now.Subtract(startTime); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Timing, "Subscribe time=" + duration.TotalMilliseconds + "ms, user=" + subscribeTransaction.TransactionRequest.Header.To.ToURI.User + ".", null)); } } catch (Exception regExcp) { logger.Error("Exception ProcessSubscribeRequest Subscribe Job. " + regExcp.Message); } } else { m_notifierARE.WaitOne(MAX_NOTIFIER_SLEEP_TIME); } } logger.Warn("ProcessSubscribeRequest thread " + Thread.CurrentThread.Name + " stopping."); } catch (Exception excp) { logger.Error("Exception ProcessSubscribeRequest (" + Thread.CurrentThread.Name + "). " + excp.Message); } } private void Subscribe(SIPTransaction subscribeTransaction) { try { SIPRequest sipRequest = subscribeTransaction.TransactionRequest; string fromUser = sipRequest.Header.From.FromURI.User; string fromHost = sipRequest.Header.From.FromURI.Host; string canonicalDomain = GetCanonicalDomain_External(fromHost, true); if (canonicalDomain == null) { FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Warn, "Subscribe request for " + fromHost + " rejected as no matching domain found.", null)); SIPResponse noDomainResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Forbidden, "Domain not serviced"); subscribeTransaction.SendFinalResponse(noDomainResponse); return; } SIPAccount sipAccount = m_sipAssetPersistor.Get(s => s.SIPUsername == fromUser && s.SIPDomain == canonicalDomain); SIPRequestAuthenticationResult authenticationResult = SIPRequestAuthenticator_External(subscribeTransaction.LocalSIPEndPoint, subscribeTransaction.RemoteEndPoint, sipRequest, sipAccount, FireProxyLogEvent); if (!authenticationResult.Authenticated) { // 401 Response with a fresh nonce needs to be sent. SIPResponse authReqdResponse = SIPTransport.GetResponse(sipRequest, authenticationResult.ErrorResponse, null); authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader; subscribeTransaction.SendFinalResponse(authReqdResponse); if (authenticationResult.ErrorResponse == SIPResponseStatusCodesEnum.Forbidden) { FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Warn, "Forbidden " + fromUser + "@" + canonicalDomain + " does not exist, " + sipRequest.Header.ProxyReceivedFrom.ToString() + ", " + sipRequest.Header.UserAgent + ".", null)); } else { FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeAuth, "Authentication required for " + fromUser + "@" + canonicalDomain + " from " + subscribeTransaction.RemoteEndPoint + ".", sipAccount.Owner)); } return; } else { if (sipRequest.Header.To.ToTag != null) { // Request is to renew an existing subscription. SIPResponseStatusCodesEnum errorResponse = SIPResponseStatusCodesEnum.None; string errorResponseReason = null; string sessionID = m_subscriptionsManager.RenewSubscription(sipRequest, out errorResponse, out errorResponseReason); if (errorResponse != SIPResponseStatusCodesEnum.None) { // A subscription renewal attempt failed SIPResponse renewalErrorResponse = SIPTransport.GetResponse(sipRequest, errorResponse, errorResponseReason); subscribeTransaction.SendFinalResponse(renewalErrorResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeFailed, "Subscription renewal failed for event type " + sipRequest.Header.Event + " " + sipRequest.URI.ToString() + ", " + errorResponse + " " + errorResponseReason + ".", sipAccount.Owner)); } else if (sipRequest.Header.Expires == 0) { // Existing subscription was closed. SIPResponse okResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); subscribeTransaction.SendFinalResponse(okResponse); } else { // Existing subscription was found. SIPResponse okResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); subscribeTransaction.SendFinalResponse(okResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeRenew, "Subscription renewal for " + sipRequest.URI.ToString() + ", event type " + sipRequest.Header.Event + " and expiry " + sipRequest.Header.Expires + ".", sipAccount.Owner)); m_subscriptionsManager.SendFullStateNotify(sessionID); } } else { // Authenticated but the this is a new subscription request and authorisation to subscribe to the requested resource also needs to be checked. SIPURI canonicalResourceURI = sipRequest.URI.CopyOf(); string resourceCanonicalDomain = GetCanonicalDomain_External(canonicalResourceURI.Host, true); canonicalResourceURI.Host = resourceCanonicalDomain; SIPAccount resourceSIPAccount = null; if (resourceCanonicalDomain == null) { SIPResponse notFoundResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotFound, "Domain " + resourceCanonicalDomain + " not serviced"); subscribeTransaction.SendFinalResponse(notFoundResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeFailed, "Subscription failed for " + sipRequest.URI.ToString() + ", event type " + sipRequest.Header.Event + ", domain not serviced.", sipAccount.Owner)); return; } if (canonicalResourceURI.User != m_wildcardUser) { resourceSIPAccount = m_sipAssetPersistor.Get(s => s.SIPUsername == canonicalResourceURI.User && s.SIPDomain == canonicalResourceURI.Host); if (resourceSIPAccount == null) { SIPResponse notFoundResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotFound, "Requested resource does not exist"); subscribeTransaction.SendFinalResponse(notFoundResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeFailed, "Subscription failed for " + sipRequest.URI.ToString() + ", event type " + sipRequest.Header.Event + ", SIP account does not exist.", sipAccount.Owner)); return; } } // Check the owner permissions on the requesting and subscribed resources. bool authorised = false; string adminID = null; if (canonicalResourceURI.User == m_wildcardUser || sipAccount.Owner == resourceSIPAccount.Owner) { authorised = true; FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeAuth, "Subscription to " + canonicalResourceURI.ToString() + " authorised due to common owner.", sipAccount.Owner)); } else { // Lookup the customer record for the requestor and check the administrative level on it. Customer requestingCustomer = GetCustomer_External(c => c.CustomerUsername == sipAccount.Owner); adminID = requestingCustomer.AdminId; if (!resourceSIPAccount.AdminMemberId.IsNullOrBlank() && requestingCustomer.AdminId == resourceSIPAccount.AdminMemberId) { authorised = true; FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeAuth, "Subscription to " + canonicalResourceURI.ToString() + " authorised due to requestor admin permissions for domain " + resourceSIPAccount.AdminMemberId + ".", sipAccount.Owner)); } else if (requestingCustomer.AdminId == m_topLevelAdminID) { authorised = true; FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeAuth, "Subscription to " + canonicalResourceURI.ToString() + " authorised due to requestor having top level admin permissions.", sipAccount.Owner)); } } if (authorised) { // Request is to create a new subscription. SIPResponseStatusCodesEnum errorResponse = SIPResponseStatusCodesEnum.None; string errorResponseReason = null; string toTag = CallProperties.CreateNewTag(); string sessionID = m_subscriptionsManager.SubscribeClient(sipAccount.Owner, adminID, sipRequest, toTag, canonicalResourceURI, out errorResponse, out errorResponseReason); if (errorResponse != SIPResponseStatusCodesEnum.None) { SIPResponse subscribeErrorResponse = SIPTransport.GetResponse(sipRequest, errorResponse, errorResponseReason); subscribeTransaction.SendFinalResponse(subscribeErrorResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeAccept, "Subscription failed for " + sipRequest.URI.ToString() + ", event type " + sipRequest.Header.Event + ", " + errorResponse + " " + errorResponseReason + ".", sipAccount.Owner)); } else { SIPResponse okResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null); okResponse.Header.To.ToTag = toTag; okResponse.Header.Expires = sipRequest.Header.Expires; okResponse.Header.Contact = new List<SIPContactHeader>() { new SIPContactHeader(null, new SIPURI(SIPSchemesEnum.sip, subscribeTransaction.LocalSIPEndPoint)) }; subscribeTransaction.SendFinalResponse(okResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeAccept, "Subscription accepted for " + sipRequest.URI.ToString() + ", event type " + sipRequest.Header.Event + " and expiry " + sipRequest.Header.Expires + ".", sipAccount.Owner)); if (sessionID != null) { m_subscriptionsManager.SendFullStateNotify(sessionID); } } } else { SIPResponse forbiddenResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Forbidden, "Requested resource not authorised"); subscribeTransaction.SendFinalResponse(forbiddenResponse); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.SubscribeFailed, "Subscription failed for " + sipRequest.URI.ToString() + ", event type " + sipRequest.Header.Event + ", requesting account " + sipAccount.Owner + " was not authorised.", sipAccount.Owner)); } } } } catch (Exception excp) { logger.Error("Exception notifiercore subscribing. " + excp.Message + "\r\n" + subscribeTransaction.TransactionRequest.ToString()); FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.Error, "Exception notifiercore subscribing. " + excp.Message, null)); SIPResponse errorResponse = SIPTransport.GetResponse(subscribeTransaction.TransactionRequest, SIPResponseStatusCodesEnum.InternalServerError, null); subscribeTransaction.SendFinalResponse(errorResponse); } } private void FireProxyLogEvent(SIPMonitorEvent monitorEvent) { if (MonitorLogEvent_External != null) { try { MonitorLogEvent_External(monitorEvent); } catch (Exception excp) { logger.Error("Exception FireProxyLogEvent NotifierCore. " + excp.Message); } } } } }
using UnityEngine; using System; using System.Collections.Generic; #if !UNITY_FLASH && !UNITY_METRO && !UNITY_WP8 using System.Reflection; #endif #if UNITY_EDITOR using UnityEditor; #endif [System.Serializable] public class MegaLoftTris { public int[] sourcetris; public int[] tris; public int offset; } public class MegaShapeBase : MonoBehaviour { public virtual void SplineNotify(MegaShape shape, int reason) {} public virtual void LayerNotify(MegaLoftLayerBase layer, int reason) {} } [ExecuteInEditMode, RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))] public class MegaShapeLoft : MegaShapeBase { public bool realtime = true; public bool rebuild = true; public Mesh mesh; public MegaLoftLayerBase[] Layers; public Vector3 CrossScale = Vector3.one; public bool Tangents = false; public bool Optimize = false; public bool DoBounds = true; public bool DoCollider = false; public Vector3 crossrot = Vector3.zero; public Vector3 up = Vector3.up; public float tangent = 0.001f; Vector3[] verts; Vector2[] uvs; Vector3[] crossverts; Vector2[] crossuvs; int[] crossids; Matrix4x4 wtm = Matrix4x4.identity; MeshCollider meshCol; public int vertcount = 0; public int polycount = 0; public float startLow = -1.0f; public float startHigh = 1.0f; public float lenLow = 0.001f; public float lenHigh = 2.0f; public float crossLow = -1.0f; public float crossHigh = 1.0f; public float crossLenLow = 0.001f; public float crossLenHigh = 2.0f; public float distlow = 0.025f; public float disthigh = 1.0f; public float cdistlow = 0.025f; public float cdisthigh = 1.0f; static bool updating = false; // Lightmap public bool genLightMap = false; public float angleError = 0.08f; public float areaError = 0.15f; public float hardAngle = 88.0f; public float packMargin = 0.0039f; // Color support public bool useColors = false; public Color defaultColor = Color.white; Color[] cols; public float conformAmount = 1.0f; public bool undo = false; [ContextMenu("Help")] public void Help() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=2087"); } public override void SplineNotify(MegaShape shape, int reason) { for ( int i = 0; i < Layers.Length; i++ ) { if ( Layers[i].SplineNotify(shape, reason) ) { rebuild = true; break; } } } public override void LayerNotify(MegaLoftLayerBase layer, int reason) { if ( Layers != null ) { for ( int i = 0; i < Layers.Length; i++ ) { if ( Layers[i].LayerNotify(layer, reason) ) { rebuild = true; break; } } } } public virtual bool LoftNotify(MegaShapeLoft loft, int reason) { if ( Layers != null ) { for ( int i = 0; i < Layers.Length; i++ ) { if ( Layers[i].LoftNotify(loft, reason) ) { rebuild = true; break; } } } return rebuild; } void Start() { #if UNITY_EDITOR PrefabUtility.DisconnectPrefabInstance(gameObject); #endif if ( Layers != null ) { Layers = GetComponents<MegaLoftLayerBase>(); // Check spline connections for ( int i = 0; i < Layers.Length; i++ ) { Layers[i].FindShapes(); //if ( Layers[i].layerPath == null && Layers[i].pathName.Length > 0 ) //{ // GameObject obj = GameObject.Find(Layers[i].pathName); // if ( obj ) // Layers[i].layerPath = obj.GetComponent<MegaShape>(); //} //if ( Layers[i].layerSection == null && Layers[i].sectionName.Length > 0 ) //{ // GameObject obj = GameObject.Find(Layers[i].sectionName); // if ( obj ) // Layers[i].layerSection = obj.GetComponent<MegaShape>(); //} } } } //void Update() //{ //BuildMeshFromLayersNew(); //} void LateUpdate() { BuildMeshFromLayersNew(); } public void BuildMeshFromLayersNew() { // Check for any valid layers if ( rebuild ) //&& Layers.Length > 0 ) { //Debug.Log("*************** Build Mesh ****************"); Layers = GetComponents<MegaLoftLayerBase>(); if ( Layers.Length > 0 ) { if ( mesh == null ) // Should be shapemesh, and this should be a util function { MeshFilter mf = gameObject.GetComponent<MeshFilter>(); if ( mf == null ) { mf = gameObject.AddComponent<MeshFilter>(); mf.name = gameObject.name; } mf.sharedMesh = new Mesh(); MeshRenderer mr = gameObject.GetComponent<MeshRenderer>(); if ( mr == null ) mr = gameObject.AddComponent<MeshRenderer>(); mesh = mf.sharedMesh; //Utils.GetMesh(gameObject); } if ( !realtime ) rebuild = false; int smcount = 0; int numverts = 0; for ( int i = 0; i < Layers.Length; i++ ) { if ( Layers[i].Valid() ) { //smcount++; //smcount += Layers[i].NumMaterials(); Layers[i].PrepareLoft(this, i); smcount += Layers[i].NumMaterials(); numverts += Layers[i].NumVerts(); } } //Debug.Log("1 " + gameObject.name); if ( numverts > 65535 ) { Debug.LogWarning("Loft Layer will have too many vertices. Lower the detail settings or disable a layer."); return; } //Debug.Log("verts " + verts.Length + " numverts " + numverts); if ( verts == null || verts.Length != numverts ) verts = new Vector3[numverts]; if ( uvs == null || uvs.Length != numverts ) uvs = new Vector2[numverts]; if ( useColors && (cols == null || cols.Length != numverts) ) cols = new Color[numverts]; //if ( useColor ) //{ // if ( colors == null || colors.Length != numverts ) // colors = new Color[numverts]; //} int offset = 0; // Check on vertex count here, if over 65000 then start a new object // TODO: Some layers wont add to mesh, ie colliders and object scatters for ( int i = 0; i < Layers.Length; i++ ) { if ( Layers[i].Valid() ) { // Only call if verts need rebuilding, so per layer rebuild (spline change will do all) Layers[i].BuildMesh(this, offset); //Debug.Log("copy " + verts.Length); if ( useColors ) Layers[i].CopyVertData(ref verts, ref uvs, ref cols, offset); else Layers[i].CopyVertData(ref verts, ref uvs, offset); offset += Layers[i].NumVerts(); //loftverts.Length; } } //Vector2[] lmuvs = mesh.uv2; mesh.Clear(); mesh.subMeshCount = smcount; mesh.vertices = verts; mesh.uv = uvs; //if ( lmuvs.Length == uvs.Length ) //{ //Debug.Log("Setting uv2"); //mesh.uv2 = lmuvs; //} if ( useColors ) mesh.colors = cols; vertcount = verts.Length; polycount = 0; Material[] mats = new Material[smcount]; int mi = 0; for ( int i = 0; i < Layers.Length; i++ ) { if ( Layers[i].Valid() ) { for ( int m = 0; m < Layers[i].NumMaterials(); m++ ) { mats[mi] = Layers[i].GetMaterial(m); // We should be able to strip this int[] tris = Layers[i].GetTris(m); mesh.SetTriangles(tris, mi); polycount += tris.Length; mi++; } } } mesh.RecalculateNormals(); if ( Tangents ) MegaUtils.BuildTangents(mesh); if ( Optimize ) mesh.Optimize(); if ( DoBounds ) mesh.RecalculateBounds(); MeshRenderer mr1 = gameObject.GetComponent<MeshRenderer>(); if ( mr1 != null ) mr1.sharedMaterials = mats; if ( DoCollider ) { //if ( meshCol == null ) meshCol = GetComponent<MeshCollider>(); if ( meshCol != null ) { meshCol.sharedMesh = null; meshCol.sharedMesh = mesh; } } if ( !updating ) { updating = true; //MegaShapeLoft[] lofts = (MegaShapeLoft[])FindSceneObjectsOfType(typeof(MegaShapeLoft)); MegaShapeLoft[] lofts = (MegaShapeLoft[])FindObjectsOfType(typeof(MegaShapeLoft)); for ( int i = 0; i < lofts.Length; i++ ) { if ( lofts[i] != this && lofts[i].LoftNotify(this, 0) ) lofts[i].BuildMeshFromLayersNew(); } updating = false; } } } } // Should be a spline method public Matrix4x4 GetDeformMat(MegaSpline spline, float alpha, bool interp) { int k = -1; Vector3 ps; Vector3 ps1; if ( spline.closed ) { alpha = Mathf.Repeat(alpha, 1.0f); ps = spline.Interpolate(alpha, interp, ref k); } else ps = spline.InterpCurve3D(alpha, interp, ref k); alpha += tangent; //0.01f; if ( spline.closed ) { alpha = alpha % 1.0f; ps1 = spline.Interpolate(alpha, interp, ref k); } else ps1 = spline.InterpCurve3D(alpha, interp, ref k); ps1.x -= ps.x; ps1.y = 0.0f; //ps.y; ps1.z -= ps.z; //wtm.SetTRS(ps, Quaternion.LookRotation(ps1, up), Vector3.one); MegaMatrix.SetTR(ref wtm, ps, Quaternion.LookRotation(ps1, up)); return wtm; } Quaternion lastrot; public Matrix4x4 GetDeformMatNew(MegaSpline spline, float alpha, bool interp, float align) { int k = -1; Vector3 ps; Vector3 ps1; if ( spline.closed ) { alpha = Mathf.Repeat(alpha, 1.0f); ps = spline.Interpolate(alpha, interp, ref k); } else ps = spline.InterpCurve3D(alpha, interp, ref k); alpha += tangent; //0.01f; if ( spline.closed ) { alpha = alpha % 1.0f; ps1 = spline.Interpolate(alpha, interp, ref k); } else ps1 = spline.InterpCurve3D(alpha, interp, ref k); ps1.x -= ps.x; ps1.y -= ps.y; // * align; ps1.z -= ps.z; ps1.y *= align; //wtm.SetTRS(ps, Quaternion.LookRotation(ps1, up), Vector3.one); Quaternion rot = lastrot; if ( ps1 != Vector3.zero ) rot = Quaternion.LookRotation(ps1, up); MegaMatrix.SetTR(ref wtm, ps, rot); lastrot = rot; return wtm; } // Keep track of up method public Matrix4x4 GetDeformMatNewMethod(MegaSpline spline, float alpha, bool interp, float align, ref Vector3 lastup) { int k = -1; Vector3 ps; Vector3 ps1; Vector3 ps2; if ( spline.closed ) { alpha = Mathf.Repeat(alpha, 1.0f); ps = spline.Interpolate(alpha, interp, ref k); } else ps = spline.InterpCurve3D(alpha, interp, ref k); alpha += tangent; //0.01f; if ( spline.closed ) { alpha = alpha % 1.0f; ps1 = spline.Interpolate(alpha, interp, ref k); } else ps1 = spline.InterpCurve3D(alpha, interp, ref k); ps1.x = ps2.x = ps1.x - ps.x; ps1.y = ps2.y = ps1.y - ps.y; ps1.z = ps2.z = ps1.z - ps.z; //ps1.x -= ps.x; //ps1.y -= ps.y; // * align; //ps1.z -= ps.z; ps1.y *= align; Quaternion rot = lastrot; if ( ps1 != Vector3.zero ) rot = Quaternion.LookRotation(ps1, lastup); //wtm.SetTRS(ps, Quaternion.LookRotation(ps1, up), Vector3.one); //Debug.Log("lupin: " + lastup); MegaMatrix.SetTR(ref wtm, ps, rot); //Quaternion.LookRotation(ps1, lastup)); lastrot = rot; // calc new up value ps2 = ps2.normalized; Vector3 cross = Vector3.Cross(ps2, lastup); lastup = Vector3.Cross(cross, ps2); //Debug.Log("lupout: " + lastup); return wtm; } // Need to do remapping of loft and layers, so run through old [ContextMenu("Clone")] public void Clone() { GameObject to = new GameObject(); MegaShapeLoft loft = to.AddComponent<MegaShapeLoft>(); Copy(loft); loft.mesh = null; MegaLoftLayerBase[] layers = GetComponents<MegaLoftLayerBase>(); for ( int i = 0; i < layers.Length; i++ ) { layers[i].Copy(to); } loft.rebuild = true; loft.BuildMeshFromLayersNew(); to.name = name + " clone"; } [ContextMenu("Clone New")] public void CloneNew() { GameObject to = new GameObject(); MegaShapeLoft loft = to.AddComponent<MegaShapeLoft>(); Copy(loft); loft.mesh = null; MegaLoftLayerBase[] layers = GetComponents<MegaLoftLayerBase>(); for ( int i = 0; i < layers.Length; i++ ) { layers[i].Copy(to); } loft.verts = null; loft.uvs = null; loft.cols = null; loft.rebuild = true; loft.BuildMeshFromLayersNew(); to.name = name + " clone"; } public MegaShapeLoft GetClone() { GameObject to = new GameObject(); MegaShapeLoft loft = to.AddComponent<MegaShapeLoft>(); Copy(loft); loft.mesh = null; MegaLoftLayerBase[] layers = GetComponents<MegaLoftLayerBase>(); for ( int i = 0; i < layers.Length; i++ ) { layers[i].Copy(to); } loft.verts = null; loft.uvs = null; loft.cols = null; loft.rebuild = true; loft.BuildMeshFromLayersNew(); to.name = name + " clone"; return loft; } public void Copy(MegaShapeLoft to) { #if !UNITY_FLASH && !UNITY_METRO && !UNITY_WP8 Type tp = this.GetType(); FieldInfo[] fields = tp.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default); //claredOnly); PropertyInfo[] properties = tp.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default); //claredOnly); for ( int j = 0; j < fields.Length; j++ ) fields[j].SetValue(to, fields[j].GetValue(this)); for ( int j = 0; j < properties.Length; j++ ) { if ( properties[j].CanWrite ) properties[j].SetValue(to, properties[j].GetValue(this, null), null); } #endif } // Conform code #if false // Should still be able to conform even if loft not updating public Vector3 direction = Vector3.down; // Direction of projection, normally down // Will have multiple in the end public GameObject target; //public Mesh targetMesh; // Do we require target to have a mesh collider? Otherwise will need to do our own raycast // for now needs collider public float[] offsets; public MeshCollider conformCollider; public Bounds bounds; //public Vector3[] cverts; public float[] last; public Vector3[] conformedVerts; //public Mesh mesh; //public bool doLateUpdate = false; public float raystartoff = 0.0f; public float offset = 0.0f; public float raydist = 100.0f; //public bool update = false; //public bool realtime = false; //public bool showdebug = false; //public Color raycol = Color.gray; //public Color raycolmiss = Color.red; //public bool recalcBounds = false; //public bool recalcNormals = true; // Need amount of conform value so can drop the loft onto the surface // Also need to be able to drop it along the loft, so perhaps this should be in simple and complex loft // since changing a loft means other layers will update anyway. public void SetTarget(GameObject targ) { target = targ; if ( target ) { //MeshFilter mf = target.GetComponent<MeshFilter>(); //targetMesh = mf.sharedMesh; conformCollider = target.GetComponent<MeshCollider>(); } } public void InitConform() { if ( conformedVerts == null || conformedVerts.Length != verts.Length ) { //MeshFilter mf = gameObject.GetComponent<MeshFilter>(); //mesh = mf.sharedMesh; //verts = mesh.vertices; bounds = mesh.bounds; conformedVerts = new Vector3[verts.Length]; // Need to run through all the source meshes and find the vertical offset from the base offsets = new float[verts.Length]; last = new float[verts.Length]; for ( int i = 0; i < verts.Length; i++ ) offsets[i] = verts[i].z - bounds.min.z; } // Only need to do this if target changes, move to SetTarget if ( target ) { //MeshFilter mf = target.GetComponent<MeshFilter>(); //targetMesh = mf.sharedMesh; conformCollider = target.GetComponent<MeshCollider>(); } } // We could do a bary centric thing if we grid up the bounds void DoConform() { //if ( !update ) // return; //if ( !realtime ) // update = false; InitConform(); if ( target && collider ) //&& mesh ) { Matrix4x4 loctoworld = transform.localToWorldMatrix; //Matrix4x4 worldtoloc = target.transform.worldToLocalMatrix; Matrix4x4 tm = loctoworld; // * worldtoloc; Matrix4x4 invtm = tm.inverse; Ray ray = new Ray(); RaycastHit hit; for ( int i = 0; i < verts.Length; i++ ) { Vector3 origin = tm.MultiplyPoint(verts[i]); origin.y += raystartoff; ray.origin = origin; ray.direction = Vector3.down; conformedVerts[i] = verts[i]; if ( conformCollider.Raycast(ray, out hit, raydist) ) { Vector3 lochit = invtm.MultiplyPoint(hit.point); conformedVerts[i].z = lochit.z + offsets[i] + offset; last[i] = conformedVerts[i].z; } else { Vector3 ht = ray.origin; ht.y -= raydist; conformedVerts[i].z = last[i]; //lochit.z + offsets[i] + offset; } } //mesh.vertices = conformedVerts; //if ( recalcBounds ) // mesh.RecalculateBounds(); //if ( recalcNormals ) // mesh.RecalculateNormals(); } } #endif }
using System; using System.Text; using System.Net; using System.IO; using System.Collections.Generic; public static class Connection { #region var private static String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"; private static String host = ""; private static String LastUri = ""; private static String Null = "0"; private static Dictionary<String, String> cookieheader_key_value = new Dictionary<string, string>(); private static CookieContainer cookie = new CookieContainer(); private static String cookieheader { get { String tmp = ""; if (cookieheader_key_value.Count != 0) { foreach (KeyValuePair<String, String> kvp in cookieheader_key_value) tmp += kvp.Key + "=" + kvp.Value + "; "; return tmp.Substring(0, tmp.Length - 2); } else return ""; } } #endregion #region Cookie public static String Cookie_GetValue(String Key) { foreach (KeyValuePair<String, String> kvp in cookieheader_key_value) { if (kvp.Key == Key) return kvp.Value; } return ""; } public static void Cookie_SetValue(String Key, String Value) { cookieheader_key_value.Add(Key, Value); } public static void Cookie_Remove(String Key) { String key = ""; foreach (KeyValuePair<String, String> kvp in cookieheader_key_value) { if (kvp.Key == Key) key = kvp.Key; } cookieheader_key_value.Remove(key); } #endregion #region Connection //Connect to a url with "Get" request and no action after that public static bool Get(String url) { return Connect(url, "", "", ref Null); } //Connect to a url with "Get" request and get the response after that public static bool Get(String url, ref String text) { return Connect(url, "", "", ref text); } //Connect to a url with "Get" request (with proxy) and no action after that public static bool Get(String url, String proxy) { return Connect(url, "", proxy, ref Null); } //Connect to a url with "Get" request (with proxy) and get the response after that public static bool Get(String url, String proxy, ref String text) { return Connect(url, "", proxy, ref text); } //Connect to a url with "Get", "Post" request and no action after that public static bool Post(String url, String post) { return Connect(url, post, "", ref Null); } //Connect to a url with "Get", "Post" request and get the response after that public static bool Post(String url, String post, ref String text) { return Connect(url, post, "", ref text); } //Connect to a url with "Get", "Post" request (with proxy) and get the response after that public static bool Post(String url, String post, String proxy, ref String text) { return Connect(url, post, proxy, ref text); } //Connect to a url with "Get", "Post" request (and decide to set cookie while request) //(fake decide the cookie header during request) and get the response after that private static bool Connect(String url, String post, String proxy, ref String text) { //fake is disable HttpWebRequest request; HttpWebResponse response; //String ori = ""; try { //Connect to url //this.form.ct_status(0, url); request = (HttpWebRequest)WebRequest.Create(@url); request.Accept = "*/*"; request.Headers.Add("Accept-Language", "zh-tw"); request.UserAgent = userAgent; request.Headers.Add("Accept-Encoding", "deflate"); if (proxy != "") request.Proxy = new WebProxy(proxy); if (request.Address.Host != host) cookieheader_key_value.Clear(); host = request.Address.Host; if (LastUri != "") request.Referer = LastUri; LastUri = url; request.Headers.Add("Cookie", cookieheader); request.AllowAutoRedirect = true; //Write to url if there are data to be posted if (post != "") { UTF8Encoding utf8 = new UTF8Encoding(); Byte[] postdata = utf8.GetBytes(post); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postdata.Length; using (Stream stm = request.GetRequestStream()) { stm.Write(postdata, 0, postdata.Length); stm.Close(); } } response = (HttpWebResponse)request.GetResponse(); if (response != null && response.Headers["Set-Cookie"] != null) // cookie = request.CookieContainer; { String tmpcook = response.Headers["Set-Cookie"]; String[] Arraytmpcook = tmpcook.Replace(" ", "").Split(new String[] {";"}, StringSplitOptions.None); for (int i = 0; i < Arraytmpcook.Length; i++) { String[] tmpcook_Key_Value = Arraytmpcook[i].Split('='); if (cookieheader_key_value.Count != 0) { String kvpkep = ""; bool add = false; foreach (KeyValuePair<String, String> kvp in cookieheader_key_value) { if (kvp.Key == tmpcook_Key_Value[0]) { kvpkep = kvp.Key; add = true; break; } } if (!add && tmpcook_Key_Value[1] != "/" && tmpcook_Key_Value[1] != "delete" && tmpcook_Key_Value[1] != "\\") cookieheader_key_value.Add(tmpcook_Key_Value[0], tmpcook_Key_Value[1]); else { cookieheader_key_value.Remove(kvpkep); if (tmpcook_Key_Value[1] != "/" && tmpcook_Key_Value[1] != "delete" && tmpcook_Key_Value[1] != "\\") cookieheader_key_value.Add(tmpcook_Key_Value[0], tmpcook_Key_Value[1]); } } else if (tmpcook_Key_Value[1] != "/" && tmpcook_Key_Value[1] != "delete" && tmpcook_Key_Value[1] != "\\") cookieheader_key_value.Add(tmpcook_Key_Value[0], tmpcook_Key_Value[1]); } } //"0" define no data to be gotten, otherwise, get data from the stm if (text != "0") { text = ""; using (Stream stm = response.GetResponseStream()) { StreamReader reader = new StreamReader(stm, Encoding.UTF8); while (!reader.EndOfStream) text += reader.ReadLine() + "\r\n"; } } response.Close(); return true; } catch { return false; } } public static bool Download(string URI, string dest) { Stream rstm; return Download(URI, dest, out rstm); } public static bool Download(string URI, out Stream rstm) { return Download(URI, null, out rstm); } private static bool Download(string URI, string dest, out Stream rstm) { HttpWebRequest request; HttpWebResponse response; request = (HttpWebRequest)WebRequest.Create(URI); request.Accept = "*/*"; request.Headers.Add("Accept-Language", "zh-tw"); request.UserAgent = userAgent; request.Headers.Add("Accept-Encoding", "deflate"); response = (HttpWebResponse)request.GetResponse(); if (response != null) { using (Stream stm = response.GetResponseStream()) { if (dest == null) { CopyStream(stm, out rstm); return true; } byte[] bytesInStream = new byte[8 * 1024]; int len; using (Stream sw = File.OpenWrite(dest)) { while ((len = stm.Read(bytesInStream, 0, (int)bytesInStream.Length)) > 0) sw.Write(bytesInStream, 0, len); } } response.Close(); } rstm = Stream.Null; return true; } #endregion private static void CopyStream(Stream input, out Stream output) { output = Stream.Null; byte[] buffer = new byte[32768]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Numerics; using System.Text; namespace Newtonsoft.Json.Serialization { internal class TraceJsonWriter : JsonWriter { private readonly JsonWriter _innerWriter; private readonly JsonTextWriter _textWriter; private readonly StringWriter _sw; public TraceJsonWriter(JsonWriter innerWriter) { _innerWriter = innerWriter; _sw = new StringWriter(CultureInfo.InvariantCulture); _textWriter = new JsonTextWriter(_sw); _textWriter.Formatting = Formatting.Indented; _textWriter.Culture = innerWriter.Culture; _textWriter.DateFormatHandling = innerWriter.DateFormatHandling; _textWriter.DateFormatString = innerWriter.DateFormatString; _textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling; _textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling; } public string GetJson() { return _sw.ToString(); } public override void WriteValue(decimal value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(bool value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte? value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(char value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte[] value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(DateTime value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(DateTimeOffset value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(double value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteUndefined() { _textWriter.WriteUndefined(); _innerWriter.WriteUndefined(); base.WriteUndefined(); } public override void WriteNull() { _textWriter.WriteNull(); _innerWriter.WriteNull(); base.WriteUndefined(); } public override void WriteValue(float value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(Guid value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(int value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(long value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(object value) { if (value is BigInteger) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); InternalWriteValue(JsonToken.Integer); } else { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } } public override void WriteValue(sbyte value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(short value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(string value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(TimeSpan value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(uint value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(ulong value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(Uri value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(ushort value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteWhitespace(string ws) { _textWriter.WriteWhitespace(ws); _innerWriter.WriteWhitespace(ws); base.WriteWhitespace(ws); } public override void WriteComment(string text) { _textWriter.WriteComment(text); _innerWriter.WriteComment(text); base.WriteComment(text); } public override void WriteStartArray() { _textWriter.WriteStartArray(); _innerWriter.WriteStartArray(); base.WriteStartArray(); } public override void WriteEndArray() { _textWriter.WriteEndArray(); _innerWriter.WriteEndArray(); base.WriteEndArray(); } public override void WriteStartConstructor(string name) { _textWriter.WriteStartConstructor(name); _innerWriter.WriteStartConstructor(name); base.WriteStartConstructor(name); } public override void WriteEndConstructor() { _textWriter.WriteEndConstructor(); _innerWriter.WriteEndConstructor(); base.WriteEndConstructor(); } public override void WritePropertyName(string name) { _textWriter.WritePropertyName(name); _innerWriter.WritePropertyName(name); base.WritePropertyName(name); } public override void WritePropertyName(string name, bool escape) { _textWriter.WritePropertyName(name, escape); _innerWriter.WritePropertyName(name, escape); // method with escape will error base.WritePropertyName(name); } public override void WriteStartObject() { _textWriter.WriteStartObject(); _innerWriter.WriteStartObject(); base.WriteStartObject(); } public override void WriteEndObject() { _textWriter.WriteEndObject(); _innerWriter.WriteEndObject(); base.WriteEndObject(); } public override void WriteRaw(string json) { _textWriter.WriteRaw(json); _innerWriter.WriteRaw(json); base.WriteRaw(json); } public override void WriteRawValue(string json) { _textWriter.WriteRawValue(json); _innerWriter.WriteRawValue(json); base.WriteRawValue(json); } public override void Close() { _textWriter.Close(); _innerWriter.Close(); base.Close(); } public override void Flush() { _textWriter.Flush(); _innerWriter.Flush(); } } } #endif
using System; using System.Collections.Generic; using System.Globalization; using AllReady.Areas.Admin.ViewModels.Validators; using AllReady.Controllers; using AllReady.DataAccess; using AllReady.Models; using AllReady.Providers.ExternalUserInformationProviders; using AllReady.Providers.ExternalUserInformationProviders.Providers; using AllReady.Security; using AllReady.Services; using Autofac; using Autofac.Extensions.DependencyInjection; using Autofac.Features.Variance; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.PlatformAbstractions; using AllReady.Security.Middleware; using Newtonsoft.Json.Serialization; using Geocoding; using Geocoding.Google; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Cors.Infrastructure; namespace AllReady { public class Startup { public Startup(IHostingEnvironment env) { // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("version.json") .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } else if(env.IsStaging() || env.IsProduction()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: false); } Configuration = builder.Build(); Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { //Add CORS support. // Must be first to avoid OPTIONS issues when calling from Angular/Browser var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("allReady", corsBuilder.Build()); }); // Add Application Insights data collection services to the services container. services.AddApplicationInsightsTelemetry(Configuration); // Add Entity Framework services to the services container. var ef = services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage")); services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection")); services.Configure<EmailSettings>(Configuration.GetSection("Email")); services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData")); services.Configure<GeneralSettings>(Configuration.GetSection("General")); services.Configure<TwitterAuthenticationSettings>(Configuration.GetSection("Authentication:Twitter")); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequiredLength = 10; options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = true; options.Password.RequireUppercase = false; options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied"); }) .AddEntityFrameworkStores<AllReadyContext>() .AddDefaultTokenProviders(); // Add Authorization rules for the app services.AddAuthorization(options => { options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin")); options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin")); }); // Add MVC services to the services container. // config add to get passed Angular failing on Options request when logging in. services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); //register MediatR //https://lostechies.com/jimmybogard/2016/07/19/mediatr-extensions-for-microsoft-dependency-injection-released/ services.AddMediatR(typeof(Startup)); // configure IoC support var container = CreateIoCContainer(services); return container.Resolve<IServiceProvider>(); } private IContainer CreateIoCContainer(IServiceCollection services) { // todo: move these to a proper autofac module // Register application services. services.AddSingleton((x) => Configuration); services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); services.AddTransient<IAllReadyDataAccess, AllReadyDataAccessEF7>(); services.AddTransient<IDetermineIfATaskIsEditable, DetermineIfATaskIsEditable>(); services.AddTransient<IValidateEventDetailModels, EventEditModelValidator>(); services.AddTransient<ITaskEditViewModelValidator, TaskEditViewModelValidator>(); services.AddTransient<IItineraryEditModelValidator, ItineraryEditModelValidator>(); services.AddTransient<IOrganizationEditModelValidator, OrganizationEditModelValidator>(); services.AddTransient<ITaskEditViewModelValidator, TaskEditViewModelValidator>(); services.AddTransient<IRedirectAccountControllerRequests, RedirectAccountControllerRequests>(); services.AddSingleton<IImageService, ImageService>(); //services.AddSingleton<GeoService>(); services.AddTransient<SampleDataGenerator>(); if (Configuration["Data:Storage:EnableAzureQueueService"] == "true") { // This setting is false by default. To enable queue processing you will // need to override the setting in your user secrets or env vars. services.AddTransient<IQueueStorageService, QueueStorageService>(); } else { // this writer service will just write to the default logger services.AddTransient<IQueueStorageService, FakeQueueWriterService>(); } var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterSource(new ContravariantRegistrationSource()); containerBuilder.RegisterAssemblyTypes(typeof(Startup).Assembly).AsImplementedInterfaces(); //ExternalUserInformationProviderFactory registration containerBuilder.RegisterType<TwitterExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Twitter"); containerBuilder.RegisterType<GoogleExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Google"); containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Microsoft"); containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Facebook"); containerBuilder.RegisterType<ExternalUserInformationProviderFactory>().As<IExternalUserInformationProviderFactory>(); //Populate the container with services that were previously registered containerBuilder.Populate(services); var container = containerBuilder.Build(); return container; } // Configure is called after ConfigureServices is called. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, IConfiguration configuration) { // Put first to avoid issues with OPTIONS when calling from Angular/Browser. app.UseCors("allReady"); // todo: in RC update we can read from a logging.json config file loggerFactory.AddConsole((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); if (env.IsDevelopment()) { // this will go to the VS output window loggerFactory.AddDebug((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); } // Configure the HTTP request pipeline. var usCultureInfo = new CultureInfo("en-US"); app.UseRequestLocalization(new RequestLocalizationOptions { SupportedCultures = new List<CultureInfo>(new[] { usCultureInfo }), SupportedUICultures = new List<CultureInfo>(new[] { usCultureInfo }) }); // Add Application Insights to the request pipeline to track HTTP request telemetry data. app.UseApplicationInsightsRequestTelemetry(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else if (env.IsStaging()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); } // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline. app.UseApplicationInsightsExceptionTelemetry(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline. app.UseIdentity(); // Add token-based protection to the request inject pipeline app.UseTokenProtection(new TokenProtectedResourceOptions { Path = "/api/request", PolicyName = "api-request-injest" }); // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 if (Configuration["Authentication:Facebook:AppId"] != null) { var options = new FacebookOptions { AppId = Configuration["Authentication:Facebook:AppId"], AppSecret = Configuration["Authentication:Facebook:AppSecret"], BackchannelHttpHandler = new FacebookBackChannelHandler(), UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name" }; options.Scope.Add("email"); app.UseFacebookAuthentication(options); } if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null) { var options = new MicrosoftAccountOptions { ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"], ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"] }; app.UseMicrosoftAccountAuthentication(options); } //TODO: mgmccarthy: working on getting email from Twitter //http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap if (Configuration["Authentication:Twitter:ConsumerKey"] != null) { var options = new TwitterOptions { ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"], ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"] }; app.UseTwitterAuthentication(options); } if (Configuration["Authentication:Google:ClientId"] != null) { var options = new GoogleOptions { ClientId = Configuration["Authentication:Google:ClientId"], ClientSecret = Configuration["Authentication:Google:ClientSecret"] }; app.UseGoogleAuthentication(options); } // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Add sample data and test admin accounts if specified in Config.Json. // for production applications, this should either be set to false or deleted. if (env.IsDevelopment() || env.IsEnvironment("Staging")) { context.Database.Migrate(); } if (Configuration["SampleData:InsertSampleData"] == "true") { sampleData.InsertTestData(); } if (Configuration["SampleData:InsertTestUsers"] == "true") { await sampleData.CreateAdminUser(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace SuperPolarity { class MainShip : Ship { public static Color BlueColor; public static Color RedColor; protected bool Shooting; protected int ShotCooldown; protected float CurrentImmortalTime; protected float MaxImmortalTime; protected bool Flashing; protected SoundEffect PolarityChange; protected SoundEffect ShootSound; protected SoundEffect Hit; // Aura stuff protected Texture2D AuraPoint; protected double AuraRadius; protected double AuraAmplitude; protected double AuraFrequency; protected double AuraSubAmplitude; protected double AuraWaveSize; protected double AuraSubPhase; protected double AuraSubFrequency; public double[] EnemyModifications; public double MaxEnemyModification; public double EnemyModificationSpread; public MainShip(SuperPolarity newGame) : base(newGame) {} ~MainShip() { } public override void Initialize(Texture2D texture, Vector2 position) { base.Initialize(texture, position); MainShip.BlueColor = new Color(71, 182, 226); MainShip.RedColor = new Color(235, 160, 185); AuraPoint = CreateCircle (2); AuraRadius = 75; AuraAmplitude = 7; AuraFrequency = 3; AuraSubAmplitude = 7; AuraWaveSize = 3; AuraSubPhase = 0; AuraSubFrequency = 9 * Math.PI / 180; MaxEnemyModification = 20; EnemyModificationSpread = 10; EnemyModifications = new double[360]; for ( int i = 0; i < EnemyModifications.Length; i++ ) { EnemyModifications[i] = 0; } PolarityChange = game.Content.Load<SoundEffect>("Sound\\polaritychange"); ShootSound = game.Content.Load<SoundEffect>("Sound\\bullet"); Hit = game.Content.Load<SoundEffect>("Sound\\hit"); SetPolarity(Polarity.Positive); ActVelocity = 2.5f; ShotCooldown = 50; MaxImmortalTime = 1500; BoxDimensions.X = 2; BoxDimensions.Y = 2; BoxDimensions.W = 2; BoxDimensions.Z = 2; InitBox(); BindInput(); } void BindInput() { InputController.Bind("moveX", HandleHorizontalMovement); InputController.Bind("moveY", HandleVerticalMovement); InputController.Bind("changePolarity", HandleChangePolarity); InputController.Bind("shoot", HandleShot); } protected void HandleShot(float value) { Shooting = true; Timer t = new Timer(new TimerCallback(UnlockShot)); t.Change(ShotCooldown, Timeout.Infinite); if (Children.Count > 10) { return; } var bullet = ActorFactory.CreateBullet(Position, Angle); Children.Add(bullet); bullet.Parent = this; ShootSound.Play(); } protected void UnlockShot(object state) { InputController.Unlock("shoot"); Shooting = false; } protected void HandleChangePolarity(float value) { SwitchPolarity(); } public void HandleHorizontalMovement(float value) { if (value >= -0.5 && value <= 0.5) { value = 0; } Velocity.X = value * MaxVelocity; } public void HandleVerticalMovement(float value) { if (value >= -0.5 && value <= 0.5) { value = 0; } Velocity.Y = value * MaxVelocity; } public override void SwitchPolarity() { base.SwitchPolarity(); PolarityChange.Play(); game.Player.ResetMultiplier(); } public override void SetPolarity(Polarity newPolarity) { base.SetPolarity(newPolarity);; } public override void Update(GameTime gameTime) { base.Update(gameTime); ConstrainToEdges(); UpdateImmortality(gameTime); } public void ResetEnemyModification() { for ( int i = 0; i < EnemyModifications.Length; i++ ) { EnemyModifications[i] = 0; } } public void UpdateImmortality(GameTime gameTime) { if (Immortal) { CurrentImmortalTime += gameTime.ElapsedGameTime.Milliseconds; if (Flashing) { Color = new Color(255, 255, 255, 128); } else { Color = Color.White; } Flashing = !Flashing; if (CurrentImmortalTime > MaxImmortalTime) { Immortal = false; Color = Color.White; } } } public override void Move(GameTime gameTime) { var VelocityLimit = MaxVelocity; var SavedVelocity = new Vector2(Velocity.X, Velocity.Y); if (Shooting) { VelocityLimit = ActVelocity; } if (SavedVelocity.X > VelocityLimit) { SavedVelocity.X = VelocityLimit; } if (SavedVelocity.X < -VelocityLimit) { SavedVelocity.X = -VelocityLimit; } if (SavedVelocity.Y > VelocityLimit) { SavedVelocity.Y = VelocityLimit; } if (SavedVelocity.Y < -VelocityLimit) { SavedVelocity.Y = -VelocityLimit; } Position.X = Position.X + SavedVelocity.X; Position.Y = Position.Y + SavedVelocity.Y; } public override void Magnetize(Ship ship, float distance, float angle) { } protected void ConstrainToEdges() { if (Position.X < 0) { Position.X = 0; if (Velocity.X < 0) { Velocity.X = 0; } } if (Position.X > game.GraphicsDevice.Viewport.Width) { Position.X = game.GraphicsDevice.Viewport.Width; if (Velocity.X > 0) { Velocity.X = 0; } } if (Position.Y < 0) { Position.Y = 0; if (Velocity.Y < 0) { Velocity.Y = 0; } } if (Position.Y > game.GraphicsDevice.Viewport.Height) { Position.Y = game.GraphicsDevice.Viewport.Height; if (Velocity.Y < 0) { Velocity.Y = 0; } } } public void UpdateEnemyModification(Ship enemy) { var dx = enemy.Position.X - Position.X; var dy = enemy.Position.Y - Position.Y; var angleInDegrees = ((360 + Math.Round (Math.Atan2 (dy, dx) * 180 / Math.PI)) % 360); for (var i = -EnemyModificationSpread; i < EnemyModificationSpread; i++) { var strength = MaxEnemyModification - Math.Abs (i * MaxEnemyModification / EnemyModificationSpread); var index = (int)((360 + angleInDegrees + i) % 360); if (enemy.CurrentPolarity == CurrentPolarity) { EnemyModifications[index] -= strength; } else { EnemyModifications[index] += strength; } if (EnemyModifications[index] > MaxEnemyModification) { EnemyModifications[index] = MaxEnemyModification; } if (EnemyModifications[index] < -MaxEnemyModification) { EnemyModifications[index] = -MaxEnemyModification; } } } public override void Draw(SpriteBatch spriteBatch) { DrawCircle (spriteBatch); base.Draw(spriteBatch); //spriteBatch.Draw(BoxTexture, Box, new Color(255, 0, 255, 25)); } protected void DrawCircle(SpriteBatch spriteBatch) { var j = AuraWaveSize; var subWaveRadius = 0.0; var randomPosition = 0.0; for (var i = 0; i < 360; i++) { var angle = i * Math.PI / 180; if (j == AuraWaveSize) { subWaveRadius = AuraSubAmplitude * Math.Sin (randomPosition + AuraSubPhase); randomPosition -= (2 * Math.PI / 8); j = 0; } j++; var radius = EnemyModifications[i] + subWaveRadius + AuraRadius + AuraAmplitude * Math.Sin (i / AuraFrequency); var x = Position.X + radius * Math.Cos (angle); var y = Position.Y + radius * Math.Sin (angle); x = Math.Round (x); y = Math.Round (y); var pointPosition = new Vector2 ((float)x, (float)y); if (CurrentPolarity == Polarity.Positive) { spriteBatch.Draw (AuraPoint, pointPosition, RedColor); } else { spriteBatch.Draw (AuraPoint, pointPosition, BlueColor); } } AuraSubPhase += AuraSubFrequency; /* var r = 50; var wave = 5; var frequency = 1.4; var randomFactor = 5; var randomAreaSize = 4; var j = AuraWaveSize; var rand = 0; var randomPosition = 0; AuraSubPhase = 0; for (var i = 0; i < 360; i++) { var rad = Math.radians(i); if (j == AuraWaveSize) { //rand = Math.random() * 2 * AuraSubAmplitude - AuraSubAmplitude; rand = AuraSubAmplitude * Math.sin(AuraSubPhase + offset); AuraSubPhase -= (2 * Math.PI / 8); j = 0; } j++; var radius = polarityModifications[i] + rand + AuraRadius + AuraAmplitude * Math.sin(i / AuraFrequency); var x = Position.x + radius * Math.cos(rad); var y = Position.y + radius * Math.sin(rad); x = Math.round(x); y = Math.round(y); draw //console.log(i, rad, x, y, dataStart); }); ctx.putImageData(imgData, 0, 0);*/ } protected Texture2D CreateCircle(int radius) { int outerRadius = radius * 2 + 2; Texture2D texture = new Texture2D (game.GraphicsDevice, outerRadius, outerRadius); Color[] data = new Color[outerRadius * outerRadius]; for (int i = 0; i < data.Length; i++) { data [i] = Color.Transparent; } double angleStep = 1f / radius; for (double angle = 0; angle < Math.PI * 2; angle += angleStep) { int x = (int)Math.Round (radius + radius * Math.Cos (angle)); int y = (int)Math.Round (radius + radius + Math.Sin (angle)); data [y * outerRadius + x + 1] = Color.White; } texture.SetData (data); return texture; } public override void Collide(Actor other, Rectangle collision) { if (other.GetType().IsAssignableFrom(typeof(StandardShip)) && !Immortal) { Die(); } } protected override void Die() { game.Player.Lives = game.Player.Lives - 1; game.Player.ResetMultiplier(); if (game.Player.Lives < 0) { Dying = true; game.GameOver(); } else { Hit.Play(); Immortal = true; CurrentImmortalTime = 0; } } public override void CleanUp() { base.CleanUp(); InputController.Unbind("moveX", HandleHorizontalMovement); InputController.Unbind("moveY", HandleVerticalMovement); InputController.Unbind("changePolarity", HandleChangePolarity); InputController.Unbind("shoot", HandleShot); } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion License using System.Collections.Generic; using Irony.Ast; using Irony.Parsing; namespace Irony.Interpreter.Ast { /* Example of use: // String literal with embedded expressions ------------------------------------------------------------------ var stringLit = new StringLiteral("string", "\"", StringOptions.AllowsAllEscapes | StringOptions.IsTemplate); stringLit.AstNodeType = typeof(StringTemplateNode); var Expr = new NonTerminal("Expr"); // By default set to Ruby-style settings var templateSettings = new StringTemplateSettings(); // This defines how to evaluate expressions inside template templateSettings.ExpressionRoot = Expr; this.SnippetRoots.Add(Expr); stringLit.AstNodeConfig = templateSettings; // Define Expr as an expression non-terminal in your grammar */ /// <summary> /// Implements Ruby-like active strings with embedded expressions /// </summary> public class StringTemplateNode : AstNode { #region embedded classes private enum SegmentType { Text, Expression } private class SegmentList : List<TemplateSegment> { } private class TemplateSegment { public AstNode ExpressionNode; /// <summary> /// Position in raw text of the token for error reporting /// </summary> public int Position; public string Text; public SegmentType Type; public TemplateSegment(string text, AstNode node, int position) { this.Type = node == null ? SegmentType.Text : SegmentType.Expression; this.Text = text; this.ExpressionNode = node; this.Position = position; } } #endregion embedded classes private readonly SegmentList segments = new SegmentList(); private string template; /// <summary> /// Copied from Terminal.AstNodeConfig /// </summary> private StringTemplateSettings templateSettings; /// <summary> /// Used for locating error /// </summary> private string tokenText; public override void Init(AstContext context, ParseTreeNode treeNode) { base.Init(context, treeNode); this.template = treeNode.Token.ValueString; this.tokenText = treeNode.Token.Text; this.templateSettings = treeNode.Term.AstConfig.Data as StringTemplateSettings; this.ParseSegments(context); this.AsString = "\"" + this.template + "\" (templated string)"; } protected override object DoEvaluate(ScriptThread thread) { // Standard prolog thread.CurrentNode = this; var value = this.BuildString(thread); // Standard epilog thread.CurrentNode = this.Parent; return value; } private object BuildString(ScriptThread thread) { var values = new string[this.segments.Count]; for (int i = 0; i < this.segments.Count; i++) { var segment = this.segments[i]; switch (segment.Type) { case SegmentType.Text: values[i] = segment.Text; break; case SegmentType.Expression: values[i] = EvaluateExpression(thread, segment); break; } } var result = string.Join(string.Empty, values); return result; } private void CopyMessages(LogMessageList fromList, LogMessageList toList, SourceLocation baseLocation, string messagePrefix) { foreach (var other in fromList) { toList.Add(new LogMessage(other.Level, baseLocation + other.Location, messagePrefix + other.Message, other.ParserState)); } } private string EvaluateExpression(ScriptThread thread, TemplateSegment segment) { try { var value = segment.ExpressionNode.Evaluate(thread); return value == null ? string.Empty : value.ToString(); } catch { // We need to catch here and set current node; ExpressionNode may have reset it, and location would be wrong // TODO: fix this - set error location to exact location inside string. thread.CurrentNode = this; throw; } } private void ParseSegments(AstContext context) { var exprParser = new Parser(context.Language, this.templateSettings.ExpressionRoot); // As we go along the "value text" (that has all escapes done), we track the position in raw token text in the variable exprPosInTokenText. // This position is position in original text in source code, including original escaping sequences and open/close quotes. // It will be passed to segment constructor, and maybe used later to compute the exact position of runtime error when it occurs. int currentPos = 0, exprPosInTokenText = 0; while (true) { var startTagPos = this.template.IndexOf(this.templateSettings.StartTag, currentPos); if (startTagPos < 0) startTagPos = this.template.Length; var text = this.template.Substring(currentPos, startTagPos - currentPos); if (!string.IsNullOrEmpty(text)) // For text segments position is not used this.segments.Add(new TemplateSegment(text, null, 0)); if (startTagPos >= this.template.Length) // We have a real start tag, grab the expression break; currentPos = startTagPos + this.templateSettings.StartTag.Length; var endTagPos = this.template.IndexOf(this.templateSettings.EndTag, currentPos); if (endTagPos < 0) { // "No ending tag '{0}' found in embedded expression." context.AddMessage(ErrorLevel.Error, this.Location, Resources.ErrNoEndTagInEmbExpr, this.templateSettings.EndTag); return; } var exprText = this.template.Substring(currentPos, endTagPos - currentPos); if (!string.IsNullOrEmpty(exprText)) { var exprTree = exprParser.Parse(exprText); if (exprTree.HasErrors()) { // We use original search in token text instead of currentPos in template to avoid distortions caused by opening quote and escaped sequences var baseLocation = this.Location + this.tokenText.IndexOf(exprText); this.CopyMessages(exprTree.ParserMessages, context.Messages, baseLocation, Resources.ErrInvalidEmbeddedPrefix); return; } // Add the expression segment exprPosInTokenText = this.tokenText.IndexOf(this.templateSettings.StartTag, exprPosInTokenText) + this.templateSettings.StartTag.Length; var segmNode = exprTree.Root.AstNode as AstNode; // Important to attach the segm node to current Module segmNode.Parent = this; this.segments.Add(new TemplateSegment(null, segmNode, exprPosInTokenText)); // Advance position beyond the expression exprPosInTokenText += exprText.Length + this.templateSettings.EndTag.Length; } currentPos = endTagPos + this.templateSettings.EndTag.Length; } } } }
/* * 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. */ // ReSharper disable UnusedVariable // ReSharper disable UnusedAutoPropertyAccessor.Global namespace Apache.Ignite.Core.Tests { using System; using System.CodeDom.Compiler; using System.Collections.Generic; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Portable; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Tests.Process; using Microsoft.CSharp; using NUnit.Framework; /// <summary> /// Tests for executable. /// </summary> public class ExecutableTest { /** Spring configuration path. */ private static readonly string SpringCfgPath = "config\\compute\\compute-standalone.xml"; /** Min memory Java task. */ private const string MinMemTask = "org.apache.ignite.platform.PlatformMinMemoryTask"; /** Max memory Java task. */ private const string MaxMemTask = "org.apache.ignite.platform.PlatformMaxMemoryTask"; /** Grid. */ private IIgnite _grid; /// <summary> /// Test fixture set-up routine. /// </summary> [TestFixtureSetUp] public void TestFixtureSetUp() { TestUtils.KillProcesses(); _grid = Ignition.Start(Configuration(SpringCfgPath)); } /// <summary> /// Test fixture tear-down routine. /// </summary> [TestFixtureTearDown] public void TestFixtureTearDown() { Ignition.StopAll(true); TestUtils.KillProcesses(); } /// <summary> /// Set-up routine. /// </summary> [SetUp] public void SetUp() { TestUtils.KillProcesses(); Assert.IsTrue(_grid.WaitTopology(1, 30000)); IgniteProcess.SaveConfigurationBackup(); } /// <summary> /// Tear-down routine. /// </summary> [TearDown] public void TearDown() { IgniteProcess.RestoreConfigurationBackup(); } /// <summary> /// Test data pass through configuration file. /// </summary> [Test] public void TestConfig() { IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test"); GenerateDll("test-1.dll"); GenerateDll("test-2.dll"); var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath() ); Assert.IsTrue(_grid.WaitTopology(2, 30000)); var cfg = RemoteConfig(); Assert.AreEqual(SpringCfgPath, cfg.SpringConfigUrl); Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2")); Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll")); Assert.AreEqual(601, cfg.JvmInitialMemoryMb); Assert.AreEqual(702, cfg.JvmMaxMemoryMb); } /// <summary> /// Test assemblies passing through command-line. /// </summary> [Test] public void TestAssemblyCmd() { GenerateDll("test-1.dll"); GenerateDll("test-2.dll"); var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-assembly=test-1.dll", "-assembly=test-2.dll" ); Assert.IsTrue(_grid.WaitTopology(2, 30000)); var cfg = RemoteConfig(); Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll")); } /// <summary> /// Test JVM options passing through command-line. /// </summary> [Test] public void TestJvmOptsCmd() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-J-DOPT1", "-J-DOPT2" ); Assert.IsTrue(_grid.WaitTopology(2, 30000)); var cfg = RemoteConfig(); Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2")); } /// <summary> /// Test JVM memory options passing through command-line: raw java options. /// </summary> [Test] public void TestJvmMemoryOptsCmdRaw() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-J-Xms506m", "-J-Xmx607m" ); Assert.IsTrue(_grid.WaitTopology(2, 30000)); var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 506*1024*1024, minMem); var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 607*1024*1024, maxMem); } /// <summary> /// Test JVM memory options passing through command-line: custom options. /// </summary> [Test] public void TestJvmMemoryOptsCmdCustom() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-JvmInitialMemoryMB=615", "-JvmMaxMemoryMB=863" ); Assert.IsTrue(_grid.WaitTopology(2, 30000)); var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 615*1024*1024, minMem); var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 863*1024*1024, maxMem); } /// <summary> /// Test JVM memory options passing from application configuration. /// </summary> [Test] public void TestJvmMemoryOptsAppConfig() { IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test"); GenerateDll("test-1.dll"); GenerateDll("test-2.dll"); var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath()); Assert.IsTrue(_grid.WaitTopology(2, 30000)); var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 601*1024*1024, minMem); var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 702*1024*1024, maxMem); proc.Kill(); Assert.IsTrue(_grid.WaitTopology(1, 30000)); // Command line options overwrite config file options // ReSharper disable once RedundantAssignment proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-J-Xms605m", "-J-Xmx706m"); Assert.IsTrue(_grid.WaitTopology(2, 30000)); minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 605*1024*1024, minMem); maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 706*1024*1024, maxMem); } /// <summary> /// Test JVM memory options passing through command-line: custom options + raw options. /// </summary> [Test] public void TestJvmMemoryOptsCmdCombined() { var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + SpringCfgPath, "-J-Xms555m", "-J-Xmx666m", "-JvmInitialMemoryMB=128", "-JvmMaxMemoryMB=256" ); Assert.IsTrue(_grid.WaitTopology(2, 30000)); // Raw JVM options (Xms/Xmx) should override custom options var minMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MinMemTask, null); Assert.AreEqual((long) 555*1024*1024, minMem); var maxMem = _grid.Cluster.ForRemotes().Compute().ExecuteJavaTask<long>(MaxMemTask, null); AssertJvmMaxMemory((long) 666*1024*1024, maxMem); } /// <summary> /// Get remote node configuration. /// </summary> /// <returns>Configuration.</returns> private RemoteConfiguration RemoteConfig() { return _grid.Cluster.ForRemotes().Compute().Call(new RemoteConfigurationClosure()); } /// <summary> /// Configuration for node. /// </summary> /// <param name="path">Path to Java XML configuration.</param> /// <returns>Node configuration.</returns> private static IgniteConfiguration Configuration(string path) { var cfg = new IgniteConfiguration(); var portCfg = new PortableConfiguration(); ICollection<PortableTypeConfiguration> portTypeCfgs = new List<PortableTypeConfiguration>(); portTypeCfgs.Add(new PortableTypeConfiguration(typeof (RemoteConfiguration))); portTypeCfgs.Add(new PortableTypeConfiguration(typeof (RemoteConfigurationClosure))); portCfg.TypeConfigurations = portTypeCfgs; cfg.PortableConfiguration = portCfg; cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = new List<string> { "-ea", "-Xcheck:jni", "-Xms4g", "-Xmx4g", "-DIGNITE_QUIET=false", "-Xnoagent", "-Djava.compiler=NONE", "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005", "-XX:+HeapDumpOnOutOfMemoryError" }; cfg.SpringConfigUrl = path; return cfg; } /// <summary> /// /// </summary> /// <param name="outputPath"></param> private static void GenerateDll(string outputPath) { var codeProvider = new CSharpCodeProvider(); #pragma warning disable 0618 var icc = codeProvider.CreateCompiler(); #pragma warning restore 0618 var parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.OutputAssembly = outputPath; var src = "namespace Apache.Ignite.Client.Test { public class Foo {}}"; var results = icc.CompileAssemblyFromSource(parameters, src); Assert.False(results.Errors.HasErrors); } /// <summary> /// Asserts that JVM maximum memory corresponds to Xmx parameter value. /// </summary> private static void AssertJvmMaxMemory(long expected, long actual) { // allow 20% tolerance because max memory in Java is not exactly equal to Xmx parameter value Assert.LessOrEqual(actual, expected); Assert.Greater(actual, expected/5*4); } /// <summary> /// Closure which extracts configuration and passes it back. /// </summary> public class RemoteConfigurationClosure : IComputeFunc<RemoteConfiguration> { #pragma warning disable 0649 /** Grid. */ [InstanceResource] private IIgnite _grid; #pragma warning restore 0649 /** <inheritDoc /> */ public RemoteConfiguration Invoke() { var grid0 = (Ignite) ((IgniteProxy) _grid).Target; var cfg = grid0.Configuration; var res = new RemoteConfiguration { IgniteHome = cfg.IgniteHome, SpringConfigUrl = cfg.SpringConfigUrl, JvmDll = cfg.JvmDllPath, JvmClasspath = cfg.JvmClasspath, JvmOptions = cfg.JvmOptions, Assemblies = cfg.Assemblies, JvmInitialMemoryMb = cfg.JvmInitialMemoryMb, JvmMaxMemoryMb = cfg.JvmMaxMemoryMb }; Console.WriteLine("RETURNING CFG: " + cfg); return res; } } /// <summary> /// Configuration. /// </summary> public class RemoteConfiguration { /// <summary> /// GG home. /// </summary> public string IgniteHome { get; set; } /// <summary> /// Spring config URL. /// </summary> public string SpringConfigUrl { get; set; } /// <summary> /// JVM DLL. /// </summary> public string JvmDll { get; set; } /// <summary> /// JVM classpath. /// </summary> public string JvmClasspath { get; set; } /// <summary> /// JVM options. /// </summary> public ICollection<string> JvmOptions { get; set; } /// <summary> /// Assemblies. /// </summary> public ICollection<string> Assemblies { get; set; } /// <summary> /// Minimum JVM memory (Xms). /// </summary> public int JvmInitialMemoryMb { get; set; } /// <summary> /// Maximum JVM memory (Xms). /// </summary> public int JvmMaxMemoryMb { get; set; } } } }
using System; #if !WINDOWS_PHONE && !XBOX using Microsoft.Xna.Framework.GamerServices; #endif namespace Cocos2D { public delegate void CCTextFieldTTFDelegate(object sender, ref string text, ref bool canceled); public class CCTextFieldTTF : CCLabelTTF, ICCTargetedTouchDelegate { private IAsyncResult m_pGuideShowHandle; private string m_sEditTitle = "Input"; private string m_sEditDescription = "Please provide input"; private bool m_bReadOnly = false; private bool m_bAutoEdit; private bool m_bTouchHandled; public event CCTextFieldTTFDelegate BeginEditing; public event CCTextFieldTTFDelegate EndEditing; public bool ReadOnly { get { return m_bReadOnly; } set { m_bReadOnly = value; if (!value) { EndEdit(); } CheckTouchState(); } } public string EditTitle { get { return m_sEditTitle; } set { m_sEditTitle = value; } } public string EditDescription { get { return m_sEditDescription; } set { m_sEditDescription = value; } } public bool AutoEdit { get { return m_bAutoEdit; } set { m_bAutoEdit = value; CheckTouchState(); } } public CCTextFieldTTF(string text, string fontName, float fontSize) : this(text, fontName, fontSize, CCSize.Zero, CCTextAlignment.Center, CCVerticalTextAlignment.Top) { } public CCTextFieldTTF(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment) : this(text, fontName, fontSize, dimensions, hAlignment, CCVerticalTextAlignment.Top) { } public CCTextFieldTTF(string text, string fontName, float fontSize, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment) { InitWithString(text, fontName, fontSize, dimensions, hAlignment, vAlignment); } public void Edit() { Edit(m_sEditTitle, m_sEditDescription); } public void Edit(string title, string defaultText) { #if !WINDOWS_PHONE && !XBOX if (!m_bReadOnly && !Guide.IsVisible) { var canceled = false; var text = Text; DoBeginEditing(ref text, ref canceled); if (!canceled) { m_pGuideShowHandle = Guide.BeginShowKeyboardInput( Microsoft.Xna.Framework.PlayerIndex.One, title, defaultText, Text, InputHandler, null ); } } #endif } private void InputHandler(IAsyncResult result) { #if !WINDOWS_PHONE && !XBOX var newText = Guide.EndShowKeyboardInput(result); m_pGuideShowHandle = null; if (newText != null && Text != newText) { bool canceled = false; ScheduleOnce( time => { DoEndEditing(ref newText, ref canceled); if (!canceled) { Text = newText; } }, 0 ); } #endif } protected virtual void DoBeginEditing(ref string newText, ref bool canceled) { if (BeginEditing != null) { BeginEditing(this, ref newText, ref canceled); } } protected virtual void DoEndEditing(ref string newText, ref bool canceled) { if (EndEditing != null) { EndEditing(this, ref newText, ref canceled); } } public void EndEdit() { if (m_pGuideShowHandle != null) { #if !WINDOWS_PHONE && !XBOX Guide.EndShowKeyboardInput(m_pGuideShowHandle); #endif m_pGuideShowHandle = null; } } private void CheckTouchState() { if (m_bRunning) { if (!m_bTouchHandled && !m_bReadOnly && m_bAutoEdit) { CCDirector.SharedDirector.TouchDispatcher.AddTargetedDelegate(this, 0, true); m_bTouchHandled = true; } else if (m_bTouchHandled && (m_bReadOnly || !m_bAutoEdit)) { CCDirector.SharedDirector.TouchDispatcher.RemoveDelegate(this); m_bTouchHandled = true; } } else { if (!m_bRunning && m_bTouchHandled) { CCDirector.SharedDirector.TouchDispatcher.RemoveDelegate(this); m_bTouchHandled = false; } } } public override void OnEnter() { base.OnEnter(); CheckTouchState(); } public override void OnExit() { base.OnExit(); CheckTouchState(); } public override bool TouchBegan(CCTouch pTouch) { var pos = ConvertTouchToNodeSpace(pTouch); if (pos.X >= 0 && pos.X < ContentSize.Width && pos.Y >= 0 && pos.Y <= ContentSize.Height) { return true; } return false; } public override void TouchMoved(CCTouch pTouch) { //nothing } public override void TouchEnded(CCTouch pTouch) { var pos = ConvertTouchToNodeSpace(pTouch); if (pos.X >= 0 && pos.X < ContentSize.Width && pos.Y >= 0 && pos.Y <= ContentSize.Height) { Edit(); } } public override void TouchCancelled(CCTouch pTouch) { //nothing } } }
/* Ben Scott * bescott@andrew.cmu.edu * 2015-07-16 * Markdown */ using System; using System.Collections.Generic; using System.Configuration; using System.Text; using System.Text.RegularExpressions; public static class Markdown { public static string EmptyElementSuffix { get { return _emptyElementSuffix; } set { _emptyElementSuffix = value; } } static string _emptyElementSuffix = " />"; public static bool LinkEmails { get { return _linkEmails; } set { _linkEmails = value; } } static bool _linkEmails = false; public static bool StrictBoldItalic { get { return _strictBoldItalic; } set { _strictBoldItalic = value; } } static bool _strictBoldItalic = true; public static bool AsteriskIntraWordEmphasis { get { return _asteriskIntraWordEmphasis; } set { _asteriskIntraWordEmphasis = value; } } static bool _asteriskIntraWordEmphasis = false; public static bool AutoNewLines { get { return _autoNewlines; } set { _autoNewlines = value; } } static bool _autoNewlines = false; public static bool AutoHyperlink { get { return _autoHyperlink; } set { _autoHyperlink = value; } } static bool _autoHyperlink = false; enum TokenType { Text, Tag } struct Token { public TokenType Type; public string Value; public Token(TokenType type, string value) { this.Type = type; this.Value = value; } } const int _nestDepth = 6; const int _tabWidth = 4; const string _markerUL = @"[*+-]"; const string _markerOL = @"\d+[.]"; static readonly Dictionary<string, string> _escapeTable; static readonly Dictionary<string, string> _invertedEscapeTable; static readonly Dictionary<string, string> _backslashEscapeTable; static readonly Dictionary<string, string> _urls = new Dictionary<string, string>(); static readonly Dictionary<string, string> _titles = new Dictionary<string, string>(); static readonly Dictionary<string, string> _htmlBlocks = new Dictionary<string, string>(); static int _listLevel; static string AutoLinkPreventionMarker = "\x1AP"; static Markdown() { _escapeTable = new Dictionary<string, string>(); _invertedEscapeTable = new Dictionary<string, string>(); _backslashEscapeTable = new Dictionary<string, string>(); string backslashPattern = ""; foreach (char c in @"\`*_{}[]()>#+-.!/:") { string key = c.ToString(); string hash = GetHashKey(key, isHtmlBlock: false); _escapeTable.Add(key, hash); _invertedEscapeTable.Add(hash, key); _backslashEscapeTable.Add(@"\" + key, hash); backslashPattern += Regex.Escape(@"\"+key)+"|"; } _backslashEscapes = new Regex( backslashPattern.Substring(0, backslashPattern.Length-1)); } public static string Transform(string text) { if (String.IsNullOrEmpty(text)) return ""; Setup(); text = Normalize(text); text = HashHTMLBlocks(text); text = StripLinkDefinitions(text); text = RunBlockGamut(text); text = Unescape(text); Cleanup(); return text + "\n"; } static string RunBlockGamut(string text, bool unhash = true, bool createParagraphs = false) { text = DoHeaders(text); text = DoHorizontalRules(text); text = DoLists(text); text = DoCodeBlocks(text); text = DoBlockQuotes(text); text = HashHTMLBlocks(text); text = FormParagraphs(text, unhash: unhash, createParagraphs: createParagraphs); return text; } static string RunSpanGamut(string text) { text = DoCodeSpans(text); text = EscapeSpecialCharsWithinTagAttributes(text); text = EscapeBackslashes(text); text = DoImages(text); text = DoAnchors(text); text = DoAutoLinks(text); text = text.Replace(AutoLinkPreventionMarker, "://"); text = EncodeAmpsAndAngles(text); text = DoItalicsAndBold(text); text = DoHardBreaks(text); return text; } static Regex _newlinesLeadingTrailing = new Regex(@"^\n+|\n+\z"); static Regex _newlinesMultiple = new Regex(@"\n{2,}"); static Regex _leadingWhitespace = new Regex(@"^[ ]*"); static Regex _htmlBlockHash = new Regex("\x1AH\\d+H"); static string FormParagraphs(string text,bool unhash = true,bool createParagraphs = false) { string[] grafs = _newlinesMultiple.Split(_newlinesLeadingTrailing.Replace(text,"")); for (int i=0;i<grafs.Length;i++){ if (grafs[i].Contains("\x1AH")) { if (unhash) { // unhashify HTML blocks int sanityCheck = 50; // just for safety, guard against an infinite loop bool keepGoing = true; // as long as replacements where made, keep going while (keepGoing && sanityCheck>0) { keepGoing = false; grafs[i] = _htmlBlockHash.Replace(grafs[i], match => { keepGoing = true; return _htmlBlocks[match.Value]; }); sanityCheck--; } } } else grafs[i] = _leadingWhitespace.Replace(RunSpanGamut(grafs[i]), createParagraphs ?"<p>":"")+(createParagraphs ?"</p>":""); } return string.Join("\n\n", grafs); } static void Setup() { _urls.Clear(); _titles.Clear(); _htmlBlocks.Clear(); _listLevel = 0; } static void Cleanup() { Setup(); } static string _nestedBracketsPattern; static string GetNestedBracketsPattern() { if (_nestedBracketsPattern == null) _nestedBracketsPattern = RepeatString(@" (?> # Atomic matching [^\[\]]+ # Anything other than brackets | \[ ", _nestDepth) + RepeatString( @" \] )*" , _nestDepth); return _nestedBracketsPattern; } static string _nestedParensPattern; static string GetNestedParensPattern() { if (_nestedParensPattern == null) _nestedParensPattern = RepeatString(@" (?> # Atomic matching [^()\s]+ # Anything other than parens or whitespace | \( ", _nestDepth) + RepeatString( @" \) )*" , _nestDepth); return _nestedParensPattern; } static Regex _linkDef = new Regex(string.Format(@" ^[ ]{{0,{0}}}\[([^\[\]]+)\]: # id = $1 [ ]* \n? # maybe *one* newline [ ]* <?(\S+?)>? # url = $2 [ ]* \n? # maybe one newline [ ]* (?: (?<=\s) # lookbehind for whitespace [""(] (.+?) # title = $3 ["")] [ ]* )? # title is optional (?:\n+|\Z)", _tabWidth - 1), RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);//| RegexOptions.Compiled); static string StripLinkDefinitions(string text) { return _linkDef.Replace(text, new MatchEvaluator(LinkEvaluator)); } static string LinkEvaluator(Match match) { string linkID = match.Groups[1].Value.ToLowerInvariant(); _urls[linkID] = EncodeAmpsAndAngles(match.Groups[2].Value); if (match.Groups[3] != null && match.Groups[3].Length > 0) _titles[linkID] = match.Groups[3].Value.Replace("\"", "&quot;"); return ""; } static Regex _blocksHtml = new Regex(GetBlockPattern(), RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace); static string GetBlockPattern() { string blockTagsA = "ins|del"; string blockTagsB = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|script|noscript|form|fieldset|iframe|math"; string attr = @" (?> # optional tag attributes \s # starts with whitespace (?> [^>""/]+ # text outside quotes | /+(?!>) # slash not followed by > | ""[^""]*"" # text inside double quotes (tolerate >) | '[^']*' # text inside single quotes (tolerate >) )* )? "; string content = RepeatString(@" (?> [^<]+ # content without tag | <\2 # nested opening tag " + attr + @" # attributes (?> /> | >", _nestDepth) + // end of opening tag ".*?" + // last level nested tag content RepeatString(@" </\2\s*> # closing nested tag ) | <(?!/\2\s*> # other tags with a different name ) )*", _nestDepth); string content2 = content.Replace(@"\2", @"\3"); string pattern = @" (?> (?> (?<=\n) # Starting at the beginning of a line | # or \A\n? # the beginning of the doc ) ( # save in $1 # Match from `\n<tag>` to `</tag>\n`, handling nested tags # in between. <($block_tags_b_re) # start tag = $2 $attr> # attributes followed by > and \n $content # content, support nesting </\2> # the matching end tag [ ]* # trailing spaces (?=\n+|\Z) # followed by a newline or end of document | # Special version for tags of group a. <($block_tags_a_re) # start tag = $3 $attr>[ ]*\n # attributes followed by > $content2 # content, support nesting </\3> # the matching end tag [ ]* # trailing spaces (?=\n+|\Z) # followed by a newline or end of document | # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. [ ]{0,$less_than_tab} <hr $attr # attributes /?> # the matching end tag [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document | # Special case for standalone HTML comments: (?<=\n\n|\A) # preceded by a blank line or start of document [ ]{0,$less_than_tab} (?s: <!--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--> ) [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document | # PHP and ASP-style processor instructions (<? and <%) [ ]{0,$less_than_tab} (?s: <([?%]) # $4 .*? \4> ) [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) )"; pattern = pattern.Replace("$less_than_tab", (_tabWidth - 1).ToString()); pattern = pattern.Replace("$block_tags_b_re", blockTagsB); pattern = pattern.Replace("$block_tags_a_re", blockTagsA); pattern = pattern.Replace("$attr", attr); pattern = pattern.Replace("$content2", content2); pattern = pattern.Replace("$content", content); return pattern; } static string HashHTMLBlocks(string text) { return _blocksHtml.Replace(text, new MatchEvaluator(HtmlEvaluator)); } static string HtmlEvaluator(Match match) { string text = match.Groups[1].Value; string key = GetHashKey(text, isHtmlBlock: true); _htmlBlocks[key] = text; return string.Concat("\n\n", key, "\n\n"); } static string GetHashKey(string s, bool isHtmlBlock) { var delim = isHtmlBlock ? 'H' : 'E'; return "\x1A" + delim + Math.Abs(s.GetHashCode()).ToString() + delim; } static Regex _htmlTokens = new Regex(@" (<!--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)-->)| # match <!-- foo --> (<\?.*?\?>)| # match <?foo?> " + RepeatString(@" (<[A-Za-z\/!$](?:[^<>]|", _nestDepth) + RepeatString(@")*>)", _nestDepth) + " # match <tag> and </tag>", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); static List<Token> TokenizeHTML(string text) { int pos = 0; int tagStart = 0; var tokens = new List<Token>(); foreach (Match m in _htmlTokens.Matches(text)) { tagStart = m.Index; if (pos < tagStart) tokens.Add(new Token(TokenType.Text, text.Substring(pos, tagStart - pos))); tokens.Add(new Token(TokenType.Tag, m.Value)); pos = tagStart + m.Length; } if (pos < text.Length) tokens.Add(new Token(TokenType.Text, text.Substring(pos, text.Length - pos))); return tokens; } static Regex _anchorRef = new Regex(string.Format(@" ( # wrap whole match in $1 \[ ({0}) # link text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] )", GetNestedBracketsPattern()), RegexOptions.IgnorePatternWhitespace); static Regex _anchorInline = new Regex(string.Format(@" ( # wrap whole match in $1 \[ ({0}) # link text = $2 \] \( # literal paren [ ]* ({1}) # href = $3 [ ]* ( # $4 (['""]) # quote char = $5 (.*?) # title = $6 \5 # matching quote [ ]* # ignore any spaces between closing quote and ) )? # title is optional \) )", GetNestedBracketsPattern(), GetNestedParensPattern()), RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); static Regex _anchorRefShortcut = new Regex(@" ( # wrap whole match in $1 \[ ([^\[\]]+) # link text = $2; can't contain [ or ] \] )", RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); static string DoAnchors(string text) { if (!text.Contains("[")) return text; text = _anchorRef.Replace(text, new MatchEvaluator(AnchorRefEvaluator)); text = _anchorInline.Replace(text, new MatchEvaluator(AnchorInlineEvaluator)); text = _anchorRefShortcut.Replace(text, new MatchEvaluator(AnchorRefShortcutEvaluator)); return text; } static string SaveFromAutoLinking(string s) { return s.Replace("://", AutoLinkPreventionMarker); } static string AnchorRefEvaluator(Match match) { string wholeMatch = match.Groups[1].Value; string linkText = SaveFromAutoLinking(match.Groups[2].Value); string linkID = match.Groups[3].Value.ToLowerInvariant(); string result; if (linkID == "") linkID = linkText.ToLowerInvariant(); if (_urls.ContainsKey(linkID)) { string url = _urls[linkID]; url = AttributeSafeUrl(url); result = "<a href=\"" + url + "\""; if (_titles.ContainsKey(linkID)) { string title = AttributeEncode(_titles[linkID]); title = AttributeEncode(EscapeBoldItalic(title)); result += " title=\"" + title + "\""; } result += ">" + linkText + "</a>"; } else result = wholeMatch; return result; } static string AnchorRefShortcutEvaluator(Match match) { string wholeMatch = match.Groups[1].Value; string linkText = SaveFromAutoLinking(match.Groups[2].Value); string linkID = Regex.Replace(linkText.ToLowerInvariant(), @"[ ]*\n[ ]*", " "); string result; if (_urls.ContainsKey(linkID)) { string url = _urls[linkID]; url = AttributeSafeUrl(url); result = "<a href=\"" + url + "\""; if (_titles.ContainsKey(linkID)) { string title = AttributeEncode(_titles[linkID]); title = EscapeBoldItalic(title); result += " title=\"" + title + "\""; } result += ">" + linkText + "</a>"; } else result = wholeMatch; return result; } static string AnchorInlineEvaluator(Match match) { string linkText = SaveFromAutoLinking(match.Groups[2].Value); string url = match.Groups[3].Value; string title = match.Groups[6].Value; string result; if (url.StartsWith("<") && url.EndsWith(">")) url = url.Substring(1, url.Length - 2); url = AttributeSafeUrl(url); result = string.Format("<a href=\"{0}\"", url); if (!String.IsNullOrEmpty(title)) { title = AttributeEncode(title); title = EscapeBoldItalic(title); result += string.Format(" title=\"{0}\"", title); } result += string.Format(">{0}</a>", linkText); return result; } static Regex _imagesRef = new Regex(@" ( # wrap whole match in $1 !\[ (.*?) # alt text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] )", RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); static Regex _imagesInline = new Regex(String.Format(@" ( # wrap whole match in $1 !\[ (.*?) # alt text = $2 \] \s? # one optional whitespace character \( # literal paren [ ]* ({0}) # href = $3 [ ]* ( # $4 (['""]) # quote char = $5 (.*?) # title = $6 \5 # matching quote [ ]* )? # title is optional \) )", GetNestedParensPattern()), RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); static string DoImages(string text) { if (!text.Contains("![")) return text; text = _imagesRef.Replace(text, new MatchEvaluator(ImageReferenceEvaluator)); text = _imagesInline.Replace(text, new MatchEvaluator(ImageInlineEvaluator)); return text; } static string EscapeImageAltText(string s) { s = EscapeBoldItalic(s); s = Regex.Replace(s, @"[\[\]()]", m => _escapeTable[m.ToString()]); return s; } static string ImageReferenceEvaluator(Match match) { string wholeMatch = match.Groups[1].Value; string altText = match.Groups[2].Value; string linkID = match.Groups[3].Value.ToLowerInvariant(); if (linkID == "") linkID = altText.ToLowerInvariant(); if (_urls.ContainsKey(linkID)) { string url = _urls[linkID]; string title = null; if (_titles.ContainsKey(linkID)) title = _titles[linkID]; return ImageTag(url, altText, title); } else return wholeMatch; } static string ImageInlineEvaluator(Match match) { string alt = match.Groups[2].Value; string url = match.Groups[3].Value; string title = match.Groups[6].Value; if (url.StartsWith("<") && url.EndsWith(">")) url = url.Substring(1, url.Length - 2); // Remove <>'s surrounding URL, if present return ImageTag(url, alt, title); } static string ImageTag(string url, string altText, string title) { altText = EscapeImageAltText(AttributeEncode(altText)); url = AttributeSafeUrl(url); var result = string.Format("<img src=\"{0}\" alt=\"{1}\"", url, altText); if (!String.IsNullOrEmpty(title)) { title = AttributeEncode(EscapeBoldItalic(title)); result += string.Format(" title=\"{0}\"", title); } result += _emptyElementSuffix; return result; } static Regex _headerSetext = new Regex(@" (.+?) # removing ^ again? [ ]* \n (=+|-+) # $1 = string of ='s or -'s [ ]* \n+", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace); static Regex _headerAtx = new Regex(@" (\#{1,6}) # $1 = string of #'s, just removed ^ from front [ ]* (.+?) # $2 = Header text [ ]* \#* # optional closing #'s (not counted) \n+", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); /// <summary> /// Turn Markdown headers into HTML header tags /// </summary> /// <remarks> /// Header 1 /// ======== /// /// Header 2 /// -------- /// /// # Header 1 /// ## Header 2 /// ## Header 2 with closing hashes ## /// ... /// ###### Header 6 /// </remarks> static string DoHeaders(string text) { text = _headerSetext.Replace(text, new MatchEvaluator(SetextHeaderEvaluator)); text = _headerAtx.Replace(text, new MatchEvaluator(AtxHeaderEvaluator)); return text; } static string SetextHeaderEvaluator(Match match) { string header = match.Groups[1].Value; int level = match.Groups[2].Value.StartsWith("=") ? 1 : 2; return string.Format("<h{1}>{0}</h{1}>\n\n", RunSpanGamut(header), level); } static string AtxHeaderEvaluator(Match match) { string header = match.Groups[2].Value; int level = match.Groups[1].Value.Length; return string.Format("<h{1}>{0}</h{1}>\n\n", RunSpanGamut(header), level); } static Regex _horizontalRules = new Regex(@" ^[ ]{0,3} # Leading space ([-*_]) # $1: First marker (?> # Repeated marker group [ ]{0,2} # Zero, one, or two spaces. \1 # Marker character ){2,} # Group repeated at least twice [ ]* # Trailing spaces $ # End of line. ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); /// <summary> /// Turn Markdown horizontal rules into HTML hr tags /// </summary> /// <remarks> /// *** /// * * * /// --- /// - - - /// </remarks> static string DoHorizontalRules(string text) { return _horizontalRules.Replace(text, "<hr" + _emptyElementSuffix + "\n"); } static string _wholeList = string.Format(@" ( # $1 = whole list ( # $2 [ ]{{0,{1}}} ({0}) # $3 = first list item marker [ ]+ ) (?s:.+?) ( # $4 \z | \n{{2,}} (?=\S) (?! # Negative lookahead for another list item marker [ ]* {0}[ ]+ ) ) )", string.Format("(?:{0}|{1})", _markerUL, _markerOL), _tabWidth - 1); static Regex _listNested = new Regex(@"^" + _wholeList, RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); static Regex _listTopLevel = new Regex(@"(?:(?<=\n\n)|\A\n?)" + _wholeList, RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace );//| RegexOptions.Compiled); /// <summary> /// Turn Markdown lists into HTML ul and ol and li tags /// </summary> static string DoLists(string text) { // We use a different prefix before nested lists than top-level lists. // See extended comment in _ProcessListItems(). if (_listLevel > 0) text = _listNested.Replace(text, new MatchEvaluator(ListEvaluator)); else text = _listTopLevel.Replace(text, new MatchEvaluator(ListEvaluator)); return text; } static string ListEvaluator(Match match) { string list = match.Groups[1].Value; string marker = match.Groups[3].Value; string listType = Regex.IsMatch(marker, _markerUL) ? "ul" : "ol"; string result; string start = ""; if (listType == "ol") { var firstNumber = int.Parse(marker.Substring(0, marker.Length - 1)); if (firstNumber != 1 && firstNumber != 0) start = " start=\"" + firstNumber + "\""; } result = ProcessListItems(list, listType == "ul" ? _markerUL : _markerOL); result = string.Format("<{0}{1}>\n{2}</{0}>\n", listType, start, result); return result; } /// <summary> /// Process the contents of a single ordered or unordered list, splitting it /// into individual list items. /// </summary> static string ProcessListItems(string list, string marker) { // The listLevel global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // We do this because when we're not inside a list, we want to treat // something like this: // I recommend upgrading to version // 8. Oops, now this line is treated // as a sub-list. // As a single paragraph, despite the fact that the second line starts // with a digit-period-space sequence. // Whereas when we're inside a list (or sub-list), that line will be // treated as the start of a sub-list. What a kludge, huh? This is // an aspect of Markdown's syntax that's hard to parse perfectly // without resorting to mind-reading. Perhaps the solution is to // change the syntax rules such that sub-lists must start with a // starting cardinal number; e.g. "1." or "a.". _listLevel++; // Trim trailing blank lines: list = Regex.Replace(list, @"\n{2,}\z", "\n"); string pattern = string.Format( @"(^[ ]*) # leading whitespace = $1 ({0}) [ ]+ # list marker = $2 ((?s:.+?) # list item text = $3 (\n+)) (?= (\z | \1 ({0}) [ ]+))", marker); //bool lastItemHadADoubleNewline = false; // has to be a closure, so subsequent invocations can share the bool MatchEvaluator ListItemEvaluator = (Match match) => { string item = match.Groups[3].Value; //bool endsWithDoubleNewline = item.EndsWith("\n\n"); //bool containsDoubleNewline = endsWithDoubleNewline || item.Contains("\n\n"); //var loose = containsDoubleNewline || lastItemHadADoubleNewline; // we could correct any bad indentation here.. item = RunBlockGamut(Outdent(item) + "\n", unhash: false, createParagraphs:false);// loose); //lastItemHadADoubleNewline = endsWithDoubleNewline; return string.Format("<li>{0}</li>\n", item); }; list = Regex.Replace(list, pattern, new MatchEvaluator(ListItemEvaluator), RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline); _listLevel--; return list; } static Regex _codeBlock = new Regex(string.Format(@" (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space (?: (?:[ ]{{{0}}}) # Lines must start with a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{{0,{0}}}[^ \t\n])|\Z) # Lookahead for non-space at line-start, or end of doc", _tabWidth), RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);// | RegexOptions.Compiled); /// <summary> /// /// Turn Markdown 4-space indented code into HTML pre code blocks /// </summary> static string DoCodeBlocks(string text) { text = _codeBlock.Replace(text, new MatchEvaluator(CodeBlockEvaluator)); return text; } static string CodeBlockEvaluator(Match match) { string codeBlock = match.Groups[1].Value; codeBlock = EncodeCode(Outdent(codeBlock)); codeBlock = _newlinesLeadingTrailing.Replace(codeBlock, ""); return string.Concat("\n\n<pre><code>", codeBlock, "\n</code></pre>\n\n"); } static Regex _codeSpan = new Regex(@" (?<![\\`]) # Character before opening ` can't be a backslash or backtick (`+) # $1 = Opening run of ` (?!`) # and no more backticks -- match the full run (.+?) # $2 = The code block (?<!`) \1 (?!`)", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);// | RegexOptions.Compiled); /// <summary> /// Turn Markdown `code spans` into HTML code tags /// </summary> static string DoCodeSpans(string text) { // * You can use multiple backticks as the delimiters if you want to // include literal backticks in the code span. So, this input: // // Just type ``foo `bar` baz`` at the prompt. // // Will translate to: // // <p>Just type <code>foo `bar` baz</code> at the prompt.</p> // // There's no arbitrary limit to the number of backticks you // can use as delimters. If you need three consecutive backticks // in your code, use four for delimiters, etc. // // * You can use spaces to get literal backticks at the edges: // // ... type `` `bar` `` ... // // Turns to: // // ... type <code>`bar`</code> ... // return _codeSpan.Replace(text, new MatchEvaluator(CodeSpanEvaluator)); } static string CodeSpanEvaluator(Match match) { string span = match.Groups[2].Value; span = Regex.Replace(span, @"^[ ]*", ""); // leading whitespace span = Regex.Replace(span, @"[ ]*$", ""); // trailing whitespace span = EncodeCode(span); span = SaveFromAutoLinking(span); // to prevent auto-linking. Not necessary in code *blocks*, but in code spans. return string.Concat("<code>", span, "</code>"); } static Regex _bold = new Regex(@"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);// | RegexOptions.Compiled); static Regex _semiStrictBold = new Regex(@"(?=.[*_]|[*_])(^|(?=\W__|(?!\*)[\W_]\*\*|\w\*\*\w).)(\*\*|__)(?!\2)(?=\S)((?:|.*?(?!\2).)(?=\S_|\w|\S\*\*(?:[\W_]|$)).)(?=__(?:\W|$)|\*\*(?:[^*]|$))\2", RegexOptions.Singleline);// | RegexOptions.Compiled); static Regex _strictBold = new Regex(@"(^|[\W_])(?:(?!\1)|(?=^))(\*|_)\2(?=\S)(.*?\S)\2\2(?!\2)(?=[\W_]|$)", RegexOptions.Singleline);// | RegexOptions.Compiled); static Regex _italic = new Regex(@"(\*|_) (?=\S) (.+?) (?<=\S) \1", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);// | RegexOptions.Compiled); static Regex _semiStrictItalic = new Regex(@"(?=.[*_]|[*_])(^|(?=\W_|(?!\*)(?:[\W_]\*|\D\*(?=\w)\D)).)(\*|_)(?!\2\2\2)(?=\S)((?:(?!\2).)*?(?=[^\s_]_|(?=\w)\D\*\D|[^\s*]\*(?:[\W_]|$)).)(?=_(?:\W|$)|\*(?:[^*]|$))\2", RegexOptions.Singleline);// | RegexOptions.Compiled); static Regex _strictItalic = new Regex(@"(^|[\W_])(?:(?!\1)|(?=^))(\*|_)(?=\S)((?:(?!\2).)*?\S)\2(?!\2)(?=[\W_]|$)", RegexOptions.Singleline);// | RegexOptions.Compiled); // Turn Markdown *italics* and **bold** into HTML strong and em tags static string DoItalicsAndBold(string text) { if (!(text.Contains("*") || text.Contains("_"))) return text; if (_strictBoldItalic) { if (_asteriskIntraWordEmphasis) { text = _semiStrictBold.Replace(text, "$1<strong>$3</strong>"); text = _semiStrictItalic.Replace(text, "$1<em>$3</em>"); } else { text = _strictBold.Replace(text, "$1<strong>$3</strong>"); text = _strictItalic.Replace(text, "$1<em>$3</em>"); } } else { text = _bold.Replace(text, "<strong>$2</strong>"); text = _italic.Replace(text, "<em>$2</em>"); } return text; } static string DoHardBreaks(string text) { if (_autoNewlines) text = Regex.Replace(text, @"\n", string.Format("<br{0}\n", _emptyElementSuffix)); else text = Regex.Replace(text, @" {2,}\n", string.Format("<br{0}\n", _emptyElementSuffix)); return text; } static Regex _blockquote = new Regex(@" ( # Wrap whole match in $1 ( ^[ ]*>[ ]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ )", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);// | RegexOptions.Compiled); static string DoBlockQuotes(string text) { return _blockquote.Replace(text, new MatchEvaluator(BlockQuoteEvaluator)); } static string BlockQuoteEvaluator(Match match) { string bq = match.Groups[1].Value; bq = Regex.Replace(bq, @"^[ ]*>[ ]?", "", RegexOptions.Multiline); // trim one level of quoting bq = Regex.Replace(bq, @"^[ ]+$", "", RegexOptions.Multiline); // trim whitespace-only lines bq = RunBlockGamut(bq); // recurse bq = Regex.Replace(bq, @"^", " ", RegexOptions.Multiline); // These leading spaces screw with <pre> content, so we need to fix that: bq = Regex.Replace(bq, @"(\s*<pre>.+?</pre>)", new MatchEvaluator(BlockQuoteEvaluator2), RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); bq = string.Format("<blockquote>\n{0}\n</blockquote>", bq); string key = GetHashKey(bq, isHtmlBlock: true); _htmlBlocks[key] = bq; return "\n\n" + key + "\n\n"; } static string BlockQuoteEvaluator2(Match match) { return Regex.Replace(match.Groups[1].Value, @"^ ", "", RegexOptions.Multiline); } const string _charInsideUrl = @"[-A-Z0-9+&@#/%?=~_|\[\]\(\)!:,\.;" + "\x1a]"; const string _charEndingUrl = "[-A-Z0-9+&@#/%=~_|\\[\\])]"; static Regex _autolinkBare = new Regex(@"(<|="")?\b(https?|ftp)(://" + _charInsideUrl + "*" + _charEndingUrl + ")(?=$|\\W)", RegexOptions.IgnoreCase);// | RegexOptions.Compiled); static Regex _endCharRegex = new Regex(_charEndingUrl, RegexOptions.IgnoreCase);// | RegexOptions.Compiled); static string handleTrailingParens(Match match) { // The first group is essentially a negative lookbehind -- if there's a < or a =", we don't touch this. // We're not using a *real* lookbehind, because of links with in links, like <a href="http://web.archive.org/web/20121130000728/http://www.google.com/"> // With a real lookbehind, the full link would never be matched, and thus the http://www.google.com *would* be matched. // With the simulated lookbehind, the full link *is* matched (just not handled, because of this early return), causing // the google link to not be matched again. if (match.Groups[1].Success) return match.Value; var protocol = match.Groups[2].Value; var link = match.Groups[3].Value; if (!link.EndsWith(")")) return "<" + protocol + link + ">"; var level = 0; foreach (Match c in Regex.Matches(link, "[()]")) { if (c.Value == "(") { if (level <= 0) level = 1; else level++; } else level--; } var tail = ""; if (level < 0) { link = Regex.Replace(link, @"\){1," + (-level) + "}$", m => { tail = m.Value; return ""; }); } if (tail.Length > 0) { var lastChar = link[link.Length - 1]; if (!_endCharRegex.IsMatch(lastChar.ToString())) { tail = lastChar + tail; link = link.Substring(0, link.Length - 1); } } return "<" + protocol + link + ">" + tail; } static string DoAutoLinks(string text) { if (_autoHyperlink) { text = _autolinkBare.Replace(text, handleTrailingParens); } text = Regex.Replace(text, "<((https?|ftp):[^'\">\\s]+)>", new MatchEvaluator(HyperlinkEvaluator)); if (_linkEmails) { string pattern = @"< (?:mailto:)? ( [-.\w]+ \@ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ ) >"; text = Regex.Replace(text, pattern, new MatchEvaluator(EmailEvaluator), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); } return text; } static string HyperlinkEvaluator(Match match) { string link = match.Groups[1].Value; string url = AttributeSafeUrl(link); return string.Format("<a href=\"{0}\">{1}</a>", url, link); } static string EmailEvaluator(Match match) { string email = Unescape(match.Groups[1].Value); // // Input: an email address, e.g. "foo@example.com" // // Output: the email address as a mailto link, with each character // of the address encoded as either a decimal or hex entity, in // the hopes of foiling most address harvesting spam bots. E.g.: // // <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; // x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; // &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> // // Based by a filter by Matthew Wickline, posted to the BBEdit-Talk // mailing list: <http://tinyurl.com/yu7ue> // email = "mailto:" + email; // leave ':' alone (to spot mailto: later) email = EncodeEmailAddress(email); email = string.Format("<a href=\"{0}\">{0}</a>", email); // strip the mailto: from the visible part email = Regex.Replace(email, "\">.+?:", "\">"); return email; } static Regex _outDent = new Regex(@"^[ ]{1,"+_tabWidth+@"}", RegexOptions.Multiline); static string Outdent(string block) { return _outDent.Replace(block, ""); } static string EncodeEmailAddress(string addr) { var sb = new StringBuilder(addr.Length * 5); var rand = new Random(); int r; foreach (char c in addr) { r = rand.Next(1, 100); if ((r > 90 || c == ':') && c != '@') sb.Append(c); // m else if (r < 45) sb.AppendFormat("&#x{0:x};", (int)c); // &#x6D else sb.AppendFormat("&#{0};", (int)c); // &#109 } return sb.ToString(); } static Regex _codeEncoder = new Regex(@"&|<|>|\\|\*|_|\{|\}|\[|\]"); static string EncodeCode(string code) { return _codeEncoder.Replace(code,EncodeCodeEvaluator);} static string EncodeCodeEvaluator(Match match) { switch (match.Value) { // Encode all ampersands; HTML entities are not // entities within a Markdown code span. #if NOT_UNITY case "&": return "&amp;"; #endif // Do the angle bracket song and dance case "<": return "&lt;"; case ">": return "&gt;"; // escape characters that are magic in Markdown default: return _escapeTable[match.Value]; } } #if NOT_UNITY static Regex _amps = new Regex(@"&(?!((#[0-9]+)|(#[xX][a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9]*));)", RegexOptions.ExplicitCapture);// | RegexOptions.Compiled); static Regex _angles = new Regex(@"<(?![A-Za-z/?\$!])", RegexOptions.ExplicitCapture); #endif static string EncodeAmpsAndAngles(string s) { #if NOT_UNITY s = _amps.Replace(s, "&amp;"); s = _angles.Replace(s, "&lt;"); #endif return s; } static Regex _backslashEscapes; static string EscapeBackslashes(string s) { return _backslashEscapes.Replace(s, new MatchEvaluator(EscapeBackslashesEvaluator)); } static string EscapeBackslashesEvaluator(Match match) { return _backslashEscapeTable[match.Value]; } static Regex _unescapes = new Regex("\x1A" + "E\\d+E");//, RegexOptions.Compiled); static string Unescape(string s) { return _unescapes.Replace(s, new MatchEvaluator(UnescapeEvaluator)); } static string UnescapeEvaluator(Match match) { return _invertedEscapeTable[match.Value]; } static string EscapeBoldItalic(string s) { s = s.Replace("*", _escapeTable["*"]); s = s.Replace("_", _escapeTable["_"]); return s; } static string AttributeEncode(string s) { return s.Replace(">", "&gt;").Replace("<", "&lt;").Replace("\"", "&quot;").Replace("'", "&#39;"); } static string AttributeSafeUrl(string s) { s = AttributeEncode(s); foreach (var c in "*_:()[]") s = s.Replace(c.ToString(), _escapeTable[c.ToString()]); return s; } /// <summary> /// Within tags -- meaning between &lt; and &gt; -- encode [\ ` * _] so they /// don't conflict with their use in Markdown for code, italics and strong. /// We're replacing each such character with its corresponding hash /// value; this is likely overkill, but it should prevent us from colliding /// with the escape values by accident. /// </summary> static string EscapeSpecialCharsWithinTagAttributes(string text) { var tokens = TokenizeHTML(text); // now, rebuild text from the tokens var sb = new StringBuilder(text.Length); foreach (var token in tokens) { string value = token.Value; if (token.Type==TokenType.Tag) { value = value.Replace(@"\", _escapeTable[@"\"]); if (_autoHyperlink && value.StartsWith("<!")) // escape slashes in comments to prevent autolinking there -- http://meta.stackexchange.com/questions/95987/html-comment-containing-url-breaks-if-followed-by-another-html-comment value = value.Replace("/", _escapeTable["/"]); value = Regex.Replace(value, "(?<=.)</?code>(?=.)", _escapeTable[@"`"]); value = EscapeBoldItalic(value); } sb.Append(value); } return sb.ToString(); } static string Normalize(string text) { var output = new StringBuilder(text.Length); var line = new StringBuilder(); bool valid = false; for (int i=0;i<text.Length;i++) { switch (text[i]) { case '\n': if (valid) output.Append(line); output.Append('\n'); line.Length = 0; valid = false; break; case '\r': if ((i < text.Length - 1) && (text[i + 1] != '\n')) { if (valid) output.Append(line); output.Append('\n'); line.Length = 0; valid = false; } break; case '\t': int width = (_tabWidth - line.Length % _tabWidth); for (int k = 0; k < width; k++) line.Append(' '); break; case '\x1A': break; default: if (!valid && text[i] != ' ') valid = true; line.Append(text[i]); break; } } if (valid) output.Append(line); output.Append('\n'); // add two newlines to the end before return return output.Append("\n\n").ToString(); } static string RepeatString(string text, int count) { var sb = new StringBuilder(text.Length * count); for (int i=0;i<count;i++) sb.Append(text); return sb.ToString(); } } #if FAIL using UnityEngine; using System.Collections; using System.Collections.Generic; using Buffer=System.Text.StringBuilder; namespace Markdown { // renders *.md to basic html public static class MarkdownExtension { static string marks = "*_-=#"; public static string md(this string s) { bool e = false, b = false; Buffer sb = new Buffer(s); for (int i=1;i<s.Length;++i) { var t = s[i]; if (marks.IndexOf(t)<0) continue; var r = (string) s[i-1]; if (r==@"\") continue; if (t!='*' || t!='_') continue; // for now if ((r=="*" && t=='*')) { b = !b; } else if (t=='*') e = !e; } return sb.ToString(); } } } /* sb.Insert(i,"<i>"); sb.Replace('*','_'); sb.Replace("<i>","</i>"); String.Format("{0:yyyy-MM-dd}",System.DateTime.Now);*/ #endif
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; namespace ZXing.OneD { /// <summary> /// <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p> /// <author>Sean Owen</author> /// @see Code93Reader /// </summary> internal sealed class Code39Reader : OneDReader { internal static String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; private static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray(); /// <summary> /// These represent the encodings of characters, as patterns of wide and narrow bars. /// The 9 least-significant bits of each int correspond to the pattern of wide and narrow, /// with 1s representing "wide" and 0s representing narrow. /// </summary> internal static int[] CHARACTER_ENCODINGS = { 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* 0x0A8, 0x0A2, 0x08A, 0x02A // $-% }; private static readonly int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; private readonly bool usingCheckDigit; private readonly bool extendedMode; private readonly StringBuilder decodeRowResult; private readonly int[] counters; /// <summary> /// Creates a reader that assumes all encoded data is data, and does not treat the final /// character as a check digit. It will not decoded "extended Code 39" sequences. /// </summary> public Code39Reader() :this(false) { } /// <summary> /// Creates a reader that can be configured to check the last character as a check digit. /// It will not decoded "extended Code 39" sequences. /// </summary> /// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not /// data, and verify that the checksum passes.</param> public Code39Reader(bool usingCheckDigit) :this(usingCheckDigit, false) { } /// <summary> /// Creates a reader that can be configured to check the last character as a check digit, /// or optionally attempt to decode "extended Code 39" sequences that are used to encode /// the full ASCII character set. /// </summary> /// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not /// data, and verify that the checksum passes.</param> /// <param name="extendedMode">if true, will attempt to decode extended Code 39 sequences in the text.</param> public Code39Reader(bool usingCheckDigit, bool extendedMode) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = extendedMode; decodeRowResult = new StringBuilder(20); counters = new int[9]; } /// <summary> /// <p>Attempts to decode a one-dimensional barcode format given a single row of /// an image.</p> /// </summary> /// <param name="rowNumber">row number from top of the row</param> /// <param name="row">the black/white pixel data of the row</param> /// <param name="hints">decode hints</param> /// <returns><see cref="Result"/>containing encoded string and start/end of barcode</returns> override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints) { for (var index = 0; index < counters.Length; index++) counters[index] = 0; decodeRowResult.Length = 0; int[] start = findAsteriskPattern(row, counters); if (start == null) return null; // Read off white space int nextStart = row.getNextSet(start[1]); int end = row.Size; char decodedChar; int lastStart; do { if (!recordPattern(row, nextStart, counters)) return null; int pattern = toNarrowWidePattern(counters); if (pattern < 0) { return null; } if (!patternToChar(pattern, out decodedChar)) return null; decodeRowResult.Append(decodedChar); lastStart = nextStart; foreach (int counter in counters) { nextStart += counter; } // Read off white space nextStart = row.getNextSet(nextStart); } while (decodedChar != '*'); decodeRowResult.Length = decodeRowResult.Length - 1; // remove asterisk // Look for whitespace after pattern: int lastPatternSize = 0; foreach (int counter in counters) { lastPatternSize += counter; } int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if (nextStart != end && (whiteSpaceAfterEnd << 1) < lastPatternSize) { return null; } // overriding constructor value is possible bool useCode39CheckDigit = usingCheckDigit; if (hints != null && hints.ContainsKey(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT)) { useCode39CheckDigit = (bool) hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT]; } if (useCode39CheckDigit) { int max = decodeRowResult.Length - 1; int total = 0; for (int i = 0; i < max; i++) { total += ALPHABET_STRING.IndexOf(decodeRowResult[i]); } if (decodeRowResult[max] != ALPHABET[total % 43]) { return null; } decodeRowResult.Length = max; } if (decodeRowResult.Length == 0) { // false positive return null; } // overriding constructor value is possible bool useCode39ExtendedMode = extendedMode; if (hints != null && hints.ContainsKey(DecodeHintType.USE_CODE_39_EXTENDED_MODE)) { useCode39ExtendedMode = (bool)hints[DecodeHintType.USE_CODE_39_EXTENDED_MODE]; } String resultString; if (useCode39ExtendedMode) { resultString = decodeExtended(decodeRowResult.ToString()); if (resultString == null) { if (hints != null && hints.ContainsKey(DecodeHintType.RELAXED_CODE_39_EXTENDED_MODE) && Convert.ToBoolean(hints[DecodeHintType.RELAXED_CODE_39_EXTENDED_MODE])) resultString = decodeRowResult.ToString(); else return null; } } else { resultString = decodeRowResult.ToString(); } float left = (start[1] + start[0])/2.0f; float right = lastStart + lastPatternSize / 2.0f; var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null : (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; if (resultPointCallback != null) { resultPointCallback(new ResultPoint(left, rowNumber)); resultPointCallback(new ResultPoint(right, rowNumber)); } return new Result( resultString, null, new[] { new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber) }, BarcodeFormat.CODE_39); } private static int[] findAsteriskPattern(BitArray row, int[] counters) { int width = row.Size; int rowOffset = row.getNextSet(0); int counterPosition = 0; int patternStart = rowOffset; bool isWhite = false; int patternLength = counters.Length; for (int i = rowOffset; i < width; i++) { if (row[i] ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (row.isRange(Math.Max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) { return new int[] { patternStart, i }; } } patternStart += counters[0] + counters[1]; Array.Copy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } return null; } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.Length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = Int32.MaxValue; foreach (var counter in counters) { if (counter < minCounter && counter > maxNarrowCounter) { minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { pattern |= 1 << (numCounters - 1 - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; i < numCounters && wideCounters > 0; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter << 1) >= totalWideCountersWidth) { return -1; } } } return pattern; } } while (wideCounters > 3); return -1; } private static bool patternToChar(int pattern, out char c) { for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { c = ALPHABET[i]; return true; } } c = '*'; return false; } private static String decodeExtended(String encoded) { int length = encoded.Length; StringBuilder decoded = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded[i]; if (c == '+' || c == '$' || c == '%' || c == '/') { if (i + 1 >= encoded.Length) { return null; } char next = encoded[i + 1]; char decodedChar = '\0'; switch (c) { case '+': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char)(next + 32); } else { return null; } break; case '$': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char)(next - 64); } else { return null; } break; case '%': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char)(next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char)(next - 11); } else { return null; } break; case '/': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char)(next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { return null; } break; } decoded.Append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.Append(c); } } return decoded.ToString(); } } }
// EntityDataView.cs // using System; using System.Collections.Generic; using Slick; using Xrm.Sdk; using jQueryApi; using System.Diagnostics; namespace SparkleXrm.GridEditor { public class EntityDataViewModel : DataViewBase { #region Fields protected bool _suspendRefresh = false; protected Entity[] _rows = new Entity[0]; protected List<Entity> _data; protected Type _entityType; protected string _fetchXml = ""; protected List<SortCol> _sortCols = new List<SortCol>(); protected bool _itemAdded = false; protected bool _lazyLoadPages = true; public string ErrorMessage = ""; public List<Entity> DeleteData; //scolson: Event allows viewmodel to save data before cache is cleared. public event Action OnBeginClearPageCache; #endregion #region Constructors public EntityDataViewModel(int pageSize, Type entityType, bool lazyLoadPages) { // Create data for server load _entityType = entityType; _lazyLoadPages = lazyLoadPages; this._data = new List<Entity>(); paging.PageSize = pageSize; paging.PageNum = 0; paging.TotalPages = 0; paging.TotalRows = 0; paging.FromRecord = 0; paging.ToRecord = 0; } #endregion #region IDataProvider public string FetchXml { get { return _fetchXml; } set { _fetchXml = value; //Refresh(); Removed since an explicit refresh is better to avoid unneccessary ones } } public override object GetItem(int index) { if (index >= this.paging.PageSize) // Fixes Issue #17 - If we are showing a non-lazy loaded grid don't return the value for the add new row return null; else return _data[index + ((int)paging.PageNum * (int)paging.PageSize)]; } public override void Reset() { // Reset the cache //scolson: use ClearPageCache method to clear data list. this.ClearPageCache(); //this._data = new List<Entity>(); this.DeleteData = new List<Entity>(); } public void ResetPaging() { paging.PageNum = 0; //this.OnPagingInfoChanged.Notify(GetPagingInfo(), null, null); } #endregion #region IDataView public override void Sort(SortColData sorting) { SortCol col = new SortCol(sorting.SortCol.Field,sorting.SortAsc); SortBy(col); } public void SortBy(SortCol col) { _sortCols.Clear(); _sortCols.Add(col); if (_lazyLoadPages) { // Clear page cache //scolson: Use ClearPageCache routine instead of nulling the data list. this.ClearPageCache(); //_data = new List<Entity>(); this.paging.extraInfo = ""; Refresh(); } else { // From SlickGrid : an extra reversal for descending sort keeps the sort stable // (assuming a stable native sort implementation, which isn't true in some cases) if (col.Ascending == false) { _data.Reverse(); } _data.Sort(delegate(Entity a, Entity b) { return Entity.SortDelegate(col.AttributeName, a, b); }); if (col.Ascending == false) { _data.Reverse(); } } } public List<Entity> GetDirtyItems() { List<Entity> dirtyCollection = new List<Entity>(); // Add new/changed items foreach (Entity item in this._data) { if (item != null && item.EntityState != EntityStates.Unchanged) dirtyCollection.Add(item); } // Add deleted items if (this.DeleteData != null) { foreach (Entity item in this.DeleteData) { if (item.EntityState == EntityStates.Deleted) dirtyCollection.Add(item); } } return dirtyCollection; } /// <summary> /// Check to see if the EntityDataViewModel contains the specified entity. /// </summary> /// <param name="Item"></param> /// <returns></returns> public bool Contains(Entity Item) { foreach (Entity value in _data) { if (Item.LogicalName == value.LogicalName && Item.Id == value.Id) { return true; } } return false; } public override void Refresh() { if (_suspendRefresh) return; _suspendRefresh = true; // check if we have loaded this page yet int firstRowIndex = (int)paging.PageNum * (int)paging.PageSize; // If we have deleted all rows, we don't want to refresh the grid on the first page bool allDataDeleted = (paging.TotalRows == 0) && (DeleteData != null) && (DeleteData.Count > 0); if (_data[firstRowIndex] == null && !allDataDeleted) { this.OnDataLoading.Notify(null, null, null); string orderBy = ApplySorting(); // We need to load the data from the server int? fetchPageSize; if (_lazyLoadPages) { fetchPageSize = this.paging.PageSize; } else { fetchPageSize = 1000; // Maximum 1000 records returned in non-lazy load grid this.paging.extraInfo = ""; this.paging.PageNum = 0; firstRowIndex = 0; } if (String.IsNullOrEmpty(_fetchXml)) // If we have no fetchxml, then don't refresh return; string parameterisedFetchXml = String.Format(_fetchXml, fetchPageSize, XmlHelper.Encode(this.paging.extraInfo), this.paging.PageNum + 1, orderBy); OrganizationServiceProxy.BeginRetrieveMultiple(parameterisedFetchXml, delegate(object result) { try { EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(result, _entityType); // Set data int i = firstRowIndex; if (_lazyLoadPages) { // We are returning just one page - so add it into the data foreach (Entity e in results.Entities) { _data[i] = (Entity)e; i = i + 1; } } else { // We are returning all results in one go _data = results.Entities.Items(); } // Notify DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.From = 0; args.To = (int)paging.PageSize - 1; this.paging.TotalRows = results.TotalRecordCount; this.paging.extraInfo = results.PagingCookie; this.paging.FromRecord = firstRowIndex + 1; this.paging.TotalPages = Math.Ceil(results.TotalRecordCount / this.paging.PageSize); this.paging.ToRecord = Math.Min(results.TotalRecordCount, firstRowIndex + paging.PageSize); if (this._itemAdded) { this.paging.TotalRows++; this.paging.ToRecord++; this._itemAdded = false; } this.CalculatePaging(GetPagingInfo()); OnPagingInfoChanged.Notify(this.paging, null, this); this.OnDataLoaded.Notify(args, null, null); } catch (Exception ex) { this.ErrorMessage = ex.Message; DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.ErrorMessage = ex.Message; this.OnDataLoaded.Notify(args, null, null); } }); } else { // We already have the data DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.From = 0; args.To = (int)paging.PageSize - 1; this.paging.FromRecord = firstRowIndex + 1; this.paging.ToRecord = Math.Min(this.paging.TotalRows, firstRowIndex + paging.PageSize); this.CalculatePaging(GetPagingInfo()); OnPagingInfoChanged.Notify(this.paging, null, this); this.OnDataLoaded.Notify(args, null, null); this._itemAdded = false; } this.OnRowsChanged.Notify(null, null, this); _suspendRefresh = false; } public Func<object, Entity> NewItemFactory; public override void RemoveItem(object id) { if (id != null) { if (DeleteData == null) DeleteData = new List<Entity>(); DeleteData.Add((Entity)id); _data.Remove((Entity)id); this.paging.TotalRows--; this.SetPagingOptions(this.GetPagingInfo()); this._selectedRows = null; RaiseOnSelectedRowsChanged(null); } } public override void AddItem(object newItem) { // If the items are empty - ensure there is a single page if (this.paging.TotalPages == 0) { this.paging.PageNum = 0; this.paging.TotalPages = 1; } Entity item; if (NewItemFactory == null) { item = (Entity)Type.CreateInstance(this._entityType); jQuery.Extend(item, newItem); } else { item = NewItemFactory(newItem); } _data[this.paging.TotalRows.Value] = ((Entity)item); // Do we need a new page? this._itemAdded = true; int lastPageSize = (paging.TotalRows.Value % paging.PageSize.Value); if (lastPageSize == paging.PageSize) { // Add a new page this.paging.TotalPages++; this.paging.PageNum=this.paging.TotalPages-1; } else { this.paging.TotalRows++; this.paging.PageNum = this.GetTotalPages(); } item.RaisePropertyChanged(null); this.SetPagingOptions(GetPagingInfo()); } protected string ApplySorting() { // Take the sorting and insert into the fetchxml string orderBy = string.Empty; foreach (SortCol col in _sortCols) { orderBy = orderBy + String.Format(@"<order attribute=""{0}"" descending=""{1}"" />", col.AttributeName, !col.Ascending ? "true" : "false"); } return orderBy; } protected void ClearPageCache() { //scolson: call any event handlers that need to take action before clearing the cache if (this.OnBeginClearPageCache != null) { this.OnBeginClearPageCache(); } _data = new List<Entity>(); paging.extraInfo = null; } #endregion #region Properties public List<Entity> Data { get { return _data; } } #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.Linq; using NodaTime; using QuantConnect.Util; namespace QuantConnect.Securities { /// <summary> /// Base exchange class providing information and helper tools for reading the current exchange situation /// </summary> public class SecurityExchange { private DateTime _localFrontier; private SecurityExchangeHours _exchangeHours; /// <summary> /// Gets the <see cref="SecurityExchangeHours"/> for this exchange /// </summary> public SecurityExchangeHours Hours { get { return _exchangeHours; } } /// <summary> /// Gets the time zone for this exchange /// </summary> public DateTimeZone TimeZone { get { return _exchangeHours.TimeZone; } } /// <summary> /// Gets the market open time for the current day /// </summary> public TimeSpan MarketOpen { get { return _exchangeHours.GetMarketHours(_localFrontier).MarketOpen; } } /// <summary> /// Gets the market close time for the current day /// </summary> public TimeSpan MarketClose { get { return _exchangeHours.GetMarketHours(_localFrontier).MarketClose; } } /// <summary> /// Gets the extended market open time for the current day /// </summary> public TimeSpan ExtendedMarketOpen { get { return _exchangeHours.GetMarketHours(_localFrontier).ExtendedMarketOpen; } } /// <summary> /// Gets the extended market close time for the current day /// </summary> public TimeSpan ExtendedMarketClose { get { return _exchangeHours.GetMarketHours(_localFrontier).ExtendedMarketClose; } } /// <summary> /// Number of trading days per year for this security. By default the market is open 365 days per year. /// </summary> /// <remarks>Used for performance statistics to calculate sharpe ratio accurately</remarks> public virtual int TradingDaysPerYear { get { return 365; } } /// <summary> /// Time from the most recent data /// </summary> public DateTime LocalTime { get { return _localFrontier; } } /// <summary> /// Boolean property for quickly testing if the exchange is open. /// </summary> public bool ExchangeOpen { get { return _exchangeHours.IsOpen(_localFrontier, false); } } /// <summary> /// Initializes a new instance of the <see cref="SecurityExchange"/> class using the specified /// exchange hours to determine open/close times /// </summary> /// <param name="exchangeHours">Contains the weekly exchange schedule plus holidays</param> public SecurityExchange(SecurityExchangeHours exchangeHours) { _exchangeHours = exchangeHours; } /// <summary> /// Set the current datetime in terms of the exchange's local time zone /// </summary> /// <param name="newLocalTime">Most recent data tick</param> public void SetLocalDateTimeFrontier(DateTime newLocalTime) { _localFrontier = newLocalTime; } /// <summary> /// Check if the *date* is open. /// </summary> /// <remarks>This is useful for first checking the date list, and then the market hours to save CPU cycles</remarks> /// <param name="dateToCheck">Date to check</param> /// <returns>Return true if the exchange is open for this date</returns> public bool DateIsOpen(DateTime dateToCheck) { return _exchangeHours.IsDateOpen(dateToCheck); } /// <summary> /// Gets the date time the market opens on the specified day /// </summary> /// <param name="time">DateTime object for this date</param> /// <returns>DateTime the market is considered open</returns> public DateTime TimeOfDayOpen(DateTime time) { return time.Date + _exchangeHours.GetMarketHours(time).MarketOpen; } /// <summary> /// Gets the date time the market closes on the specified day /// </summary> /// <param name="time">DateTime object for this date</param> /// <returns>DateTime the market day is considered closed</returns> public DateTime TimeOfDayClosed(DateTime time) { return time.Date + _exchangeHours.GetMarketHours(time).MarketClose; } /// <summary> /// Check if this DateTime is open. /// </summary> /// <param name="dateTime">DateTime to check</param> /// <returns>Boolean true if the market is open</returns> public bool DateTimeIsOpen(DateTime dateTime) { return _exchangeHours.IsOpen(dateTime, false); } /// <summary> /// Check if the object is open including the *Extended* market hours /// </summary> /// <param name="time">Current time of day</param> /// <returns>True if we are in extended or primary marketing hours.</returns> public bool DateTimeIsExtendedOpen(DateTime time) { return _exchangeHours.IsOpen(time, true); } /// <summary> /// Determines if the exchange was open at any time between start and stop /// </summary> public bool IsOpenDuringBar(DateTime barStartTime, DateTime barEndTime, bool isExtendedMarketHours) { return _exchangeHours.IsOpen(barStartTime, barEndTime, isExtendedMarketHours); } /// <summary> /// Sets the regular market hours for the specified days. Extended market hours are /// set to the same as the regular market hours. If no days are specified then /// all days will be updated. /// <para>Specify <see cref="TimeSpan.Zero"/> for both <paramref name="marketOpen"/> /// and <paramref name="marketClose"/> to close the exchange for the specified days.</para> /// <para>Specify /// <see cref="TimeSpan.Zero"/> for <paramref name="marketOpen"/> and <see cref="QuantConnect.Time.OneDay"/> /// for open all day</para> /// </summary> /// <param name="marketOpen">The time of day the market opens</param> /// <param name="marketClose">The time of day the market closes</param> /// <param name="days">The days of the week to set these times for</param> public void SetMarketHours(TimeSpan marketOpen, TimeSpan marketClose, params DayOfWeek[] days) { SetMarketHours(marketOpen, marketOpen, marketClose, marketClose, days); } /// <summary> /// Sets the regular market hours for the specified days If no days are specified then /// all days will be updated. /// </summary> /// <param name="extendedMarketOpen">The time of day the pre market opens</param> /// <param name="marketOpen">The time of day the market opens</param> /// <param name="marketClose">The time of day the market closes</param> /// <param name="extendedMarketClose">The time of day the post market opens</param> /// <param name="days">The days of the week to set these times for</param> public void SetMarketHours(TimeSpan extendedMarketOpen, TimeSpan marketOpen, TimeSpan marketClose, TimeSpan extendedMarketClose, params DayOfWeek[] days) { if (days.IsNullOrEmpty()) days = Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToArray(); // make sure extended hours are outside of regular hours extendedMarketOpen = TimeSpan.FromTicks(Math.Min(extendedMarketOpen.Ticks, marketOpen.Ticks)); extendedMarketClose = TimeSpan.FromTicks(Math.Max(extendedMarketClose.Ticks, marketClose.Ticks)); var marketHours = _exchangeHours.MarketHours.ToDictionary(); foreach (var day in days) { if (marketOpen == TimeSpan.Zero && marketClose == TimeSpan.Zero) { marketHours[day] = LocalMarketHours.ClosedAllDay(day); } else if (marketOpen == TimeSpan.Zero && marketClose == Time.OneDay) { marketHours[day] = LocalMarketHours.OpenAllDay(day); } else { marketHours[day] = new LocalMarketHours(day, extendedMarketOpen, marketOpen, marketClose, extendedMarketClose); } } // create a new exchange hours instance for the new hours _exchangeHours = new SecurityExchangeHours(_exchangeHours.TimeZone, _exchangeHours.Holidays, marketHours); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: LocalDataStoreMgr ** ** ** Purpose: Class that manages stores of local data. This class is used in ** cooperation with the LocalDataStore class. ** ** =============================================================================*/ namespace System { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; // This class is an encapsulation of a slot so that it is managed in a secure fashion. // It is constructed by the LocalDataStoreManager, holds the slot and the manager // and cleans up when it is finalized. // This class will not be marked serializable [System.Runtime.InteropServices.ComVisible(true)] public sealed class LocalDataStoreSlot { private LocalDataStoreMgr m_mgr; private int m_slot; private long m_cookie; // Construct the object to encapsulate the slot. internal LocalDataStoreSlot(LocalDataStoreMgr mgr, int slot, long cookie) { m_mgr = mgr; m_slot = slot; m_cookie = cookie; } // Accessors for the two fields of this class. internal LocalDataStoreMgr Manager { get { return m_mgr; } } internal int Slot { get { return m_slot; } } internal long Cookie { get { return m_cookie; } } // Release the slot reserved by this object when this object goes away. ~LocalDataStoreSlot() { LocalDataStoreMgr mgr = m_mgr; if (mgr == null) return; int slot = m_slot; // Mark the slot as free. m_slot = -1; mgr.FreeDataSlot(slot, m_cookie); } } // This class will not be marked serializable sealed internal class LocalDataStoreMgr { private const int InitialSlotTableSize = 64; private const int SlotTableDoubleThreshold = 512; private const int LargeSlotTableSizeIncrease = 128; /*========================================================================= ** Create a data store to be managed by this manager and add it to the ** list. The initial size of the new store matches the number of slots ** allocated in this manager. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated public LocalDataStoreHolder CreateLocalDataStore() { // Create a new local data store. LocalDataStore store = new LocalDataStore(this, m_SlotInfoTable.Length); LocalDataStoreHolder holder = new LocalDataStoreHolder(store); bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); // Add the store to the array list and return it. m_ManagedLocalDataStores.Add(store); } finally { if (tookLock) Monitor.Exit(this); } return holder; } /*========================================================================= * Remove the specified store from the list of managed stores.. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated public void DeleteLocalDataStore(LocalDataStore store) { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); // Remove the store to the array list and return it. m_ManagedLocalDataStores.Remove(store); } finally { if (tookLock) Monitor.Exit(this); } } /*========================================================================= ** Allocates a data slot by finding an available index and wrapping it ** an object to prevent clients from manipulating it directly, allowing us ** to make assumptions its integrity. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated public LocalDataStoreSlot AllocateDataSlot() { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); LocalDataStoreSlot slot; int slotTableSize = m_SlotInfoTable.Length; // In case FreeDataSlot has moved the pointer back, the next slot may not be available. // Find the first actually available slot. int availableSlot = m_FirstAvailableSlot; while (availableSlot < slotTableSize) { if (!m_SlotInfoTable[availableSlot]) break; availableSlot++; } // Check if there are any slots left. if (availableSlot >= slotTableSize) { // The table is full so we need to increase its size. int newSlotTableSize; if (slotTableSize < SlotTableDoubleThreshold) { // The table is still relatively small so double it. newSlotTableSize = slotTableSize * 2; } else { // The table is relatively large so simply increase its size by a given amount. newSlotTableSize = slotTableSize + LargeSlotTableSizeIncrease; } // Allocate the new slot info table. bool[] newSlotInfoTable = new bool[newSlotTableSize]; // Copy the old array into the new one. Array.Copy(m_SlotInfoTable, newSlotInfoTable, slotTableSize); m_SlotInfoTable = newSlotInfoTable; } // availableSlot is the index of the empty slot. m_SlotInfoTable[availableSlot] = true; // We do not need to worry about overflowing m_CookieGenerator. It would take centuries // of intensive slot allocations on current machines to get the 2^64 counter to overflow. // We will perform the increment with overflow check just to play it on the safe side. slot = new LocalDataStoreSlot(this, availableSlot, checked(m_CookieGenerator++)); // Save the new "first available slot".hint m_FirstAvailableSlot = availableSlot + 1; // Return the selected slot return slot; } finally { if (tookLock) Monitor.Exit(this); } } /*========================================================================= ** Allocate a slot and associate a name with it. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated public LocalDataStoreSlot AllocateNamedDataSlot(String name) { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); // Allocate a normal data slot. LocalDataStoreSlot slot = AllocateDataSlot(); // Insert the association between the name and the data slot number // in the hash table. m_KeyToSlotMap.Add(name, slot); return slot; } finally { if (tookLock) Monitor.Exit(this); } } /*========================================================================= ** Retrieve the slot associated with a name, allocating it if no such ** association has been defined. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated public LocalDataStoreSlot GetNamedDataSlot(String name) { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); // Lookup in the hashtable to try find a slot for the name. LocalDataStoreSlot slot = m_KeyToSlotMap.GetValueOrDefault(name); // If the name is not yet in the hashtable then add it. if (null == slot) return AllocateNamedDataSlot(name); // The name was in the hashtable so return the associated slot. return slot; } finally { if (tookLock) Monitor.Exit(this); } } /*========================================================================= ** Eliminate the association of a name with a slot. The actual slot will ** be reclaimed when the finalizer for the slot object runs. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated public void FreeNamedDataSlot(String name) { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); // Remove the name slot association from the hashtable. m_KeyToSlotMap.Remove(name); } finally { if (tookLock) Monitor.Exit(this); } } /*========================================================================= ** Free's a previously allocated data slot on ALL the managed data stores. =========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated internal void FreeDataSlot(int slot, long cookie) { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); // Go thru all the managed stores and set the data on the specified slot to 0. for (int i = 0; i < m_ManagedLocalDataStores.Count; i++) { ((LocalDataStore)m_ManagedLocalDataStores[i]).FreeData(slot, cookie); } // Mark the slot as being no longer occupied. m_SlotInfoTable[slot] = false; if (slot < m_FirstAvailableSlot) m_FirstAvailableSlot = slot; } finally { if (tookLock) Monitor.Exit(this); } } /*========================================================================= ** Check that this is a valid slot for this store =========================================================================*/ public void ValidateSlot(LocalDataStoreSlot slot) { // Make sure the slot was allocated for this store. if (slot == null || slot.Manager != this) throw new ArgumentException(Environment.GetResourceString("Argument_ALSInvalidSlot")); Contract.EndContractBlock(); } /*========================================================================= ** Return the number of allocated slots in this manager. =========================================================================*/ internal int GetSlotTableLength() { return m_SlotInfoTable.Length; } private bool[] m_SlotInfoTable = new bool[InitialSlotTableSize]; private int m_FirstAvailableSlot; private List<LocalDataStore> m_ManagedLocalDataStores = new List<LocalDataStore>(); private Dictionary<String, LocalDataStoreSlot> m_KeyToSlotMap = new Dictionary<String, LocalDataStoreSlot>(); private long m_CookieGenerator; } }
// <copyright file="IPlayGamesClient.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.BasicApi { using System; using GooglePlayGames.BasicApi.Multiplayer; using UnityEngine; using UnityEngine.SocialPlatforms; /// <summary> /// Defines an abstract interface for a Play Games Client. /// </summary> /// <remarks>Concrete implementations /// might be, for example, the client for Android or for iOS. One fundamental concept /// that implementors of this class must adhere to is stable authentication state. /// This means that once Authenticate() returns true through its callback, the user is /// considered to be forever after authenticated while the app is running. The implementation /// must make sure that this is the case -- for example, it must try to silently /// re-authenticate the user if authentication is lost or wait for the authentication /// process to get fixed if it is temporarily in a bad state (such as when the /// Activity in Android has just been brought to the foreground and the connection to /// the Games services hasn't yet been established). To the user of this /// interface, once the user is authenticated, they're forever authenticated. /// Unless, of course, there is an unusual permanent failure such as the underlying /// service dying, in which it's acceptable that API method calls will fail. /// /// <para>All methods can be called from the game thread. The user of this interface /// DOES NOT NEED to call them from the UI thread of the game. Transferring to the UI /// thread when necessary is a responsibility of the implementors of this interface.</para> /// /// <para>CALLBACKS: all callbacks must be invoked in Unity's main thread. /// Implementors of this interface must guarantee that (suggestion: use /// <see cref="GooglePlayGames.OurUtils.RunOnGameThread(System.Action action)"/>).</para> /// </remarks> public interface IPlayGamesClient { /// <summary> /// Starts the authentication process. /// </summary> /// <remarks>If silent == true, no UIs will be shown /// (if UIs are needed, it will fail rather than show them). If silent == false, /// this may show UIs, consent dialogs, etc. /// At the end of the process, callback will be invoked to notify of the result. /// Once the callback returns true, the user is considered to be authenticated /// forever after. /// </remarks> /// <param name="callback">Callback.</param> /// <param name="silent">If set to <c>true</c> silent.</param> void Authenticate(System.Action<bool, string> callback, bool silent); /// <summary> /// Returns whether or not user is authenticated. /// </summary> /// <returns><c>true</c> if the user is authenticated; otherwise, <c>false</c>.</returns> bool IsAuthenticated(); /// <summary> /// Signs the user out. /// </summary> void SignOut(); /// <summary> /// Returns the authenticated user's ID. Note that this value may change if a user signs /// on and signs in with a different account. /// </summary> /// <returns>The user's ID, <code>null</code> if the user is not logged in.</returns> string GetUserId(); /// <summary> /// Load friends of the authenticated user. /// </summary> /// <param name="callback">Callback invoked when complete. bool argument /// indicates success.</param> void LoadFriends(Action<bool> callback); /// <summary> /// Returns a human readable name for the user, if they are logged in. /// </summary> /// <returns>The user's human-readable name. <code>null</code> if they are not logged /// in</returns> string GetUserDisplayName(); /// <summary> /// Returns an id token, which can be verified server side, if they are logged in. /// </summary> string GetIdToken(); /// <summary> /// The server auth code for this client. /// </summary> /// <remarks> /// Note: This function is currently only implemented for Android. /// </remarks> string GetServerAuthCode(); /// <summary> /// Gets the user's email. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available. /// </remarks> /// <returns>The user email or null if not authenticated or the permission is /// not available.</returns> string GetUserEmail(); /// <summary> /// Returns the user's avatar url, if they are logged in and have an avatar. /// </summary> /// <returns>The URL to load the avatar image. <code>null</code> if they are not logged /// in</returns> string GetUserImageUrl(); /// <summary>Gets the player stats.</summary> /// <param name="callback">Callback for response.</param> void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback); /// <summary> /// Loads the users specified. This is mainly used by the leaderboard /// APIs to get the information of a high scorer. /// </summary> /// <param name="userIds">User identifiers.</param> /// <param name="callback">Callback.</param> void LoadUsers(string[] userIds, Action<IUserProfile[]> callback); /// <summary> /// Returns the achievement corresponding to the passed achievement identifier. /// </summary> /// <returns>The achievement corresponding to the identifer. <code>null</code> if no such /// achievement is found or if authentication has not occurred.</returns> /// <param name="achievementId">The identifier of the achievement.</param> Achievement GetAchievement(string achievementId); /// <summary> /// Loads the achievements for the current signed in user and invokes /// the callback. /// </summary> void LoadAchievements(Action<Achievement[]> callback); /// <summary> /// Unlocks the achievement with the passed identifier. /// </summary> /// <remarks>If the operation succeeds, the callback /// will be invoked on the game thread with <code>true</code>. If the operation fails, the /// callback will be invoked with <code>false</code>. This operation will immediately fail if /// the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). If the achievement is already unlocked, this call will /// succeed immediately. /// </remarks> /// <param name="achievementId">The ID of the achievement to unlock.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void UnlockAchievement(string achievementId, Action<bool> successOrFailureCalllback); /// <summary> /// Reveals the achievement with the passed identifier. /// </summary> /// <remarks>If the operation succeeds, the callback /// will be invoked on the game thread with <code>true</code>. If the operation fails, the /// callback will be invoked with <code>false</code>. This operation will immediately fail if /// the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). If the achievement is already in a revealed state, this call will /// succeed immediately. /// </remarks> /// <param name="achievementId">The ID of the achievement to reveal.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void RevealAchievement(string achievementId, Action<bool> successOrFailureCalllback); /// <summary> /// Increments the achievement with the passed identifier. /// </summary> /// <remarks>If the operation succeeds, the /// callback will be invoked on the game thread with <code>true</code>. If the operation fails, /// the callback will be invoked with <code>false</code>. This operation will immediately fail /// if the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). /// </remarks> /// <param name="achievementId">The ID of the achievement to increment.</param> /// <param name="steps">The number of steps to increment by.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void IncrementAchievement(string achievementId, int steps, Action<bool> successOrFailureCalllback); /// <summary> /// Set an achievement to have at least the given number of steps completed. /// </summary> /// <remarks> /// Calling this method while the achievement already has more steps than /// the provided value is a no-op. Once the achievement reaches the /// maximum number of steps, the achievement is automatically unlocked, /// and any further mutation operations are ignored. /// </remarks> /// <param name="achId">Ach identifier.</param> /// <param name="steps">Steps.</param> /// <param name="callback">Callback.</param> void SetStepsAtLeast(string achId, int steps, Action<bool> callback); /// <summary> /// Shows the appropriate platform-specific achievements UI. /// <param name="callback">The callback to invoke when complete. If null, /// no callback is called. </param> /// </summary> void ShowAchievementsUI(Action<UIStatus> callback); /// <summary> /// Shows the leaderboard UI for a specific leaderboard. /// </summary> /// <remarks>If the passed ID is <code>null</code>, all leaderboards are displayed. /// </remarks> /// <param name="leaderboardId">The leaderboard to display. <code>null</code> to display /// all.</param> /// <param name="span">Timespan to display for the leaderboard</param> /// <param name="callback">If non-null, the callback to invoke when the /// leaderboard is dismissed. /// </param> void ShowLeaderboardUI(string leaderboardId, LeaderboardTimeSpan span, Action<UIStatus> callback); /// <summary> /// Loads the score data for the given leaderboard. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="start">Start indicating the top scores or player centric</param> /// <param name="rowCount">max number of scores to return. non-positive indicates // no rows should be returned. This causes only the summary info to /// be loaded. This can be limited // by the SDK.</param> /// <param name="collection">leaderboard collection: public or social</param> /// <param name="timeSpan">leaderboard timespan</param> /// <param name="callback">callback with the scores, and a page token. /// The token can be used to load next/prev pages.</param> void LoadScores(string leaderboardId, LeaderboardStart start, int rowCount, LeaderboardCollection collection, LeaderboardTimeSpan timeSpan, Action<LeaderboardScoreData> callback); /// <summary> /// Loads the more scores for the leaderboard. /// </summary> /// <remarks>The token is accessed /// by calling LoadScores() with a positive row count. /// </remarks> /// <param name="token">Token for tracking the score loading.</param> /// <param name="rowCount">max number of scores to return. /// This can be limited by the SDK.</param> /// <param name="callback">Callback.</param> void LoadMoreScores(ScorePageToken token, int rowCount, Action<LeaderboardScoreData> callback); /// <summary> /// Returns the max number of scores returned per call. /// </summary> /// <returns>The max results.</returns> int LeaderboardMaxResults(); /// <summary> /// Submits the passed score to the passed leaderboard. /// </summary> /// <remarks>This operation will immediately fail /// if the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). /// </remarks> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="score">Score.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void SubmitScore(string leaderboardId, long score, Action<bool> successOrFailureCalllback); /// <summary> /// Submits the score for the currently signed-in player. /// </summary> /// <param name="score">Score.</param> /// <param name="board">leaderboard id.</param> /// <param name="metadata">metadata about the score.</param> /// <param name="callback">Callback upon completion.</param> void SubmitScore(string leaderboardId, long score, string metadata, Action<bool> successOrFailureCalllback); /// <summary> /// Returns a real-time multiplayer client. /// </summary> /// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"/> /// <returns>The rtmp client.</returns> IRealTimeMultiplayerClient GetRtmpClient(); /// <summary> /// Returns a turn-based multiplayer client. /// </summary> /// <returns>The tbmp client.</returns> ITurnBasedMultiplayerClient GetTbmpClient(); /// <summary> /// Gets the saved game client. /// </summary> /// <returns>The saved game client.</returns> SavedGame.ISavedGameClient GetSavedGameClient(); /// <summary> /// Gets the events client. /// </summary> /// <returns>The events client.</returns> Events.IEventsClient GetEventsClient(); /// <summary> /// Gets the quests client. /// </summary> /// <returns>The quests client.</returns> Quests.IQuestsClient GetQuestsClient(); /// <summary> /// Gets the video client. /// </summary> /// <returns>The video client.</returns> Video.IVideoClient GetVideoClient(); /// <summary> /// Registers the invitation delegate. /// </summary> /// <param name="invitationDelegate">Invitation delegate.</param> void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate); IUserProfile[] GetFriends(); /// <summary> /// Gets the Android API client. Returns null on non-Android players. /// </summary> /// <returns>The API client.</returns> IntPtr GetApiClient(); } /// <summary> /// Delegate that handles an incoming invitation (for both RTMP and TBMP). /// </summary> /// <param name="invitation">The invitation received.</param> /// <param name="shouldAutoAccept">If this is true, then the game should immediately /// accept the invitation and go to the game screen without prompting the user. If /// false, you should prompt the user before accepting the invitation. As an example, /// when a user taps on the "Accept" button on a notification in Android, it is /// clear that they want to accept that invitation right away, so the plugin calls this /// delegate with shouldAutoAccept = true. However, if we receive an incoming invitation /// that the player hasn't specifically indicated they wish to accept (for example, /// we received one in the background from the server), this delegate will be called /// with shouldAutoAccept=false to indicate that you should confirm with the user /// to see if they wish to accept or decline the invitation.</param> public delegate void InvitationReceivedDelegate(Invitation invitation, bool shouldAutoAccept); } #endif
/* * 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 NVelocity.Runtime.Parser.Node { using System; using System.Text; using Context; using Log; /// <summary> </summary> public class SimpleNode : INode { /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.getLastToken()"> /// </seealso> public virtual Token LastToken { get { return last; } } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.getType()"> /// </seealso> public virtual int Type { get { return id; } } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.getInfo()"> /// </seealso> /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.setInfo(int)"> /// </seealso> public virtual int Info { get { return info; } set { this.info = value; } } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.getLine()"> /// </seealso> public virtual int Line { get { return first.BeginLine; } } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.getColumn()"> /// </seealso> public virtual int Column { get { return first.BeginColumn; } } public virtual string TemplateName { get { return templateName; } } protected internal IRuntimeServices rsvc = null; protected internal Log log = null; protected internal INode parent; protected internal INode[] children; protected internal int id; // TODO - It seems that this field is only valid when parsing, and should not be kept around. protected internal Parser parser; protected internal int info; // added public bool state; protected internal bool invalid = false; protected internal Token first; protected internal Token last; protected internal string templateName; /// <param name="i"> /// </param> public SimpleNode(int i) { id = i; } /// <param name="p"> /// </param> /// <param name="i"> /// </param> public SimpleNode(Parser p, int i) : this(i) { parser = p; templateName = parser.currentTemplateName; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtOpen()"> /// </seealso> public virtual void Open() { first = parser.getToken(1); // added } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtClose()"> /// </seealso> public virtual void Close() { last = parser.getToken(0); // added } /// <param name="t"> /// </param> public virtual void SetFirstToken(Token t) { this.first = t; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.getFirstToken()"> /// </seealso> public virtual Token FirstToken { get { return first; } } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtGetParent()"> /// </seealso> /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtSetParent(NVelocity.Runtime.Paser.Node.Node)"> /// </seealso> public virtual INode Parent { get { return parent; } set { parent = value; } } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtAddChild(NVelocity.Runtime.Paser.Node.Node, int)"> /// </seealso> public virtual void AddChild(INode n, int i) { if (children == null) { children = new INode[i + 1]; } else if (i >= children.Length) { INode[] c = new INode[i + 1]; Array.Copy(children, 0, c, 0, children.Length); children = c; } children[i] = n; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtGetChild(int)"> /// </seealso> public virtual INode GetChild(int i) { return children[i]; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtGetNumChildren()"> /// </seealso> public virtual int GetNumChildren() { return (children == null) ? 0 : children.Length; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.jjtAccept(NVelocity.Runtime.Paser.Node.ParserVisitor, java.lang.Object)"> /// </seealso> public virtual object Accept(IParserVisitor visitor, object data) { return visitor.Visit(this, data); } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.childrenAccept(NVelocity.Runtime.Paser.Node.ParserVisitor, java.lang.Object)"> /// </seealso> public virtual object ChildrenAccept(IParserVisitor visitor, object data) { if (children != null) { for (int i = 0; i < children.Length; ++i) { children[i].Accept(visitor, data); } } return data; } /* You can override these two methods in subclasses of SimpleNode to customize the way the node appears when the tree is dumped. If your output uses more than one line you should override toString(String), otherwise overriding toString() is probably all you need to do. */ // public String toString() // { // return ParserTreeConstants.jjtNodeName[id]; // } /// <param name="prefix"> /// </param> /// <returns> String representation of this node. /// </returns> public virtual string ToString(string prefix) { return prefix + ToString(); } /// <summary> Override this method if you want to customize how the node dumps /// out its children. /// /// </summary> /// <param name="prefix"> /// </param> public virtual void Dump(string prefix) { if (children != null) { for (int i = 0; i < children.Length; ++i) { SimpleNode n = (SimpleNode)children[i]; if (n != null) { n.Dump(prefix + " "); } } } } /// <summary> Return a string that tells the current location of this node.</summary> protected internal virtual string GetLocation(IInternalContextAdapter context) { return Log.FormatFileString(this); } // All additional methods /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.literal()"> /// </seealso> public virtual string Literal { get { // if we have only one string, just return it and avoid // buffer allocation. VELOCITY-606 if (first == last) { return NodeUtils.TokenLiteral(first); } Token t = first; StringBuilder sb = new StringBuilder(NodeUtils.TokenLiteral(t)); while (t != last) { t = t.Next; sb.Append(NodeUtils.TokenLiteral(t)); } return sb.ToString(); } } /// <throws> TemplateInitException </throws> /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.Init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)"> /// </seealso> public virtual object Init(IInternalContextAdapter context, object data) { /* * hold onto the RuntimeServices */ rsvc = (IRuntimeServices)data; log = rsvc.Log; int i, k = GetNumChildren(); for (i = 0; i < k; i++) { GetChild(i).Init(context, data); } return data; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.Evaluate(org.apache.velocity.context.InternalContextAdapter)"> /// </seealso> public virtual bool Evaluate(IInternalContextAdapter context) { return false; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.value(org.apache.velocity.context.InternalContextAdapter)"> /// </seealso> public virtual object Value(IInternalContextAdapter context) { return null; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)"> /// </seealso> public virtual bool Render(IInternalContextAdapter context, System.IO.TextWriter writer) { int i, k = GetNumChildren(); for (i = 0; i < k; i++) GetChild(i).Render(context, writer); return true; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.Execute(java.lang.Object, org.apache.velocity.context.InternalContextAdapter)"> /// </seealso> public virtual object Execute(object o, IInternalContextAdapter context) { return null; } /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.setInvalid()"> /// </seealso> /// <seealso cref="NVelocity.Runtime.Paser.Node.Node.isInvalid()"> /// </seealso> public virtual bool IsInvalid { get { return invalid; } set { invalid = true; } } /// <since> 1.5 /// </since> public override string ToString() { StringBuilder tokens = new StringBuilder(); for (Token t = FirstToken; t != null; ) { tokens.Append("[").Append(t.Image).Append("]"); if (t.Next != null) { if (t.Equals(LastToken)) { break; } else { tokens.Append(", "); } } t = t.Next; } return new StringBuilder().AppendFormat("id:{0}", Type).AppendFormat("info:{0}", Info).AppendFormat("invalid:{0}", IsInvalid).AppendFormat("children:{0}", GetNumChildren()).AppendFormat("tokens:{0}", tokens).ToString(); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Semver; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Infrastructure.ModelsBuilder.Building; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded { [TestFixture] public class BuilderTests { [Test] public void GenerateSimpleType() { // Umbraco returns nice, pascal-cased names. var type1 = new TypeModel { Id = 1, Alias = "type1", ClrName = "Type1", Name = "type1Name", ParentId = 0, BaseType = null, ItemType = TypeModel.ItemTypes.Content, }; type1.Properties.Add(new PropertyModel { Alias = "prop1", ClrName = "Prop1", Name = "prop1Name", ModelClrType = typeof(string), }); TypeModel[] types = new[] { type1 }; var modelsBuilderConfig = new ModelsBuilderSettings(); var builder = new TextBuilder(modelsBuilderConfig, types); var sb = new StringBuilder(); builder.Generate(sb, builder.GetModelsToGenerate().First()); var gen = sb.ToString(); SemVersion version = ApiVersion.Current.Version; var expected = @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v" + version + @" // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { /// <summary>type1Name</summary> [PublishedModel(""type1"")] public partial class Type1 : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const string ModelTypeAlias = ""type1""; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<Type1, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public Type1(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties ///<summary> /// prop1Name ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] [ImplementPropertyType(""prop1"")] public virtual string Prop1 => this.Value<string>(_publishedValueFallback, ""prop1""); } } "; Console.WriteLine(gen); Assert.AreEqual(expected.ClearLf(), gen); } [Test] public void GenerateSimpleType_Ambiguous_Issue() { // Umbraco returns nice, pascal-cased names. var type1 = new TypeModel { Id = 1, Alias = "type1", ClrName = "Type1", ParentId = 0, BaseType = null, ItemType = TypeModel.ItemTypes.Content, }; type1.Properties.Add(new PropertyModel { Alias = "foo", ClrName = "Foo", ModelClrType = typeof(IEnumerable<>).MakeGenericType(ModelType.For("foo")), }); var type2 = new TypeModel { Id = 2, Alias = "foo", ClrName = "Foo", ParentId = 0, BaseType = null, ItemType = TypeModel.ItemTypes.Element, }; TypeModel[] types = new[] { type1, type2 }; var modelsBuilderConfig = new ModelsBuilderSettings(); var builder = new TextBuilder(modelsBuilderConfig, types) { ModelsNamespace = "Umbraco.Cms.Web.Common.PublishedModels" }; var sb1 = new StringBuilder(); builder.Generate(sb1, builder.GetModelsToGenerate().Skip(1).First()); var gen1 = sb1.ToString(); Console.WriteLine(gen1); var sb = new StringBuilder(); builder.Generate(sb, builder.GetModelsToGenerate().First()); var gen = sb.ToString(); SemVersion version = ApiVersion.Current.Version; var expected = @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v" + version + @" // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { [PublishedModel(""type1"")] public partial class Type1 : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const string ModelTypeAlias = ""type1""; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<Type1, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public Type1(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] [ImplementPropertyType(""foo"")] public virtual global::System.Collections.Generic.IEnumerable<global::" + modelsBuilderConfig.ModelsNamespace + @".Foo> Foo => this.Value<global::System.Collections.Generic.IEnumerable<global::" + modelsBuilderConfig.ModelsNamespace + @".Foo>>(_publishedValueFallback, ""foo""); } } "; Console.WriteLine(gen); Assert.AreEqual(expected.ClearLf(), gen); } [Test] public void GenerateAmbiguous() { var type1 = new TypeModel { Id = 1, Alias = "type1", ClrName = "Type1", ParentId = 0, BaseType = null, ItemType = TypeModel.ItemTypes.Content, IsMixin = true, }; type1.Properties.Add(new PropertyModel { Alias = "prop1", ClrName = "Prop1", ModelClrType = typeof(IPublishedContent), }); type1.Properties.Add(new PropertyModel { Alias = "prop2", ClrName = "Prop2", ModelClrType = typeof(StringBuilder), }); type1.Properties.Add(new PropertyModel { Alias = "prop3", ClrName = "Prop3", ModelClrType = typeof(global::Umbraco.Cms.Core.Exceptions.BootFailedException), }); TypeModel[] types = new[] { type1 }; var modelsBuilderConfig = new ModelsBuilderSettings(); var builder = new TextBuilder(modelsBuilderConfig, types) { ModelsNamespace = "Umbraco.ModelsBuilder.Models" // forces conflict with Umbraco.ModelsBuilder.Umbraco }; var sb = new StringBuilder(); foreach (TypeModel model in builder.GetModelsToGenerate()) { builder.Generate(sb, model); } var gen = sb.ToString(); Console.WriteLine(gen); Assert.IsTrue(gen.Contains(" global::Umbraco.Cms.Core.Models.PublishedContent.IPublishedContent Prop1")); Assert.IsTrue(gen.Contains(" global::System.Text.StringBuilder Prop2")); Assert.IsTrue(gen.Contains(" global::Umbraco.Cms.Core.Exceptions.BootFailedException Prop3")); } [Test] public void GenerateInheritedType() { var parentType = new TypeModel { Id = 1, Alias = "parentType", ClrName = "ParentType", Name = "parentTypeName", ParentId = 0, IsParent = true, BaseType = null, ItemType = TypeModel.ItemTypes.Content, }; parentType.Properties.Add(new PropertyModel { Alias = "prop1", ClrName = "Prop1", Name = "prop1Name", ModelClrType = typeof(string), }); var childType = new TypeModel { Id = 2, Alias = "childType", ClrName = "ChildType", Name = "childTypeName", ParentId = 1, BaseType = parentType, ItemType = TypeModel.ItemTypes.Content, }; TypeModel[] docTypes = new[] { parentType, childType }; var modelsBuilderConfig = new ModelsBuilderSettings(); var builder = new TextBuilder(modelsBuilderConfig, docTypes); var sb = new StringBuilder(); builder.Generate(sb, builder.GetModelsToGenerate().First()); var genParent = sb.ToString(); SemVersion version = ApiVersion.Current.Version; var expectedParent = @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v" + version + @" // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { /// <summary>parentTypeName</summary> [PublishedModel(""parentType"")] public partial class ParentType : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const string ModelTypeAlias = ""parentType""; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<ParentType, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public ParentType(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties ///<summary> /// prop1Name ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] [ImplementPropertyType(""prop1"")] public virtual string Prop1 => this.Value<string>(_publishedValueFallback, ""prop1""); } } "; Console.WriteLine(genParent); Assert.AreEqual(expectedParent.ClearLf(), genParent); var sb2 = new StringBuilder(); builder.Generate(sb2, builder.GetModelsToGenerate().Skip(1).First()); var genChild = sb2.ToString(); var expectedChild = @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v" + version + @" // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { /// <summary>childTypeName</summary> [PublishedModel(""childType"")] public partial class ChildType : ParentType { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const string ModelTypeAlias = ""childType""; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<ChildType, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public ChildType(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties } } "; Console.WriteLine(genChild); Assert.AreEqual(expectedChild.ClearLf(), genChild); } [Test] public void GenerateComposedType() { // Umbraco returns nice, pascal-cased names. var composition1 = new TypeModel { Id = 2, Alias = "composition1", ClrName = "Composition1", Name = "composition1Name", ParentId = 0, BaseType = null, ItemType = TypeModel.ItemTypes.Content, IsMixin = true, }; composition1.Properties.Add(new PropertyModel { Alias = "compositionProp", ClrName = "CompositionProp", Name = "compositionPropName", ModelClrType = typeof(string), ClrTypeName = typeof(string).FullName }); var type1 = new TypeModel { Id = 1, Alias = "type1", ClrName = "Type1", Name = "type1Name", ParentId = 0, BaseType = null, ItemType = TypeModel.ItemTypes.Content, }; type1.Properties.Add(new PropertyModel { Alias = "prop1", ClrName = "Prop1", Name = "prop1Name", ModelClrType = typeof(string), }); type1.MixinTypes.Add(composition1); TypeModel[] types = new[] { type1, composition1 }; var modelsBuilderConfig = new ModelsBuilderSettings(); var builder = new TextBuilder(modelsBuilderConfig, types); SemVersion version = ApiVersion.Current.Version; var sb = new StringBuilder(); builder.Generate(sb, builder.GetModelsToGenerate().First()); var genComposed = sb.ToString(); var expectedComposed = @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v" + version + @" // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { /// <summary>type1Name</summary> [PublishedModel(""type1"")] public partial class Type1 : PublishedContentModel, IComposition1 { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const string ModelTypeAlias = ""type1""; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<Type1, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public Type1(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties ///<summary> /// prop1Name ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] [ImplementPropertyType(""prop1"")] public virtual string Prop1 => this.Value<string>(_publishedValueFallback, ""prop1""); ///<summary> /// compositionPropName ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] [ImplementPropertyType(""compositionProp"")] public virtual string CompositionProp => global::Umbraco.Cms.Web.Common.PublishedModels.Composition1.GetCompositionProp(this, _publishedValueFallback); } } "; Console.WriteLine(genComposed); Assert.AreEqual(expectedComposed.ClearLf(), genComposed); var sb2 = new StringBuilder(); builder.Generate(sb2, builder.GetModelsToGenerate().Skip(1).First()); var genComposition = sb2.ToString(); var expectedComposition = @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder.Embedded v" + version + @" // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq.Expressions; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Infrastructure.ModelsBuilder; using Umbraco.Cms.Core; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.PublishedModels { // Mixin Content Type with alias ""composition1"" /// <summary>composition1Name</summary> public partial interface IComposition1 : IPublishedContent { /// <summary>compositionPropName</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] string CompositionProp { get; } } /// <summary>composition1Name</summary> [PublishedModel(""composition1"")] public partial class Composition1 : PublishedContentModel, IComposition1 { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const string ModelTypeAlias = ""composition1""; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public new static IPublishedContentType GetModelContentType(IPublishedSnapshotAccessor publishedSnapshotAccessor) => PublishedModelUtility.GetModelContentType(publishedSnapshotAccessor, ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static IPublishedPropertyType GetModelPropertyType<TValue>(IPublishedSnapshotAccessor publishedSnapshotAccessor, Expression<Func<Composition1, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(publishedSnapshotAccessor), selector); #pragma warning restore 0109 private IPublishedValueFallback _publishedValueFallback; // ctor public Composition1(IPublishedContent content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback) { _publishedValueFallback = publishedValueFallback; } // properties ///<summary> /// compositionPropName ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [global::System.Diagnostics.CodeAnalysis.MaybeNull] [ImplementPropertyType(""compositionProp"")] public virtual string CompositionProp => GetCompositionProp(this, _publishedValueFallback); /// <summary>Static getter for compositionPropName</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""Umbraco.ModelsBuilder.Embedded"", """ + version + @""")] [return: global::System.Diagnostics.CodeAnalysis.MaybeNull] public static string GetCompositionProp(IComposition1 that, IPublishedValueFallback publishedValueFallback) => that.Value<string>(publishedValueFallback, ""compositionProp""); } } "; Console.WriteLine(genComposition); Assert.AreEqual(expectedComposition.ClearLf(), genComposition); } [TestCase("int", typeof(int))] [TestCase("global::System.Collections.Generic.IEnumerable<int>", typeof(IEnumerable<int>))] [TestCase("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.BuilderTestsClass1", typeof(BuilderTestsClass1))] [TestCase("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.BuilderTests.Class1", typeof(Class1))] public void WriteClrType(string expected, Type input) { // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things var builder = new TextBuilder { ModelsNamespaceForTests = "ModelsNamespace" }; var sb = new StringBuilder(); builder.WriteClrType(sb, input); Assert.AreEqual(expected, sb.ToString()); } [TestCase("int", typeof(int))] [TestCase("global::System.Collections.Generic.IEnumerable<int>", typeof(IEnumerable<int>))] [TestCase("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.BuilderTestsClass1", typeof(BuilderTestsClass1))] [TestCase("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.BuilderTests.Class1", typeof(Class1))] public void WriteClrTypeUsing(string expected, Type input) { // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things var builder = new TextBuilder(); builder.Using.Add("Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder"); builder.ModelsNamespaceForTests = "ModelsNamespace"; var sb = new StringBuilder(); builder.WriteClrType(sb, input); Assert.AreEqual(expected, sb.ToString()); } [Test] public void WriteClrType_WithUsing() { var builder = new TextBuilder(); builder.Using.Add("System.Text"); builder.ModelsNamespaceForTests = "Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Models"; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(StringBuilder)); // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things Assert.AreEqual("global::System.Text.StringBuilder", sb.ToString()); } [Test] public void WriteClrTypeAnother_WithoutUsing() { var builder = new TextBuilder { ModelsNamespaceForTests = "Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Models" }; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(StringBuilder)); Assert.AreEqual("global::System.Text.StringBuilder", sb.ToString()); } [Test] public void WriteClrType_Ambiguous1() { var builder = new TextBuilder(); builder.Using.Add("System.Text"); builder.Using.Add("Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded"); builder.ModelsNamespaceForTests = "SomeRandomNamespace"; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(global::System.Text.ASCIIEncoding)); // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things Assert.AreEqual("global::System.Text.ASCIIEncoding", sb.ToString()); } [Test] public void WriteClrType_Ambiguous() { var builder = new TextBuilder(); builder.Using.Add("System.Text"); builder.Using.Add("Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded"); builder.ModelsNamespaceForTests = "SomeBorkedNamespace"; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(global::System.Text.ASCIIEncoding)); // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things Assert.AreEqual("global::System.Text.ASCIIEncoding", sb.ToString()); } [Test] public void WriteClrType_Ambiguous2() { var builder = new TextBuilder(); builder.Using.Add("System.Text"); builder.Using.Add("Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded"); builder.ModelsNamespaceForTests = "SomeRandomNamespace"; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(ASCIIEncoding)); // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things Assert.AreEqual("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.ASCIIEncoding", sb.ToString()); } [Test] public void WriteClrType_AmbiguousNot() { var builder = new TextBuilder(); builder.Using.Add("System.Text"); builder.Using.Add("Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded"); builder.ModelsNamespaceForTests = "Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Models"; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(ASCIIEncoding)); // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things Assert.AreEqual("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.ASCIIEncoding", sb.ToString()); } [Test] public void WriteClrType_AmbiguousWithNested() { var builder = new TextBuilder(); builder.Using.Add("System.Text"); builder.Using.Add("Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded"); builder.ModelsNamespaceForTests = "SomeRandomNamespace"; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(ASCIIEncoding.Nested)); // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things Assert.AreEqual("global::Umbraco.Cms.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.ASCIIEncoding.Nested", sb.ToString()); } public class Class1 { } } // make it public to be ambiguous (see above) public class ASCIIEncoding { // can we handle nested types? public class Nested { } } public class BuilderTestsClass1 { } public class System { } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; namespace ColorRamps { public class Form2 : System.Windows.Forms.Form { private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.ComponentModel.Container components = null; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private ESRI.ArcGIS.Controls.AxSymbologyControl axSymbologyControl1; private IClassBreaksRenderer m_classBreaksRenderer; private IStyleGalleryItem m_styleGalleryItem; private IFeatureLayer m_featureLayer; public Form2() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form2)); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.axSymbologyControl1 = new ESRI.ArcGIS.Controls.AxSymbologyControl(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axSymbologyControl1)).BeginInit(); this.SuspendLayout(); // // comboBox1 // this.comboBox1.Location = new System.Drawing.Point(16, 56); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(168, 21); this.comboBox1.TabIndex = 0; this.comboBox1.Text = "comboBox1"; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.comboBox1); this.groupBox1.Location = new System.Drawing.Point(304, 24); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(232, 100); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "FeatureLayer"; // // label1 // this.label1.Location = new System.Drawing.Point(16, 32); this.label1.Name = "label1"; this.label1.TabIndex = 1; this.label1.Text = "Numeric Fields:"; // // groupBox2 // this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.textBox3); this.groupBox2.Controls.Add(this.textBox2); this.groupBox2.Controls.Add(this.textBox1); this.groupBox2.Location = new System.Drawing.Point(304, 128); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(232, 128); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "Break"; // // label4 // this.label4.Location = new System.Drawing.Point(8, 96); this.label4.Name = "label4"; this.label4.TabIndex = 7; this.label4.Text = "Max Value:"; // // label3 // this.label3.Location = new System.Drawing.Point(8, 64); this.label3.Name = "label3"; this.label3.TabIndex = 6; this.label3.Text = "Min Value:"; // // label2 // this.label2.Location = new System.Drawing.Point(8, 32); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(104, 23); this.label2.TabIndex = 5; this.label2.Text = "Number of Classes:"; // // textBox3 // this.textBox3.Enabled = false; this.textBox3.Location = new System.Drawing.Point(120, 96); this.textBox3.Name = "textBox3"; this.textBox3.TabIndex = 4; this.textBox3.Text = ""; // // textBox2 // this.textBox2.Enabled = false; this.textBox2.Location = new System.Drawing.Point(120, 64); this.textBox2.Name = "textBox2"; this.textBox2.TabIndex = 3; this.textBox2.Text = ""; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(120, 32); this.textBox1.Name = "textBox1"; this.textBox1.TabIndex = 2; this.textBox1.Text = ""; this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave); // // groupBox3 // this.groupBox3.Controls.Add(this.axSymbologyControl1); this.groupBox3.Location = new System.Drawing.Point(8, 8); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(288, 288); this.groupBox3.TabIndex = 3; this.groupBox3.TabStop = false; this.groupBox3.Text = "Symbology"; // // axSymbologyControl1 // this.axSymbologyControl1.ContainingControl = this; this.axSymbologyControl1.Location = new System.Drawing.Point(8, 16); this.axSymbologyControl1.Name = "axSymbologyControl1"; this.axSymbologyControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axSymbologyControl1.OcxState"))); this.axSymbologyControl1.Size = new System.Drawing.Size(272, 265); this.axSymbologyControl1.TabIndex = 0; this.axSymbologyControl1.OnItemSelected += new ESRI.ArcGIS.Controls.ISymbologyControlEvents_Ax_OnItemSelectedEventHandler(this.axSymbologyControl1_OnItemSelected); // // button2 // this.button2.Location = new System.Drawing.Point(384, 264); this.button2.Name = "button2"; this.button2.TabIndex = 3; this.button2.Text = "OK"; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(464, 264); this.button3.Name = "button3"; this.button3.TabIndex = 4; this.button3.Text = "Cancel"; this.button3.Click += new System.EventHandler(this.button3_Click); // // Form2 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(546, 304); this.Controls.Add(this.button3); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox2); this.Controls.Add(this.button2); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "Form2"; this.Text = "Class Breaks Renderer"; this.Load += new System.EventHandler(this.Form3_Load); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axSymbologyControl1)).EndInit(); this.ResumeLayout(false); } #endregion private void Form3_Load(object sender, System.EventArgs e) { //Get the ArcGIS install location string sInstall = ESRI.ArcGIS.RuntimeManager.ActiveRuntime.Path; //Load the ESRI.ServerStyle file into the SymbologyControl axSymbologyControl1.LoadStyleFile(sInstall + "\\Styles\\ESRI.ServerStyle"); //Set the style class axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassColorRamps; //Select the color ramp item axSymbologyControl1.GetStyleClass(axSymbologyControl1.StyleClass).SelectItem(0); } private void button2_Click(object sender, System.EventArgs e) { //Create a new ClassBreaksRenderer and set properties m_classBreaksRenderer = new ClassBreaksRenderer(); m_classBreaksRenderer.Field = comboBox1.SelectedItem.ToString(); m_classBreaksRenderer.BreakCount = Convert.ToInt32(textBox1.Text); m_classBreaksRenderer.MinimumBreak = Convert.ToDouble(textBox2.Text); //Calculate the class interval by a simple mean value double interval = (Convert.ToDouble(textBox3.Text) - m_classBreaksRenderer.MinimumBreak) / m_classBreaksRenderer.BreakCount; //Get the color ramp IColorRamp colorRamp = (IColorRamp) m_styleGalleryItem.Item; //Set the size of the color ramp and recreate it colorRamp.Size = Convert.ToInt32(textBox1.Text); bool createRamp; colorRamp.CreateRamp(out createRamp); //Get the enumeration of colors from the color ramp IEnumColors enumColors = colorRamp.Colors; enumColors.Reset(); double currentBreak = m_classBreaksRenderer.MinimumBreak; ISimpleFillSymbol simpleFillSymbol; //Loop through each class break for (int i = 0; i <= m_classBreaksRenderer.BreakCount-1; i++) { //Set class break m_classBreaksRenderer.set_Break(i,currentBreak); //Create simple fill symbol and set color simpleFillSymbol = new SimpleFillSymbolClass(); simpleFillSymbol.Color = enumColors.Next(); //Add symbol to renderer m_classBreaksRenderer.set_Symbol(i, (ISymbol)simpleFillSymbol); currentBreak += interval; } //Hide the form this.Hide(); } private void button3_Click(object sender, System.EventArgs e) { this.Hide(); } private void textBox1_Leave(object sender, System.EventArgs e) { IColorRamp colorRamp = (IColorRamp) m_styleGalleryItem.Item; //Ensure is numeric if (IsInteger(textBox1.Text) == false) { System.Windows.Forms.MessageBox.Show("Must be a numeric!"); textBox1.Text = "10"; return; } else if (Convert.ToInt32(textBox1.Text) <= 0) { //Ensure is not zero System.Windows.Forms.MessageBox.Show("Must be greater than 0!"); textBox1.Text = "10"; return; } else if (Convert.ToInt32(textBox1.Text) > colorRamp.Size) { //Ensure does not exceed number of colors in color ramp System.Windows.Forms.MessageBox.Show("Must be less than " + colorRamp.Size + "!"); textBox1.Text = "10"; return; } } private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e) { //Find the selected field in the feature layer IFeatureClass featureClass = m_featureLayer.FeatureClass; IField field = featureClass.Fields.get_Field(featureClass.FindField(comboBox1.Text)); //Get a feature cursor ICursor cursor = (ICursor) m_featureLayer.Search(null, false); //Create a DataStatistics object and initialize properties IDataStatistics dataStatistics = new DataStatisticsClass(); dataStatistics.Field = field.Name; dataStatistics.Cursor = cursor; //Get the result statistics IStatisticsResults statisticsResults = dataStatistics.Statistics; //Set the values min and max values textBox2.Text = statisticsResults.Minimum.ToString(); textBox3.Text = statisticsResults.Maximum.ToString(); textBox1.Text = "10"; } public IClassBreaksRenderer GetClassBreaksRenderer(IFeatureLayer featureLayer) { m_featureLayer = featureLayer; comboBox1.Items.Clear(); //Add numeric fields names to the combobox IFields fields = m_featureLayer.FeatureClass.Fields; for (int i = 0; i<=fields.FieldCount-1; i++) { if ((fields.get_Field(i).Type == esriFieldType.esriFieldTypeDouble) || (fields.get_Field(i).Type == esriFieldType.esriFieldTypeInteger) || (fields.get_Field(i).Type == esriFieldType.esriFieldTypeSingle) || (fields.get_Field(i).Type == esriFieldType.esriFieldTypeSmallInteger) ) { comboBox1.Items.Add(fields.get_Field(i).Name); } } comboBox1.SelectedIndex = 0; //Show form modally and wait for user input this.ShowDialog(); //Return the ClassBreaksRenderer return m_classBreaksRenderer; } private void axSymbologyControl1_OnItemSelected(object sender, ESRI.ArcGIS.Controls.ISymbologyControlEvents_OnItemSelectedEvent e) { //Get the selected item m_styleGalleryItem = (IStyleGalleryItem) e.styleGalleryItem; } public bool IsInteger(string s) { try { Int32.Parse(s); } catch { return false; } return true; } } }
using System; using System.Text.RegularExpressions; using System.IO; using System.Reflection; using System.Timers; using System.Net.NetworkInformation; using System.Drawing; using System.Windows.Forms; using tsonamu; namespace tsonamu { class MainClass { public static NotifyIcon tray; public static System.Timers.Timer WriteWithDelay (String[] texts, double delay = 1) { Console.WriteLine(texts[0]); int i = 1; int p = texts.Length; System.Timers.Timer delaytimer = new System.Timers.Timer (delay * 1000); delaytimer.AutoReset = true; delaytimer.Elapsed += (object sender, ElapsedEventArgs e) => { if(i < p) { Console.WriteLine(texts[i]); i++; } else { delaytimer.Stop(); return; } }; delaytimer.Start (); return delaytimer; } public static string TimeInBrackets() { string returnvalue = "[" + DateTime.Now.ToString ("HH:mm:ss") + "]"; return returnvalue; } public static System.Timers.Timer monitorStatus(string hostname, string filename, bool log = true, double delay = 1) { LogWriter Logger = new LogWriter (filename); bool connection = true; int last_ping = 50; if (log == true) { Logger.LogText ("[" + DateTime.Now.ToString ("yyyy-MM-dd") + "] " + hostname, true); } ConsoleColor defaultcolor = Console.ForegroundColor; System.Timers.Timer monitortimer = new System.Timers.Timer (delay * 1000); monitortimer.AutoReset = true; monitortimer.Elapsed += (object sender, ElapsedEventArgs e) => { Ping pinging = new Ping (); try { PingReply pingstatus = pinging.Send (hostname); if(pingstatus.Status != IPStatus.Success) { throw(new Exception("Ping unsuccessful!")); } Console.WriteLine (TimeInBrackets () + " " + pingstatus.Status.ToString () + ": " + pingstatus.RoundtripTime.ToString () + "ms"); if(log == true) { Logger.LogText (TimeInBrackets () + " " + pingstatus.Status.ToString () + ": " + pingstatus.RoundtripTime.ToString () + "ms", true); } if(connection == false) { tray.BalloonTipTitle = "tsonamu"; tray.BalloonTipText = "Internet connection re-established!"; tray.BalloonTipIcon = ToolTipIcon.Info; tray.ShowBalloonTip(5000); connection = true; } if((pingstatus.RoundtripTime / last_ping) > 4 && last_ping > 250) { tray.BalloonTipTitle = "tsonamu"; tray.BalloonTipText = "Dramatic ping increase!"; tray.BalloonTipIcon = ToolTipIcon.Warning; tray.ShowBalloonTip(5000); } if((pingstatus.RoundtripTime / last_ping) > 4 && last_ping > 250) { tray.BalloonTipTitle = "tsonamu"; tray.BalloonTipText = "Ping has returned to normal!"; tray.BalloonTipIcon = ToolTipIcon.Info; tray.ShowBalloonTip(5000); } } catch { Console.ForegroundColor = ConsoleColor.Red; if (Uri.CheckHostName (hostname) == UriHostNameType.Unknown) { Console.WriteLine (TimeInBrackets () + " Can't resolve hostname: " + hostname); if(log == true) { Logger.LogText(TimeInBrackets () + " DNS", true); } } else { Console.WriteLine (TimeInBrackets () + " Error!"); if(log == true) { Logger.LogText(TimeInBrackets () + " ERR", true); } } if(connection == true) { tray.BalloonTipTitle = "tsonamu"; tray.BalloonTipText = "Internet connection was lost!"; tray.BalloonTipIcon = ToolTipIcon.Error; tray.ShowBalloonTip(5000); connection = false; } Console.ForegroundColor = defaultcolor; } }; monitortimer.Start (); return monitortimer; } public static void Main (string[] args) { tray = new NotifyIcon(); Icon appicon = Icon.ExtractAssociatedIcon (Assembly.GetExecutingAssembly ().Location); tray.Icon = appicon; tray.Visible = true; string hostname = "google.com"; bool log = true; if (args.Length != 0) { string arguments = string.Join (" ", args, 0, args.Length); Regex regexHelp = new Regex(@"/\?"); Match matchHelp = regexHelp.Match (arguments); if (matchHelp.Success) { Console.WriteLine ("tsonamu: the simplest of network availability monitorung utilities\n\nUsage:\n\ntsonamu.exe [-hostname url] [-nolog]\n\n-hostname Hostname This URL will be used to test internet connection. You can use any valid URL.\n-nolog Do not log The results will be printed to the console, but not saved to a text file."); return; } Regex regexHostname = new Regex("(?<=-hostname )(.*\\.[a-zA-Z]*)"); Match matchHostname = regexHostname.Match(arguments); if (matchHostname.Success) { hostname = matchHostname.Value; } Regex regexLog = new Regex("(-nolog)"); Match matchLog = regexLog.Match(arguments); if (matchLog.Success) { log = false; } } DirectoryInfo outputpath; if (args.Length != 0 && Directory.Exists (args [0].ToString ())) { outputpath = new DirectoryInfo (args [0].ToString ()); } else { outputpath = new DirectoryInfo (Directory.GetCurrentDirectory ()); } string logfile = outputpath.ToString () + "/tsonamu_log_" + DateTime.Now.ToString ("yyyy-MM-dd-HH-mm-ss") + ".txt"; System.Timers.Timer writingtimer1 = WriteWithDelay (new string[] { "Welcome to TSONAMU!", "Loading secret libraries...", "Hiding critical evidence...", "Poisoning witnesses...\n", "OTACON: Snake, TSONAMU is ready to fire!", " \n \n TSONAMU \n \n ox oo\n xx-----ox-----ox\n xx-----xx-----ox\n xx II ox\n II \n II \n II \n II \n oooo \n ooxx \n\n", "Press the return key to stop the program!\n\n" }, 0.5); while (writingtimer1.Enabled) { } //FileStream out_strm = new FileStream (outputpath.ToString () + "/tsonamu_log_" + DateTime.Now.ToString ("yyyy-MM-dd-HH-mm-ss") + ".txt", FileMode.OpenOrCreate, FileAccess.Write); //StreamWriter out_wrtr = new StreamWriter (out_strm); //Console.SetOut (out_wrtr); Console.WriteLine ("[" + DateTime.Now.ToString ("HH:mm:ss") + "] Observation started!"); if (log == true) { monitorStatus (hostname, logfile, true, 5); } else { monitorStatus (hostname, logfile, false, 5); } Console.ReadLine (); tray.Visible = false; tray.Dispose (); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; using Pathfinding.Util; using Pathfinding.Serialization.JsonFx; namespace Pathfinding { /** A class for holding a user placed connection */ public class UserConnection { public Vector3 p1; public Vector3 p2; public ConnectionType type; //Connection [JsonName("doOverCost")] public bool doOverrideCost = false; [JsonName("overCost")] public int overrideCost = 0; public bool oneWay = false; public bool enable = true; public float width = 0; //Modify Node [JsonName("doOverWalkable")] public bool doOverrideWalkability = true; [JsonName("doOverCost")] public bool doOverridePenalty = false; [JsonName("overPenalty")] public uint overridePenalty = 0; } [System.Serializable] /** Stores editor colors */ public class AstarColor { public Color _NodeConnection; public Color _UnwalkableNode; public Color _BoundsHandles; public Color _ConnectionLowLerp; public Color _ConnectionHighLerp; public Color _MeshEdgeColor; public Color _MeshColor; /** Holds user set area colors. * Use GetAreaColor to get an area color */ public Color[] _AreaColors; public static Color NodeConnection = new Color (1,1,1,0.9F); public static Color UnwalkableNode = new Color (1,0,0,0.5F); public static Color BoundsHandles = new Color (0.29F,0.454F,0.741F,0.9F); public static Color ConnectionLowLerp = new Color (0,1,0,0.5F); public static Color ConnectionHighLerp = new Color (1,0,0,0.5F); public static Color MeshEdgeColor = new Color (0,0,0,0.5F); public static Color MeshColor = new Color (0,0,0,0.5F); /** Holds user set area colors. * Use GetAreaColor to get an area color */ private static Color[] AreaColors; /** Returns an color for an area, uses both user set ones and calculated. * If the user has set a color for the area, it is used, but otherwise the color is calculated using Mathfx.IntToColor * \see #AreaColors */ public static Color GetAreaColor (int area) { if (AreaColors == null || area >= AreaColors.Length) { return Mathfx.IntToColor (area,1F); } return AreaColors[area]; } /** Pushes all local variables out to static ones */ public void OnEnable () { NodeConnection = _NodeConnection; UnwalkableNode = _UnwalkableNode; BoundsHandles = _BoundsHandles; ConnectionLowLerp = _ConnectionLowLerp; ConnectionHighLerp = _ConnectionHighLerp; MeshEdgeColor = _MeshEdgeColor; MeshColor = _MeshColor; AreaColors = _AreaColors; } public AstarColor () { _NodeConnection = new Color (1,1,1,0.9F); _UnwalkableNode = new Color (1,0,0,0.5F); _BoundsHandles = new Color (0.29F,0.454F,0.741F,0.9F); _ConnectionLowLerp = new Color (0,1,0,0.5F); _ConnectionHighLerp = new Color (1,0,0,0.5F); _MeshEdgeColor = new Color (0,0,0,0.5F); _MeshColor = new Color (0.125F, 0.686F, 0, 0.19F); } //new Color (0.909F,0.937F,0.243F,0.6F); } /** Returned by graph ray- or linecasts containing info about the hit. This will only be set up if something was hit. */ public struct GraphHitInfo { public Vector3 origin; public Vector3 point; public Node node; public Vector3 tangentOrigin; public Vector3 tangent; public bool success; public float distance { get { return (point-origin).magnitude; } } public GraphHitInfo (Vector3 point) { success = false; tangentOrigin = Vector3.zero; origin = Vector3.zero; this.point = point; node = null; tangent = Vector3.zero; //this.distance = distance; } } /** Nearest node constraint. Constrains which nodes will be returned by the GetNearest function */ public class NNConstraint { /** Graphs treated as valid to search on. * This is a bitmask meaning that bit 0 specifies whether or not the first graph in the graphs list should be able to be included in the search, * bit 1 specifies whether or not the second graph should be included and so on. * \code * //Enables the first and third graphs to be included, but not the rest * myNNConstraint.graphMask = (1 << 0) | (1 << 2); * \endcode * \note This does only affect which nodes are returned from a GetNearest call, if an invalid graph is linked to from a valid graph, it might be searched anyway. * * \see AstarPath.GetNearest */ public int graphMask = -1; public bool constrainArea = false; /**< Only treat nodes in the area #area as suitable. Does not affect anything if #area is less than 0 (zero) */ public int area = -1; /**< Area ID to constrain to. Will not affect anything if less than 0 (zero) or if #constrainArea is false */ public bool constrainWalkability = true; /**< Only treat nodes with the walkable flag set to the same as #walkable as suitable */ public bool walkable = true; /**< What must the walkable flag on a node be for it to be suitable. Does not affect anything if #constrainWalkability if false */ public bool constrainTags = true; /**< Sets if tags should be constrained */ public int tags = -1; /**< Nodes which have any of these tags set are suitable. This is a bitmask, i.e bit 0 indicates that tag 0 is good, bit 3 indicates tag 3 is good etc. */ /** Constrain distance to node. * Uses distance from AstarPath.maxNearestNodeDistance. * If this is false, it will completely ignore the distance limit. * \note This value is not used in this class, it is used by the AstarPath.GetNearest function. */ public bool constrainDistance = true; /** Returns whether or not the graph conforms to this NNConstraint's rules. */ public virtual bool SuitableGraph (int graphIndex, NavGraph graph) { return ((graphMask >> graphIndex) & 1) != 0; } /** Returns whether or not the node conforms to this NNConstraint's rules */ public virtual bool Suitable (Node node) { if (constrainWalkability && node.walkable != walkable) return false; if (constrainArea && area >= 0 && node.area != area) return false; #if ConfigureTagsAsMultiple if (constrainTags && (tags & node.tags) == 0) return false; #else if (constrainTags && (tags >> node.tags & 0x1) == 0) return false; #endif return true; } /** The default NNConstraint. * Equivalent to new NNConstraint (). * This NNConstraint has settings which works for most, it only finds walkable nodes * and it constrains distance set by A* Inspector -> Settings -> Max Nearest Node Distance */ public static NNConstraint Default { get { return new NNConstraint (); } } /** Returns a constraint which will not filter the results */ public static NNConstraint None { get { NNConstraint n = new NNConstraint (); n.constrainWalkability = false; n.constrainArea = false; n.constrainTags = false; n.constrainDistance = false; n.graphMask = -1; return n; } } /** Default constructor. Equals to the property #Default */ public NNConstraint () { } } /** A special NNConstraint which can use different logic for the start node and end node in a path. * A PathNNConstraint can be assigned to the Path.nnConstraint field, the path will first search for the start node, then it will call #SetStart and proceed with searching for the end node (nodes in the case of a MultiTargetPath).\n * The default PathNNConstraint will constrain the end point to lie inside the same area as the start point. */ public class PathNNConstraint : NNConstraint { public static new PathNNConstraint Default { get { PathNNConstraint n = new PathNNConstraint (); n.constrainArea = true; return n; } } /** Called after the start node has been found. This is used to get different search logic for the start and end nodes in a path */ public virtual void SetStart (Node node) { if (node != null) { area = node.area; } else { constrainArea = false; } } } public struct NNInfo { /** Closest node found. * This node is not necessarily accepted by any NNConstraint passed. * \see constrainedNode */ public Node node; /** Optional to be filled in. * If the search will be able to find the constrained node without any extra effort it can fill it in. */ public Node constrainedNode; /** The position clamped to the closest point on the #node. */ public Vector3 clampedPosition; /** Clamped position for the optional constrainedNode */ public Vector3 constClampedPosition; public NNInfo (Node node) { this.node = node; constrainedNode = null; constClampedPosition = Vector3.zero; if (node != null) { clampedPosition = (Vector3)node.position; } else { clampedPosition = Vector3.zero; } } /** Sets the constrained node */ public void SetConstrained (Node constrainedNode, Vector3 clampedPosition) { this.constrainedNode = constrainedNode; constClampedPosition = clampedPosition; } /** Updates #clampedPosition and #constClampedPosition from node positions */ public void UpdateInfo () { if (node != null) { clampedPosition = (Vector3)node.position; } else { clampedPosition = Vector3.zero; } if (constrainedNode != null) { constClampedPosition = (Vector3)constrainedNode.position; } else { constClampedPosition = Vector3.zero; } } public static explicit operator Vector3 (NNInfo ob) { return ob.clampedPosition; } public static explicit operator Node (NNInfo ob) { return ob.node; } public static explicit operator NNInfo (Node ob) { return new NNInfo (ob); } } /** Progress info for e.g a progressbar. * Used by the scan functions in the project * \see AstarPath.ScanLoop */ public struct Progress { public float progress; public string description; public Progress (float p, string d) { progress = p; description = d; } } /** Graphs which can be updated during runtime */ public interface IUpdatableGraph { /** Updates an area using the specified GraphUpdateObject. * * Notes to implementators. * This function should (in order): * -# Call o.WillUpdateNode on the GUO for every node it will update, it is important that this is called BEFORE any changes are made to the nodes. * -# Update walkabilty using special settings such as the usePhysics flag used with the GridGraph. * -# Call Apply on the GUO for every node which should be updated with the GUO. * -# Update eventual connectivity info if appropriate (GridGraphs updates connectivity, but most other graphs don't since then the connectivity cannot be recovered later). */ void UpdateArea (GraphUpdateObject o); } [System.Serializable] /** Holds a tagmask. * This is used to store which tags to change and what to set them to in a Pathfinding.GraphUpdateObject. * All variables are bitmasks.\n * I wanted to make it a struct, but due to technical limitations when working with Unity's GenericMenu, I couldn't. * So be wary of this when passing it as it will be passed by reference, not by value as e.g LayerMask. */ public class TagMask { public int tagsChange; public int tagsSet; public TagMask () {} public TagMask (int change, int set) { tagsChange = change; tagsSet = set; } public void SetValues (System.Object boxedTagMask) { TagMask o = (TagMask)boxedTagMask; tagsChange = o.tagsChange; tagsSet = o.tagsSet; //Debug.Log ("Set tags to "+tagsChange +" "+tagsSet+" "+someVar); } public override string ToString () { return ""+System.Convert.ToString (tagsChange,2)+"\n"+System.Convert.ToString (tagsSet,2); } } /** Represents a collection of settings used to update nodes in a specific area of a graph. * \see AstarPath.UpdateGraphs */ public class GraphUpdateObject { /** The bounds to update nodes within */ public Bounds bounds; /** Performance boost. * This controlls if a flood fill will be carried out after this GUO has been applied.\n * If you are sure that a GUO will not modify walkability or connections. You can set this to false. * For example when only updating penalty values it can save processing power when setting this to false. Especially on large graphs. * \note If you set this to false, even though it does change e.g walkability, it can lead to paths returning that they failed even though there is a path, * or the try to search the whole graph for a path even though there is none, and will in the processes use wast amounts of processing power. * * If using the basic GraphUpdateObject (not a derived class), a quick way to check if it is going to need a flood fill is to check if #modifyWalkability is true or #updatePhysics is true. * */ public bool requiresFloodFill = true; /** Use physics checks to update nodes. * When updating a grid graph and this is true, the nodes' position and walkability will be updated using physics checks * with settings from "Collision Testing" and "Height Testing". * Also when updating a PointGraph, setting this to true will make it re-evaluate all connections in the graph which passes through the #bounds. * This has no effect when updating GridGraphs if #modifyWalkability is turned on */ public bool updatePhysics = true; /** When #updatePhysics is true, GridGraphs will normally reset penalties, with this option you can override it. * Good to use when you want to keep old penalties even when you update the graph. * * The images below shows two overlapping graph update objects, the right one happened to be applied before the left one. They both have updatePhysics = true and are * set to increase the penalty of the nodes by some amount. * * The first image shows the result when resetPenaltyOnPhysics is false. Both penalties are added correctly. * \shadowimage{resetPenaltyOnPhysics_False.png} * * This second image shows when resetPenaltyOnPhysics is set to true. The first GUO is applied correctly, but then the second one (the left one) is applied * and during its updating, it resets the penalties first and then adds penalty to the nodes. The result is that the penalties from both GUOs are not added together. * The green patch in at the border is there because physics recalculation (recalculation of the position of the node, checking for obstacles etc.) affects a slightly larger * area than the original GUO bounds because of the Grid Graph -> Collision Testing -> Diameter setting (it is enlarged by that value). So some extra nodes have their penalties reset. * * \shadowimage{resetPenaltyOnPhysics_True.png} */ public bool resetPenaltyOnPhysics = true; /** Update Erosion for GridGraphs. * When enabled, erosion will be recalculated for grid graphs * after the GUO has been applied. * * In the below image you can see the different effects you can get with the different values.\n * The first image shows the graph when no GUO has been applied. The blue box is not identified as an obstacle by the graph, the reason * there are unwalkable nodes around it is because there is a height difference (nodes are placed on top of the box) so erosion will be applied (an erosion value of 2 is used in this graph). * The orange box is identified as an obstacle, so the area of unwalkable nodes around it is a bit larger since both erosion and collision has made * nodes unwalkable.\n * The GUO used simply sets walkability to true, i.e making all nodes walkable. * * \shadowimage{updateErosion.png} * * When updateErosion=True, the reason the blue box still has unwalkable nodes around it is because there is still a height difference * so erosion will still be applied. The orange box on the other hand has no height difference and all nodes are set to walkable.\n * \n * When updateErosion=False, all nodes walkability are simply set to be walkable in this example. * * \see Pathfinding.GridGraph */ public bool updateErosion = true; /** NNConstraint to use. * The Pathfinding.NNConstraint.SuitableGraph function will be called on the NNConstraint to enable filtering of which graphs to update.\n * \note As the Pathfinding.NNConstraint.SuitableGraph function is A* Pathfinding Project Pro only, this variable doesn't really affect anything in the free version. * * * \astarpro */ public NNConstraint nnConstraint = NNConstraint.None; /** Penalty to add to the nodes */ public int addPenalty = 0; public bool modifyWalkability = false; /**< If true, all nodes \a walkable variables will be set to #setWalkability */ public bool setWalkability = false; /**< If #modifyWalkability is true, the nodes' \a walkable variable will be set to this */ #if ConfigureTagsAsMultiple public TagMask tags; #else public bool modifyTag = false; public int setTag = 0; #endif /** Track which nodes are changed and save backup data. * Used internally to revert changes if needed. */ public bool trackChangedNodes = false; private List<Node> changedNodes; private List<ulong> backupData; private List<Int3> backupPositionData; public GraphUpdateShape shape = null; /** Should be called on every node which is updated with this GUO before it is updated. * \param node The node to save fields for. If null, nothing will be done * \see #trackChangedNodes */ public virtual void WillUpdateNode (Node node) { if (trackChangedNodes && node != null) { if (changedNodes == null) { changedNodes = ListPool<Node>.Claim(); backupData = ListPool<ulong>.Claim(); backupPositionData = ListPool<Int3>.Claim(); } changedNodes.Add (node); backupPositionData.Add (node.position); backupData.Add ((ulong)node.penalty<<32 | (ulong)node.flags); } } /** Reverts penalties and flags (which includes walkability) on every node which was updated using this GUO. * Data for reversion is only saved if #trackChangedNodes is true */ public virtual void RevertFromBackup () { if (trackChangedNodes) { if (changedNodes == null) return; for (int i=0;i<changedNodes.Count;i++) { changedNodes[i].penalty = (uint)(backupData[i]>>32); changedNodes[i].flags = (int)(backupData[i] & 0xFFFFFFFF); changedNodes[i].position = backupPositionData[i]; ListPool<Node>.Release (changedNodes); ListPool<ulong>.Release(backupData); ListPool<Int3>.Release(backupPositionData); } } else { throw new System.InvalidOperationException ("Changed nodes have not been tracked, cannot revert from backup"); } } /** Updates the specified node using this GUO's settings */ public virtual void Apply (Node node) { if (shape == null || shape.Contains (node)) { //Update penalty and walkability node.penalty = (uint)(node.penalty+addPenalty); if (modifyWalkability) { node.walkable = setWalkability; } //Update tags #if ConfigureTagsAsMultiple node.tags = (node.tags & ~tags.tagsChange) | (tags.tagsSet & tags.tagsChange); #else if (modifyTag) node.tags = setTag; #endif } } public GraphUpdateObject () { } /** Creates a new GUO with the specified bounds */ public GraphUpdateObject (Bounds b) { bounds = b; } } public interface IRaycastableGraph { bool Linecast (Vector3 start, Vector3 end); bool Linecast (Vector3 start, Vector3 end, Node hint); bool Linecast (Vector3 start, Vector3 end, Node hint, out GraphHitInfo hit); } /** Holds info about one pathfinding thread. * Mainly used to send information about how the thread should execute when starting it */ public struct PathThreadInfo { public int threadIndex; public AstarPath astar; public NodeRunData runData; private System.Object _lock; public System.Object Lock { get {return _lock; }} public PathThreadInfo (int index, AstarPath astar, NodeRunData runData) { this.threadIndex = index; this.astar = astar; this.runData = runData; _lock = new object(); } } /** Integer Rectangle. * Works almost like UnityEngine.Rect but with integer coordinates */ public struct IntRect { public int xmin, ymin, xmax, ymax; public IntRect (int xmin, int ymin, int xmax, int ymax) { this.xmin = xmin; this.xmax = xmax; this.ymin = ymin; this.ymax = ymax; } public bool Contains (int x, int y) { return !(x < xmin || y < ymin || x > xmax || y > ymax); } /** Returns if this rectangle is valid. * An invalid rect could have e.g xmin > xmax */ public bool IsValid () { return xmin <= xmax && ymin <= ymax; } /** Returns the intersection rect between the two rects. * The intersection rect is the area which is inside both rects. * If the rects do not have an intersection, an invalid rect is returned. * \see IsValid */ public static IntRect Intersection (IntRect a, IntRect b) { IntRect r = new IntRect( System.Math.Max(a.xmin,b.xmin), System.Math.Max(a.ymin,b.ymin), System.Math.Min(a.xmax,b.xmax), System.Math.Min(a.ymax,b.ymax) ); return r; } /** Returns a new rect which contains both input rects. * This rectangle may contain areas outside both input rects as well in some cases. */ public static IntRect Union (IntRect a, IntRect b) { IntRect r = new IntRect( System.Math.Min(a.xmin,b.xmin), System.Math.Min(a.ymin,b.ymin), System.Math.Max(a.xmax,b.xmax), System.Math.Max(a.ymax,b.ymax) ); return r; } /** Returns a new rect which is expanded by \a range in all directions. * \param range How far to expand. Negative values are permitted. */ public IntRect Expand (int range) { return new IntRect(xmin-range, ymin-range, xmax+range, ymax+range ); } /** Draws some debug lines representing the rect */ public void DebugDraw (Matrix4x4 matrix, Color col) { Vector3 p1 = matrix.MultiplyPoint3x4 (new Vector3(xmin,0,ymin)); Vector3 p2 = matrix.MultiplyPoint3x4 (new Vector3(xmin,0,ymax)); Vector3 p3 = matrix.MultiplyPoint3x4 (new Vector3(xmax,0,ymax)); Vector3 p4 = matrix.MultiplyPoint3x4 (new Vector3(xmax,0,ymin)); Debug.DrawLine (p1,p2,col); Debug.DrawLine (p2,p3,col); Debug.DrawLine (p3,p4,col); Debug.DrawLine (p4,p1,col); } } } #region Delegates /* Delegate with on Path object as parameter. * This is used for callbacks when a path has finished calculation.\n * Example function: * \code public void Start () { //Assumes a Seeker component is attached to the GameObject Seeker seeker = GetComponent<Seeker>(); //seeker.pathCallback is a OnPathDelegate, we add the function OnPathComplete to it so it will be called whenever a path has finished calculating on that seeker seeker.pathCallback += OnPathComplete; } public void OnPathComplete (Path p) { Debug.Log ("This is called when a path is completed on the seeker attached to this GameObject"); }\endcode */ public delegate void OnPathDelegate (Path p); public delegate Vector3[] GetNextTargetDelegate (Path p, Vector3 currentPosition); public delegate void NodeDelegate (Node node); public delegate void OnGraphDelegate (NavGraph graph); public delegate void OnScanDelegate (AstarPath script); public delegate void OnVoidDelegate (); #endregion #region Enums /** How path results are logged by the system */ public enum PathLog { None, /**< Does not log anything */ Normal, /**< Logs basic info about the paths */ Heavy, /**< Includes additional info */ InGame, /**< Same as heavy, but displays the info in-game using GUI */ OnlyErrors /**< Same as normal, but logs only paths which returned an error */ } /** Heuristic to use. Heuristic is the estimated cost from the current node to the target */ public enum Heuristic { Manhattan, DiagonalManhattan, Euclidean, None } /** What data to draw the graph debugging with */ public enum GraphDebugMode { Areas, G, H, F, Penalty, Connections, Tags } /** Type of connection for a user placed link */ public enum ConnectionType { Connection, ModifyNode } public enum ThreadCount { Automatic = -1, None = 0, One = 1, Two, Three, Four, Five, Six, Seven, Eight } public enum PathState { Created = 0, PathQueue = 1, Processing = 2, ReturnQueue = 3, Returned = 4 } public enum PathCompleteState { NotCalculated = 0, Error = 1, Complete = 2, Partial = 3 } #endregion
using System; using System.IO; using NTumbleBit.BouncyCastle.Utilities.IO; namespace NTumbleBit.BouncyCastle.Asn1 { /** * a general purpose ASN.1 decoder - note: this class differs from the * others in that it returns null after it has read the last object in * the stream. If an ASN.1 Null is encountered a Der/BER Null object is * returned. */ internal class Asn1InputStream : FilterStream { private readonly int limit; private readonly byte[][] tmpBuffers; internal static int FindLimit(Stream input) { if(input is LimitedInputStream) { return ((LimitedInputStream)input).GetRemaining(); } else if(input is MemoryStream) { MemoryStream mem = (MemoryStream)input; return (int)(mem.Length - mem.Position); } return int.MaxValue; } public Asn1InputStream( Stream inputStream) : this(inputStream, FindLimit(inputStream)) { } /** * Create an ASN1InputStream where no DER object will be longer than limit. * * @param input stream containing ASN.1 encoded data. * @param limit maximum size of a DER encoded object. */ public Asn1InputStream( Stream inputStream, int limit) : base(inputStream) { this.limit = limit; tmpBuffers = new byte[16][]; } /** * Create an ASN1InputStream based on the input byte array. The length of DER objects in * the stream is automatically limited to the length of the input array. * * @param input array containing ASN.1 encoded data. */ public Asn1InputStream( byte[] input) : this(new MemoryStream(input, false), input.Length) { } /** * build an object given its tag and the number of bytes to construct it from. */ private Asn1Object BuildObject( int tag, int tagNo, int length) { bool isConstructed = (tag & Asn1Tags.Constructed) != 0; DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(s, length); if((tag & Asn1Tags.Application) != 0) { throw new IOException("invalid ECDSA sig"); } if((tag & Asn1Tags.Tagged) != 0) { throw new IOException("invalid ECDSA sig"); } if(isConstructed) { switch(tagNo) { case Asn1Tags.Sequence: return CreateDerSequence(defIn); default: throw new IOException("unknown tag " + tagNo + " encountered"); } } return CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers); } internal Asn1EncodableVector BuildEncodableVector() { Asn1EncodableVector v = new Asn1EncodableVector(); Asn1Object o; while((o = ReadObject()) != null) { v.Add(o); } return v; } internal virtual Asn1EncodableVector BuildDerEncodableVector( DefiniteLengthInputStream dIn) { return new Asn1InputStream(dIn).BuildEncodableVector(); } internal virtual DerSequence CreateDerSequence( DefiniteLengthInputStream dIn) { return DerSequence.FromVector(BuildDerEncodableVector(dIn)); } public Asn1Object ReadObject() { int tag = ReadByte(); if(tag <= 0) { if(tag == 0) throw new IOException("unexpected end-of-contents marker"); return null; } // // calculate tag number // int tagNo = ReadTagNumber(s, tag); // // calculate length // int length = ReadLength(s, limit); if(length < 0) // indefinite length method { throw new IOException("indefinite length primitive encoding encountered"); } else { try { return BuildObject(tag, tagNo, length); } catch(ArgumentException e) { throw new Asn1Exception("corrupted stream detected", e); } } } internal static int ReadTagNumber( Stream s, int tag) { int tagNo = tag & 0x1f; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if(tagNo == 0x1f) { tagNo = 0; int b = s.ReadByte(); // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if((b & 0x7f) == 0) // Note: -1 will pass { throw new IOException("Corrupted stream - invalid high tag number found"); } while((b >= 0) && ((b & 0x80) != 0)) { tagNo |= (b & 0x7f); tagNo <<= 7; b = s.ReadByte(); } if(b < 0) throw new EndOfStreamException("EOF found inside tag value."); tagNo |= (b & 0x7f); } return tagNo; } internal static int ReadLength( Stream s, int limit) { int length = s.ReadByte(); if(length < 0) throw new EndOfStreamException("EOF found when length expected"); if(length == 0x80) return -1; // indefinite-length encoding if(length > 127) { int size = length & 0x7f; // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here if(size > 4) throw new IOException("DER length more than 4 bytes: " + size); length = 0; for(int i = 0; i < size; i++) { int next = s.ReadByte(); if(next < 0) throw new EndOfStreamException("EOF found reading length"); length = (length << 8) + next; } if(length < 0) throw new IOException("Corrupted stream - negative length found"); if(length >= limit) // after all we must have read at least 1 byte throw new IOException("Corrupted stream - out of bounds length found"); } return length; } internal static byte[] GetBuffer(DefiniteLengthInputStream defIn, byte[][] tmpBuffers) { int len = defIn.GetRemaining(); if(len >= tmpBuffers.Length) { return defIn.ToArray(); } byte[] buf = tmpBuffers[len]; if(buf == null) { buf = tmpBuffers[len] = new byte[len]; } defIn.ReadAllIntoByteArray(buf); return buf; } internal static Asn1Object CreatePrimitiveDerObject( int tagNo, DefiniteLengthInputStream defIn, byte[][] tmpBuffers) { switch(tagNo) { case Asn1Tags.Boolean: throw new IOException("invalid ECDSA sig"); case Asn1Tags.Enumerated: throw new IOException("invalid ECDSA sig"); case Asn1Tags.ObjectIdentifier: return DerObjectIdentifier.FromOctetString(GetBuffer(defIn, tmpBuffers)); } byte[] bytes = defIn.ToArray(); switch(tagNo) { case Asn1Tags.Integer: return new DerInteger(bytes); case Asn1Tags.OctetString: return new DerOctetString(bytes); case Asn1Tags.Null: return DerNull.Instance; // actual content is ignored (enforce 0 length?) default: throw new IOException("unknown tag " + tagNo + " encountered"); } } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Glass.Mapper.Configuration; using Glass.Mapper.Configuration.Attributes; using NSubstitute; using NUnit.Framework; namespace Glass.Mapper.Tests.Configuration.Attributes { [TestFixture] public class AttributeConfigurationLoaderFixture { private StubAttributeConfigurationLoader _loader; [SetUp] public void Setup() { _loader = new StubAttributeConfigurationLoader(); } #region Method - Create [Test] public void Load_LoadsTypesUsingAssemblyNameWithDllAtEnd_TypeReturnedWithTwoProperties() { //Assign string assemblyName = "Glass.Mapper.Tests.dll"; _loader = new StubAttributeConfigurationLoader(assemblyName); //Act var results = _loader.Load(); //Assert Assert.IsTrue(results.Any()); Assert.AreEqual(1, results.Count(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties))); var config = results.First(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties)); Assert.AreEqual(2, config.Properties.Count()); } [Test] public void Load_LoadsTypesUsingAssemblyNameWithoutDllAtEnd_TypeReturnedWithTwoProperties() { //Assign string assemblyName = "Glass.Mapper.Tests"; _loader = new StubAttributeConfigurationLoader(assemblyName); //Act var results = _loader.Load(); //Assert Assert.IsTrue(results.Any()); Assert.AreEqual(1, results.Count(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties))); var config = results.First(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties)); Assert.AreEqual(2, config.Properties.Count()); } [Test] public void Load_AssemblyDoesntExist_ThrowsException() { //Assign string assemblyName = "DoesNotExist"; _loader = new StubAttributeConfigurationLoader(assemblyName); //Act Assert.Throws<ConfigurationException>(() => { var results = _loader.Load(); }); //Exception } #endregion #region Method - LoadFromAssembly [Test] public void LoadFromAssembly_TypesDefinedInThisAssembly_LoadsAtLeastOneType() { //Assign var assembly = Assembly.GetExecutingAssembly(); //Act var results = _loader.LoadFromAssembly(assembly); //Assert Assert.IsTrue(results.Any()); Assert.AreEqual(1, results.Count(x=>x.Type == typeof(StubClassWithTypeAttribute))); } [Test] public void LoadFromAssembly_TypesDefinedInThisAssemblyWithTwoProperties_LoadsAtLeastOneTypeWithTwoProperties() { //Assign var assembly = Assembly.GetExecutingAssembly(); //Act var results = _loader.LoadFromAssembly(assembly); //Assert Assert.IsTrue(results.Any()); Assert.AreEqual(1, results.Count(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties))); var config = results.First(x => x.Type == typeof (StubClassWithTypeAttributeAndProperties)); Assert.AreEqual(2, config.Properties.Count()); } #endregion #region Stubs public class StubTypeConfiguration : AbstractTypeConfiguration { } public class StubPropertyConfiguration : AbstractPropertyConfiguration { protected override AbstractPropertyConfiguration CreateCopy() { throw new NotImplementedException(); } } public class StubAttributeConfigurationLoader : AttributeConfigurationLoader { public StubAttributeConfigurationLoader(params string [] assemblies):base(assemblies) { } public IEnumerable<AbstractTypeConfiguration> LoadFromAssembly(Assembly assembly) { return base.LoadFromAssembly(assembly); } } public class StubAbstractTypeAttribute : AbstractTypeAttribute { public override AbstractTypeConfiguration Configure(Type type) { var config = new StubTypeConfiguration(); base.Configure(type, config); return config; } } public class StubAbstractPropertyAttribute : AbstractPropertyAttribute { public override AbstractPropertyConfiguration Configure(PropertyInfo propertyInfo) { var config = new StubPropertyConfiguration(); base.Configure(propertyInfo, config); return config; } } [StubAbstractType] public class StubClassWithTypeAttribute { } [StubAbstractType] public class StubClassWithTypeAttributeAndProperties { [StubAbstractProperty] public string PropertyWithAttribute1 { get; set; } [StubAbstractProperty] public string PropertyWithAttribute2 { get; set; } } public class StubClassWithProperties { [StubAbstractProperty] public string PropertyWithAttribute { get; set; } public string PropertyWithoutAttribute { get; set; } } public class StubSubClassWithProperties: StubClassWithProperties { } public interface StubInterfaceWithProperties { [StubAbstractProperty] string PropertyWithAttribute { get; set; } } public interface StubSubInterfaceWithProperties : StubInterfaceWithProperties { } public class StubClassFromInterface : StubSubInterfaceWithProperties { public string PropertyWithAttribute { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } public class StubClassFromTwoInterfaces : StubInferfaceOne, StubInferfaceTwo { public string PropertyWithAttribute { get; set; } } public interface StubInferfaceOne { [StubAbstractProperty] string PropertyWithAttribute { get; set; } } public interface StubInferfaceTwo { string PropertyWithAttribute { get; set; } } #endregion } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using NLog.Layouts; using Xunit; public class CsvLayoutTests : NLogTestBase { [Fact] public void EndToEndTest() { try { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'> <layout type='CSVLayout'> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> <delimiter>Comma</delimiter> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt")) { Assert.Equal("level,message,counter", sr.ReadLine()); Assert.Equal("Debug,msg,1", sr.ReadLine()); Assert.Equal("Info,msg2,2", sr.ReadLine()); Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine()); } } finally { if (File.Exists("CSVLayoutEndToEnd1.txt")) { File.Delete("CSVLayoutEndToEnd1.txt"); } } } /// <summary> /// Custom header overwrites file headers /// /// Note: maybe changed with an option in the future /// </summary> [Fact] public void CustomHeaderTest() { try { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'> <layout type='CSVLayout'> <header>headertest</header> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> <delimiter>Comma</delimiter> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt")) { Assert.Equal("headertest", sr.ReadLine()); // Assert.Equal("level,message,counter", sr.ReadLine()); Assert.Equal("Debug,msg,1", sr.ReadLine()); Assert.Equal("Info,msg2,2", sr.ReadLine()); Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine()); } } finally { if (File.Exists("CSVLayoutEndToEnd1.txt")) { File.Delete("CSVLayoutEndToEnd1.txt"); } } } [Fact] public void NoHeadersTest() { try { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='f' type='File' fileName='CSVLayoutEndToEnd2.txt'> <layout type='CSVLayout' withHeader='false'> <delimiter>Comma</delimiter> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd2.txt")) { Assert.Equal("Debug,msg,1", sr.ReadLine()); Assert.Equal("Info,msg2,2", sr.ReadLine()); Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine()); } } finally { if (File.Exists("CSVLayoutEndToEnd2.txt")) { File.Delete("CSVLayoutEndToEnd2.txt"); } } } [Fact] public void CsvLayoutRenderingNoQuoting() { var delimiters = new Dictionary<CsvColumnDelimiterMode, string> { { CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator }, { CsvColumnDelimiterMode.Comma, "," }, { CsvColumnDelimiterMode.Semicolon, ";" }, { CsvColumnDelimiterMode.Space, " " }, { CsvColumnDelimiterMode.Tab, "\t" }, { CsvColumnDelimiterMode.Pipe, "|" }, { CsvColumnDelimiterMode.Custom, "zzz" }, }; foreach (var delim in delimiters) { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Nothing, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, Delimiter = delim.Key, CustomColumnDelimiter = "zzz", }; var ev = new LogEventInfo(); ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56); ev.Level = LogLevel.Info; ev.Message = "hello, world"; string sep = delim.Value; Assert.Equal("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "hello, world", csvLayout.Render(ev)); Assert.Equal("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev)); } } [Fact] public void CsvLayoutRenderingFullQuoting() { var delimiters = new Dictionary<CsvColumnDelimiterMode, string> { { CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator }, { CsvColumnDelimiterMode.Comma, "," }, { CsvColumnDelimiterMode.Semicolon, ";" }, { CsvColumnDelimiterMode.Space, " " }, { CsvColumnDelimiterMode.Tab, "\t" }, { CsvColumnDelimiterMode.Pipe, "|" }, { CsvColumnDelimiterMode.Custom, "zzz" }, }; foreach (var delim in delimiters) { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.All, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, QuoteChar = "'", Delimiter = delim.Key, CustomColumnDelimiter = "zzz", }; var ev = new LogEventInfo(); ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56); ev.Level = LogLevel.Info; ev.Message = "hello, world"; string sep = delim.Value; Assert.Equal("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'hello, world'", csvLayout.Render(ev)); Assert.Equal("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev)); } } [Fact] public void CsvLayoutRenderingAutoQuoting() { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Auto, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, QuoteChar = "'", Delimiter = CsvColumnDelimiterMode.Semicolon, }; // no quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;hello, world", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" })); // multi-line string - requires quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello\rworld'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\rworld" })); // multi-line string - requires quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello\nworld'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\nworld" })); // quote character used in string, will be quoted and doubled Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello''world'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello'world" })); Assert.Equal("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void CsvLayoutCachingTest() { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Auto, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), }, QuoteChar = "'", Delimiter = CsvColumnDelimiterMode.Semicolon, }; var e1 = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; var e2 = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57), Level = LogLevel.Info, Message = "hello, world" }; var r11 = csvLayout.Render(e1); var r12 = csvLayout.Render(e1); var r21 = csvLayout.Render(e2); var r22 = csvLayout.Render(e2); var h11 = csvLayout.Header.Render(e1); var h12 = csvLayout.Header.Render(e1); var h21 = csvLayout.Header.Render(e2); var h22 = csvLayout.Header.Render(e2); Assert.Same(r11, r12); Assert.Same(r21, r22); Assert.NotSame(r11, r21); Assert.NotSame(r12, r22); Assert.Same(h11, h12); Assert.Same(h21, h22); Assert.NotSame(h11, h21); Assert.NotSame(h12, h22); } } }
/* ==================================================================== 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 NPOI.POIFS.Common; using NPOI.POIFS.FileSystem; using System; using System.Collections.Generic; using System.IO; using NPOI.Util; namespace NPOI.POIFS.FileSystem { /** * This handles Reading and writing a stream within a * {@link NPOIFSFileSystem}. It can supply an iterator * to read blocks, and way to write out to existing and * new blocks. * Most users will want a higher level version of this, * which deals with properties to track which stream * this is. * This only works on big block streams, it doesn't * handle small block ones. * This uses the new NIO code * * TODO Implement a streaming write method, and append */ public class NPOIFSStream : IEnumerable<ByteBuffer> { private BlockStore blockStore; private int startBlock; /** * Constructor for an existing stream. It's up to you * to know how to Get the start block (eg from a * {@link HeaderBlock} or a {@link Property}) */ public NPOIFSStream(BlockStore blockStore, int startBlock) { this.blockStore = blockStore; this.startBlock = startBlock; } /** * Constructor for a new stream. A start block won't * be allocated until you begin writing to it. */ public NPOIFSStream(BlockStore blockStore) { this.blockStore = blockStore; this.startBlock = POIFSConstants.END_OF_CHAIN; } /** * What block does this stream start at? * Will be {@link POIFSConstants#END_OF_CHAIN} for a * new stream that hasn't been written to yet. */ public int GetStartBlock() { return startBlock; } #region IEnumerable<byte[]> Members //public IEnumerator<byte[]> GetEnumerator() public IEnumerator<ByteBuffer> GetEnumerator() { return GetBlockIterator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetBlockIterator(); } #endregion /** * Returns an iterator that'll supply one {@link ByteBuffer} * per block in the stream. */ public IEnumerator<ByteBuffer> GetBlockIterator() { if (startBlock == POIFSConstants.END_OF_CHAIN) { throw new InvalidOperationException( "Can't read from a new stream before it has been written to" ); } return new StreamBlockByteBufferIterator(this.blockStore, startBlock); } /** * Updates the contents of the stream to the new * Set of bytes. * Note - if this is property based, you'll still * need to update the size in the property yourself */ public void UpdateContents(byte[] contents) { // How many blocks are we going to need? int blockSize = blockStore.GetBlockStoreBlockSize(); int blocks = (int)Math.Ceiling(((double)contents.Length) / blockSize); // Make sure we don't encounter a loop whilst overwriting // the existing blocks ChainLoopDetector loopDetector = blockStore.GetChainLoopDetector(); // Start writing int prevBlock = POIFSConstants.END_OF_CHAIN; int nextBlock = startBlock; for (int i = 0; i < blocks; i++) { int thisBlock = nextBlock; // Allocate a block if needed, otherwise figure // out what the next block will be if (thisBlock == POIFSConstants.END_OF_CHAIN) { thisBlock = blockStore.GetFreeBlock(); loopDetector.Claim(thisBlock); // We're on the end of the chain nextBlock = POIFSConstants.END_OF_CHAIN; // Mark the previous block as carrying on to us if needed if (prevBlock != POIFSConstants.END_OF_CHAIN) { blockStore.SetNextBlock(prevBlock, thisBlock); } blockStore.SetNextBlock(thisBlock, POIFSConstants.END_OF_CHAIN); // If we've just written the first block on a // new stream, save the start block offset if (this.startBlock == POIFSConstants.END_OF_CHAIN) { this.startBlock = thisBlock; } } else { loopDetector.Claim(thisBlock); nextBlock = blockStore.GetNextBlock(thisBlock); } // Write it //byte[] buffer = blockStore.CreateBlockIfNeeded(thisBlock); ByteBuffer buffer = blockStore.CreateBlockIfNeeded(thisBlock); int startAt = i * blockSize; int endAt = Math.Min(contents.Length - startAt, blockSize); buffer.Write(contents, startAt, endAt); //for (int index = startAt, j = 0; index < endAt; index++, j++) // buffer[j] = contents[index]; // Update pointers prevBlock = thisBlock; } int lastBlock = prevBlock; // If we're overwriting, free any remaining blocks NPOIFSStream toFree = new NPOIFSStream(blockStore, nextBlock); toFree.free(loopDetector); // Mark the end of the stream blockStore.SetNextBlock(lastBlock, POIFSConstants.END_OF_CHAIN); } // TODO Streaming write support // TODO then convert fixed sized write to use streaming internally // TODO Append write support (probably streaming) /** * Frees all blocks in the stream */ public void free() { ChainLoopDetector loopDetector = blockStore.GetChainLoopDetector(); free(loopDetector); } private void free(ChainLoopDetector loopDetector) { int nextBlock = startBlock; while (nextBlock != POIFSConstants.END_OF_CHAIN) { int thisBlock = nextBlock; loopDetector.Claim(thisBlock); nextBlock = blockStore.GetNextBlock(thisBlock); blockStore.SetNextBlock(thisBlock, POIFSConstants.UNUSED_BLOCK); } this.startBlock = POIFSConstants.END_OF_CHAIN; } /* * Class that handles a streaming read of one stream */ } //public class StreamBlockByteBufferIterator : IEnumerator<byte[]> public class StreamBlockByteBufferIterator : IEnumerator<ByteBuffer> { private ChainLoopDetector loopDetector; private int nextBlock; private BlockStore blockStore; private ByteBuffer current; public StreamBlockByteBufferIterator(BlockStore blockStore, int firstBlock) { this.blockStore = blockStore; this.nextBlock = firstBlock; try { this.loopDetector = blockStore.GetChainLoopDetector(); } catch (IOException e) { //throw new System.RuntimeException(e); throw new Exception(e.Message); } } public bool HasNext() { if (nextBlock == POIFSConstants.END_OF_CHAIN) { return false; } return true; } public ByteBuffer Next() { if (nextBlock == POIFSConstants.END_OF_CHAIN) { throw new IndexOutOfRangeException("Can't read past the end of the stream"); } try { loopDetector.Claim(nextBlock); //byte[] data = blockStore.GetBlockAt(nextBlock); ByteBuffer data = blockStore.GetBlockAt(nextBlock); nextBlock = blockStore.GetNextBlock(nextBlock); return data; } catch (IOException e) { throw new RuntimeException(e.Message); } } public void Remove() { //throw new UnsupportedOperationException(); throw new NotImplementedException("Unsupported Operations!"); } public ByteBuffer Current { get { return current; } } Object System.Collections.IEnumerator.Current { get { return current; } } void System.Collections.IEnumerator.Reset() { throw new NotImplementedException(); } bool System.Collections.IEnumerator.MoveNext() { if (nextBlock == POIFSConstants.END_OF_CHAIN) { //throw new IndexOutOfBoundsException("Can't read past the end of the stream"); //throw new Exception("Can't read past the end of the stream"); return false; } try { loopDetector.Claim(nextBlock); // byte[] data = blockStore.GetBlockAt(nextBlock); current = blockStore.GetBlockAt(nextBlock); nextBlock = blockStore.GetNextBlock(nextBlock); return true; } catch (IOException) { return false; // throw new RuntimeException(e); //throw new Exception(e.Message); } } public void Dispose() { } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.IO; using dnlib.IO; using dnlib.DotNet.Pdb; using dnlib.PE; using dnlib.W32Resources; using dnlib.DotNet.MD; using System.Diagnostics; namespace dnlib.DotNet.Writer { /// <summary> /// Common module writer options base class /// </summary> public class ModuleWriterOptionsBase { IModuleWriterListener listener; PEHeadersOptions peHeadersOptions; Cor20HeaderOptions cor20HeaderOptions; MetaDataOptions metaDataOptions; ILogger logger; ILogger metaDataLogger; Win32Resources win32Resources; StrongNameKey strongNameKey; StrongNamePublicKey strongNamePublicKey; bool delaySign; /// <summary> /// Gets/sets the listener /// </summary> public IModuleWriterListener Listener { get { return listener; } set { listener = value; } } /// <summary> /// Gets/sets the logger. If this is <c>null</c>, any errors result in a /// <see cref="ModuleWriterException"/> being thrown. To disable this behavior, either /// create your own logger or use <see cref="DummyLogger.NoThrowInstance"/>. /// </summary> public ILogger Logger { get { return logger; } set { logger = value; } } /// <summary> /// Gets/sets the <see cref="MetaData"/> writer logger. If this is <c>null</c>, use /// <see cref="Logger"/>. /// </summary> public ILogger MetaDataLogger { get { return metaDataLogger; } set { metaDataLogger = value; } } /// <summary> /// Gets/sets the <see cref="PEHeaders"/> options. This is never <c>null</c>. /// </summary> public PEHeadersOptions PEHeadersOptions { get { return peHeadersOptions ?? (peHeadersOptions = new PEHeadersOptions()); } set { peHeadersOptions = value; } } /// <summary> /// Gets/sets the <see cref="ImageCor20Header"/> options. This is never <c>null</c>. /// </summary> public Cor20HeaderOptions Cor20HeaderOptions { get { return cor20HeaderOptions ?? (cor20HeaderOptions = new Cor20HeaderOptions()); } set { cor20HeaderOptions = value; } } /// <summary> /// Gets/sets the <see cref="MetaData"/> options. This is never <c>null</c>. /// </summary> public MetaDataOptions MetaDataOptions { get { return metaDataOptions ?? (metaDataOptions = new MetaDataOptions()); } set { metaDataOptions = value; } } /// <summary> /// Gets/sets the Win32 resources. If this is <c>null</c>, use the module's /// Win32 resources if any. /// </summary> public Win32Resources Win32Resources { get { return win32Resources; } set { win32Resources = value; } } /// <summary> /// true to delay sign the assembly. Initialize <see cref="StrongNamePublicKey"/> to the /// public key to use, and don't initialize <see cref="StrongNameKey"/>. To generate the /// public key from your strong name key file, execute <c>sn -p mykey.snk mypublickey.snk</c> /// </summary> public bool DelaySign { get { return delaySign; } set { delaySign = value; } } /// <summary> /// Gets/sets the strong name key. When you enhance strong name sign an assembly, /// this instance's HashAlgorithm must be initialized to its public key's HashAlgorithm. /// You should call <see cref="InitializeStrongNameSigning(ModuleDef,StrongNameKey)"/> /// to initialize this property if you use normal strong name signing. /// You should call <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey)"/> /// or <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey,StrongNameKey,StrongNamePublicKey)"/> /// to initialize this property if you use enhanced strong name signing. /// </summary> public StrongNameKey StrongNameKey { get { return strongNameKey; } set { strongNameKey = value; } } /// <summary> /// Gets/sets the new public key that should be used. If this is <c>null</c>, use /// the public key generated from <see cref="StrongNameKey"/>. If it is also <c>null</c>, /// use the module's Assembly's public key. /// You should call <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey)"/> /// or <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey,StrongNameKey,StrongNamePublicKey)"/> /// to initialize this property if you use enhanced strong name signing. /// </summary> public StrongNamePublicKey StrongNamePublicKey { get { return strongNamePublicKey; } set { strongNamePublicKey = value; } } /// <summary> /// <c>true</c> if method bodies can be shared (two or more method bodies can share the /// same RVA), <c>false</c> if method bodies can't be shared. Don't enable it if there /// must be a 1:1 relationship with method bodies and their RVAs. /// </summary> public bool ShareMethodBodies { get; set; } /// <summary> /// <c>true</c> if the PE header CheckSum field should be updated, <c>false</c> if the /// CheckSum field isn't updated. /// </summary> public bool AddCheckSum { get; set; } /// <summary> /// <c>true</c> if it's a 64-bit module, <c>false</c> if it's a 32-bit or AnyCPU module. /// </summary> public bool Is64Bit { get { if (!PEHeadersOptions.Machine.HasValue) return false; return PEHeadersOptions.Machine == Machine.IA64 || PEHeadersOptions.Machine == Machine.AMD64 || PEHeadersOptions.Machine == Machine.ARM64; } } /// <summary> /// Gets/sets the module kind /// </summary> public ModuleKind ModuleKind { get; set; } /// <summary> /// <c>true</c> if it should be written as an EXE file, <c>false</c> if it should be /// written as a DLL file. /// </summary> public bool IsExeFile { get { return ModuleKind != ModuleKind.Dll && ModuleKind != ModuleKind.NetModule; } } /// <summary> /// Set it to <c>true</c> to enable writing a PDB file. Default is <c>false</c> (a PDB file /// won't be written to disk). /// </summary> public bool WritePdb { get; set; } /// <summary> /// PDB file name. If it's <c>null</c> a PDB file with the same name as the output assembly /// will be created but with a PDB extension. <see cref="WritePdb"/> must be <c>true</c> or /// this property is ignored. /// </summary> public string PdbFileName { get; set; } /// <summary> /// PDB stream. If this is initialized, then you should also set <see cref="PdbFileName"/> /// to the name of the PDB file since the file name must be written to the PE debug directory. /// <see cref="WritePdb"/> must be <c>true</c> or this property is ignored. /// </summary> public Stream PdbStream { get; set; } /// <summary> /// If <see cref="PdbFileName"/> or <see cref="PdbStream"/> aren't enough, this can be used /// to create a new <see cref="ISymbolWriter2"/> instance. <see cref="WritePdb"/> must be /// <c>true</c> or this property is ignored. /// </summary> public CreatePdbSymbolWriterDelegate CreatePdbSymbolWriter { get; set; } /// <summary> /// Default constructor /// </summary> protected ModuleWriterOptionsBase() { ShareMethodBodies = true; ModuleKind = ModuleKind.Windows; } /// <summary> /// Constructor /// </summary> /// <param name="module">The module</param> protected ModuleWriterOptionsBase(ModuleDef module) : this(module, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">The module</param> /// <param name="listener">Module writer listener</param> protected ModuleWriterOptionsBase(ModuleDef module, IModuleWriterListener listener) { this.listener = listener; ShareMethodBodies = true; MetaDataOptions.MetaDataHeaderOptions.VersionString = module.RuntimeVersion; ModuleKind = module.Kind; PEHeadersOptions.Machine = module.Machine; PEHeadersOptions.Characteristics = module.Characteristics; PEHeadersOptions.DllCharacteristics = module.DllCharacteristics; if (module.Kind == ModuleKind.Windows) PEHeadersOptions.Subsystem = Subsystem.WindowsGui; else PEHeadersOptions.Subsystem = Subsystem.WindowsCui; PEHeadersOptions.NumberOfRvaAndSizes = 0x10; Cor20HeaderOptions.Flags = module.Cor20HeaderFlags; if (module.Assembly != null && !PublicKeyBase.IsNullOrEmpty2(module.Assembly.PublicKey)) Cor20HeaderOptions.Flags |= ComImageFlags.StrongNameSigned; if (module.Cor20HeaderRuntimeVersion != null) { Cor20HeaderOptions.MajorRuntimeVersion = (ushort)(module.Cor20HeaderRuntimeVersion.Value >> 16); Cor20HeaderOptions.MinorRuntimeVersion = (ushort)module.Cor20HeaderRuntimeVersion.Value; } else if (module.IsClr1x) { Cor20HeaderOptions.MajorRuntimeVersion = 2; Cor20HeaderOptions.MinorRuntimeVersion = 0; } else { Cor20HeaderOptions.MajorRuntimeVersion = 2; Cor20HeaderOptions.MinorRuntimeVersion = 5; } if (module.TablesHeaderVersion != null) { MetaDataOptions.TablesHeapOptions.MajorVersion = (byte)(module.TablesHeaderVersion.Value >> 8); MetaDataOptions.TablesHeapOptions.MinorVersion = (byte)module.TablesHeaderVersion.Value; } else if (module.IsClr1x) { // Generics aren't supported MetaDataOptions.TablesHeapOptions.MajorVersion = 1; MetaDataOptions.TablesHeapOptions.MinorVersion = 0; } else { // Generics are supported MetaDataOptions.TablesHeapOptions.MajorVersion = 2; MetaDataOptions.TablesHeapOptions.MinorVersion = 0; } // Some tools crash if #GUID is missing so always create it by default MetaDataOptions.Flags |= MetaDataFlags.AlwaysCreateGuidHeap; var modDefMD = module as ModuleDefMD; if (modDefMD != null) { var ntHeaders = modDefMD.MetaData.PEImage.ImageNTHeaders; PEHeadersOptions.TimeDateStamp = ntHeaders.FileHeader.TimeDateStamp; PEHeadersOptions.MajorLinkerVersion = ntHeaders.OptionalHeader.MajorLinkerVersion; PEHeadersOptions.MinorLinkerVersion = ntHeaders.OptionalHeader.MinorLinkerVersion; PEHeadersOptions.ImageBase = ntHeaders.OptionalHeader.ImageBase; AddCheckSum = ntHeaders.OptionalHeader.CheckSum != 0; } if (Is64Bit) { PEHeadersOptions.Characteristics &= ~Characteristics._32BitMachine; PEHeadersOptions.Characteristics |= Characteristics.LargeAddressAware; } else PEHeadersOptions.Characteristics |= Characteristics._32BitMachine; } /// <summary> /// Initializes <see cref="StrongNameKey"/> and <see cref="StrongNamePublicKey"/> /// for normal strong name signing. /// </summary> /// <param name="module">Module</param> /// <param name="signatureKey">Signature strong name key pair</param> public void InitializeStrongNameSigning(ModuleDef module, StrongNameKey signatureKey) { StrongNameKey = signatureKey; StrongNamePublicKey = null; if (module.Assembly != null) module.Assembly.CustomAttributes.RemoveAll("System.Reflection.AssemblySignatureKeyAttribute"); } /// <summary> /// Initializes <see cref="StrongNameKey"/> and <see cref="StrongNamePublicKey"/> /// for enhanced strong name signing (without key migration). See /// http://msdn.microsoft.com/en-us/library/hh415055.aspx /// </summary> /// <param name="module">Module</param> /// <param name="signatureKey">Signature strong name key pair</param> /// <param name="signaturePubKey">Signature public key</param> public void InitializeEnhancedStrongNameSigning(ModuleDef module, StrongNameKey signatureKey, StrongNamePublicKey signaturePubKey) { InitializeStrongNameSigning(module, signatureKey); StrongNameKey.HashAlgorithm = signaturePubKey.HashAlgorithm; } /// <summary> /// Initializes <see cref="StrongNameKey"/> and <see cref="StrongNamePublicKey"/> /// for enhanced strong name signing (with key migration). See /// http://msdn.microsoft.com/en-us/library/hh415055.aspx /// </summary> /// <param name="module">Module</param> /// <param name="signatureKey">Signature strong name key pair</param> /// <param name="signaturePubKey">Signature public key</param> /// <param name="identityKey">Identity strong name key pair</param> /// <param name="identityPubKey">Identity public key</param> public void InitializeEnhancedStrongNameSigning(ModuleDef module, StrongNameKey signatureKey, StrongNamePublicKey signaturePubKey, StrongNameKey identityKey, StrongNamePublicKey identityPubKey) { StrongNameKey = signatureKey; StrongNameKey.HashAlgorithm = signaturePubKey.HashAlgorithm; StrongNamePublicKey = identityPubKey; if (module.Assembly != null) module.Assembly.UpdateOrCreateAssemblySignatureKeyAttribute(identityPubKey, identityKey, signaturePubKey); } } /// <summary> /// Creates a new <see cref="ISymbolWriter2"/> instance /// </summary> /// <param name="writer">Module writer</param> /// <returns>A new <see cref="ISymbolWriter2"/> instance</returns> public delegate ISymbolWriter2 CreatePdbSymbolWriterDelegate(ModuleWriterBase writer); /// <summary> /// Module writer base class /// </summary> public abstract class ModuleWriterBase : IMetaDataListener, ILogger { /// <summary>Default alignment of all constants</summary> protected internal const uint DEFAULT_CONSTANTS_ALIGNMENT = 8; /// <summary>Default alignment of all method bodies</summary> protected const uint DEFAULT_METHODBODIES_ALIGNMENT = 4; /// <summary>Default alignment of all .NET resources</summary> protected const uint DEFAULT_NETRESOURCES_ALIGNMENT = 8; /// <summary>Default alignment of the .NET metadata</summary> protected const uint DEFAULT_METADATA_ALIGNMENT = 4; /// <summary>Default Win32 resources alignment</summary> protected internal const uint DEFAULT_WIN32_RESOURCES_ALIGNMENT = 8; /// <summary>Default strong name signature alignment</summary> protected const uint DEFAULT_STRONGNAMESIG_ALIGNMENT = 16; /// <summary>Default COR20 header alignment</summary> protected const uint DEFAULT_COR20HEADER_ALIGNMENT = 4; /// <summary>Default debug directory alignment</summary> protected const uint DEFAULT_DEBUGDIRECTORY_ALIGNMENT = 4; /// <summary>See <see cref="DestinationStream"/></summary> protected Stream destStream; /// <summary>See <see cref="Constants"/></summary> protected UniqueChunkList<ByteArrayChunk> constants; /// <summary>See <see cref="MethodBodies"/></summary> protected MethodBodyChunks methodBodies; /// <summary>See <see cref="NetResources"/></summary> protected NetResources netResources; /// <summary>See <see cref="MetaData"/></summary> protected MetaData metaData; /// <summary>See <see cref="Win32Resources"/></summary> protected Win32ResourcesChunk win32Resources; /// <summary>Offset where the module is written. Usually 0.</summary> protected long destStreamBaseOffset; IModuleWriterListener listener; /// <summary>Debug directory</summary> protected DebugDirectory debugDirectory; string createdPdbFileName; /// <summary> /// Strong name signature /// </summary> protected StrongNameSignature strongNameSignature; /// <summary> /// Returns the module writer options /// </summary> public abstract ModuleWriterOptionsBase TheOptions { get; } /// <summary> /// Gets/sets the module writer listener /// </summary> protected IModuleWriterListener Listener { get { return listener ?? DummyModuleWriterListener.Instance; } set { listener = value; } } /// <summary> /// Gets the destination stream /// </summary> public Stream DestinationStream { get { return destStream; } } /// <summary> /// Gets the constants /// </summary> public UniqueChunkList<ByteArrayChunk> Constants { get { return constants; } } /// <summary> /// Gets the method bodies /// </summary> public MethodBodyChunks MethodBodies { get { return methodBodies; } } /// <summary> /// Gets the .NET resources /// </summary> public NetResources NetResources { get { return netResources; } } /// <summary> /// Gets the .NET metadata /// </summary> public MetaData MetaData { get { return metaData; } } /// <summary> /// Gets the Win32 resources or <c>null</c> if there's none /// </summary> public Win32ResourcesChunk Win32Resources { get { return win32Resources; } } /// <summary> /// Gets the strong name signature or <c>null</c> if there's none /// </summary> public StrongNameSignature StrongNameSignature { get { return strongNameSignature; } } /// <summary> /// Gets all <see cref="PESection"/>s /// </summary> public abstract List<PESection> Sections { get; } /// <summary> /// Gets the <c>.text</c> section /// </summary> public abstract PESection TextSection { get; } /// <summary> /// Gets the <c>.rsrc</c> section or <c>null</c> if there's none /// </summary> public abstract PESection RsrcSection { get; } /// <summary> /// Gets the debug directory or <c>null</c> if there's none /// </summary> public DebugDirectory DebugDirectory { get { return debugDirectory; } } /// <summary> /// <c>true</c> if <c>this</c> is a <see cref="NativeModuleWriter"/>, <c>false</c> if /// <c>this</c> is a <see cref="ModuleWriter"/>. /// </summary> public bool IsNativeWriter { get { return this is NativeModuleWriter; } } /// <summary> /// Writes the module to a file /// </summary> /// <param name="fileName">File name. The file will be truncated if it exists.</param> public void Write(string fileName) { using (var dest = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { dest.SetLength(0); try { Write(dest); } catch { // Writing failed. Delete the file since it's useless. dest.Close(); DeleteFileNoThrow(fileName); throw; } } } static void DeleteFileNoThrow(string fileName) { if (string.IsNullOrEmpty(fileName)) return; try { File.Delete(fileName); } catch { } } /// <summary> /// Writes the module to a <see cref="Stream"/> /// </summary> /// <param name="dest">Destination stream</param> public void Write(Stream dest) { if (TheOptions.DelaySign) { Debug.Assert(TheOptions.StrongNamePublicKey != null, "Options.StrongNamePublicKey must be initialized when delay signing the assembly"); Debug.Assert(TheOptions.StrongNameKey == null, "Options.StrongNameKey must be null when delay signing the assembly"); TheOptions.Cor20HeaderOptions.Flags &= ~ComImageFlags.StrongNameSigned; } else if (TheOptions.StrongNameKey != null || TheOptions.StrongNamePublicKey != null) TheOptions.Cor20HeaderOptions.Flags |= ComImageFlags.StrongNameSigned; Listener = TheOptions.Listener ?? DummyModuleWriterListener.Instance; destStream = dest; destStreamBaseOffset = destStream.Position; Listener.OnWriterEvent(this, ModuleWriterEvent.Begin); var imageLength = WriteImpl(); destStream.Position = destStreamBaseOffset + imageLength; Listener.OnWriterEvent(this, ModuleWriterEvent.End); } /// <summary> /// Returns the module that is written /// </summary> public abstract ModuleDef Module { get; } /// <summary> /// Writes the module to <see cref="destStream"/>. <see cref="Listener"/> and /// <see cref="destStream"/> have been initialized when this method is called. /// </summary> /// <returns>Number of bytes written</returns> protected abstract long WriteImpl(); /// <summary> /// Creates the strong name signature if the module has one of the strong name flags /// set or wants to sign the assembly. /// </summary> protected void CreateStrongNameSignature() { if (TheOptions.DelaySign && TheOptions.StrongNamePublicKey != null) { int len = TheOptions.StrongNamePublicKey.CreatePublicKey().Length - 0x20; strongNameSignature = new StrongNameSignature(len > 0 ? len : 0x80); } else if (TheOptions.StrongNameKey != null) strongNameSignature = new StrongNameSignature(TheOptions.StrongNameKey.SignatureSize); else if (Module.Assembly != null && !PublicKeyBase.IsNullOrEmpty2(Module.Assembly.PublicKey)) { int len = Module.Assembly.PublicKey.Data.Length - 0x20; strongNameSignature = new StrongNameSignature(len > 0 ? len : 0x80); } else if (((TheOptions.Cor20HeaderOptions.Flags ?? Module.Cor20HeaderFlags) & ComImageFlags.StrongNameSigned) != 0) strongNameSignature = new StrongNameSignature(0x80); } /// <summary> /// Creates the .NET metadata chunks (constants, method bodies, .NET resources, /// the metadata, and Win32 resources) /// </summary> /// <param name="module"></param> protected void CreateMetaDataChunks(ModuleDef module) { constants = new UniqueChunkList<ByteArrayChunk>(); methodBodies = new MethodBodyChunks(TheOptions.ShareMethodBodies); netResources = new NetResources(DEFAULT_NETRESOURCES_ALIGNMENT); metaData = MetaData.Create(module, constants, methodBodies, netResources, TheOptions.MetaDataOptions); metaData.Logger = TheOptions.MetaDataLogger ?? this; metaData.Listener = this; // StrongNamePublicKey is used if the user wants to override the assembly's // public key or when enhanced strong naming the assembly. var pk = TheOptions.StrongNamePublicKey; if (pk != null) metaData.AssemblyPublicKey = pk.CreatePublicKey(); else if (TheOptions.StrongNameKey != null) metaData.AssemblyPublicKey = TheOptions.StrongNameKey.PublicKey; var w32Resources = GetWin32Resources(); if (w32Resources != null) win32Resources = new Win32ResourcesChunk(w32Resources); } /// <summary> /// Gets the Win32 resources that should be written to the new image or <c>null</c> if none /// </summary> protected abstract Win32Resources GetWin32Resources(); /// <summary> /// Calculates <see cref="RVA"/> and <see cref="FileOffset"/> of all <see cref="IChunk"/>s /// </summary> /// <param name="chunks">All chunks</param> /// <param name="offset">Starting file offset</param> /// <param name="rva">Starting RVA</param> /// <param name="fileAlignment">File alignment</param> /// <param name="sectionAlignment">Section alignment</param> protected void CalculateRvasAndFileOffsets(List<IChunk> chunks, FileOffset offset, RVA rva, uint fileAlignment, uint sectionAlignment) { foreach (var chunk in chunks) { chunk.SetOffset(offset, rva); offset += chunk.GetFileLength(); rva += chunk.GetVirtualSize(); offset = offset.AlignUp(fileAlignment); rva = rva.AlignUp(sectionAlignment); } } /// <summary> /// Writes all chunks to <paramref name="writer"/> /// </summary> /// <param name="writer">The writer</param> /// <param name="chunks">All chunks</param> /// <param name="offset">File offset of first chunk</param> /// <param name="fileAlignment">File alignment</param> protected void WriteChunks(BinaryWriter writer, List<IChunk> chunks, FileOffset offset, uint fileAlignment) { foreach (var chunk in chunks) { chunk.VerifyWriteTo(writer); offset += chunk.GetFileLength(); var newOffset = offset.AlignUp(fileAlignment); writer.WriteZeros((int)(newOffset - offset)); offset = newOffset; } } /// <summary> /// Strong name sign the assembly /// </summary> /// <param name="snSigOffset">Strong name signature offset</param> protected void StrongNameSign(long snSigOffset) { var snSigner = new StrongNameSigner(destStream, destStreamBaseOffset); snSigner.WriteSignature(TheOptions.StrongNameKey, snSigOffset); } bool CanWritePdb() { return TheOptions.WritePdb && Module.PdbState != null; } /// <summary> /// Creates the debug directory if a PDB file should be written /// </summary> protected void CreateDebugDirectory() { if (CanWritePdb()) debugDirectory = new DebugDirectory(); } /// <summary> /// Write the PDB file. The caller should send the PDB events before and after calling this /// method. /// </summary> protected void WritePdbFile() { if (!CanWritePdb()) return; if (debugDirectory == null) throw new InvalidOperationException("debugDirectory is null but WritePdb is true"); var pdbState = Module.PdbState; if (pdbState == null) { Error("TheOptions.WritePdb is true but module has no PdbState"); debugDirectory.DontWriteAnything = true; return; } var symWriter = GetSymbolWriter2(); if (symWriter == null) { Error("Could not create a PDB symbol writer. A Windows OS might be required."); debugDirectory.DontWriteAnything = true; return; } var pdbWriter = new PdbWriter(symWriter, pdbState, metaData); try { pdbWriter.Logger = TheOptions.Logger; pdbWriter.Write(); debugDirectory.Data = pdbWriter.GetDebugInfo(out debugDirectory.debugDirData); debugDirectory.TimeDateStamp = GetTimeDateStamp(); pdbWriter.Dispose(); } catch { pdbWriter.Dispose(); DeleteFileNoThrow(createdPdbFileName); throw; } } uint GetTimeDateStamp() { var td = TheOptions.PEHeadersOptions.TimeDateStamp; if (td.HasValue) return (uint)td; TheOptions.PEHeadersOptions.TimeDateStamp = PEHeadersOptions.CreateNewTimeDateStamp(); return (uint)TheOptions.PEHeadersOptions.TimeDateStamp; } ISymbolWriter2 GetSymbolWriter2() { if (TheOptions.CreatePdbSymbolWriter != null) { var writer = TheOptions.CreatePdbSymbolWriter(this); if (writer != null) return writer; } if (TheOptions.PdbStream != null) { return SymbolWriterCreator.Create(TheOptions.PdbStream, TheOptions.PdbFileName ?? GetStreamName(TheOptions.PdbStream) ?? GetDefaultPdbFileName()); } if (!string.IsNullOrEmpty(TheOptions.PdbFileName)) { createdPdbFileName = TheOptions.PdbFileName; return SymbolWriterCreator.Create(createdPdbFileName); } createdPdbFileName = GetDefaultPdbFileName(); if (createdPdbFileName == null) return null; return SymbolWriterCreator.Create(createdPdbFileName); } static string GetStreamName(Stream stream) { var fs = stream as FileStream; return fs == null ? null : fs.Name; } string GetDefaultPdbFileName() { var destFileName = GetStreamName(destStream); if (string.IsNullOrEmpty(destFileName)) { Error("TheOptions.WritePdb is true but it's not possible to guess the default PDB file name. Set PdbFileName to the name of the PDB file."); return null; } return Path.ChangeExtension(destFileName, "pdb"); } /// <inheritdoc/> void IMetaDataListener.OnMetaDataEvent(MetaData metaData, MetaDataEvent evt) { switch (evt) { case MetaDataEvent.BeginCreateTables: Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeginCreateTables); break; case MetaDataEvent.AllocateTypeDefRids: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateTypeDefRids); break; case MetaDataEvent.AllocateMemberDefRids: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids); break; case MetaDataEvent.AllocateMemberDefRids0: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids0); break; case MetaDataEvent.AllocateMemberDefRids1: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids1); break; case MetaDataEvent.AllocateMemberDefRids2: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids2); break; case MetaDataEvent.AllocateMemberDefRids3: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids3); break; case MetaDataEvent.AllocateMemberDefRids4: Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids4); break; case MetaDataEvent.MemberDefRidsAllocated: Listener.OnWriterEvent(this, ModuleWriterEvent.MDMemberDefRidsAllocated); break; case MetaDataEvent.InitializeTypeDefsAndMemberDefs0: Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs0); break; case MetaDataEvent.InitializeTypeDefsAndMemberDefs1: Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs1); break; case MetaDataEvent.InitializeTypeDefsAndMemberDefs2: Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs2); break; case MetaDataEvent.InitializeTypeDefsAndMemberDefs3: Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs3); break; case MetaDataEvent.InitializeTypeDefsAndMemberDefs4: Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs4); break; case MetaDataEvent.MemberDefsInitialized: Listener.OnWriterEvent(this, ModuleWriterEvent.MDMemberDefsInitialized); break; case MetaDataEvent.BeforeSortTables: Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeforeSortTables); break; case MetaDataEvent.MostTablesSorted: Listener.OnWriterEvent(this, ModuleWriterEvent.MDMostTablesSorted); break; case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes0: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes0); break; case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes1: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes1); break; case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes2: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes2); break; case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes3: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes3); break; case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes4: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes4); break; case MetaDataEvent.MemberDefCustomAttributesWritten: Listener.OnWriterEvent(this, ModuleWriterEvent.MDMemberDefCustomAttributesWritten); break; case MetaDataEvent.BeginAddResources: Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeginAddResources); break; case MetaDataEvent.EndAddResources: Listener.OnWriterEvent(this, ModuleWriterEvent.MDEndAddResources); break; case MetaDataEvent.BeginWriteMethodBodies: Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeginWriteMethodBodies); break; case MetaDataEvent.WriteMethodBodies0: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies0); break; case MetaDataEvent.WriteMethodBodies1: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies1); break; case MetaDataEvent.WriteMethodBodies2: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies2); break; case MetaDataEvent.WriteMethodBodies3: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies3); break; case MetaDataEvent.WriteMethodBodies4: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies4); break; case MetaDataEvent.WriteMethodBodies5: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies5); break; case MetaDataEvent.WriteMethodBodies6: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies6); break; case MetaDataEvent.WriteMethodBodies7: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies7); break; case MetaDataEvent.WriteMethodBodies8: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies8); break; case MetaDataEvent.WriteMethodBodies9: Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies9); break; case MetaDataEvent.EndWriteMethodBodies: Listener.OnWriterEvent(this, ModuleWriterEvent.MDEndWriteMethodBodies); break; case MetaDataEvent.OnAllTablesSorted: Listener.OnWriterEvent(this, ModuleWriterEvent.MDOnAllTablesSorted); break; case MetaDataEvent.EndCreateTables: Listener.OnWriterEvent(this, ModuleWriterEvent.MDEndCreateTables); break; default: break; } } ILogger GetLogger() { return TheOptions.Logger ?? DummyLogger.ThrowModuleWriterExceptionOnErrorInstance; } /// <inheritdoc/> void ILogger.Log(object sender, LoggerEvent loggerEvent, string format, params object[] args) { GetLogger().Log(this, loggerEvent, format, args); } /// <inheritdoc/> bool ILogger.IgnoresEvent(LoggerEvent loggerEvent) { return GetLogger().IgnoresEvent(loggerEvent); } /// <summary> /// Logs an error message /// </summary> /// <param name="format">Format</param> /// <param name="args">Format args</param> protected void Error(string format, params object[] args) { GetLogger().Log(this, LoggerEvent.Error, format, args); } /// <summary> /// Logs a warning message /// </summary> /// <param name="format">Format</param> /// <param name="args">Format args</param> protected void Warning(string format, params object[] args) { GetLogger().Log(this, LoggerEvent.Warning, format, args); } } }
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 DistanceCalculator.WebApiService.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; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Framework.Logging; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Edit.Tools; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI; using osu.Game.Screens.Edit; using osu.Game.Screens.Edit.Components.RadioButtons; using osu.Game.Screens.Edit.Compose; using osu.Game.Screens.Edit.Compose.Components; using osuTK; using Key = osuTK.Input.Key; namespace osu.Game.Rulesets.Edit { [Cached(Type = typeof(IPlacementHandler))] public abstract class HitObjectComposer<TObject> : HitObjectComposer, IPlacementHandler where TObject : HitObject { protected IRulesetConfigManager Config { get; private set; } protected readonly Ruleset Ruleset; [Resolved] protected IFrameBasedClock EditorClock { get; private set; } [Resolved] protected EditorBeatmap EditorBeatmap { get; private set; } [Resolved] private IAdjustableClock adjustableClock { get; set; } [Resolved] private IBeatSnapProvider beatSnapProvider { get; set; } protected ComposeBlueprintContainer BlueprintContainer { get; private set; } private DrawableEditRulesetWrapper<TObject> drawableRulesetWrapper; private Container distanceSnapGridContainer; private DistanceSnapGrid distanceSnapGrid; private readonly List<Container> layerContainers = new List<Container>(); private InputManager inputManager; private RadioButtonCollection toolboxCollection; protected HitObjectComposer(Ruleset ruleset) { Ruleset = ruleset; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(IFrameBasedClock framedClock) { Config = Dependencies.Get<RulesetConfigCache>().GetConfigFor(Ruleset); try { drawableRulesetWrapper = new DrawableEditRulesetWrapper<TObject>(CreateDrawableRuleset(Ruleset, EditorBeatmap.PlayableBeatmap)) { Clock = framedClock, ProcessCustomClock = false }; } catch (Exception e) { Logger.Error(e, "Could not load beatmap sucessfully!"); return; } var layerBelowRuleset = drawableRulesetWrapper.CreatePlayfieldAdjustmentContainer().WithChildren(new Drawable[] { distanceSnapGridContainer = new Container { RelativeSizeAxes = Axes.Both }, new EditorPlayfieldBorder { RelativeSizeAxes = Axes.Both } }); var layerAboveRuleset = drawableRulesetWrapper.CreatePlayfieldAdjustmentContainer().WithChild(BlueprintContainer = CreateBlueprintContainer()); layerContainers.Add(layerBelowRuleset); layerContainers.Add(layerAboveRuleset); InternalChild = new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new FillFlowContainer { Name = "Sidebar", RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Right = 10 }, Children = new Drawable[] { new ToolboxGroup { Child = toolboxCollection = new RadioButtonCollection { RelativeSizeAxes = Axes.X } } } }, new Container { Name = "Content", RelativeSizeAxes = Axes.Both, Children = new Drawable[] { layerBelowRuleset, drawableRulesetWrapper, layerAboveRuleset } } }, }, ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, 200), } }; toolboxCollection.Items = CompositionTools .Prepend(new SelectTool()) .Select(t => new RadioButton(t.Name, () => toolSelected(t))) .ToList(); setSelectTool(); BlueprintContainer.SelectionChanged += selectionChanged; } protected override bool OnKeyDown(KeyDownEvent e) { if (e.Key >= Key.Number1 && e.Key <= Key.Number9) { var item = toolboxCollection.Items.ElementAtOrDefault(e.Key - Key.Number1); if (item != null) { item.Select(); return true; } } return base.OnKeyDown(e); } protected override void LoadComplete() { base.LoadComplete(); inputManager = GetContainingInputManager(); } private double lastGridUpdateTime; protected override void Update() { base.Update(); if (EditorClock.CurrentTime != lastGridUpdateTime && !(BlueprintContainer.CurrentTool is SelectTool)) showGridFor(Enumerable.Empty<HitObject>()); } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); layerContainers.ForEach(l => { l.Anchor = drawableRulesetWrapper.Playfield.Anchor; l.Origin = drawableRulesetWrapper.Playfield.Origin; l.Position = drawableRulesetWrapper.Playfield.Position; l.Size = drawableRulesetWrapper.Playfield.Size; }); } private void selectionChanged(IEnumerable<HitObject> selectedHitObjects) { var hitObjects = selectedHitObjects.ToArray(); if (hitObjects.Any()) { // ensure in selection mode if a selection is made. setSelectTool(); showGridFor(hitObjects); } else distanceSnapGridContainer.Hide(); } private void setSelectTool() => toolboxCollection.Items.First().Select(); private void toolSelected(HitObjectCompositionTool tool) { BlueprintContainer.CurrentTool = tool; if (tool is SelectTool) distanceSnapGridContainer.Hide(); else { EditorBeatmap.SelectedHitObjects.Clear(); showGridFor(Enumerable.Empty<HitObject>()); } } private void showGridFor(IEnumerable<HitObject> selectedHitObjects) { distanceSnapGridContainer.Clear(); distanceSnapGrid = CreateDistanceSnapGrid(selectedHitObjects); if (distanceSnapGrid != null) { distanceSnapGridContainer.Child = distanceSnapGrid; distanceSnapGridContainer.Show(); } lastGridUpdateTime = EditorClock.CurrentTime; } public override IEnumerable<DrawableHitObject> HitObjects => drawableRulesetWrapper.Playfield.AllHitObjects; public override bool CursorInPlacementArea => drawableRulesetWrapper.Playfield.ReceivePositionalInputAt(inputManager.CurrentState.Mouse.Position); protected abstract IReadOnlyList<HitObjectCompositionTool> CompositionTools { get; } protected abstract ComposeBlueprintContainer CreateBlueprintContainer(); protected abstract DrawableRuleset<TObject> CreateDrawableRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null); public void BeginPlacement(HitObject hitObject) { EditorBeatmap.PlacementObject.Value = hitObject; if (distanceSnapGrid != null) hitObject.StartTime = GetSnappedPosition(distanceSnapGrid.ToLocalSpace(inputManager.CurrentState.Mouse.Position), hitObject.StartTime).time; } public void EndPlacement(HitObject hitObject, bool commit) { EditorBeatmap.PlacementObject.Value = null; if (commit) { EditorBeatmap.Add(hitObject); adjustableClock.Seek(hitObject.GetEndTime()); } showGridFor(Enumerable.Empty<HitObject>()); } public void Delete(HitObject hitObject) => EditorBeatmap.Remove(hitObject); public override (Vector2 position, double time) GetSnappedPosition(Vector2 position, double time) => distanceSnapGrid?.GetSnappedPosition(position) ?? (position, time); public override float GetBeatSnapDistanceAt(double referenceTime) { DifficultyControlPoint difficultyPoint = EditorBeatmap.ControlPointInfo.DifficultyPointAt(referenceTime); return (float)(100 * EditorBeatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier * difficultyPoint.SpeedMultiplier / beatSnapProvider.BeatDivisor); } public override float DurationToDistance(double referenceTime, double duration) { double beatLength = beatSnapProvider.GetBeatLengthAtTime(referenceTime); return (float)(duration / beatLength * GetBeatSnapDistanceAt(referenceTime)); } public override double DistanceToDuration(double referenceTime, float distance) { double beatLength = beatSnapProvider.GetBeatLengthAtTime(referenceTime); return distance / GetBeatSnapDistanceAt(referenceTime) * beatLength; } public override double GetSnappedDurationFromDistance(double referenceTime, float distance) => beatSnapProvider.SnapTime(referenceTime + DistanceToDuration(referenceTime, distance), referenceTime) - referenceTime; public override float GetSnappedDistanceFromDistance(double referenceTime, float distance) { var snappedEndTime = beatSnapProvider.SnapTime(referenceTime + DistanceToDuration(referenceTime, distance), referenceTime); return DurationToDistance(referenceTime, snappedEndTime - referenceTime); } } [Cached(typeof(HitObjectComposer))] [Cached(typeof(IDistanceSnapProvider))] public abstract class HitObjectComposer : CompositeDrawable, IDistanceSnapProvider { internal HitObjectComposer() { RelativeSizeAxes = Axes.Both; } /// <summary> /// All the <see cref="DrawableHitObject"/>s. /// </summary> public abstract IEnumerable<DrawableHitObject> HitObjects { get; } /// <summary> /// Whether the user's cursor is currently in an area of the <see cref="HitObjectComposer"/> that is valid for placement. /// </summary> public abstract bool CursorInPlacementArea { get; } /// <summary> /// Creates the <see cref="DistanceSnapGrid"/> applicable for a <see cref="HitObject"/> selection. /// </summary> /// <param name="selectedHitObjects">The <see cref="HitObject"/> selection.</param> /// <returns>The <see cref="DistanceSnapGrid"/> for <paramref name="selectedHitObjects"/>. If empty, a grid is returned for the current point in time.</returns> [CanBeNull] protected virtual DistanceSnapGrid CreateDistanceSnapGrid([NotNull] IEnumerable<HitObject> selectedHitObjects) => null; public abstract (Vector2 position, double time) GetSnappedPosition(Vector2 position, double time); public abstract float GetBeatSnapDistanceAt(double referenceTime); public abstract float DurationToDistance(double referenceTime, double duration); public abstract double DistanceToDuration(double referenceTime, float distance); public abstract double GetSnappedDurationFromDistance(double referenceTime, float distance); public abstract float GetSnappedDistanceFromDistance(double referenceTime, float distance); } }
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32 { /// <summary>Static class providing access to information about the operating system under which the assembly is executing.</summary> public static class OperatingSystem { /// <summary>A set of flags that describe the named Windows versions.</summary> /// <remarks>The values of the enumeration are ordered. A later released operating system version has a higher number, so comparisons between named versions are meaningful.</remarks> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Os")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Os")] public enum EnumOsName { /// <summary>A Windows version earlier than Windows 2000.</summary> Earlier = -1, /// <summary>Windows 2000 (Server or Professional).</summary> Windows2000 = 0, /// <summary>Windows XP.</summary> WindowsXP = 1, /// <summary>Windows Server 2003.</summary> WindowsServer2003 = 2, /// <summary>Windows Vista.</summary> WindowsVista = 3, /// <summary>Windows Server 2008.</summary> WindowsServer2008 = 4, /// <summary>Windows 7.</summary> Windows7 = 5, /// <summary>Windows Server 2008 R2.</summary> WindowsServer2008R2 = 6, /// <summary>Windows 8.</summary> Windows8 = 7, /// <summary>Windows Server 2012.</summary> WindowsServer2012 = 8, /// <summary>Windows 8.1.</summary> Windows81 = 9, /// <summary>Windows Server 2012 R2</summary> WindowsServer2012R2 = 10, /// <summary>Windows 10</summary> Windows10 = 11, /// <summary>Windows Server 2016</summary> WindowsServer2016 = 12, /// <summary>A later version of Windows than currently installed.</summary> Later = 65535 } /// <summary>A set of flags to indicate the current processor architecture for which the operating system is targeted and running.</summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pa")] [SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32")] public enum EnumProcessorArchitecture { /// <summary>PROCESSOR_ARCHITECTURE_INTEL /// <para>The system is running a 32-bit version of Windows.</para> /// </summary> X86 = 0, /// <summary>PROCESSOR_ARCHITECTURE_IA64 /// <para>The system is running on a Itanium processor.</para> /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ia")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ia")] IA64 = 6, /// <summary>PROCESSOR_ARCHITECTURE_AMD64 /// <para>The system is running a 64-bit version of Windows.</para> /// </summary> X64 = 9, /// <summary>PROCESSOR_ARCHITECTURE_UNKNOWN /// <para>Unknown architecture.</para> /// </summary> Unknown = 65535 } #region Properties private static bool _isServer; /// <summary>Gets a value indicating whether the operating system is a server operating system.</summary> /// <value><c>true</c> if the current operating system is a server operating system; otherwise, <c>false</c>.</value> public static bool IsServer { get { if (null == _servicePackVersion) UpdateData(); return _isServer; } } private static bool? _isWow64Process; /// <summary>Gets a value indicating whether the current process is running under WOW64.</summary> /// <value><c>true</c> if the current process is running under WOW64; otherwise, <c>false</c>.</value> public static bool IsWow64Process { get { if (null == _isWow64Process) { bool value; var processHandle = Process.GetCurrentProcess().Handle; if (!NativeMethods.IsWow64Process(processHandle, out value)) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); // A pointer to a value that is set to TRUE if the process is running under WOW64. // If the process is running under 32-bit Windows, the value is set to FALSE. // If the process is a 64-bit application running under 64-bit Windows, the value is also set to FALSE. _isWow64Process = value; } return (bool) _isWow64Process; } } private static Version _osVersion; /// <summary>Gets the numeric version of the operating system.</summary> /// <value>The numeric version of the operating system.</value> public static Version OSVersion { get { if (null == _osVersion) UpdateData(); return _osVersion; } } private static EnumOsName _enumOsName = EnumOsName.Later; /// <summary>Gets the named version of the operating system.</summary> /// <value>The named version of the operating system.</value> public static EnumOsName VersionName { get { if (null == _servicePackVersion) UpdateData(); return _enumOsName; } } private static EnumProcessorArchitecture _processorArchitecture; /// <summary>Gets the processor architecture for which the operating system is targeted.</summary> /// <value>The processor architecture for which the operating system is targeted.</value> /// <remarks>If running under WOW64 this will return a 32-bit processor. Use <see cref="IsWow64Process"/> to determine if this is the case.</remarks> public static EnumProcessorArchitecture ProcessorArchitecture { get { if (null == _servicePackVersion) UpdateData(); return _processorArchitecture; } } private static Version _servicePackVersion; /// <summary>Gets the version of the service pack currently installed on the operating system.</summary> /// <value>The version of the service pack currently installed on the operating system.</value> /// <remarks>Only the <see cref="System.Version.Major"/> and <see cref="System.Version.Minor"/> fields are used.</remarks> public static Version ServicePackVersion { get { if (null == _servicePackVersion) UpdateData(); return _servicePackVersion; } } #endregion // Properties #region Methods /// <summary>Determines whether the operating system is of the specified version or later.</summary> /// <returns><c>true</c> if the operating system is of the specified <paramref name="version"/> or later; otherwise, <c>false</c>.</returns> /// <param name="version">The lowest version for which to return true.</param> public static bool IsAtLeast(EnumOsName version) { return VersionName >= version; } /// <summary>Determines whether the operating system is of the specified version or later, allowing specification of a minimum service pack that must be installed on the lowest version.</summary> /// <returns><c>true</c> if the operating system matches the specified <paramref name="version"/> with the specified service pack, or if the operating system is of a later version; otherwise, <c>false</c>.</returns> /// <param name="version">The minimum required version.</param> /// <param name="servicePackVersion">The major version of the service pack that must be installed on the minimum required version to return true. This can be 0 to indicate that no service pack is required.</param> public static bool IsAtLeast(EnumOsName version, int servicePackVersion) { return IsAtLeast(version) && ServicePackVersion.Major >= servicePackVersion; } #endregion // Methods #region Private [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "RtlGetVersion")] private static void UpdateData() { var verInfo = new NativeMethods.RTL_OSVERSIONINFOEXW(); // Needed to prevent: System.Runtime.InteropServices.COMException: // The data area passed to a system call is too small. (Exception from HRESULT: 0x8007007A) verInfo.dwOSVersionInfoSize = Marshal.SizeOf(verInfo); var sysInfo = new NativeMethods.SYSTEM_INFO(); NativeMethods.GetNativeSystemInfo(ref sysInfo); // RtlGetVersion returns STATUS_SUCCESS (0). var success = !NativeMethods.RtlGetVersion(ref verInfo); var lastError = Marshal.GetLastWin32Error(); if (!success) throw new Win32Exception(lastError, "Function RtlGetVersion() failed to retrieve the operating system information."); _osVersion = new Version(verInfo.dwMajorVersion, verInfo.dwMinorVersion, verInfo.dwBuildNumber); _processorArchitecture = sysInfo.wProcessorArchitecture; _servicePackVersion = new Version(verInfo.wServicePackMajor, verInfo.wServicePackMinor); _isServer = verInfo.wProductType == NativeMethods.VER_NT_DOMAIN_CONTROLLER || verInfo.wProductType == NativeMethods.VER_NT_SERVER; // RtlGetVersion: https://msdn.microsoft.com/en-us/library/windows/hardware/ff561910%28v=vs.85%29.aspx // Operating System Version: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx // The following table summarizes the most recent operating system version numbers. // Operating system Version number Other // ================================================================================ // Windows 10 10.0 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2016 10.0 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows 8.1 6.3 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2012 R2 6.3 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows 8 6.2 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2012 6.2 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows 7 6.1 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2008 R2 6.1 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows Server 2008 6.0 OSVERSIONINFOEX.wProductType != VER_NT_WORKSTATION // Windows Vista 6.0 OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION // Windows Server 2003 R2 5.2 GetSystemMetrics(SM_SERVERR2) != 0 // Windows Server 2003 5.2 GetSystemMetrics(SM_SERVERR2) == 0 // Windows XP 64-Bit Edition 5.2 (OSVERSIONINFOEX.wProductType == VER_NT_WORKSTATION) && (sysInfo.PaName == PaName.X64) // Windows XP 5.1 Not applicable // Windows 2000 5.0 Not applicable // 2017-01-07: 10 == The lastest MajorVersion of Windows. if (verInfo.dwMajorVersion > 10) _enumOsName = EnumOsName.Later; else switch (verInfo.dwMajorVersion) { #region Version 10 case 10: // Windows 10 or Windows Server 2016 _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows10 : EnumOsName.WindowsServer2016; break; #endregion // Version 10 #region Version 6 case 6: switch (verInfo.dwMinorVersion) { // Windows 8.1 or Windows Server 2012 R2 case 3: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows81 : EnumOsName.WindowsServer2012R2; break; // Windows 8 or Windows Server 2012 case 2: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows8 : EnumOsName.WindowsServer2012; break; // Windows 7 or Windows Server 2008 R2 case 1: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.Windows7 : EnumOsName.WindowsServer2008R2; break; // Windows Vista or Windows Server 2008 case 0: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION ? EnumOsName.WindowsVista : EnumOsName.WindowsServer2008; break; default: _enumOsName = EnumOsName.Later; break; } break; #endregion // Version 6 #region Version 5 case 5: switch (verInfo.dwMinorVersion) { case 2: _enumOsName = verInfo.wProductType == NativeMethods.VER_NT_WORKSTATION && _processorArchitecture == EnumProcessorArchitecture.X64 ? EnumOsName.WindowsXP : verInfo.wProductType != NativeMethods.VER_NT_WORKSTATION ? EnumOsName.WindowsServer2003 : EnumOsName.Later; break; case 1: _enumOsName = EnumOsName.WindowsXP; break; case 0: _enumOsName = EnumOsName.Windows2000; break; default: _enumOsName = EnumOsName.Later; break; } break; #endregion // Version 5 default: _enumOsName = EnumOsName.Earlier; break; } } private static class NativeMethods { internal const short VER_NT_WORKSTATION = 1; internal const short VER_NT_DOMAIN_CONTROLLER = 2; internal const short VER_NT_SERVER = 3; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct RTL_OSVERSIONINFOEXW { public int dwOSVersionInfoSize; public readonly int dwMajorVersion; public readonly int dwMinorVersion; public readonly int dwBuildNumber; public readonly int dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public readonly string szCSDVersion; public readonly ushort wServicePackMajor; public readonly ushort wServicePackMinor; public readonly ushort wSuiteMask; public readonly byte wProductType; public readonly byte wReserved; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SYSTEM_INFO { public readonly EnumProcessorArchitecture wProcessorArchitecture; private readonly ushort wReserved; public readonly uint dwPageSize; public readonly IntPtr lpMinimumApplicationAddress; public readonly IntPtr lpMaximumApplicationAddress; public readonly IntPtr dwActiveProcessorMask; public readonly uint dwNumberOfProcessors; public readonly uint dwProcessorType; public readonly uint dwAllocationGranularity; public readonly ushort wProcessorLevel; public readonly ushort wProcessorRevision; } /// <summary>The RtlGetVersion routine returns version information about the currently running operating system.</summary> /// <returns>RtlGetVersion returns STATUS_SUCCESS.</returns> /// <remarks>Available starting with Windows 2000.</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule"), DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RtlGetVersion([MarshalAs(UnmanagedType.Struct)] ref RTL_OSVERSIONINFOEXW lpVersionInformation); /// <summary>Retrieves information about the current system to an application running under WOW64. /// If the function is called from a 64-bit application, it is equivalent to the GetSystemInfo function. /// </summary> /// <returns>This function does not return a value.</returns> /// <remarks>To determine whether a Win32-based application is running under WOW64, call the <see cref="IsWow64Process"/> function.</remarks> /// <remarks>Minimum supported client: Windows XP [desktop apps | Windows Store apps]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps | Windows Store apps]</remarks> [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void GetNativeSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo); /// <summary>Determines whether the specified process is running under WOW64.</summary> /// <returns> /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks>Minimum supported client: Windows Vista, Windows XP with SP2 [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2008, Windows Server 2003 with SP1 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWow64Process([In] IntPtr hProcess, [Out, MarshalAs(UnmanagedType.Bool)] out bool lpSystemInfo); } #endregion // Private } }
using System; using System.Threading.Tasks; namespace Morpe { /// <summary> /// Represents an instance of the MoRPE classifier. /// </summary> public class Classifier { /// <summary> /// The number of categories. /// </summary> public int Ncats; /// <summary> /// The spatial dimensionality. /// </summary> public int Ndims; /// <summary> /// The number of polynomials. /// </summary> public int Npoly; /// <summary> /// Allows a multivariate polynomial to be constructed. /// </summary> public Poly Coeffs; /// <summary> /// This is used to condition the data prior to a polynomial expansion. /// </summary> public SpatialConditioner Conditioner; /// <summary> /// The model parameters. Each row specifies coefficients for a polynomial, so this array has <see cref="Npoly"/> /// rows and <see cref="Coeffs"/>.Ncoeff columns (See <see cref="Poly.Ncoeff"/>). /// </summary> public float[][] Params; /// <summary> /// Holds data related to the quantization of the decision variable (for each polynomial) throughout the training sample. /// Creates a monotonic mapping from the decision variable to a probability of category membership; /// </summary> public Quantization[] Quant; /// <summary> /// Initializes an untrained instance of the <see cref="Morpe.Classifier"/> class. The classifier should be trained /// (see <see cref="Train"/>) before it can be used for classification. /// </summary> /// <param name="nCats"><see cref="Ncats"/></param> /// <param name="nDims"><see cref="Ndims"/></param> /// <param name="rank"><see cref="Rank"/></param> public Classifier(int nCats, int nDims, int rank) { this.Ncats = nCats; this.Ndims = nDims; this.Coeffs = new Poly (nDims, rank); this.Npoly = 1; if (this.Ncats > 2) this.Npoly = this.Ncats; this.Params = Static.NewArrays<float>(this.Npoly, this.Coeffs.Ncoeffs); this.Quant = new Quantization[this.Npoly]; } protected Classifier(Classifier toCopy) { this.Ncats = toCopy.Ncats; this.Ndims = toCopy.Ndims; this.Coeffs = new Poly(this.Ndims, toCopy.Coeffs.Rank); this.Npoly = 1; if (this.Ncats > 2) this.Npoly = this.Ncats; this.Params = Static.Copy<float>(toCopy.Params); this.Quant = new Quantization[this.Npoly]; Quantization q; for (int i = 0; i < this.Npoly; i++) { q = toCopy.Quant[i]; if(q!=null) this.Quant[i] = q.Copy(); } } /// <summary> /// This is used by <see cref="GetDual"/> and <see cref="GetDuals"/>. /// </summary> /// <param name="toCopy">A classifier having more than 1 polynomial.</param> /// <param name="targetPoly">The target polynomial function.</param> protected Classifier(Classifier toCopy, int targetPoly) { this.Ncats = 2; this.Ndims = toCopy.Ndims; this.Coeffs = new Poly(this.Ndims, toCopy.Coeffs.Rank); this.Npoly = 1; this.Params = Static.NewArrays<float>(this.Npoly, this.Coeffs.Ncoeffs); Array.Copy(toCopy.Params[targetPoly], this.Params[0], this.Coeffs.Ncoeffs); this.Quant = new Quantization[this.Npoly]; Quantization q; q = toCopy.Quant[targetPoly]; if (q != null) this.Quant[0] = q.Copy(); } /// <summary> /// If the given classifier has the same number of categories, spatial dimensions, and polynomial rank; then this /// classifier will mimic it. /// </summary> /// <param name="toMimic">The classifier to be mimicked.</param> public void Mimic(Classifier toMimic) { if (toMimic.Ncats != this.Ncats) throw new ArgumentException("Cannot mimic another classifier having a different number of categories."); if (toMimic.Ndims != this.Ndims) throw new ArgumentException("Cannot mimic another classifier having a different number of spatial dimensions."); if(toMimic.Coeffs.Rank != this.Coeffs.Rank) throw new ArgumentException("Cannot mimic another classifier having a different polynomial rank."); Static.Copy<float>(toMimic.Params, this.Params); Quantization q; for (int i = 0; i < this.Npoly; i++) { q = toMimic.Quant[i]; if (q != null) this.Quant[i] = q.Copy(); } } /// <summary> /// Classifies the multivariate coordinate. /// </summary> /// <param name="x">The multivariate coordiante.</param> /// <returns>A vector of length <see cref="Ncats"/> giving the conditional probability of category membership for each category. /// Sums to exactly 1.0 (guaranteed).</returns> public double[] Classify(float[] x) { return this.ClassifyExpanded(this.Coeffs.Expand(x)); } /// <summary> /// Classifies the expanded multivariate coordinate. /// </summary> /// <param name="x">The expanded multivariate coordinate. For more information, see <see cref="Poly.Expand"/>.</param> /// <returns>A vector of length <see cref="Ncats"/> giving the conditional probability of category membership for each category. /// Sums to exactly 1.0 (guaranteed).</returns> public double[] ClassifyExpanded(float[] x) { double p = 0.0; if (this.Npoly == 1) { double y = this.EvalPolyFromExpanded(0, x); Quantization q = this.Quant[0]; if (y < q.Ymid[0]) p = q.P[0]; else if (y > q.Ymid[q.Nquantiles - 1]) p = q.P[q.Nquantiles - 1]; else p = Static.Linterp(q.Ymid, q.P, y); return new double[] { p, 1.0 - p }; } else { double[] output = new double[this.Ncats]; double pSum = 0.0; for (int iCat = 0; iCat < this.Ncats; iCat++) { double y = this.EvalPolyFromExpanded(iCat, x); Quantization q = this.Quant[iCat]; if (y < q.Ymid[0]) p = q.P[0]; else if (y > q.Ymid[q.Nquantiles - 1]) p = q.P[q.Nquantiles - 1]; else p = Static.Linterp(q.Ymid, q.P, y); output[iCat] = p; pSum += p; } for (int iCat = 0; iCat < this.Ncats; iCat++) output[iCat] /= pSum; return output; } } /// <summary> /// Classifies the polynomial outputs. /// </summary> /// <param name="y">The output of each polynomial.</param> /// <returns>A vector of length <see cref="Ncats"/> giving the conditional probability of category membership for each category. /// Sums to exactly 1.0 (guaranteed).</returns> public double[] ClassifyPolynomialOutputs(float[] y) { double p = 0.0; if (this.Npoly == 1) { Quantization q = this.Quant[0]; if (y[0] < q.Ymid[0]) p = q.P[0]; else if (y[0] > q.Ymid[q.Nquantiles - 1]) p = q.P[q.Nquantiles - 1]; else p = Static.Linterp(q.Ymid, q.P, y[0]); return new double[] { p, 1.0 - p }; } else { double[] output = new double[this.Ncats]; double pSum = 0.0; for (int iCat = 0; iCat < this.Ncats; iCat++) { Quantization q = this.Quant[iCat]; if (y[iCat] < q.Ymid[0]) p = q.P[0]; else if (y[iCat] > q.Ymid[q.Nquantiles - 1]) p = q.P[q.Nquantiles - 1]; else p = Static.Linterp(q.Ymid, q.P, y[iCat]); output[iCat] = p; pSum += p; } for (int iCat = 0; iCat < this.Ncats; iCat++) output[iCat] /= pSum; return output; } } /// <summary> /// Creates a copy of the classifier which utilizes totally different memory resources. /// </summary> /// <returns>A copy of the classifier, with identical parameter values, but utilizing completely different memory resources.</returns> public Classifier Copy() { return new Classifier(this); } /// <summary> /// Evaluates the specified polynomial function for an expanded multivariate coordinate. /// </summary> /// <param name="iPoly">The polynomial to evaluate. This is a zero-based index into a row of <see cref="Params"/>.</param> /// <param name="x">The expanded multivariate coordinate. For more information, see <see cref="Poly.Expand"/>.</param> /// <returns>The value of the polynomial expression.</returns> public double EvalPolyFromExpanded(int iPoly, float[] x) { double output = 0.0; float[] poly = this.Params[iPoly]; for (int i = 0; i < poly.Length; i++) output += poly[i] * x[i]; return output; } /// <summary> /// If this classifier has more than 1 polynomial, this function returns the "dual" classifier consisting of 1 polynomial. /// It is named "dual" because it deals only with 2 categories. /// </summary> /// <param name="targetPoly">The target polynomial, also the target category. All other polynomials are discarded, and all /// other categories are merged into 1.</param> /// <returns>The dual classifier.</returns> public Classifier GetDual(int targetPoly) { if (this.Npoly == 1) return null; return new Classifier(this, targetPoly); } /// <summary> /// If this classifier has more than 1 polynomial, this function returns all "dual" classifiers. See <see cref="GetDual"/> for more information. /// </summary> /// <returns>All dual classifiers.</returns> public Classifier[] GetDuals() { if (this.Npoly == 1) return null; Classifier[] output = new Classifier[this.Npoly]; for (int iPoly = 0; iPoly < this.Npoly; iPoly++) output[iPoly] = this.GetDual(iPoly); return output; } /// <summary> /// Trains the classifier by optimizing parameters based on the training data using default solver options. /// </summary> /// <param name="ops">Sets the <see cref="Trainer.Options"/> of the trainer. If a value is not provided, default options are used.</param> public Task<Trainer> Train(CategorizedData data, SolverOptions ops) { if (data == null) throw new ArgumentException("Argument cannot be null."); Trainer trainer = new Trainer(this); return trainer.Train(data, ops); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Management.Storage.ScenarioTest.Common; using Management.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; namespace Management.Storage.ScenarioTest { /// <summary> /// this class contains all the functional test cases for PowerShell Blob cmdlets /// </summary> [TestClass] class CLIBlobFunc { private static CloudStorageAccount StorageAccount; private static CloudBlobHelper BlobHelper; private static string BlockFilePath; private static string PageFilePath; private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { Trace.WriteLine("ClassInit"); Test.FullClassName = testContext.FullyQualifiedTestClassName; StorageAccount = TestBase.GetCloudStorageAccountFromConfig(); //init the blob helper for blob related operations BlobHelper = new CloudBlobHelper(StorageAccount); // import module string moduleFilePath = Test.Data.Get("ModuleFilePath"); if (moduleFilePath.Length > 0) PowerShellAgent.ImportModule(moduleFilePath); // $context = New-AzureStorageContext -ConnectionString ... PowerShellAgent.SetStorageContext(StorageAccount.ToString(true)); BlockFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName()); PageFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName()); FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(BlockFilePath)); FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(PageFilePath)); // Generate block file and page file which are used for uploading Helper.GenerateMediumFile(BlockFilePath, 1); Helper.GenerateMediumFile(PageFilePath, 1); } // //Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void MyClassCleanup() { Trace.WriteLine("ClasssCleanup"); } //Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { Trace.WriteLine("TestInit"); Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } //Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { Trace.WriteLine("TestCleanup"); // do not clean up the blobs here for investigation // every test case should do cleanup in its init Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } #endregion [TestMethod] [TestCategory(Tag.Function)] public void RootBlobOperations() { string DownloadDirPath = Test.Data.Get("DownloadDir"); RootBlobOperations(new PowerShellAgent(), BlockFilePath, DownloadDirPath, Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob); RootBlobOperations(new PowerShellAgent(), PageFilePath, DownloadDirPath, Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob); } [TestMethod] [TestCategory(Tag.Function)] public void GetNonExistingBlob() { GetNonExistingBlob(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void RemoveNonExistingBlob() { RemoveNonExistingBlob(new PowerShellAgent()); } /// <summary> /// Functional Cases: /// 1. Upload a new blob file in the root container (Set-AzureStorageBlobContent Positive 2) /// 2. Get an existing blob in the root container (Get-AzureStorageBlob Positive 2) /// 3. Download an existing blob in the root container (Get-AzureStorageBlobContent Positive 2) /// 4. Remove an existing blob in the root container (Remove-AzureStorageBlob Positive 2) /// </summary> internal void RootBlobOperations(Agent agent, string UploadFilePath, string DownloadDirPath, Microsoft.WindowsAzure.Storage.Blob.BlobType Type) { const string ROOT_CONTAINER_NAME = "$root"; string blobName = Path.GetFileName(UploadFilePath); string downloadFilePath = Path.Combine(DownloadDirPath, blobName); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Blob, blobName); dic["BlobType"] = Type; comp.Add(dic); // create the container CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetRootContainerReference(); container.CreateIfNotExists(); //--------------Upload operation-------------- Test.Assert(agent.SetAzureStorageBlobContent(UploadFilePath, ROOT_CONTAINER_NAME, Type), Utility.GenComparisonData("SendAzureStorageBlob", true)); ICloudBlob blob = BlobHelper.QueryBlob(ROOT_CONTAINER_NAME, blobName); blob.FetchAttributes(); // Verification for returned values CloudBlobUtil.PackBlobCompareData(blob, dic); agent.OutputValidation(comp); Test.Assert(blob.Exists(), "blob " + blobName + " should exist!"); // validate the ContentType value for GetAzureStorageBlob operation if (Type == Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob) { dic["ContentType"] = "application/octet-stream"; } //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageBlob(blobName, ROOT_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageBlob", true)); // Verification for returned values agent.OutputValidation(comp); //--------------Download operation-------------- downloadFilePath = Path.Combine(DownloadDirPath, blobName); Test.Assert(agent.GetAzureStorageBlobContent(blobName, downloadFilePath, ROOT_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageBlobContent", true)); // Verification for returned values agent.OutputValidation(comp); Test.Assert(Helper.CompareTwoFiles(downloadFilePath, UploadFilePath), String.Format("File '{0}' should be bit-wise identicial to '{1}'", downloadFilePath, UploadFilePath)); //--------------Remove operation-------------- Test.Assert(agent.RemoveAzureStorageBlob(blobName, ROOT_CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageBlob", true)); blob = BlobHelper.QueryBlob(ROOT_CONTAINER_NAME, blobName); Test.Assert(blob == null, "blob {0} should not exist!", blobName); } /// <summary> /// Negative Functional Cases : for Get-AzureStorageBlob /// 1. Get a non-existing blob (Negative 1) /// </summary> internal void GetNonExistingBlob(Agent agent) { string CONTAINER_NAME = Utility.GenNameString("upload-"); // create the container CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME); container.CreateIfNotExists(); try { string BLOB_NAME = Utility.GenNameString("nonexisting"); // Delete the blob if it exists ICloudBlob blob = BlobHelper.QueryBlob(CONTAINER_NAME, BLOB_NAME); if (blob != null) blob.DeleteIfExists(); //--------------Get operation-------------- Test.Assert(!agent.GetAzureStorageBlob(BLOB_NAME, CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageBlob", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find blob '{0}' in container '{1}'.", BLOB_NAME, CONTAINER_NAME)), agent.ErrorMessages[0]); } finally { // cleanup container.DeleteIfExists(); } } /// <summary> /// Negative Functional Cases : for Remove-AzureStorageBlob /// 1. Remove a non-existing blob (Negative 2) /// </summary> internal void RemoveNonExistingBlob(Agent agent) { string CONTAINER_NAME = Utility.GenNameString("upload-"); string BLOB_NAME = Utility.GenNameString("nonexisting"); // create the container CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME); container.CreateIfNotExists(); try { // Delete the blob if it exists ICloudBlob blob = BlobHelper.QueryBlob(CONTAINER_NAME, BLOB_NAME); if (blob != null) blob.DeleteIfExists(); //--------------Remove operation-------------- Test.Assert(!agent.RemoveAzureStorageBlob(BLOB_NAME, CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageBlob", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find blob '{0}' in container '{1}'.", BLOB_NAME, CONTAINER_NAME)), agent.ErrorMessages[0]); } finally { container.DeleteIfExists(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner Builder class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableHashSet<T> { /// <summary> /// A hash set that mutates with little or no memory allocations, /// can produce and/or build on immutable hash set instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableHashSet&lt;T&gt;.Union(IEnumerable&lt;T&gt;)"/> and other bulk change methods /// already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] public sealed class Builder : IReadOnlyCollection<T>, ISet<T> { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode; /// <summary> /// The equality comparer. /// </summary> private IEqualityComparer<T> equalityComparer; /// <summary> /// The number of elements in this collection. /// </summary> private int count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableHashSet<T> immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int version; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet&lt;T&gt;.Builder"/> class. /// </summary> /// <param name="set">The set.</param> internal Builder(ImmutableHashSet<T> set) { Requires.NotNull(set, "set"); this.root = set.root; this.count = set.count; this.equalityComparer = set.equalityComparer; this.immutable = set; } #region ISet<T> Properties /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</returns> public int Count { get { return this.count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.</returns> bool ICollection<T>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<T> KeyComparer { get { return this.equalityComparer; } set { Requires.NotNull(value, "value"); if (value != this.equalityComparer) { var result = Union(this, new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, value, 0)); this.immutable = null; this.equalityComparer = value; this.Root = result.Root; this.count = result.Count; // whether the offset or absolute, since the base is 0, it's no difference. } } } /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return this.version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, this.equalityComparer, this.count); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private SortedInt32KeyNode<HashBucket> Root { get { return this.root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. this.version++; if (this.root != value) { this.root = value; // Clear any cached value for the immutable view since it is now invalidated. this.immutable = null; } } } #region Public methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this.root, this); } /// <summary> /// Creates an immutable hash set based on the contents of this instance. /// </summary> /// <returns>An immutable set.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableHashSet<T> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (this.immutable == null) { this.immutable = ImmutableHashSet<T>.Wrap(this.root, this.equalityComparer, this.count); } return this.immutable; } #endregion #region ISet<T> Methods /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns>True if the item did not already belong to the collection.</returns> public bool Add(T item) { var result = ImmutableHashSet<T>.Add(item, this.Origin); this.Apply(result); return result.Count != 0; } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(T item) { var result = ImmutableHashSet<T>.Remove(item, this.Origin); this.Apply(result); return result.Count != 0; } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> public bool Contains(T item) { return ImmutableHashSet<T>.Contains(item, this.Origin); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { this.count = 0; this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode; } /// <summary> /// Removes all elements in the specified collection from the current set. /// </summary> /// <param name="other">The collection of items to remove from the set.</param> public void ExceptWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.Except(other, this.equalityComparer, this.root); this.Apply(result); } /// <summary> /// Modifies the current set so that it contains only elements that are also in a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void IntersectWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.Intersect(other, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the current set is a proper (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> public bool IsProperSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a proper (strict) superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsProperSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> public bool IsSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> public bool Overlaps(IEnumerable<T> other) { return ImmutableHashSet<T>.Overlaps(other, this.Origin); } /// <summary> /// Determines whether the current set and the specified collection contain the same elements. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is equal to other; otherwise, false.</returns> public bool SetEquals(IEnumerable<T> other) { if (object.ReferenceEquals(this, other)) { return true; } return ImmutableHashSet<T>.SetEquals(other, this.Origin); } /// <summary> /// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void SymmetricExceptWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.SymmetricExcept(other, this.Origin); this.Apply(result); } /// <summary> /// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void UnionWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.Union(other, this.Origin); this.Apply(result); } #endregion #region ICollection<T> Members /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> void ICollection<T>.Add(T item) { this.Add(item); } /// <summary> /// See the <see cref="ICollection&lt;T&gt;"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private void Apply(MutationResult result) { this.Root = result.Root; if (result.CountType == CountType.Adjustment) { this.count += result.Count; } else { this.count = result.Count; } } } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System.Collections.Generic; using System.Linq; using System.Web; using MbUnit.Framework; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Data; using Subtext.Framework.Providers; namespace UnitTests.Subtext.Framework { /// <summary> /// Unit tests of Subtext.Framework.Links class methods /// </summary> [TestFixture] public class LinksTests { [Test] [RollBack2] public void CanGetCategoriesByPostId() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); int category1Id = repository.CreateLinkCategory(CreateCategory("Post Category 1", "Cody roolz!", CategoryType.PostCollection, true)); int category2Id = repository.CreateLinkCategory(CreateCategory("Post Category 2", "Cody roolz again!", CategoryType.PostCollection, true)); repository.CreateLinkCategory(CreateCategory("Post Category 3", "Cody roolz and again!", CategoryType.PostCollection, true)); Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("phil", "title", "body"); int entryId = UnitTestHelper.Create(entry); repository.SetEntryCategoryList(entryId, new[] { category1Id, category2Id }); ICollection<LinkCategory> categories = repository.GetLinkCategoriesByPostId(entryId); Assert.AreEqual(2, categories.Count, "Expected two of the three categories"); Assert.AreEqual(category1Id, categories.First().Id); Assert.AreEqual(category2Id, categories.ElementAt(1).Id); Assert.AreEqual(Config.CurrentBlog.Id, categories.First().BlogId); } [Test] [RollBack2] public void CanGetActiveCategories() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); int[] categoryIds = CreateSomeLinkCategories(repository); CreateLink(repository, "Link one", categoryIds[0], null); CreateLink(repository, "Link two", categoryIds[0], null); CreateLink(repository, "Link one-two", categoryIds[1], null); ICollection<LinkCategory> linkCollections = repository.GetActiveCategories(); //Test ordering by title Assert.AreEqual("Google Blogs", linkCollections.First().Title); Assert.AreEqual("My Favorite Feeds", linkCollections.ElementAt(1).Title); //Check link counts Assert.AreEqual(1, linkCollections.First().Links.Count); Assert.AreEqual(2, linkCollections.ElementAt(1).Links.Count); } [Test] [RollBack2] public void CanUpdateLink() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); // Create the categories CreateSomeLinkCategories(repository); int categoryId = repository.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds", CategoryType.LinkCollection, true)); Link link = CreateLink(repository, "Test", categoryId, null); int linkId = link.Id; Link loaded = repository.GetLink(linkId); Assert.AreEqual("Test", loaded.Title); Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "test"); //Make changes then update. link.PostId = entry.Id; link.Title = "Another title"; link.NewWindow = true; repository.UpdateLink(link); loaded = repository.GetLink(linkId); Assert.AreEqual("Another title", loaded.Title); Assert.IsTrue(loaded.NewWindow); Assert.AreEqual(entry.Id, loaded.PostId); } [Test] [RollBack2] public void CanCreateAndDeleteLink() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); int categoryId = repository.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds", CategoryType.LinkCollection, true)); Link link = CreateLink(repository, "Title", categoryId, null); int linkId = link.Id; Link loaded = repository.GetLink(linkId); Assert.AreEqual("Title", loaded.Title); Assert.AreEqual(NullValue.NullInt32, loaded.PostId); Assert.AreEqual(Config.CurrentBlog.Id, loaded.BlogId); repository.DeleteLink(linkId); Assert.IsNull(repository.GetLink(linkId)); } [Test] [RollBack2] public void CanCreateAndDeleteLinkCategory() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); // Create some categories int categoryId = repository.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds", CategoryType.LinkCollection, true)); LinkCategory category = repository.GetLinkCategory(categoryId, true); Assert.AreEqual(Config.CurrentBlog.Id, category.BlogId); Assert.AreEqual("My Favorite Feeds", category.Title); Assert.AreEqual("Some of my favorite RSS feeds", category.Description); Assert.IsTrue(category.HasDescription); Assert.IsFalse(category.HasLinks); Assert.IsFalse(category.HasImages); Assert.IsTrue(category.IsActive); Assert.AreEqual(CategoryType.LinkCollection, category.CategoryType); Assert.IsNotNull(category); repository.DeleteLinkCategory(categoryId); Assert.IsNull(repository.GetLinkCategory(categoryId, true)); } /// <summary> /// Ensures CreateLinkCategory assigns unique CatIDs /// </summary> [Test] [RollBack2] public void CreateLinkCategoryAssignsUniqueCatIDs() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); // Create some categories CreateSomeLinkCategories(repository); ICollection<LinkCategory> linkCategoryCollection = repository.GetCategories(CategoryType.LinkCollection, ActiveFilter.None); LinkCategory first = null; LinkCategory second = null; LinkCategory third = null; foreach (LinkCategory linkCategory in linkCategoryCollection) { if (first == null) { first = linkCategory; continue; } if (second == null) { second = linkCategory; continue; } if (third == null) { third = linkCategory; continue; } } // Ensure the CategoryIDs are unique Assert.AreNotEqual(first.Id, second.Id); Assert.AreNotEqual(first.Id, third.Id); Assert.AreNotEqual(second.Id, third.Id); } [Test] [RollBack2] public void CanGetPostCollectionCategories() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); CreateSomePostCategories(repository); // Retrieve the categories, grab the first one and update it ICollection<LinkCategory> originalCategories = repository.GetCategories(CategoryType.PostCollection, ActiveFilter.None); Assert.IsTrue(originalCategories.Count > 0); } /// <summary> /// Ensure UpdateLInkCategory updates the correct link category /// </summary> [Test] [RollBack2] public void UpdateLinkCategoryIsFine() { UnitTestHelper.SetupBlog(); var repository = new DatabaseObjectProvider(); // Create the categories CreateSomeLinkCategories(repository); // Retrieve the categories, grab the first one and update it ICollection<LinkCategory> originalCategories = repository.GetCategories(CategoryType.LinkCollection, ActiveFilter.None); Assert.Greater(originalCategories.Count, 0, "Expected some categories in there."); LinkCategory linkCat = null; foreach (LinkCategory linkCategory in originalCategories) { linkCat = linkCategory; break; } LinkCategory originalCategory = linkCat; originalCategory.Description = "New Description"; originalCategory.IsActive = false; bool updated = repository.UpdateLinkCategory(originalCategory); // Retrieve the categories and find the one we updated ICollection<LinkCategory> updatedCategories = repository.GetCategories(CategoryType.LinkCollection, ActiveFilter.None); LinkCategory updatedCategory = null; foreach (LinkCategory lc in updatedCategories) { if (lc.Id == originalCategory.Id) { updatedCategory = lc; } } // Ensure the update was successful Assert.IsTrue(updated); Assert.IsNotNull(updatedCategory); Assert.AreEqual("New Description", updatedCategory.Description); Assert.AreEqual(false, updatedCategory.IsActive); } static int[] CreateSomeLinkCategories(ObjectRepository repository) { var categoryIds = new int[3]; categoryIds[0] = repository.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds", CategoryType.LinkCollection, true)); categoryIds[1] = repository.CreateLinkCategory(CreateCategory("Google Blogs", "My favorite Google blogs", CategoryType.LinkCollection, true)); categoryIds[2] = repository.CreateLinkCategory(CreateCategory("Microsoft Blogs", "My favorite Microsoft blogs", CategoryType.LinkCollection, false)); return categoryIds; } static int[] CreateSomePostCategories(ObjectRepository repository) { var categoryIds = new int[3]; categoryIds[0] = repository.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds", CategoryType.PostCollection, true)); categoryIds[1] = repository.CreateLinkCategory(CreateCategory("Google Blogs", "My favorite Google blogs", CategoryType.PostCollection, true)); categoryIds[2] = repository.CreateLinkCategory(CreateCategory("Microsoft Blogs", "My favorite Microsoft blogs", CategoryType.PostCollection, false)); return categoryIds; } static LinkCategory CreateCategory(string title, string description, CategoryType categoryType, bool isActive) { var linkCategory = new LinkCategory(); linkCategory.BlogId = Config.CurrentBlog.Id; linkCategory.Title = title; linkCategory.Description = description; linkCategory.CategoryType = categoryType; linkCategory.IsActive = isActive; return linkCategory; } static Link CreateLink(ObjectRepository repository, string title, int? categoryId, int? postId) { var link = new Link(); link.IsActive = true; link.BlogId = Config.CurrentBlog.Id; if (categoryId != null) { link.CategoryId = (int)categoryId; } link.Title = title; if (postId != null) { link.PostId = (int)postId; } int linkId = repository.CreateLink(link); Assert.AreEqual(linkId, link.Id); return link; } /// <summary> /// Sets the up test fixture. This is called once for /// this test fixture before all the tests run. /// </summary> [TestFixtureSetUp] public void SetUpTestFixture() { //Confirm app settings UnitTestHelper.AssertAppSettings(); } [TearDown] public void TearDown() { HttpContext.Current = null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; namespace System.Collections.Immutable { /// <summary> /// A thin wrapper around the <see cref="IDictionary{TKey, TValue}.Keys"/> or <see cref="IDictionary{TKey, TValue}.Values"/> enumerators so they look like a collection. /// </summary> /// <typeparam name="TKey">The type of key in the dictionary.</typeparam> /// <typeparam name="TValue">The type of value in the dictionary.</typeparam> /// <typeparam name="T">Either TKey or TValue.</typeparam> internal abstract class KeysOrValuesCollectionAccessor<TKey, TValue, T> : ICollection<T>, ICollection { /// <summary> /// The underlying wrapped dictionary. /// </summary> private readonly IImmutableDictionary<TKey, TValue> _dictionary; /// <summary> /// The key or value enumerable that this instance wraps. /// </summary> private readonly IEnumerable<T> _keysOrValues; /// <summary> /// Initializes a new instance of the <see cref="KeysOrValuesCollectionAccessor{TKey, TValue, T}"/> class. /// </summary> /// <param name="dictionary">The dictionary to base on.</param> /// <param name="keysOrValues">The keys or values enumeration to wrap as a collection.</param> protected KeysOrValuesCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary, IEnumerable<T> keysOrValues) { Requires.NotNull(dictionary, "dictionary"); Requires.NotNull(keysOrValues, "keysOrValues"); _dictionary = dictionary; _keysOrValues = keysOrValues; } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public bool IsReadOnly { get { return true; } } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _dictionary.Count; } } /// <summary> /// Gets the wrapped dictionary. /// </summary> protected IImmutableDictionary<TKey, TValue> Dictionary { get { return _dictionary; } } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public void Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public void Clear() { throw new NotSupportedException(); } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public abstract bool Contains(T item); /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public void CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public bool Remove(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="IEnumerable{T}"/> /// </summary> public IEnumerator<T> GetEnumerator() { return _keysOrValues.GetEnumerator(); } /// <summary> /// See <see cref="System.Collections.IEnumerable"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array.SetValue(item, arrayIndex++); } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return true; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } } /// <summary> /// A lightweight collection view over and IEnumerable of keys. /// </summary> internal class KeysCollectionAccessor<TKey, TValue> : KeysOrValuesCollectionAccessor<TKey, TValue, TKey> { /// <summary> /// Initializes a new instance of the <see cref="KeysCollectionAccessor{TKey, TValue}"/> class. /// </summary> internal KeysCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary) : base(dictionary, dictionary.Keys) { } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public override bool Contains(TKey item) { return this.Dictionary.ContainsKey(item); } } /// <summary> /// A lightweight collection view over and IEnumerable of values. /// </summary> internal class ValuesCollectionAccessor<TKey, TValue> : KeysOrValuesCollectionAccessor<TKey, TValue, TValue> { /// <summary> /// Initializes a new instance of the <see cref="ValuesCollectionAccessor{TKey, TValue}"/> class. /// </summary> internal ValuesCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary) : base(dictionary, dictionary.Values) { } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> public override bool Contains(TValue item) { var sortedDictionary = this.Dictionary as ImmutableSortedDictionary<TKey, TValue>; if (sortedDictionary != null) { return sortedDictionary.ContainsValue(item); } var dictionary = this.Dictionary as IImmutableDictionaryInternal<TKey, TValue>; if (dictionary != null) { return dictionary.ContainsValue(item); } throw new NotSupportedException(); } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Bot Framework: http://botframework.com // // Bot Builder SDK Github: // https://github.com/Microsoft/BotBuilder // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.Bot.Builder.Internals.Fibers { public interface IWaiter { IWait Wait { get; } IWait<T> NextWait<T>(); } public interface IFiber : IWaiter { void Push(); void Done(); } public interface IFiberLoop : IFiber { Task<IWait> PollAsync(); } public interface IFrameLoop { Task<IWait> PollAsync(IFiber fiber); } public interface IFrame : IWaiter, IFrameLoop { } [Serializable] public sealed class Frame : IFrame { private readonly IWaitFactory factory; private IWait wait; public Frame(IWaitFactory factory) { SetField.NotNull(out this.factory, nameof(factory), factory); this.wait = NullWait.Instance; } public override string ToString() { return this.wait.ToString(); } IWait IWaiter.Wait { get { return this.wait; } } IWait<T> IWaiter.NextWait<T>() { if (this.wait is NullWait) { this.wait = null; } if (this.wait != null) { if (this.wait.Need != Need.Call) { throw new InvalidNeedException(this.wait, Need.Call); } this.wait = null; } var wait = this.factory.Make<T>(); this.wait = wait; return wait; } async Task<IWait> IFrameLoop.PollAsync(IFiber fiber) { return await this.wait.PollAsync(fiber); } } public interface IFrameFactory { IFrame Make(); } [Serializable] public sealed class FrameFactory : IFrameFactory { private readonly IWaitFactory factory; public FrameFactory(IWaitFactory factory) { SetField.NotNull(out this.factory, nameof(factory), factory); } IFrame IFrameFactory.Make() { return new Frame(this.factory); } } [Serializable] public sealed class Fiber : IFiber, IFiberLoop { private readonly Stack<IFrame> stack = new Stack<IFrame>(); private readonly IFrameFactory factory; public Fiber(IFrameFactory factory) { SetField.NotNull(out this.factory, nameof(factory), factory); } public IFrameFactory Factory { get { return this.factory; } } void IFiber.Push() { this.stack.Push(this.factory.Make()); } void IFiber.Done() { this.stack.Pop(); } IWait IWaiter.Wait { get { if (this.stack.Count > 0) { var leaf = this.stack.Peek(); return leaf.Wait; } else { return NullWait.Instance; } } } IWait<T> IWaiter.NextWait<T>() { var leaf = this.stack.Peek(); return leaf.NextWait<T>(); } async Task<IWait> IFiberLoop.PollAsync() { while (this.stack.Count > 0) { var leaf = this.stack.Peek(); var wait = leaf.Wait; switch (wait.Need) { case Need.None: case Need.Wait: case Need.Done: return wait; case Need.Poll: break; default: throw new InvalidNeedException(wait, Need.Poll); } try { var next = await leaf.PollAsync(this); var peek = this.stack.Peek(); bool fine = object.ReferenceEquals(next, peek.Wait) || next is NullWait; if (!fine) { throw new InvalidNextException(next); } } catch (Exception error) { this.stack.Pop(); if (this.stack.Count == 0) { throw; } else { var parent = this.stack.Peek(); parent.Wait.Fail(error); } } } return NullWait.Instance; } } }
/* * * (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.Configuration; using System.Linq; using System.Security; using ASC.Core.Billing; using ASC.Core.Data; using ASC.Core.Security.Authentication; using ASC.Core.Tenants; using ASC.Core.Users; namespace ASC.Core { public class HostedSolution { private readonly ITenantService tenantService; private readonly IUserService userService; private readonly IQuotaService quotaService; private readonly ITariffService tariffService; private readonly TenantManager clientTenantManager; private readonly DbSettingsManager settingsManager; public string Region { get; private set; } public string DbId { get; private set; } public HostedSolution(ConnectionStringSettings connectionString) : this(connectionString, null) { } public HostedSolution(ConnectionStringSettings connectionString, string region) { tenantService = new DbTenantService(connectionString); userService = new DbUserService(connectionString); quotaService = new DbQuotaService(connectionString); tariffService = new TariffService(connectionString, quotaService, tenantService); clientTenantManager = new TenantManager(tenantService, quotaService, tariffService); settingsManager = new DbSettingsManager(connectionString); Region = region ?? string.Empty; DbId = connectionString.Name; } public List<Tenant> GetTenants(DateTime from) { return tenantService.GetTenants(from).Select(AddRegion).ToList(); } public List<Tenant> FindTenants(string login) { return FindTenants(login, null); } public List<Tenant> FindTenants(string login, string passwordHash) { if (!string.IsNullOrEmpty(passwordHash) && userService.GetUserByPasswordHash(Tenant.DEFAULT_TENANT, login, passwordHash) == null) { throw new SecurityException("Invalid login or password."); } return tenantService.GetTenants(login, passwordHash).Select(AddRegion).ToList(); } public Tenant GetTenant(String domain) { return AddRegion(tenantService.GetTenant(domain)); } public Tenant GetTenant(int id) { return AddRegion(tenantService.GetTenant(id)); } public void CheckTenantAddress(string address) { tenantService.ValidateDomain(address); } public void RegisterTenant(TenantRegistrationInfo ri, out Tenant tenant) { tenant = null; if (ri == null) throw new ArgumentNullException("registrationInfo"); if (string.IsNullOrEmpty(ri.Address)) throw new Exception("Address can not be empty"); if (string.IsNullOrEmpty(ri.Email)) throw new Exception("Account email can not be empty"); if (ri.FirstName == null) throw new Exception("Account firstname can not be empty"); if (ri.LastName == null) throw new Exception("Account lastname can not be empty"); if (!UserFormatter.IsValidUserName(ri.FirstName, ri.LastName)) throw new Exception("Incorrect firstname or lastname"); if (string.IsNullOrEmpty(ri.PasswordHash)) ri.PasswordHash = Guid.NewGuid().ToString(); // create tenant tenant = new Tenant(ri.Address.ToLowerInvariant()) { Name = ri.Name, Language = ri.Culture.Name, TimeZone = ri.TimeZoneInfo, HostedRegion = ri.HostedRegion, PartnerId = ri.PartnerId, AffiliateId = ri.AffiliateId, Campaign = ri.Campaign, Industry = ri.Industry, Spam = ri.Spam, Calls = ri.Calls }; tenant = tenantService.SaveTenant(tenant); // create user var user = new UserInfo { UserName = ri.Email.Substring(0, ri.Email.IndexOf('@')), LastName = ri.LastName, FirstName = ri.FirstName, Email = ri.Email, MobilePhone = ri.MobilePhone, WorkFromDate = TenantUtil.DateTimeNow(tenant.TimeZone), ActivationStatus = ri.ActivationStatus }; user = userService.SaveUser(tenant.TenantId, user); userService.SetUserPasswordHash(tenant.TenantId, user.ID, ri.PasswordHash); userService.SaveUserGroupRef(tenant.TenantId, new UserGroupRef(user.ID, Constants.GroupAdmin.ID, UserGroupRefType.Contains)); // save tenant owner tenant.OwnerId = user.ID; tenant = tenantService.SaveTenant(tenant); settingsManager.SaveSettings(new TenantControlPanelSettings { LimitedAccess = ri.LimitedControlPanel }, tenant.TenantId); } public Tenant SaveTenant(Tenant tenant) { return tenantService.SaveTenant(tenant); } public void RemoveTenant(Tenant tenant) { tenantService.RemoveTenant(tenant.TenantId); } public string CreateAuthenticationCookie(int tenantId, Guid userId) { var u = userService.GetUser(tenantId, userId); return CreateAuthenticationCookie(tenantId, u); } private string CreateAuthenticationCookie(int tenantId, UserInfo user) { if (user == null) return null; var tenantSettings = settingsManager.LoadSettingsFor<TenantCookieSettings>(tenantId, Guid.Empty); var expires = tenantSettings.IsDefault() ? DateTime.UtcNow.AddYears(1) : DateTime.UtcNow.AddMinutes(tenantSettings.LifeTime); var userSettings = settingsManager.LoadSettingsFor<TenantCookieSettings>(tenantId, user.ID); return CookieStorage.EncryptCookie(tenantId, user.ID, tenantSettings.Index, expires, userSettings.Index); } public Tariff GetTariff(int tenant, bool withRequestToPaymentSystem = true) { return tariffService.GetTariff(tenant, withRequestToPaymentSystem); } public TenantQuota GetTenantQuota(int tenant) { return clientTenantManager.GetTenantQuota(tenant); } public IEnumerable<TenantQuota> GetTenantQuotas() { return clientTenantManager.GetTenantQuotas(); } public TenantQuota SaveTenantQuota(TenantQuota quota) { return clientTenantManager.SaveTenantQuota(quota); } public void SetTariff(int tenant, bool paid) { var quota = quotaService.GetTenantQuotas().FirstOrDefault(q => paid ? q.NonProfit : q.Trial); if (quota != null) { tariffService.SetTariff(tenant, new Tariff { QuotaId = quota.Id, DueDate = DateTime.MaxValue, }); } } public void SetTariff(int tenant, Tariff tariff) { tariffService.SetTariff(tenant, tariff); } public void SaveButton(int tariffId, string partnerId, string buttonUrl) { tariffService.SaveButton(tariffId, partnerId, buttonUrl); } public IEnumerable<UserInfo> FindUsers(IEnumerable<string> userIds) { return userService.GetUsersAllTenants(userIds); } private Tenant AddRegion(Tenant tenant) { if (tenant != null) { tenant.HostedRegion = Region; } return tenant; } } }
using System; using System.Collections.Generic; using System.Text; using System.Web.Security; using Rainbow.Framework.Providers.RainbowRoleProvider; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.Diagnostics; using Rainbow.Framework.Providers.RainbowMembershipProvider; using System.Collections; using System.Configuration.Provider; namespace Rainbow.Framework.Providers.RainbowRoleProvider { public class RainbowSqlRoleProvider : RainbowRoleProvider { protected string pApplicationName; protected string connectionString; private string eventSource = "RainbowSqlRoleProvider"; private string eventLog = "Application"; public override void Initialize( string name, System.Collections.Specialized.NameValueCollection config ) { // // Initialize values from web.config. // if ( config == null ) throw new ArgumentNullException( "config" ); if ( name == null || name.Length == 0 ) name = "RainbowSqlRoleProvider"; if ( String.IsNullOrEmpty( config["description"] ) ) { config.Remove( "description" ); config.Add( "description", "Rainbow Sql Role provider" ); } // Initialize the abstract base class. base.Initialize( name, config ); pApplicationName = GetConfigValue( config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath ); pWriteExceptionsToEventLog = Convert.ToBoolean( GetConfigValue( config["writeExceptionsToEventLog"], "true" ) ); // Initialize SqlConnection. ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; if ( ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim().Equals( string.Empty ) ) { throw new RainbowRoleProviderException( "Connection string cannot be blank." ); } connectionString = ConnectionStringSettings.ConnectionString; } #region Overriden properties public override string ApplicationName { get { return pApplicationName; } set { pApplicationName = value; } } #endregion #region Properties // // If false, exceptions are thrown to the caller. If true, // exceptions are written to the event log. // private bool pWriteExceptionsToEventLog; public bool WriteExceptionsToEventLog { get { return pWriteExceptionsToEventLog; } set { pWriteExceptionsToEventLog = value; } } #endregion #region Overriden methods public override void AddUsersToRoles( string[] usernames, string[] roleNames ) { Guid[] userIds = new Guid[usernames.Length]; Guid[] roleIds = new Guid[roleNames.Length]; RainbowUser user = null; for ( int i = 0; i < usernames.Length; i++ ) { user = ( RainbowUser )Membership.GetUser( usernames[i] ); if ( user == null ) { throw new RainbowMembershipProviderException( "User " + usernames[i] + " doesn't exist" ); } userIds[i] = user.ProviderUserKey; } RainbowRole role = null; for ( int i = 0; i < roleNames.Length; i++ ) { role = GetRoleByName( ApplicationName, roleNames[i] ); roleIds[i] = role.Id; } AddUsersToRoles( ApplicationName, userIds, roleIds ); } public override void CreateRole( string roleName ) { CreateRole( ApplicationName, roleName ); } public override bool DeleteRole( string roleName, bool throwOnPopulatedRole ) { RainbowRole role = GetRoleByName( ApplicationName, roleName ); return DeleteRole( ApplicationName, role.Id, throwOnPopulatedRole ); } public override string[] FindUsersInRole( string roleName, string usernameToMatch ) { return FindUsersInRole( ApplicationName, roleName, usernameToMatch ); } public override string[] GetAllRoles() { IList<RainbowRole> roles = GetAllRoles( ApplicationName ); string[] result = new string[roles.Count]; for ( int i = 0; i < roles.Count; i++ ) { result[i] = roles[i].Name; } return result; } public override string[] GetRolesForUser( string username ) { RainbowUser user = ( RainbowUser )Membership.GetUser( username ); IList<RainbowRole> roles = GetRolesForUser( ApplicationName, user.ProviderUserKey ); string[] result = new string[roles.Count]; for ( int i = 0; i < roles.Count; i++ ) { result[i] = roles[i].Name; } return result; } public override string[] GetUsersInRole( string roleName ) { RainbowRole role = GetRoleByName( ApplicationName, roleName ); return GetUsersInRole( ApplicationName, role.Id ); } public override bool IsUserInRole( string username, string roleName ) { RainbowUser user = ( RainbowUser )Membership.GetUser( username ); if ( user == null ) { throw new RainbowRoleProviderException( "User doesn't exist" ); } RainbowRole role = GetRoleByName( ApplicationName, roleName ); return IsUserInRole( ApplicationName, user.ProviderUserKey, role.Id ); } public override void RemoveUsersFromRoles( string[] usernames, string[] roleNames ) { Guid[] userIds = new Guid[usernames.Length]; Guid[] roleIds = new Guid[roleNames.Length]; RainbowUser user = null; for ( int i = 0; i < usernames.Length; i++ ) { user = ( RainbowUser )Membership.GetUser( usernames[i] ); if ( user == null ) { throw new RainbowMembershipProviderException( "User " + usernames[i] + " doesn't exist" ); } userIds[i] = user.ProviderUserKey; } RainbowRole role = null; for ( int i = 0; i < roleNames.Length; i++ ) { role = GetRoleByName( ApplicationName, roleNames[i] ); roleIds[i] = role.Id; } RemoveUsersFromRoles( ApplicationName, userIds, roleIds ); } public override bool RoleExists( string roleName ) { try { IList<RainbowRole> allRoles = GetAllRoles( ApplicationName ); foreach ( RainbowRole role in allRoles ) { if ( role.Name.Equals( roleName ) ) { return true; } } return false; } catch { return false; } } #endregion #region Rainbow-specific Provider methods public override void AddUsersToRoles( string portalAlias, Guid[] userIds, Guid[] roleIds ) { string userIdsStr = string.Empty; string roleIdsStr = string.Empty; foreach ( Guid userId in userIds ) { userIdsStr += userId.ToString() + ","; } userIdsStr = userIdsStr.Substring( 0, userIdsStr.Length - 1 ); foreach ( Guid roleId in roleIds ) { roleIdsStr += roleId.ToString() + ","; } roleIdsStr = roleIdsStr.Substring( 0, roleIdsStr.Length - 1 ); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_UsersInRoles_AddUsersToRoles"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@UserIds", SqlDbType.VarChar, 4000 ).Value = userIdsStr; cmd.Parameters.Add( "@RoleIds", SqlDbType.VarChar, 4000 ).Value = roleIdsStr; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; switch ( returnCode ) { case 0: return; case 2: throw new RainbowRoleProviderException( "Application " + portalAlias + " doesn't exist" ); case 3: throw new RainbowRoleProviderException( "One of the roles doesn't exist" ); case 4: throw new RainbowMembershipProviderException( "One of the users doesn't exist" ); default: throw new RainbowRoleProviderException( "aspnet_UsersInRoles_AddUsersToRoles returned error code " + returnCode ); } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "CreateRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_UsersInRoles_AddUsersToRoles stored proc", e ); } finally { cmd.Connection.Close(); } } public override Guid CreateRole( string portalAlias, string roleName ) { if ( roleName.IndexOf( ',' ) != -1 ) { throw new RainbowRoleProviderException( "Role name can't contain commas" ); } SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_Roles_CreateRole"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@RoleName", SqlDbType.NVarChar, 256 ).Value = roleName; SqlParameter newRoleIdParam = cmd.Parameters.Add( "@NewRoleId", SqlDbType.UniqueIdentifier ); newRoleIdParam.Direction = ParameterDirection.Output; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; SqlDataReader reader = null; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; if ( returnCode != 0 ) { throw new RainbowRoleProviderException( "Error creating role " + roleName ); } return ( Guid )newRoleIdParam.Value; } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "CreateRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_Roles_CreateRole stored proc", e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override bool DeleteRole( string portalAlias, Guid roleId, bool throwOnPopulatedRole ) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_Roles_DeleteRole"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@RoleId", SqlDbType.UniqueIdentifier ).Value = roleId; if ( throwOnPopulatedRole ) { cmd.Parameters.Add( "@DeleteOnlyIfRoleIsEmpty", SqlDbType.Bit ).Value = 1; } else { cmd.Parameters.Add( "@DeleteOnlyIfRoleIsEmpty", SqlDbType.Bit ).Value = 0; } SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; SqlDataReader reader = null; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; switch ( returnCode ) { case 0: return true; case 1: throw new RainbowRoleProviderException( "Application " + portalAlias + " doesn't exist" ); case 2: throw new RainbowRoleProviderException( "Role has members and throwOnPopulatedRole is true" ); default: throw new RainbowRoleProviderException( "Error deleting role" ); } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "DeleteRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_Roles_DeleteRole stored proc", e ); } catch ( Exception e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "DeleteRole" ); } throw new RainbowRoleProviderException( "Error deleting role " + roleId.ToString(), e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override bool RenameRole( string portalAlias, Guid roleId, string newRoleName ) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_rbRoles_RenameRole"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@RoleId", SqlDbType.UniqueIdentifier ).Value = roleId; cmd.Parameters.Add( "@NewRoleName", SqlDbType.VarChar, 256 ).Value = newRoleName; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; SqlDataReader reader = null; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; switch ( returnCode ) { case 0: return true; case 1: throw new RainbowRoleProviderException( "Role doesn't exist" ); default: throw new RainbowRoleProviderException( "Error renaming role" ); } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "DeleteRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_rbRoles_RenameRole stored proc", e ); } catch ( Exception e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "RenameRole" ); } throw new RainbowRoleProviderException( "Error renaming role " + roleId.ToString(), e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override string[] FindUsersInRole( string portalAlias, string roleName, string usernameToMatch ) { throw new Exception( "The method or operation is not implemented." ); } public override IList<RainbowRole> GetAllRoles( string portalAlias ) { IList<RainbowRole> result = new List<RainbowRole>(); result.Insert( 0, new RainbowRole( AllUsersGuid, AllUsersRoleName, AllUsersRoleName ) ); result.Insert( 1, new RainbowRole( AuthenticatedUsersGuid, AuthenticatedUsersRoleName, AuthenticatedUsersRoleName ) ); result.Insert( 2, new RainbowRole( UnauthenticatedUsersGuid, UnauthenticatedUsersRoleName, UnauthenticatedUsersRoleName ) ); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_Roles_GetAllRoles"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; SqlDataReader reader = null; try { cmd.Connection.Open(); using ( reader = cmd.ExecuteReader() ) { while ( reader.Read() ) { RainbowRole role = GetRoleFromReader( reader ); result.Add( role ); } reader.Close(); } return result; } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetAllRoles" ); } throw new RainbowRoleProviderException( "Error executing aspnet_Roles_GetAllRoles stored proc", e ); } catch ( Exception e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetAllRoles" ); } throw new RainbowRoleProviderException( "Error getting all roles", e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override IList<RainbowRole> GetRolesForUser( string portalAlias, Guid userId ) { IList<RainbowRole> result = new List<RainbowRole>(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_UsersInRoles_GetRolesForUser"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@UserId", SqlDbType.UniqueIdentifier ).Value = userId; SqlParameter returnCode = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCode.Direction = ParameterDirection.ReturnValue; SqlDataReader reader = null; try { cmd.Connection.Open(); using ( reader = cmd.ExecuteReader() ) { while ( reader.Read() ) { RainbowRole role = GetRoleFromReader( reader ); result.Add( role ); } reader.Close(); if ( ( ( int )returnCode.Value ) == 1 ) { throw new RainbowRoleProviderException( "User doesn't exist" ); } } return result; } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetAllRoles" ); } throw new RainbowRoleProviderException( "Error executing aspnet_Roles_GetAllRoles stored proc", e ); } catch ( RainbowRoleProviderException ) { throw; } catch ( Exception e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetAllRoles" ); } throw new RainbowRoleProviderException( "Error getting roles for user " + userId.ToString(), e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override string[] GetUsersInRole( string portalAlias, Guid roleId ) { ArrayList result = new ArrayList(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_UsersInRoles_GetUsersInRoles"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@RoleId", SqlDbType.UniqueIdentifier ).Value = roleId; SqlParameter returnCode = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCode.Direction = ParameterDirection.ReturnValue; SqlDataReader reader = null; try { cmd.Connection.Open(); using ( reader = cmd.ExecuteReader() ) { while ( reader.Read() ) { result.Add( reader.GetString( 0 ) ); } reader.Close(); if ( ( ( int )returnCode.Value ) == 1 ) { throw new RainbowRoleProviderException( "Role doesn't exist" ); } } return ( string[] )result.ToArray( typeof( string ) ); } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetAllRoles" ); } throw new RainbowRoleProviderException( "Error executing aspnet_UsersInRoles_GetUsersInRoles stored proc", e ); } catch ( Exception e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetAllRoles" ); } throw new RainbowRoleProviderException( "Error getting users for role " + roleId.ToString(), e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override bool IsUserInRole( string portalAlias, Guid userId, Guid roleId ) { if ( roleId.Equals( AllUsersGuid ) || roleId.Equals( AuthenticatedUsersGuid ) ) { return true; } else if ( roleId.Equals( UnauthenticatedUsersGuid ) ) { return false; } SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_UsersInRoles_IsUserInRole"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@RoleId", SqlDbType.UniqueIdentifier ).Value = roleId; cmd.Parameters.Add( "@userId", SqlDbType.UniqueIdentifier ).Value = userId; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; switch ( returnCode ) { case 0: return false; case 1: return true; case 2: throw new RainbowRoleProviderException( "User with Id = " + userId + " does not exist" ); case 3: throw new RainbowRoleProviderException( "Role with Id = " + roleId + " does not exist" ); default: throw new RainbowRoleProviderException( "Error executing IsUserInRole" ); } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "IsUserInRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_UsersInRoles_IsUserInRole stored proc", e ); } finally { cmd.Connection.Close(); } } public override void RemoveUsersFromRoles( string portalAlias, Guid[] userIds, Guid[] roleIds ) { string userIdsStr = string.Empty; string roleIdsStr = string.Empty; foreach ( Guid userId in userIds ) { userIdsStr += userId.ToString() + ","; } userIdsStr = userIdsStr.Substring( 0, userIdsStr.Length - 1 ); foreach ( Guid roleId in roleIds ) { roleIdsStr += roleId.ToString() + ","; } roleIdsStr = roleIdsStr.Substring( 0, roleIdsStr.Length - 1 ); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_UsersInRoles_RemoveUsersFromRoles"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@UserIds", SqlDbType.VarChar, 4000 ).Value = userIdsStr; cmd.Parameters.Add( "@RoleIds", SqlDbType.VarChar, 4000 ).Value = roleIdsStr; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; switch ( returnCode ) { case 0: return; case 1: throw new RainbowRoleProviderException( "One of the users is not in one of the specified roles" ); case 2: throw new RainbowRoleProviderException( "Application " + portalAlias + " doesn't exist" ); case 3: throw new RainbowRoleProviderException( "One of the roles doesn't exist" ); case 4: throw new RainbowMembershipProviderException( "One of the users doesn't exist" ); default: throw new RainbowRoleProviderException( "aspnet_UsersInRoles_RemoveUsersToRoles returned error code " + returnCode ); } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "CreateRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_UsersInRoles_RemoveUsersToRoles stored proc", e ); } finally { cmd.Connection.Close(); } } public override bool RoleExists( string portalAlias, Guid roleId ) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_Roles_RoleExists"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@RoleId", SqlDbType.UniqueIdentifier ).Value = roleId; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; try { cmd.Connection.Open(); cmd.ExecuteNonQuery(); int returnCode = ( int )returnCodeParam.Value; return ( returnCode == 1 ); } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "RoleExists" ); } throw new RainbowRoleProviderException( "Error executing aspnet_Roles_RoleExists stored proc", e ); } finally { cmd.Connection.Close(); } } public override RainbowRole GetRoleByName( string portalAlias, string roleName ) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "aspnet_Roles_GetRoleByName"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = new SqlConnection( connectionString ); cmd.Parameters.Add( "@ApplicationName", SqlDbType.NVarChar, 256 ).Value = portalAlias; cmd.Parameters.Add( "@RoleName", SqlDbType.NVarChar, 256 ).Value = roleName; SqlParameter returnCodeParam = cmd.Parameters.Add( "@ReturnCode", SqlDbType.Int ); returnCodeParam.Direction = ParameterDirection.ReturnValue; SqlDataReader reader = null; try { cmd.Connection.Open(); using ( reader = cmd.ExecuteReader() ) { if ( reader.Read() ) { return GetRoleFromReader( reader ); } else { throw new RainbowRoleProviderException( "Role doesn't exist" ); } } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "CreateRole" ); } throw new RainbowRoleProviderException( "Error executing aspnet_UsersInRoles_IsUserInRole stored proc", e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } public override RainbowRole GetRoleById( Guid roleId ) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT RoleId, RoleName, Description FROM aspnet_Roles WHERE RoleId=@RoleId"; cmd.Parameters.Add( "@RoleId", SqlDbType.UniqueIdentifier ).Value = roleId; cmd.Connection = new SqlConnection( connectionString ); SqlDataReader reader = null; try { cmd.Connection.Open(); using ( reader = cmd.ExecuteReader() ) { if ( reader.Read() ) { return GetRoleFromReader( reader ); } else { throw new RainbowRoleProviderException( "Role doesn't exist" ); } } } catch ( SqlException e ) { if ( WriteExceptionsToEventLog ) { WriteToEventLog( e, "GetRoleById" ); } throw new RainbowRoleProviderException( "Error executing method GetRoleById", e ); } finally { if ( reader != null ) { reader.Close(); } cmd.Connection.Close(); } } #endregion #region Private helper methods /// <summary> /// A helper function to retrieve config values from the configuration file. /// </summary> /// <param name="configValue"></param> /// <param name="defaultValue"></param> /// <returns></returns> private string GetConfigValue( string configValue, string defaultValue ) { if ( String.IsNullOrEmpty( configValue ) ) return defaultValue; return configValue; } /// <summary> /// A helper function that writes exception detail to the event log. Exceptions are written to the event log as a security /// measure to avoid private database details from being returned to the browser. If a method does not return a status /// or boolean indicating the action succeeded or failed, a generic exception is also thrown by the caller. /// </summary> /// <param name="e"></param> /// <param name="action"></param> private void WriteToEventLog( Exception e, string action ) { EventLog log = new EventLog(); log.Source = eventSource; log.Log = eventLog; string message = "An exception occurred communicating with the data source.\n\n"; message += "Action: " + action + "\n\n"; message += "Exception: " + e.ToString(); log.WriteEntry( message ); } private RainbowRole GetRoleFromReader( SqlDataReader reader ) { Guid roleId = reader.GetGuid( 0 ); string roleName = reader.GetString( 1 ); string roleDescription = string.Empty; if ( !reader.IsDBNull( 2 ) ) { roleDescription = reader.GetString( 2 ); } return new RainbowRole( roleId, roleName, roleDescription ); } #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.IO; using System.Xml; using log4net.Config; using log4net.Core; using log4net.Layout; using log4net.Repository; using log4net.Tests.Appender; using log4net.Util; using NUnit.Framework; using System.Globalization; namespace log4net.Tests.Layout { [TestFixture] public class XmlLayoutTest { private CultureInfo _currentCulture; private CultureInfo _currentUICulture; [SetUp] public void SetUp() { // set correct thread culture _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; _currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; } [TearDown] public void TearDown() { // restore previous culture System.Threading.Thread.CurrentThread.CurrentCulture = _currentCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = _currentUICulture; } /// <summary> /// Build a basic <see cref="LoggingEventData"/> object with some default values. /// </summary> /// <returns>A useful LoggingEventData object</returns> private LoggingEventData CreateBaseEvent() { LoggingEventData ed = new LoggingEventData(); ed.Domain = "Tests"; ed.ExceptionString = ""; ed.Identity = "TestRunner"; ed.Level = Level.Info; ed.LocationInfo = new LocationInfo(GetType()); ed.LoggerName = "TestLogger"; ed.Message = "Test message"; ed.ThreadName = "TestThread"; ed.TimeStamp = DateTime.Today; ed.UserName = "TestRunner"; ed.Properties = new PropertiesDictionary(); return ed; } private static string CreateEventNode(string message) { return String.Format("<event logger=\"TestLogger\" timestamp=\"{0}\" level=\"INFO\" thread=\"TestThread\" domain=\"Tests\" identity=\"TestRunner\" username=\"TestRunner\"><message>{1}</message></event>" + Environment.NewLine, #if !NETCF XmlConvert.ToString(DateTime.Today, XmlDateTimeSerializationMode.Local), #else XmlConvert.ToString(DateTime.Today), #endif message); } private static string CreateEventNode(string key, string value) { return String.Format("<event logger=\"TestLogger\" timestamp=\"{0}\" level=\"INFO\" thread=\"TestThread\" domain=\"Tests\" identity=\"TestRunner\" username=\"TestRunner\"><message>Test message</message><properties><data name=\"{1}\" value=\"{2}\" /></properties></event>" + Environment.NewLine, #if !NETCF XmlConvert.ToString(DateTime.Today, XmlDateTimeSerializationMode.Local), #else XmlConvert.ToString(DateTime.Today), #endif key, value); } [Test] public void TestBasicEventLogging() { TextWriter writer = new StringWriter(); XmlLayout layout = new XmlLayout(); LoggingEventData evt = CreateBaseEvent(); layout.Format(writer, new LoggingEvent(evt)); string expected = CreateEventNode("Test message"); Assert.AreEqual(expected, writer.ToString()); } [Test] public void TestIllegalCharacterMasking() { TextWriter writer = new StringWriter(); XmlLayout layout = new XmlLayout(); LoggingEventData evt = CreateBaseEvent(); evt.Message = "This is a masked char->\uFFFF"; layout.Format(writer, new LoggingEvent(evt)); string expected = CreateEventNode("This is a masked char-&gt;?"); Assert.AreEqual(expected, writer.ToString()); } [Test] public void TestCDATAEscaping1() { TextWriter writer = new StringWriter(); XmlLayout layout = new XmlLayout(); LoggingEventData evt = CreateBaseEvent(); //The &'s trigger the use of a cdata block evt.Message = "&&&&&&&Escape this ]]>. End here."; layout.Format(writer, new LoggingEvent(evt)); string expected = CreateEventNode("<![CDATA[&&&&&&&Escape this ]]>]]<![CDATA[>. End here.]]>"); Assert.AreEqual(expected, writer.ToString()); } [Test] public void TestCDATAEscaping2() { TextWriter writer = new StringWriter(); XmlLayout layout = new XmlLayout(); LoggingEventData evt = CreateBaseEvent(); //The &'s trigger the use of a cdata block evt.Message = "&&&&&&&Escape the end ]]>"; layout.Format(writer, new LoggingEvent(evt)); string expected = CreateEventNode("<![CDATA[&&&&&&&Escape the end ]]>]]&gt;"); Assert.AreEqual(expected, writer.ToString()); } [Test] public void TestCDATAEscaping3() { TextWriter writer = new StringWriter(); XmlLayout layout = new XmlLayout(); LoggingEventData evt = CreateBaseEvent(); //The &'s trigger the use of a cdata block evt.Message = "]]>&&&&&&&Escape the begining"; layout.Format(writer, new LoggingEvent(evt)); string expected = CreateEventNode("<![CDATA[]]>]]<![CDATA[>&&&&&&&Escape the begining]]>"); Assert.AreEqual(expected, writer.ToString()); } [Test] public void TestBase64EventLogging() { TextWriter writer = new StringWriter(); XmlLayout layout = new XmlLayout(); LoggingEventData evt = CreateBaseEvent(); layout.Base64EncodeMessage = true; layout.Format(writer, new LoggingEvent(evt)); string expected = CreateEventNode("VGVzdCBtZXNzYWdl"); Assert.AreEqual(expected, writer.ToString()); } [Test] public void TestPropertyEventLogging() { LoggingEventData evt = CreateBaseEvent(); evt.Properties["Property1"] = "prop1"; XmlLayout layout = new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = CreateEventNode("Property1", "prop1"); Assert.AreEqual(expected, stringAppender.GetString()); } [Test] public void TestBase64PropertyEventLogging() { LoggingEventData evt = CreateBaseEvent(); evt.Properties["Property1"] = "prop1"; XmlLayout layout = new XmlLayout(); layout.Base64EncodeProperties = true; StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = CreateEventNode("Property1", "cHJvcDE="); Assert.AreEqual(expected, stringAppender.GetString()); } [Test] public void TestPropertyCharacterEscaping() { LoggingEventData evt = CreateBaseEvent(); evt.Properties["Property1"] = "prop1 \"quoted\""; XmlLayout layout = new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = CreateEventNode("Property1", "prop1 &quot;quoted&quot;"); Assert.AreEqual(expected, stringAppender.GetString()); } [Test] public void TestPropertyIllegalCharacterMasking() { LoggingEventData evt = CreateBaseEvent(); evt.Properties["Property1"] = "mask this ->\uFFFF"; XmlLayout layout = new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = CreateEventNode("Property1", "mask this -&gt;?"); Assert.AreEqual(expected, stringAppender.GetString()); } [Test] public void TestPropertyIllegalCharacterMaskingInName() { LoggingEventData evt = CreateBaseEvent(); evt.Properties["Property\uFFFF"] = "mask this ->\uFFFF"; XmlLayout layout = new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = CreateEventNode("Property?", "mask this -&gt;?"); Assert.AreEqual(expected, stringAppender.GetString()); } #if FRAMEWORK_4_0_OR_ABOVE [Test] public void BracketsInStackTracesKeepLogWellFormed() { XmlLayout layout = new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestLogger"); Action<int> bar = foo => { try { throw new NullReferenceException(); } catch (Exception ex) { log1.Error(string.Format("Error {0}", foo), ex); } }; bar(42); // really only asserts there is no exception var loggedDoc = new XmlDocument(); loggedDoc.LoadXml(stringAppender.GetString()); } [Test] public void BracketsInStackTracesAreEscapedProperly() { XmlLayout layout = new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestLogger"); Action<int> bar = foo => { try { throw new NullReferenceException(); } catch (Exception ex) { log1.Error(string.Format("Error {0}", foo), ex); } }; bar(42); var log = stringAppender.GetString(); var startOfExceptionText = log.IndexOf("<exception>", StringComparison.InvariantCulture) + 11; var endOfExceptionText = log.IndexOf("</exception>", StringComparison.InvariantCulture); var sub = log.Substring(startOfExceptionText, endOfExceptionText - startOfExceptionText); if (sub.StartsWith("<![CDATA[")) { StringAssert.EndsWith("]]>", sub); } else { StringAssert.DoesNotContain("<", sub); StringAssert.DoesNotContain(">", sub); } } #endif } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This source file is machine generated. Please do not change the code manually. using System; using System.Collections.Generic; using System.IO.Packaging; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml; namespace DocumentFormat.OpenXml.Office2010.Ink { /// <summary> /// <para>Defines the ContextNode Class.</para> /// <para> When the object is serialized out as xml, its qualified name is msink:context.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>ContextNodeProperty &lt;msink:property></description></item> ///<item><description>SourceLink &lt;msink:sourceLink></description></item> ///<item><description>DestinationLink &lt;msink:destinationLink></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(ContextNodeProperty))] [ChildElementInfo(typeof(SourceLink))] [ChildElementInfo(typeof(DestinationLink))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ContextNode : OpenXmlCompositeElement { private const string tagName = "context"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 45; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12758; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","type","rotatedBoundingBox","alignmentLevel","contentType","ascender","descender","baseline","midline","customRecognizerId","mathML","mathStruct","mathSymbol","beginModifierType","endModifierType","rotationAngle","hotPoints","centroid","semanticType","shapeName","shapeGeometry" }; private static byte[] attributeNamespaceIds = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: id </para> /// </summary> [SchemaAttr(0, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public StringValue Type { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> rotatedBoundingBox.</para> /// <para>Represents the following attribute in the schema: rotatedBoundingBox </para> /// </summary> [SchemaAttr(0, "rotatedBoundingBox")] public ListValue<StringValue> RotatedBoundingBox { get { return (ListValue<StringValue>)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> alignmentLevel.</para> /// <para>Represents the following attribute in the schema: alignmentLevel </para> /// </summary> [SchemaAttr(0, "alignmentLevel")] public Int32Value AlignmentLevel { get { return (Int32Value)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> contentType.</para> /// <para>Represents the following attribute in the schema: contentType </para> /// </summary> [SchemaAttr(0, "contentType")] public Int32Value ContentType { get { return (Int32Value)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// <para> ascender.</para> /// <para>Represents the following attribute in the schema: ascender </para> /// </summary> [SchemaAttr(0, "ascender")] public StringValue Ascender { get { return (StringValue)Attributes[5]; } set { Attributes[5] = value; } } /// <summary> /// <para> descender.</para> /// <para>Represents the following attribute in the schema: descender </para> /// </summary> [SchemaAttr(0, "descender")] public StringValue Descender { get { return (StringValue)Attributes[6]; } set { Attributes[6] = value; } } /// <summary> /// <para> baseline.</para> /// <para>Represents the following attribute in the schema: baseline </para> /// </summary> [SchemaAttr(0, "baseline")] public StringValue Baseline { get { return (StringValue)Attributes[7]; } set { Attributes[7] = value; } } /// <summary> /// <para> midline.</para> /// <para>Represents the following attribute in the schema: midline </para> /// </summary> [SchemaAttr(0, "midline")] public StringValue Midline { get { return (StringValue)Attributes[8]; } set { Attributes[8] = value; } } /// <summary> /// <para> customRecognizerId.</para> /// <para>Represents the following attribute in the schema: customRecognizerId </para> /// </summary> [SchemaAttr(0, "customRecognizerId")] public StringValue CustomRecognizerId { get { return (StringValue)Attributes[9]; } set { Attributes[9] = value; } } /// <summary> /// <para> mathML.</para> /// <para>Represents the following attribute in the schema: mathML </para> /// </summary> [SchemaAttr(0, "mathML")] public StringValue MathML { get { return (StringValue)Attributes[10]; } set { Attributes[10] = value; } } /// <summary> /// <para> mathStruct.</para> /// <para>Represents the following attribute in the schema: mathStruct </para> /// </summary> [SchemaAttr(0, "mathStruct")] public StringValue MathStruct { get { return (StringValue)Attributes[11]; } set { Attributes[11] = value; } } /// <summary> /// <para> mathSymbol.</para> /// <para>Represents the following attribute in the schema: mathSymbol </para> /// </summary> [SchemaAttr(0, "mathSymbol")] public StringValue MathSymbol { get { return (StringValue)Attributes[12]; } set { Attributes[12] = value; } } /// <summary> /// <para> beginModifierType.</para> /// <para>Represents the following attribute in the schema: beginModifierType </para> /// </summary> [SchemaAttr(0, "beginModifierType")] public StringValue BeginModifierType { get { return (StringValue)Attributes[13]; } set { Attributes[13] = value; } } /// <summary> /// <para> endModifierType.</para> /// <para>Represents the following attribute in the schema: endModifierType </para> /// </summary> [SchemaAttr(0, "endModifierType")] public StringValue EndModifierType { get { return (StringValue)Attributes[14]; } set { Attributes[14] = value; } } /// <summary> /// <para> rotationAngle.</para> /// <para>Represents the following attribute in the schema: rotationAngle </para> /// </summary> [SchemaAttr(0, "rotationAngle")] public Int32Value RotationAngle { get { return (Int32Value)Attributes[15]; } set { Attributes[15] = value; } } /// <summary> /// <para> hotPoints.</para> /// <para>Represents the following attribute in the schema: hotPoints </para> /// </summary> [SchemaAttr(0, "hotPoints")] public ListValue<StringValue> HotPoints { get { return (ListValue<StringValue>)Attributes[16]; } set { Attributes[16] = value; } } /// <summary> /// <para> centroid.</para> /// <para>Represents the following attribute in the schema: centroid </para> /// </summary> [SchemaAttr(0, "centroid")] public StringValue Centroid { get { return (StringValue)Attributes[17]; } set { Attributes[17] = value; } } /// <summary> /// <para> semanticType.</para> /// <para>Represents the following attribute in the schema: semanticType </para> /// </summary> [SchemaAttr(0, "semanticType")] public StringValue SemanticType { get { return (StringValue)Attributes[18]; } set { Attributes[18] = value; } } /// <summary> /// <para> shapeName.</para> /// <para>Represents the following attribute in the schema: shapeName </para> /// </summary> [SchemaAttr(0, "shapeName")] public StringValue ShapeName { get { return (StringValue)Attributes[19]; } set { Attributes[19] = value; } } /// <summary> /// <para> shapeGeometry.</para> /// <para>Represents the following attribute in the schema: shapeGeometry </para> /// </summary> [SchemaAttr(0, "shapeGeometry")] public ListValue<StringValue> ShapeGeometry { get { return (ListValue<StringValue>)Attributes[20]; } set { Attributes[20] = value; } } /// <summary> /// Initializes a new instance of the ContextNode class. /// </summary> public ContextNode():base(){} /// <summary> ///Initializes a new instance of the ContextNode class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ContextNode(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ContextNode class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ContextNode(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ContextNode class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ContextNode(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 45 == namespaceId && "property" == name) return new ContextNodeProperty(); if( 45 == namespaceId && "sourceLink" == name) return new SourceLink(); if( 45 == namespaceId && "destinationLink" == name) return new DestinationLink(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "type" == name) return new StringValue(); if( 0 == namespaceId && "rotatedBoundingBox" == name) return new ListValue<StringValue>(); if( 0 == namespaceId && "alignmentLevel" == name) return new Int32Value(); if( 0 == namespaceId && "contentType" == name) return new Int32Value(); if( 0 == namespaceId && "ascender" == name) return new StringValue(); if( 0 == namespaceId && "descender" == name) return new StringValue(); if( 0 == namespaceId && "baseline" == name) return new StringValue(); if( 0 == namespaceId && "midline" == name) return new StringValue(); if( 0 == namespaceId && "customRecognizerId" == name) return new StringValue(); if( 0 == namespaceId && "mathML" == name) return new StringValue(); if( 0 == namespaceId && "mathStruct" == name) return new StringValue(); if( 0 == namespaceId && "mathSymbol" == name) return new StringValue(); if( 0 == namespaceId && "beginModifierType" == name) return new StringValue(); if( 0 == namespaceId && "endModifierType" == name) return new StringValue(); if( 0 == namespaceId && "rotationAngle" == name) return new Int32Value(); if( 0 == namespaceId && "hotPoints" == name) return new ListValue<StringValue>(); if( 0 == namespaceId && "centroid" == name) return new StringValue(); if( 0 == namespaceId && "semanticType" == name) return new StringValue(); if( 0 == namespaceId && "shapeName" == name) return new StringValue(); if( 0 == namespaceId && "shapeGeometry" == name) return new ListValue<StringValue>(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ContextNode>(deep); } } /// <summary> /// <para>Defines the ContextNodeProperty Class.</para> /// <para> When the object is serialized out as xml, its qualified name is msink:property.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ContextNodeProperty : OpenXmlLeafTextElement { private const string tagName = "property"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 45; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12759; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "type" }; private static byte[] attributeNamespaceIds = { 0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public StringValue Type { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// Initializes a new instance of the ContextNodeProperty class. /// </summary> public ContextNodeProperty():base(){} /// <summary> /// Initializes a new instance of the ContextNodeProperty class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ContextNodeProperty(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new HexBinaryValue(){ InnerText = text }; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "type" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ContextNodeProperty>(deep); } } /// <summary> /// <para>Defines the SourceLink Class.</para> /// <para> When the object is serialized out as xml, its qualified name is msink:sourceLink.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class SourceLink : ContextLinkType { private const string tagName = "sourceLink"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 45; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12760; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the SourceLink class. /// </summary> public SourceLink():base(){} /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<SourceLink>(deep); } } /// <summary> /// <para>Defines the DestinationLink Class.</para> /// <para> When the object is serialized out as xml, its qualified name is msink:destinationLink.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class DestinationLink : ContextLinkType { private const string tagName = "destinationLink"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 45; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12761; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the DestinationLink class. /// </summary> public DestinationLink():base(){} /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<DestinationLink>(deep); } } /// <summary> /// Defines the ContextLinkType class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public abstract partial class ContextLinkType : OpenXmlLeafElement { private static string[] attributeTagNames = { "direction","ref" }; private static byte[] attributeNamespaceIds = { 0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> direction.</para> /// <para>Represents the following attribute in the schema: direction </para> /// </summary> [SchemaAttr(0, "direction")] public EnumValue<DocumentFormat.OpenXml.Office2010.Ink.LinkDirectionValues> Direction { get { return (EnumValue<DocumentFormat.OpenXml.Office2010.Ink.LinkDirectionValues>)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> ref.</para> /// <para>Represents the following attribute in the schema: ref </para> /// </summary> [SchemaAttr(0, "ref")] public StringValue Reference { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "direction" == name) return new EnumValue<DocumentFormat.OpenXml.Office2010.Ink.LinkDirectionValues>(); if( 0 == namespaceId && "ref" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Initializes a new instance of the ContextLinkType class. /// </summary> protected ContextLinkType(){} } /// <summary> /// Defines the KnownContextNodeTypeValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum KnownContextNodeTypeValues { ///<summary> ///root. ///<para>When the item is serialized out as xml, its value is "root".</para> ///</summary> [EnumString("root")] Root, ///<summary> ///unclassifiedInk. ///<para>When the item is serialized out as xml, its value is "unclassifiedInk".</para> ///</summary> [EnumString("unclassifiedInk")] UnclassifiedInk, ///<summary> ///writingRegion. ///<para>When the item is serialized out as xml, its value is "writingRegion".</para> ///</summary> [EnumString("writingRegion")] WritingRegion, ///<summary> ///analysisHint. ///<para>When the item is serialized out as xml, its value is "analysisHint".</para> ///</summary> [EnumString("analysisHint")] AnalysisHint, ///<summary> ///object. ///<para>When the item is serialized out as xml, its value is "object".</para> ///</summary> [EnumString("object")] Object, ///<summary> ///inkDrawing. ///<para>When the item is serialized out as xml, its value is "inkDrawing".</para> ///</summary> [EnumString("inkDrawing")] InkDrawing, ///<summary> ///image. ///<para>When the item is serialized out as xml, its value is "image".</para> ///</summary> [EnumString("image")] Image, ///<summary> ///paragraph. ///<para>When the item is serialized out as xml, its value is "paragraph".</para> ///</summary> [EnumString("paragraph")] Paragraph, ///<summary> ///line. ///<para>When the item is serialized out as xml, its value is "line".</para> ///</summary> [EnumString("line")] Line, ///<summary> ///inkBullet. ///<para>When the item is serialized out as xml, its value is "inkBullet".</para> ///</summary> [EnumString("inkBullet")] InkBullet, ///<summary> ///inkWord. ///<para>When the item is serialized out as xml, its value is "inkWord".</para> ///</summary> [EnumString("inkWord")] InkWord, ///<summary> ///textWord. ///<para>When the item is serialized out as xml, its value is "textWord".</para> ///</summary> [EnumString("textWord")] TextWord, ///<summary> ///customRecognizer. ///<para>When the item is serialized out as xml, its value is "customRecognizer".</para> ///</summary> [EnumString("customRecognizer")] CustomRecognizer, ///<summary> ///mathRegion. ///<para>When the item is serialized out as xml, its value is "mathRegion".</para> ///</summary> [EnumString("mathRegion")] MathRegion, ///<summary> ///mathEquation. ///<para>When the item is serialized out as xml, its value is "mathEquation".</para> ///</summary> [EnumString("mathEquation")] MathEquation, ///<summary> ///mathStruct. ///<para>When the item is serialized out as xml, its value is "mathStruct".</para> ///</summary> [EnumString("mathStruct")] MathStruct, ///<summary> ///mathSymbol. ///<para>When the item is serialized out as xml, its value is "mathSymbol".</para> ///</summary> [EnumString("mathSymbol")] MathSymbol, ///<summary> ///mathIdentifier. ///<para>When the item is serialized out as xml, its value is "mathIdentifier".</para> ///</summary> [EnumString("mathIdentifier")] MathIdentifier, ///<summary> ///mathOperator. ///<para>When the item is serialized out as xml, its value is "mathOperator".</para> ///</summary> [EnumString("mathOperator")] MathOperator, ///<summary> ///mathNumber. ///<para>When the item is serialized out as xml, its value is "mathNumber".</para> ///</summary> [EnumString("mathNumber")] MathNumber, ///<summary> ///nonInkDrawing. ///<para>When the item is serialized out as xml, its value is "nonInkDrawing".</para> ///</summary> [EnumString("nonInkDrawing")] NonInkDrawing, ///<summary> ///groupNode. ///<para>When the item is serialized out as xml, its value is "groupNode".</para> ///</summary> [EnumString("groupNode")] GroupNode, ///<summary> ///mixedDrawing. ///<para>When the item is serialized out as xml, its value is "mixedDrawing".</para> ///</summary> [EnumString("mixedDrawing")] MixedDrawing, } /// <summary> /// Defines the LinkDirectionValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum LinkDirectionValues { ///<summary> ///to. ///<para>When the item is serialized out as xml, its value is "to".</para> ///</summary> [EnumString("to")] To, ///<summary> ///from. ///<para>When the item is serialized out as xml, its value is "from".</para> ///</summary> [EnumString("from")] From, ///<summary> ///with. ///<para>When the item is serialized out as xml, its value is "with".</para> ///</summary> [EnumString("with")] With, } /// <summary> /// Defines the KnownSemanticTypeValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum KnownSemanticTypeValues { ///<summary> ///none. ///<para>When the item is serialized out as xml, its value is "none".</para> ///</summary> [EnumString("none")] None, ///<summary> ///underline. ///<para>When the item is serialized out as xml, its value is "underline".</para> ///</summary> [EnumString("underline")] Underline, ///<summary> ///strikethrough. ///<para>When the item is serialized out as xml, its value is "strikethrough".</para> ///</summary> [EnumString("strikethrough")] Strikethrough, ///<summary> ///highlight. ///<para>When the item is serialized out as xml, its value is "highlight".</para> ///</summary> [EnumString("highlight")] Highlight, ///<summary> ///scratchOut. ///<para>When the item is serialized out as xml, its value is "scratchOut".</para> ///</summary> [EnumString("scratchOut")] ScratchOut, ///<summary> ///verticalRange. ///<para>When the item is serialized out as xml, its value is "verticalRange".</para> ///</summary> [EnumString("verticalRange")] VerticalRange, ///<summary> ///callout. ///<para>When the item is serialized out as xml, its value is "callout".</para> ///</summary> [EnumString("callout")] Callout, ///<summary> ///enclosure. ///<para>When the item is serialized out as xml, its value is "enclosure".</para> ///</summary> [EnumString("enclosure")] Enclosure, ///<summary> ///comment. ///<para>When the item is serialized out as xml, its value is "comment".</para> ///</summary> [EnumString("comment")] Comment, ///<summary> ///container. ///<para>When the item is serialized out as xml, its value is "container".</para> ///</summary> [EnumString("container")] Container, ///<summary> ///connector. ///<para>When the item is serialized out as xml, its value is "connector".</para> ///</summary> [EnumString("connector")] Connector, } }
// 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.Xml.Schema; namespace System.Xml { /// <summary> /// Implementations of XmlRawWriter are intended to be wrapped by the XmlWellFormedWriter. The /// well-formed writer performs many checks in behalf of the raw writer, and keeps state that the /// raw writer otherwise would have to keep. Therefore, the well-formed writer will call the /// XmlRawWriter using the following rules, in order to make raw writers easier to implement: /// /// 1. The well-formed writer keeps a stack of element names, and always calls /// WriteEndElement(string, string, string) instead of WriteEndElement(). /// 2. The well-formed writer tracks namespaces, and will pass himself in via the /// WellformedWriter property. It is used in the XmlRawWriter's implementation of IXmlNamespaceResolver. /// Thus, LookupPrefix does not have to be implemented. /// 3. The well-formed writer tracks write states, so the raw writer doesn't need to. /// 4. The well-formed writer will always call StartElementContent. /// 5. The well-formed writer will always call WriteNamespaceDeclaration for namespace nodes, /// rather than calling WriteStartAttribute(). If the writer is supporting namespace declarations in chunks /// (SupportsNamespaceDeclarationInChunks is true), the XmlWellFormedWriter will call WriteStartNamespaceDeclaration, /// then any method that can be used to write out a value of an attribute (WriteString, WriteChars, WriteRaw, WriteCharEntity...) /// and then WriteEndNamespaceDeclaration - instead of just a single WriteNamespaceDeclaration call. This feature will be /// supported by raw writers serializing to text that wish to preserve the attribute value escaping etc. /// 6. The well-formed writer guarantees a well-formed document, including correct call sequences, /// correct namespaces, and correct document rule enforcement. /// 7. All element and attribute names will be fully resolved and validated. Null will never be /// passed for any of the name parts. /// 8. The well-formed writer keeps track of xml:space and xml:lang. /// 9. The well-formed writer verifies NmToken, Name, and QName values and calls WriteString(). /// </summary> internal abstract partial class XmlRawWriter : XmlWriter { // // Fields // // base64 converter protected XmlRawWriterBase64Encoder base64Encoder; // namespace resolver protected IXmlNamespaceResolver resolver; // // XmlWriter implementation // // Raw writers do not have to track whether this is a well-formed document. public override void WriteStartDocument() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteStartDocument(bool standalone) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteEndDocument() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { } // Raw writers do not have to keep a stack of element names. public override void WriteEndElement() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to keep a stack of element names. public override void WriteFullEndElement() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // By default, convert base64 value to string and call WriteString. public override void WriteBase64(byte[] buffer, int index, int count) { if (base64Encoder == null) { base64Encoder = new XmlRawWriterBase64Encoder(this); } // Encode will call WriteRaw to write out the encoded characters base64Encoder.Encode(buffer, index, count); } // Raw writers do not have to keep track of namespaces. public override string LookupPrefix(string ns) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to keep track of write states. public override WriteState WriteState { get { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Raw writers do not have to keep track of xml:space. public override XmlSpace XmlSpace { get { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Raw writers do not have to keep track of xml:lang. public override string XmlLang { get { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Raw writers do not have to verify NmToken values. public override void WriteNmToken(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to verify Name values. public override void WriteName(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to verify QName values. public override void WriteQualifiedName(string localName, string ns) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Forward call to WriteString(string). public override void WriteCData(string text) { WriteString(text); } // Forward call to WriteString(string). public override void WriteCharEntity(char ch) { WriteString(new string(ch, 1)); } // Forward call to WriteString(string). public override void WriteSurrogateCharEntity(char lowChar, char highChar) { WriteString(new string(new char[] { lowChar, highChar })); } // Forward call to WriteString(string). public override void WriteWhitespace(string ws) { WriteString(ws); } // Forward call to WriteString(string). public override void WriteChars(char[] buffer, int index, int count) { WriteString(new string(buffer, index, count)); } // Forward call to WriteString(string). public override void WriteRaw(char[] buffer, int index, int count) { WriteString(new string(buffer, index, count)); } // Forward call to WriteString(string). public override void WriteRaw(string data) { WriteString(data); } // Override in order to handle Xml simple typed values and to pass resolver for QName values public override void WriteValue(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } WriteString(XmlUntypedConverter.ToString(value, resolver)); } // Override in order to handle Xml simple typed values and to pass resolver for QName values public override void WriteValue(string value) { WriteString(value); } public override void WriteValue(DateTimeOffset value) { // For compatibility with custom writers, XmlWriter writes DateTimeOffset as DateTime. // Our internal writers should use the DateTimeOffset-String conversion from XmlConvert. WriteString(XmlConvert.ToString(value)); } // Copying to XmlRawWriter is not currently supported. public override void WriteAttributes(XmlReader reader, bool defattr) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteNode(XmlReader reader, bool defattr) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // // XmlRawWriter methods and properties // // Get and set the namespace resolver that's used by this RawWriter to resolve prefixes. internal virtual IXmlNamespaceResolver NamespaceResolver { get { return resolver; } set { resolver = value; } } // Write the xml declaration. This must be the first call. internal virtual void WriteXmlDeclaration(XmlStandalone standalone) { } internal virtual void WriteXmlDeclaration(string xmldecl) { } // Called after an element's attributes have been enumerated, but before any children have been // enumerated. This method must always be called, even for empty elements. internal abstract void StartElementContent(); // Called before a root element is written (before the WriteStartElement call) // the conformanceLevel specifies the current conformance level the writer is operating with. internal virtual void OnRootElement(ConformanceLevel conformanceLevel) { } // WriteEndElement() and WriteFullEndElement() overloads, in which caller gives the full name of the // element, so that raw writers do not need to keep a stack of element names. This method should // always be called instead of WriteEndElement() or WriteFullEndElement() without parameters. internal abstract void WriteEndElement(string prefix, string localName, string ns); internal virtual void WriteFullEndElement(string prefix, string localName, string ns) { WriteEndElement(prefix, localName, ns); } internal virtual void WriteQualifiedName(string prefix, string localName, string ns) { if (prefix.Length != 0) { WriteString(prefix); WriteString(":"); } WriteString(localName); } // This method must be called instead of WriteStartAttribute() for namespaces. internal abstract void WriteNamespaceDeclaration(string prefix, string ns); // When true, the XmlWellFormedWriter will call: // 1) WriteStartNamespaceDeclaration // 2) any method that can be used to write out a value of an attribute: WriteString, WriteChars, WriteRaw, WriteCharEntity... // 3) WriteEndNamespaceDeclaration // instead of just a single WriteNamespaceDeclaration call. // // This feature will be supported by raw writers serializing to text that wish to preserve the attribute value escaping and entities. internal virtual bool SupportsNamespaceDeclarationInChunks { get { return false; } } internal virtual void WriteStartNamespaceDeclaration(string prefix) { throw new NotSupportedException(); } internal virtual void WriteEndNamespaceDeclaration() { throw new NotSupportedException(); } // This is called when the remainder of a base64 value should be output. internal virtual void WriteEndBase64() { // The Flush will call WriteRaw to write out the rest of the encoded characters base64Encoder.Flush(); } internal virtual void Close(WriteState currentState) { Dispose(); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; // This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event. // These are used in EngineCallback.cs. // The events are how the engine tells the debugger about what is happening in the debuggee process. // There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These // each implement the IDebugEvent2.GetAttributes method for the type of event they represent. // Most events sent the debugger are asynchronous events. // For more info on events, see https://msdn.microsoft.com/en-us/library/bb161367.aspx namespace Cosmos.Debug.VSDebugEngine { #region Event base classes class AD7AsynchronousEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return VSConstants.S_OK; } } class AD7StoppingEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return VSConstants.S_OK; } } class AD7SynchronousEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return VSConstants.S_OK; } } class AD7SynchronousStoppingEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return VSConstants.S_OK; } } #endregion sealed class AD7StepCompletedEvent : IDebugEvent2, IDebugStepCompleteEvent2 { public const string IID = "0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D"; public static void Send(AD7Engine engine) { var xEvent = new AD7StepCompletedEvent(); engine.Callback.Send(xEvent, IID, engine.mProcess.Thread); } #region IDebugEvent2 Members public int GetAttributes(out uint pdwAttrib) { pdwAttrib = (uint)(enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP); return VSConstants.S_OK; } #endregion } // The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created. sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2 { public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06"; private IDebugEngine2 m_engine; AD7EngineCreateEvent(AD7Engine engine) { m_engine = engine; } public static void Send(AD7Engine engine) { AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine); engine.Callback.Send(eventObject, IID, null, null); } int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine) { engine = m_engine; return VSConstants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to. sealed class AD7ProgramCreateEvent : AD7AsynchronousEvent, IDebugProgramCreateEvent2 { public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139"; internal static void Send(AD7Engine engine) { AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent(); engine.Callback.Send(eventObject, IID, null); } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded. sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2 { public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2"; readonly AD7Module m_module; readonly bool m_fLoad; public AD7ModuleLoadEvent(AD7Module module, bool fLoad) { m_module = module; m_fLoad = fLoad; } int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad) { module = m_module; if (m_fLoad) { //debugMessage = String.Concat("Loaded '", m_module.DebuggedModule.Name, "'"); fIsLoad = 1; } else { //debugMessage = String.Concat("Unloaded '", m_module.DebuggedModule.Name, "'"); fIsLoad = 0; } return VSConstants.S_OK; } internal static void Send(AD7Engine engine, AD7Module aModule, bool fLoad) { var eventObject = new AD7ModuleLoadEvent(aModule, fLoad); engine.Callback.Send(eventObject, IID, null); } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion // or is otherwise destroyed. sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2 { public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5"; readonly uint m_exitCode; public AD7ProgramDestroyEvent(uint exitCode) { m_exitCode = exitCode; } #region IDebugProgramDestroyEvent2 Members int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode) { exitCode = m_exitCode; return VSConstants.S_OK; } #endregion } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged. sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2 { public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA"; internal static void Send(AD7Engine engine, IDebugThread2 aThread) { var eventObject = new AD7ThreadCreateEvent(); engine.Callback.Send(eventObject, IID, aThread); } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited. sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2 { public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541"; readonly uint m_exitCode; public AD7ThreadDestroyEvent(uint exitCode) { m_exitCode = exitCode; } #region IDebugThreadDestroyEvent2 Members int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode) { exitCode = m_exitCode; return VSConstants.S_OK; } internal static void Send(AD7Engine aEngine, IDebugThread2 aThread, uint aExitCode) { var xObj = new AD7ThreadDestroyEvent(aExitCode); aEngine.Callback.Send(xObj, IID, aThread); } #endregion } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed. sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2 { public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B"; public AD7LoadCompleteEvent() { } internal static void Send(AD7Engine aEngine, AD7Thread aThread) { var xMessage = new AD7LoadCompleteEvent(); aEngine.Callback.Send(xMessage, IID, aThread); } } // This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed. sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2 { public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b"; } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing. sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2 { public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e"; private string m_str; public AD7OutputDebugStringEvent(string str) { m_str = str; } #region IDebugOutputStringEvent2 Members int IDebugOutputStringEvent2.GetString(out string pbstrString) { pbstrString = m_str; return VSConstants.S_OK; } #endregion } // This interface is sent by the debug engine (DE) to indicate the results of searching for symbols for a module in the debuggee sealed class AD7SymbolSearchEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2 { public const string IID = "638F7C54-C160-4c7b-B2D0-E0337BC61F8C"; private AD7Module m_module; private string m_searchInfo; private enum_MODULE_INFO_FLAGS m_symbolFlags; public AD7SymbolSearchEvent(AD7Module module, string searchInfo, enum_MODULE_INFO_FLAGS symbolFlags) { m_module = module; m_searchInfo = searchInfo; m_symbolFlags = symbolFlags; } #region IDebugSymbolSearchEvent2 Members int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags) { pModule = m_module; pbstrDebugMessage = m_searchInfo; pdwModuleInfoFlags[0] = m_symbolFlags; return VSConstants.S_OK; } #endregion } // This interface is sent when a pending breakpoint has been bound in the debuggee. sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2 { public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0"; private AD7PendingBreakpoint m_pendingBreakpoint; private AD7BoundBreakpoint m_boundBreakpoint; public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint) { m_pendingBreakpoint = pendingBreakpoint; m_boundBreakpoint = boundBreakpoint; } #region IDebugBreakpointBoundEvent2 Members int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1]; boundBreakpoints[0] = m_boundBreakpoint; ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints); return VSConstants.S_OK; } int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP) { ppPendingBP = m_pendingBreakpoint; return VSConstants.S_OK; } #endregion } // This Event is sent when a breakpoint is hit in the debuggee sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2 { public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74"; IEnumDebugBoundBreakpoints2 m_boundBreakpoints; public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints) { m_boundBreakpoints = boundBreakpoints; } #region IDebugBreakpointEvent2 Members int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { ppEnum = m_boundBreakpoints; return VSConstants.S_OK; } #endregion } sealed class AD7EntrypointEvent : AD7StoppingEvent, IDebugEntryPointEvent2 { public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9"; public static void Send(AD7Engine aEngine) { aEngine.Callback.Send(new AD7EntrypointEvent(), IID, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplyAddDouble() { var test = new SimpleTernaryOpTest__MultiplyAddDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyAddDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public Vector128<Double> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddDouble testClass) { var result = Fma.MultiplyAdd(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) fixed (Vector128<Double>* pFld3 = &_fld3) { var result = Fma.MultiplyAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Double[] _data3 = new Double[Op3ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private static Vector128<Double> _clsVar3; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private Vector128<Double> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleTernaryOpTest__MultiplyAddDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplyAdd( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplyAdd( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplyAdd( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplyAdd( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) fixed (Vector128<Double>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplyAdd( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)), Sse2.LoadVector128((Double*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr); var result = Fma.MultiplyAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplyAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplyAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddDouble(); var result = Fma.MultiplyAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) fixed (Vector128<Double>* pFld3 = &test._fld3) { var result = Fma.MultiplyAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplyAdd(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) fixed (Vector128<Double>* pFld3 = &_fld3) { var result = Fma.MultiplyAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplyAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplyAdd( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)), Sse2.LoadVector128((Double*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[0] * secondOp[0]) + thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) + thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplyAdd)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Pixator.Api.Areas.HelpPage.ModelDescriptions; using Pixator.Api.Areas.HelpPage.Models; namespace Pixator.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; namespace System.IO.Tests { public class FileInfo_GetSetTimes : InfoGetSetTimes<FileInfo> { public override FileInfo GetExistingItem() { string path = GetTestFilePath(); File.Create(path).Dispose(); return new FileInfo(path); } private static bool HasNonZeroNanoseconds(DateTime dt) => dt.Ticks % 10 != 0; public FileInfo GetNonZeroMilliseconds() { FileInfo fileinfo = new FileInfo(GetTestFilePath()); fileinfo.Create().Dispose(); if (fileinfo.LastWriteTime.Millisecond == 0) { DateTime dt = fileinfo.LastWriteTime; dt = dt.AddMilliseconds(1); fileinfo.LastWriteTime = dt; } Assert.NotEqual(0, fileinfo.LastWriteTime.Millisecond); return fileinfo; } public FileInfo GetNonZeroNanoseconds() { FileInfo fileinfo = new FileInfo(GetTestFilePath()); fileinfo.Create().Dispose(); if (!HasNonZeroNanoseconds(fileinfo.LastWriteTime)) { if (PlatformDetection.IsOSX) return null; DateTime dt = fileinfo.LastWriteTime; dt = dt.AddTicks(1); fileinfo.LastWriteTime = dt; } Assert.True(HasNonZeroNanoseconds(fileinfo.LastWriteTime)); return fileinfo; } public override FileInfo GetMissingItem() => new FileInfo(GetTestFilePath()); public override string GetItemPath(FileInfo item) => item.FullName; public override void InvokeCreate(FileInfo item) => item.Create(); public override IEnumerable<TimeFunction> TimeFunctions(bool requiresRoundtripping = false) { if (IOInputs.SupportsGettingCreationTime && (!requiresRoundtripping || IOInputs.SupportsSettingCreationTime)) { yield return TimeFunction.Create( ((testFile, time) => { testFile.CreationTime = time; }), ((testFile) => testFile.CreationTime), DateTimeKind.Local); yield return TimeFunction.Create( ((testFile, time) => { testFile.CreationTimeUtc = time; }), ((testFile) => testFile.CreationTimeUtc), DateTimeKind.Unspecified); yield return TimeFunction.Create( ((testFile, time) => { testFile.CreationTimeUtc = time; }), ((testFile) => testFile.CreationTimeUtc), DateTimeKind.Utc); } yield return TimeFunction.Create( ((testFile, time) => { testFile.LastAccessTime = time; }), ((testFile) => testFile.LastAccessTime), DateTimeKind.Local); yield return TimeFunction.Create( ((testFile, time) => { testFile.LastAccessTimeUtc = time; }), ((testFile) => testFile.LastAccessTimeUtc), DateTimeKind.Unspecified); yield return TimeFunction.Create( ((testFile, time) => { testFile.LastAccessTimeUtc = time; }), ((testFile) => testFile.LastAccessTimeUtc), DateTimeKind.Utc); yield return TimeFunction.Create( ((testFile, time) => { testFile.LastWriteTime = time; }), ((testFile) => testFile.LastWriteTime), DateTimeKind.Local); yield return TimeFunction.Create( ((testFile, time) => { testFile.LastWriteTimeUtc = time; }), ((testFile) => testFile.LastWriteTimeUtc), DateTimeKind.Unspecified); yield return TimeFunction.Create( ((testFile, time) => { testFile.LastWriteTimeUtc = time; }), ((testFile) => testFile.LastWriteTimeUtc), DateTimeKind.Utc); } [ConditionalFact(nameof(isNotHFS))] public void CopyToMillisecondPresent() { FileInfo input = GetNonZeroMilliseconds(); FileInfo output = new FileInfo(Path.Combine(GetTestFilePath(), input.Name)); Assert.Equal(0, output.LastWriteTime.Millisecond); output.Directory.Create(); output = input.CopyTo(output.FullName, true); Assert.Equal(input.LastWriteTime.Millisecond, output.LastWriteTime.Millisecond); Assert.NotEqual(0, output.LastWriteTime.Millisecond); } [ConditionalFact(nameof(isNotHFS))] public void CopyToNanosecondsPresent() { FileInfo input = GetNonZeroNanoseconds(); if (input == null) return; FileInfo output = new FileInfo(Path.Combine(GetTestFilePath(), input.Name)); output.Directory.Create(); output = input.CopyTo(output.FullName, true); Assert.Equal(input.LastWriteTime.Ticks, output.LastWriteTime.Ticks); Assert.True(HasNonZeroNanoseconds(output.LastWriteTime)); } [ConditionalFact(nameof(isHFS))] public void CopyToNanosecondsPresent_HFS() { FileInfo input = new FileInfo(GetTestFilePath()); input.Create().Dispose(); FileInfo output = new FileInfo(Path.Combine(GetTestFilePath(), input.Name)); output.Directory.Create(); output = input.CopyTo(output.FullName, true); Assert.Equal(input.LastWriteTime.Ticks, output.LastWriteTime.Ticks); Assert.False(HasNonZeroNanoseconds(output.LastWriteTime)); } [ConditionalFact(nameof(isHFS))] public void MoveToMillisecondPresent_HFS() { FileInfo input = new FileInfo(GetTestFilePath()); input.Create().Dispose(); string dest = Path.Combine(input.DirectoryName, GetTestFileName()); input.MoveTo(dest); FileInfo output = new FileInfo(dest); Assert.Equal(0, output.LastWriteTime.Millisecond); } [ConditionalFact(nameof(isNotHFS))] public void MoveToMillisecondPresent() { FileInfo input = GetNonZeroMilliseconds(); string dest = Path.Combine(input.DirectoryName, GetTestFileName()); input.MoveTo(dest); FileInfo output = new FileInfo(dest); Assert.NotEqual(0, output.LastWriteTime.Millisecond); } [ConditionalFact(nameof(isHFS))] public void CopyToMillisecondPresent_HFS() { FileInfo input = new FileInfo(GetTestFilePath()); input.Create().Dispose(); FileInfo output = new FileInfo(Path.Combine(GetTestFilePath(), input.Name)); output.Directory.Create(); output = input.CopyTo(output.FullName, true); Assert.Equal(input.LastWriteTime.Millisecond, output.LastWriteTime.Millisecond); Assert.Equal(0, output.LastWriteTime.Millisecond); } [Fact] public void DeleteAfterEnumerate_TimesStillSet() { // When enumerating we populate the state as we already have it. DateTime beforeTime = DateTime.UtcNow.AddSeconds(-1); string filePath = GetTestFilePath(); File.Create(filePath).Dispose(); FileInfo info = new DirectoryInfo(TestDirectory).EnumerateFiles().First(); DateTime afterTime = DateTime.UtcNow.AddSeconds(1); // Deleting doesn't change any info state info.Delete(); ValidateSetTimes(info, beforeTime, afterTime); } [Fact] [PlatformSpecific(TestPlatforms.Linux)] public void BirthTimeIsNotNewerThanLowestOfAccessModifiedTimes() { // On Linux (if no birth time), we synthesize CreationTime from the oldest of // status changed time (ctime) and write time (mtime) // Sanity check that it is in that range. DateTime before = DateTime.UtcNow.AddMinutes(-1); FileInfo fi = GetExistingItem(); // should set ctime fi.LastWriteTimeUtc = DateTime.UtcNow.AddMinutes(1); // mtime fi.LastAccessTimeUtc = DateTime.UtcNow.AddMinutes(2); // atime // Assert.InRange is inclusive Assert.InRange(fi.CreationTimeUtc, before, fi.LastWriteTimeUtc); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't read root in appcontainer [PlatformSpecific(TestPlatforms.Windows)] public void PageFileHasTimes() { // Typically there is a page file on the C: drive, if not, don't bother trying to track it down. string pageFilePath = Directory.EnumerateFiles(@"C:\", "pagefile.sys").FirstOrDefault(); if (pageFilePath != null) { Assert.All(TimeFunctions(), (item) => { var time = item.Getter(new FileInfo(pageFilePath)); Assert.NotEqual(DateTime.FromFileTime(0), time); }); } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Collections.Specialized; using System.Diagnostics; using Fonlow.CommonSync; using System.Runtime.Remoting.Messaging; [assembly: CLSCompliant(false)] namespace Fonlow.CommonSync { /// <summary> /// For event /// </summary> public class TextChangedEventArgs : StatusEventArgs { public TextChangedEventArgs(string text) : base(text) { } } /// <summary> /// Basic facade framework for OcPlaxo and SyncML /// </summary> public class SyncFacadeBase { /// <summary> /// construct the facade and wire with platformProvider /// </summary> /// <param name="platformProvider"></param> public SyncFacadeBase(ILocalDataSource platformProvider) { this.localDataSource = platformProvider; } /// <summary> /// Generally for unit testing /// </summary> public SyncFacadeBase() { } private System.Net.WebProxy proxy; /// <summary> /// Proxy for the web connection, external. /// </summary> public System.Net.WebProxy Proxy { get { return proxy; } set { proxy = value; } } private TraceSwitch traceSwitch; /// <summary> /// External trace switch /// </summary> public TraceSwitch TraceSwitch { get { return traceSwitch; } set { traceSwitch = value; } } private string basicUriStr; /// <summary> /// Basic URI connection to a sync server. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Str")] public string BasicUriStr { get { return basicUriStr; } set { basicUriStr = value; } } private DateTime lastAnchorTime; /// <summary> /// Last anchor. /// </summary> public DateTime LastAnchorTime { get { return lastAnchorTime; } set { lastAnchorTime = value; } } private int lastAnchor; public int LastAnchor { get { return lastAnchor; } set { lastAnchor = value; } } public int NextAnchor { get { return lastAnchor + 1; } } public string LastAnchorTimeStr { get { return LastAnchorTime.ToString("yyyyMMddTHHmmssZ"); } } private ILocalDataSource localDataSource; /// <summary> /// External address book platform provider /// </summary> public ILocalDataSource LocalDataSource { get { return localDataSource; } } /// <summary> /// Provide an internal namespace to group strings which will be used to represent categories of trace. /// </summary> protected sealed class TraceCategory { private TraceCategory() { } public const string OperationStatus = "OperationStatus"; public const string Error = "Error"; public const string Warning = "private const string"; public const string PositiveError = "PositiveError"; public const string Exception = "Exception"; } private bool firstSync; /// <summary> /// Indicate whether sync was done before. This flag is generally initialized by checking some persistent settings. /// </summary> public bool FirstSync { get { return firstSync; } set { firstSync = value; } } /// <summary> /// Fire when a major operation start, with message telling the world. The client codes will start hourglass cursor. /// </summary> public event EventHandler<StatusEventArgs> StartOperationEvent; /// <summary> /// Tell application's GUI about the start of the sync operation through wired StartOperationEvent. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void TellStartOperation(object sender, StatusEventArgs e) { if (StartOperationEvent != null) StartOperationEvent(sender, e); } /// <summary> /// Fire when a major operation end normally or abnormally, with message telling the world. The client codes will show default cursor. /// </summary> public event EventHandler<StatusEventArgs> EndOperationEvent; /// <summary> /// Tell application's GUI that the sync is completed, through the wired EndOperationEvent. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void TellEndOperation(object sender, StatusEventArgs e) { if (EndOperationEvent != null) EndOperationEvent(sender, e); } /// <summary> /// Fire to show operation message to user. /// </summary> public event EventHandler<StatusEventArgs> OperationStatusEvent; /// <summary> /// Fire event for displaying status of an operation in application's GUI. /// This function will be used by inherited classes and /// some worker classes inside the same assembly. /// This function is to tell important message that may concern the end users. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DisplayOperationStatus(object sender, StatusEventArgs e) { if (OperationStatusEvent != null) OperationStatusEvent(sender, e); } public void DisplayOperationMessage(string message) { DisplayOperationStatus(this, new StatusEventArgs(message)); } /// <summary> /// Fire when last anchor gets updated /// </summary> public event EventHandler<AnchorChangedEventArgs> LastAnchorChangedEvent; protected void NotifyLastAnchorChanged(DateTime anchorTime, int anchor) { if (LastAnchorChangedEvent != null) LastAnchorChangedEvent(this, new AnchorChangedEventArgs(anchorTime, anchor)); } #region Functions of reporting errors /// <summary> /// Trace with custom error message, under category Error. /// </summary> /// <param name="text"></param> protected static void HandleErrorStatus(string text) { Trace.WriteLine(text, TraceCategory.Error); } /*private static void HandleErrorPositive(string text) { Trace.WriteLine(text, TraceCategory.positiveError); }*/ /// <summary> /// Trace Error message of exception, under category Exception /// </summary> /// <param name="exception"></param> protected static void WriteErrorException(Exception exception) { Trace.WriteLine(exception.Message, TraceCategory.Exception); } /// <summary> /// Provide general handling of async call back /// </summary> /// <param name="asyncResult"></param> protected static void GeneralCompletionCallback(IAsyncResult asyncResult) { AsyncResult resultObj = (AsyncResult)asyncResult; ActionHandler d = (ActionHandler)resultObj.AsyncDelegate; try { d.EndInvoke(asyncResult); } catch (Exception e) { WriteErrorException(e); throw; } } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="X509Name.cs"> // Copyright (c) 2014 Alexander Logger. // Copyright (c) 2000 - 2013 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org). // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Raksha.Asn1.Pkcs; using Raksha.Utilities; using Raksha.Utilities.Encoders; namespace Raksha.Asn1.X509 { /** * <pre> * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type OBJECT IDENTIFIER, * value ANY } * </pre> */ public class X509Name : Asn1Encodable { /** * country code - StringType(SIZE(2)) */ public static readonly DerObjectIdentifier C = new DerObjectIdentifier("2.5.4.6"); /** * organization - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier O = new DerObjectIdentifier("2.5.4.10"); /** * organizational unit name - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier OU = new DerObjectIdentifier("2.5.4.11"); /** * Title */ public static readonly DerObjectIdentifier T = new DerObjectIdentifier("2.5.4.12"); /** * common name - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier CN = new DerObjectIdentifier("2.5.4.3"); /** * street - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier Street = new DerObjectIdentifier("2.5.4.9"); /** * device serial number name - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier SerialNumber = new DerObjectIdentifier("2.5.4.5"); /** * locality name - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier L = new DerObjectIdentifier("2.5.4.7"); /** * state, or province name - StringType(SIZE(1..64)) */ public static readonly DerObjectIdentifier ST = new DerObjectIdentifier("2.5.4.8"); /** * Naming attributes of type X520name */ public static readonly DerObjectIdentifier Surname = new DerObjectIdentifier("2.5.4.4"); public static readonly DerObjectIdentifier GivenName = new DerObjectIdentifier("2.5.4.42"); public static readonly DerObjectIdentifier Initials = new DerObjectIdentifier("2.5.4.43"); public static readonly DerObjectIdentifier Generation = new DerObjectIdentifier("2.5.4.44"); public static readonly DerObjectIdentifier UniqueIdentifier = new DerObjectIdentifier("2.5.4.45"); /** * businessCategory - DirectoryString(SIZE(1..128) */ public static readonly DerObjectIdentifier BusinessCategory = new DerObjectIdentifier("2.5.4.15"); /** * postalCode - DirectoryString(SIZE(1..40) */ public static readonly DerObjectIdentifier PostalCode = new DerObjectIdentifier("2.5.4.17"); /** * dnQualifier - DirectoryString(SIZE(1..64) */ public static readonly DerObjectIdentifier DnQualifier = new DerObjectIdentifier("2.5.4.46"); /** * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) */ public static readonly DerObjectIdentifier Pseudonym = new DerObjectIdentifier("2.5.4.65"); /** * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z */ public static readonly DerObjectIdentifier DateOfBirth = new DerObjectIdentifier("1.3.6.1.5.5.7.9.1"); /** * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) */ public static readonly DerObjectIdentifier PlaceOfBirth = new DerObjectIdentifier("1.3.6.1.5.5.7.9.2"); /** * RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" */ public static readonly DerObjectIdentifier Gender = new DerObjectIdentifier("1.3.6.1.5.5.7.9.3"); /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static readonly DerObjectIdentifier CountryOfCitizenship = new DerObjectIdentifier("1.3.6.1.5.5.7.9.4"); /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static readonly DerObjectIdentifier CountryOfResidence = new DerObjectIdentifier("1.3.6.1.5.5.7.9.5"); /** * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) */ public static readonly DerObjectIdentifier NameAtBirth = new DerObjectIdentifier("1.3.36.8.3.14"); /** * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF * DirectoryString(SIZE(1..30)) */ public static readonly DerObjectIdentifier PostalAddress = new DerObjectIdentifier("2.5.4.16"); /** * RFC 2256 dmdName */ public static readonly DerObjectIdentifier DmdName = new DerObjectIdentifier("2.5.4.54"); /** * id-at-telephoneNumber */ public static readonly DerObjectIdentifier TelephoneNumber = X509ObjectIdentifiers.id_at_telephoneNumber; /** * id-at-name */ public static readonly DerObjectIdentifier Name = X509ObjectIdentifiers.id_at_name; /** * Email address (RSA PKCS#9 extension) - IA5String. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.</p> */ public static readonly DerObjectIdentifier EmailAddress = PkcsObjectIdentifiers.Pkcs9AtEmailAddress; /** * more from PKCS#9 */ public static readonly DerObjectIdentifier UnstructuredName = PkcsObjectIdentifiers.Pkcs9AtUnstructuredName; public static readonly DerObjectIdentifier UnstructuredAddress = PkcsObjectIdentifiers.Pkcs9AtUnstructuredAddress; /** * email address in Verisign certificates */ public static readonly DerObjectIdentifier E = EmailAddress; /* * others... */ public static readonly DerObjectIdentifier DC = new DerObjectIdentifier("0.9.2342.19200300.100.1.25"); /** * LDAP User id. */ public static readonly DerObjectIdentifier UID = new DerObjectIdentifier("0.9.2342.19200300.100.1.1"); /** * determines whether or not strings should be processed and printed * from back to front. */ // public static bool DefaultReverse = false; public static bool DefaultReverse { get { return DefaultReversePrivate[0]; } set { DefaultReversePrivate[0] = value; } } private static readonly bool[] DefaultReversePrivate = {false}; /** * default look up table translating OID values into their common symbols following * the convention in RFC 2253 with a few extras */ public static readonly IDictionary DefaultSymbols = Platform.CreateHashtable(); /** * look up table translating OID values into their common symbols following the convention in RFC 2253 */ public static readonly IDictionary RFC2253Symbols = Platform.CreateHashtable(); /** * look up table translating OID values into their common symbols following the convention in RFC 1779 * */ public static readonly IDictionary RFC1779Symbols = Platform.CreateHashtable(); /** * look up table translating common symbols into their OIDS. */ public static readonly IDictionary DefaultLookup = Platform.CreateHashtable(); static X509Name() { DefaultSymbols.Add(C, "C"); DefaultSymbols.Add(O, "O"); DefaultSymbols.Add(T, "T"); DefaultSymbols.Add(OU, "OU"); DefaultSymbols.Add(CN, "CN"); DefaultSymbols.Add(L, "L"); DefaultSymbols.Add(ST, "ST"); DefaultSymbols.Add(SerialNumber, "SERIALNUMBER"); DefaultSymbols.Add(EmailAddress, "E"); DefaultSymbols.Add(DC, "DC"); DefaultSymbols.Add(UID, "UID"); DefaultSymbols.Add(Street, "STREET"); DefaultSymbols.Add(Surname, "SURNAME"); DefaultSymbols.Add(GivenName, "GIVENNAME"); DefaultSymbols.Add(Initials, "INITIALS"); DefaultSymbols.Add(Generation, "GENERATION"); DefaultSymbols.Add(UnstructuredAddress, "unstructuredAddress"); DefaultSymbols.Add(UnstructuredName, "unstructuredName"); DefaultSymbols.Add(UniqueIdentifier, "UniqueIdentifier"); DefaultSymbols.Add(DnQualifier, "DN"); DefaultSymbols.Add(Pseudonym, "Pseudonym"); DefaultSymbols.Add(PostalAddress, "PostalAddress"); DefaultSymbols.Add(NameAtBirth, "NameAtBirth"); DefaultSymbols.Add(CountryOfCitizenship, "CountryOfCitizenship"); DefaultSymbols.Add(CountryOfResidence, "CountryOfResidence"); DefaultSymbols.Add(Gender, "Gender"); DefaultSymbols.Add(PlaceOfBirth, "PlaceOfBirth"); DefaultSymbols.Add(DateOfBirth, "DateOfBirth"); DefaultSymbols.Add(PostalCode, "PostalCode"); DefaultSymbols.Add(BusinessCategory, "BusinessCategory"); DefaultSymbols.Add(TelephoneNumber, "TelephoneNumber"); RFC2253Symbols.Add(C, "C"); RFC2253Symbols.Add(O, "O"); RFC2253Symbols.Add(OU, "OU"); RFC2253Symbols.Add(CN, "CN"); RFC2253Symbols.Add(L, "L"); RFC2253Symbols.Add(ST, "ST"); RFC2253Symbols.Add(Street, "STREET"); RFC2253Symbols.Add(DC, "DC"); RFC2253Symbols.Add(UID, "UID"); RFC1779Symbols.Add(C, "C"); RFC1779Symbols.Add(O, "O"); RFC1779Symbols.Add(OU, "OU"); RFC1779Symbols.Add(CN, "CN"); RFC1779Symbols.Add(L, "L"); RFC1779Symbols.Add(ST, "ST"); RFC1779Symbols.Add(Street, "STREET"); DefaultLookup.Add("c", C); DefaultLookup.Add("o", O); DefaultLookup.Add("t", T); DefaultLookup.Add("ou", OU); DefaultLookup.Add("cn", CN); DefaultLookup.Add("l", L); DefaultLookup.Add("st", ST); DefaultLookup.Add("serialnumber", SerialNumber); DefaultLookup.Add("street", Street); DefaultLookup.Add("emailaddress", E); DefaultLookup.Add("dc", DC); DefaultLookup.Add("e", E); DefaultLookup.Add("uid", UID); DefaultLookup.Add("surname", Surname); DefaultLookup.Add("givenname", GivenName); DefaultLookup.Add("initials", Initials); DefaultLookup.Add("generation", Generation); DefaultLookup.Add("unstructuredaddress", UnstructuredAddress); DefaultLookup.Add("unstructuredname", UnstructuredName); DefaultLookup.Add("uniqueidentifier", UniqueIdentifier); DefaultLookup.Add("dn", DnQualifier); DefaultLookup.Add("pseudonym", Pseudonym); DefaultLookup.Add("postaladdress", PostalAddress); DefaultLookup.Add("nameofbirth", NameAtBirth); DefaultLookup.Add("countryofcitizenship", CountryOfCitizenship); DefaultLookup.Add("countryofresidence", CountryOfResidence); DefaultLookup.Add("gender", Gender); DefaultLookup.Add("placeofbirth", PlaceOfBirth); DefaultLookup.Add("dateofbirth", DateOfBirth); DefaultLookup.Add("postalcode", PostalCode); DefaultLookup.Add("businesscategory", BusinessCategory); DefaultLookup.Add("telephonenumber", TelephoneNumber); } private readonly IList ordering = Platform.CreateArrayList(); private readonly X509NameEntryConverter converter; private readonly IList values = Platform.CreateArrayList(); private readonly IList added = Platform.CreateArrayList(); private Asn1Sequence seq; /** * Return a X509Name based on the passed in tagged object. * * @param obj tag object holding name. * @param explicitly true if explicitly tagged false otherwise. * @return the X509Name */ public static X509Name GetInstance(Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } public static X509Name GetInstance(object obj) { if (obj == null || obj is X509Name) { return (X509Name) obj; } if (obj != null) { return new X509Name(Asn1Sequence.GetInstance(obj)); } throw new ArgumentException("null object in factory", "obj"); } protected X509Name() { } /** * Constructor from Asn1Sequence * * the principal will be a list of constructed sets, each containing an (OID, string) pair. */ protected X509Name(Asn1Sequence seq) { this.seq = seq; foreach (Asn1Encodable asn1Obj in seq) { Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object()); for (int i = 0; i < asn1Set.Count; i++) { Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object()); if (s.Count != 2) { throw new ArgumentException("badly sized pair"); } ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object())); Asn1Object derValue = s[1].ToAsn1Object(); if (derValue is IAsn1String && !(derValue is DerUniversalString)) { string v = ((IAsn1String) derValue).GetString(); if (v.StartsWith("#")) { v = "\\" + v; } values.Add(v); } else { values.Add("#" + Hex.ToHexString(derValue.GetEncoded())); } added.Add(i != 0); } } } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/string pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering ArrayList should contain the OIDs * in the order they are meant to be encoded or printed in ToString.</p> */ public X509Name(IList ordering, IDictionary attributes) : this(ordering, attributes, new X509DefaultEntryConverter()) { } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/string pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering ArrayList should contain the OIDs * in the order they are meant to be encoded or printed in ToString.</p> * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts.</p> */ public X509Name(IList ordering, IDictionary attributes, X509NameEntryConverter converter) { this.converter = converter; foreach (DerObjectIdentifier oid in ordering) { object attribute = attributes[oid]; if (attribute == null) { throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name"); } this.ordering.Add(oid); added.Add(false); values.Add(attribute); // copy the hash table } } /** * Takes two vectors one of the oids and the other of the values. */ public X509Name(IList oids, IList values) : this(oids, values, new X509DefaultEntryConverter()) { } /** * Takes two vectors one of the oids and the other of the values. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts.</p> */ public X509Name(IList oids, IList values, X509NameEntryConverter converter) { this.converter = converter; if (oids.Count != values.Count) { throw new ArgumentException("'oids' must be same length as 'values'."); } for (int i = 0; i < oids.Count; i++) { ordering.Add(oids[i]); this.values.Add(values[i]); added.Add(false); } } // private static bool IsEncoded( // string s) // { // return s.StartsWith("#"); // } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. */ public X509Name(string dirName) : this(DefaultReverse, DefaultLookup, dirName) { } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. */ public X509Name(string dirName, X509NameEntryConverter converter) : this(DefaultReverse, DefaultLookup, dirName, converter) { } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. If reverse * is true, create the encoded version of the sequence starting from the * last element in the string. */ public X509Name(bool reverse, string dirName) : this(reverse, DefaultLookup, dirName) { } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. If reverse is true the ASN.1 sequence representing the DN will * be built by starting at the end of the string, rather than the start. */ public X509Name(bool reverse, string dirName, X509NameEntryConverter converter) : this(reverse, DefaultLookup, dirName, converter) { } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DerObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. * <br/> * If reverse is true, create the encoded version of the sequence * starting from the last element in the string. * @param reverse true if we should start scanning from the end (RFC 2553). * @param lookUp table of names and their oids. * @param dirName the X.500 string to be parsed. */ public X509Name(bool reverse, IDictionary lookUp, string dirName) : this(reverse, lookUp, dirName, new X509DefaultEntryConverter()) { } private DerObjectIdentifier DecodeOid(string name, IDictionary lookUp) { if (name.ToUpperInvariant().StartsWith("OID.")) { return new DerObjectIdentifier(name.Substring(4)); } if (name[0] >= '0' && name[0] <= '9') { return new DerObjectIdentifier(name); } var oid = (DerObjectIdentifier) lookUp[name.ToLowerInvariant()]; if (oid == null) { throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name"); } return oid; } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DerObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. The passed in converter is used to convert the * string values to the right of each equals sign to their ASN.1 counterparts. * <br/> * @param reverse true if we should start scanning from the end, false otherwise. * @param lookUp table of names and oids. * @param dirName the string dirName * @param converter the converter to convert string values into their ASN.1 equivalents */ public X509Name(bool reverse, IDictionary lookUp, string dirName, X509NameEntryConverter converter) { this.converter = converter; var nTok = new X509NameTokenizer(dirName); while (nTok.HasMoreTokens()) { string token = nTok.NextToken(); int index = token.IndexOf('='); if (index == -1) { throw new ArgumentException("badly formated directory string"); } string name = token.Substring(0, index); string value = token.Substring(index + 1); DerObjectIdentifier oid = DecodeOid(name, lookUp); if (value.IndexOf('+') > 0) { var vTok = new X509NameTokenizer(value, '+'); string v = vTok.NextToken(); ordering.Add(oid); values.Add(v); added.Add(false); while (vTok.HasMoreTokens()) { string sv = vTok.NextToken(); int ndx = sv.IndexOf('='); string nm = sv.Substring(0, ndx); string vl = sv.Substring(ndx + 1); ordering.Add(DecodeOid(nm, lookUp)); values.Add(vl); added.Add(true); } } else { ordering.Add(oid); values.Add(value); added.Add(false); } } if (reverse) { // this.ordering.Reverse(); // this.values.Reverse(); // this.added.Reverse(); IList o = Platform.CreateArrayList(); IList v = Platform.CreateArrayList(); IList a = Platform.CreateArrayList(); int count = 1; for (int i = 0; i < ordering.Count; i++) { if (!((bool) added[i])) { count = 0; } int index = count++; o.Insert(index, ordering[i]); v.Insert(index, values[i]); a.Insert(index, added[i]); } ordering = o; values = v; added = a; } } /** * return an IList of the oids in the name, in the order they were found. */ public IList GetOidList() { return Platform.CreateArrayList(ordering); } /** * return an IList of the values found in the name, in the order they * were found. */ public IList GetValueList() { return Platform.CreateArrayList(values); } /** * return an IList of the values found in the name, in the order they * were found, with the DN label corresponding to passed in oid. */ public IList GetValueList(DerObjectIdentifier oid) { IList v = Platform.CreateArrayList(); DoGetValueList(oid, v); return v; } private void DoGetValueList(DerObjectIdentifier oid, IList v) { for (int i = 0; i != values.Count; i++) { if (ordering[i].Equals(oid)) { var val = (string) values[i]; if (val.StartsWith("\\#")) { val = val.Substring(1); } v.Add(val); } } } public override Asn1Object ToAsn1Object() { if (seq == null) { var vec = new Asn1EncodableVector(); var sVec = new Asn1EncodableVector(); DerObjectIdentifier lstOid = null; for (int i = 0; i != ordering.Count; i++) { var oid = (DerObjectIdentifier) ordering[i]; var str = (string) values[i]; if (lstOid == null || ((bool) added[i])) { } else { vec.Add(new DerSet(sVec)); sVec = new Asn1EncodableVector(); } sVec.Add(new DerSequence(oid, converter.GetConvertedValue(oid, str))); lstOid = oid; } vec.Add(new DerSet(sVec)); seq = new DerSequence(vec); } return seq; } /// <param name="other">The X509Name object to test equivalency against.</param> /// <param name="inOrder"> /// If true, the order of elements must be the same, /// as well as the values associated with each element. /// </param> public bool Equivalent(X509Name other, bool inOrder) { if (!inOrder) { return Equivalent(other); } if (other == null) { return false; } if (other == this) { return true; } int orderingSize = ordering.Count; if (orderingSize != other.ordering.Count) { return false; } for (int i = 0; i < orderingSize; i++) { var oid = (DerObjectIdentifier) ordering[i]; var oOid = (DerObjectIdentifier) other.ordering[i]; if (!oid.Equals(oOid)) { return false; } var val = (string) values[i]; var oVal = (string) other.values[i]; if (!equivalentStrings(val, oVal)) { return false; } } return true; } /** * test for equivalence - note: case is ignored. */ public bool Equivalent(X509Name other) { if (other == null) { return false; } if (other == this) { return true; } int orderingSize = ordering.Count; if (orderingSize != other.ordering.Count) { return false; } var indexes = new bool[orderingSize]; int start, end, delta; if (ordering[0].Equals(other.ordering[0])) // guess forward { start = 0; end = orderingSize; delta = 1; } else // guess reversed - most common problem { start = orderingSize - 1; end = -1; delta = -1; } for (int i = start; i != end; i += delta) { bool found = false; var oid = (DerObjectIdentifier) ordering[i]; var value = (string) values[i]; for (int j = 0; j < orderingSize; j++) { if (indexes[j]) { continue; } var oOid = (DerObjectIdentifier) other.ordering[j]; if (oid.Equals(oOid)) { var oValue = (string) other.values[j]; if (equivalentStrings(value, oValue)) { indexes[j] = true; found = true; break; } } } if (!found) { return false; } } return true; } private static bool equivalentStrings(string s1, string s2) { string v1 = canonicalize(s1); string v2 = canonicalize(s2); if (!v1.Equals(v2)) { v1 = stripInternalSpaces(v1); v2 = stripInternalSpaces(v2); if (!v1.Equals(v2)) { return false; } } return true; } private static string canonicalize(string s) { string v = s.ToLowerInvariant().Trim(); if (v.StartsWith("#")) { Asn1Object obj = decodeObject(v); if (obj is IAsn1String) { v = ((IAsn1String) obj).GetString().ToLowerInvariant().Trim(); } } return v; } private static Asn1Object decodeObject(string v) { try { return Asn1Object.FromByteArray(Hex.Decode(v.Substring(1))); } catch (IOException e) { throw new InvalidOperationException("unknown encoding in name: " + e.Message, e); } } private static string stripInternalSpaces(string str) { var res = new StringBuilder(); if (str.Length != 0) { char c1 = str[0]; res.Append(c1); for (int k = 1; k < str.Length; k++) { char c2 = str[k]; if (!(c1 == ' ' && c2 == ' ')) { res.Append(c2); } c1 = c2; } } return res.ToString(); } private void AppendValue(StringBuilder buf, IDictionary oidSymbols, DerObjectIdentifier oid, string val) { var sym = (string) oidSymbols[oid]; if (sym != null) { buf.Append(sym); } else { buf.Append(oid.Id); } buf.Append('='); int index = buf.Length; buf.Append(val); int end = buf.Length; if (val.StartsWith("\\#")) { index += 2; } while (index != end) { if ((buf[index] == ',') || (buf[index] == '"') || (buf[index] == '\\') || (buf[index] == '+') || (buf[index] == '=') || (buf[index] == '<') || (buf[index] == '>') || (buf[index] == ';')) { buf.Insert(index++, "\\"); end++; } index++; } } /** * convert the structure to a string - if reverse is true the * oids and values are listed out starting with the last element * in the sequence (ala RFC 2253), otherwise the string will begin * with the first element of the structure. If no string definition * for the oid is found in oidSymbols the string value of the oid is * added. Two standard symbol tables are provided DefaultSymbols, and * RFC2253Symbols as part of this class. * * @param reverse if true start at the end of the sequence and work back. * @param oidSymbols look up table strings for oids. */ public string ToString(bool reverse, IDictionary oidSymbols) { var components = new List<object>(); StringBuilder ava = null; for (int i = 0; i < ordering.Count; i++) { if ((bool) added[i]) { ava.Append('+'); AppendValue(ava, oidSymbols, (DerObjectIdentifier) ordering[i], (string) values[i]); } else { ava = new StringBuilder(); AppendValue(ava, oidSymbols, (DerObjectIdentifier) ordering[i], (string) values[i]); components.Add(ava); } } if (reverse) { components.Reverse(); } var buf = new StringBuilder(); if (components.Count > 0) { buf.Append(components[0]); for (int i = 1; i < components.Count; ++i) { buf.Append(','); buf.Append(components[i]); } } return buf.ToString(); } public override string ToString() { return ToString(DefaultReverse, DefaultSymbols); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Configuration; using Glass.Mapper.IoC; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateInterface; using NSubstitute; using NUnit.Framework; namespace Glass.Mapper.Tests.Pipelines.ObjectConstruction.Tasks.CreateInterface { [TestFixture] public class CreateInterfaceTaskFixture { private CreateInterfaceTask _task; [SetUp] public void Setup() { _task = new CreateInterfaceTask(); } #region Method - Execute [Test] public void Execute_ConcreteClass_ObjectNotCreated() { //Assign Type type = typeof(StubClass); var service = Substitute.For<IAbstractService>(); Context context = Context.Create(Substitute.For<IDependencyResolver>()); AbstractTypeCreationContext abstractTypeCreationContext = Substitute.For<AbstractTypeCreationContext>(); abstractTypeCreationContext.RequestedType = type; var configuration = Substitute.For<AbstractTypeConfiguration>(); configuration.Type = type; ObjectConstructionArgs args = new ObjectConstructionArgs(context, abstractTypeCreationContext, configuration, service); //Act _task.Execute(args); //Assert Assert.IsNull(args.Result); Assert.IsFalse(args.IsAborted); } [Test] public void Execute_ProxyInterface_ProxyGetsCreated() { //Assign Type type = typeof(IStubInterface); var glassConfig = Substitute.For<IGlassConfiguration>(); var service = Substitute.For<IAbstractService>(); Context context = Context.Create(Substitute.For<IDependencyResolver>()); AbstractTypeCreationContext abstractTypeCreationContext = Substitute.For<AbstractTypeCreationContext>(); abstractTypeCreationContext.RequestedType = typeof (IStubInterface); var configuration = Substitute.For<AbstractTypeConfiguration>(); configuration.Type = type; ObjectConstructionArgs args = new ObjectConstructionArgs(context, abstractTypeCreationContext, configuration, service); //Act _task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsFalse(args.IsAborted); Assert.IsTrue(args.Result is IStubInterface); Assert.IsFalse(args.Result.GetType() == typeof(IStubInterface)); } [Test] public void Execute_TwoClassesWithTheSameName_ProxyGetsCreated() { //Assign var glassConfig = Substitute.For<IGlassConfiguration>(); var service = Substitute.For<IAbstractService>(); Context context = Context.Create(Substitute.For<IDependencyResolver>()); AbstractTypeCreationContext abstractTypeCreationContext1 = Substitute.For<AbstractTypeCreationContext>(); abstractTypeCreationContext1.RequestedType = typeof(NS1.ProxyTest1); var configuration1 = Substitute.For<AbstractTypeConfiguration>(); configuration1.Type = typeof(NS1.ProxyTest1); ObjectConstructionArgs args1 = new ObjectConstructionArgs(context, abstractTypeCreationContext1, configuration1, service); AbstractTypeCreationContext abstractTypeCreationContext2 = Substitute.For<AbstractTypeCreationContext>(); abstractTypeCreationContext2.RequestedType = typeof(NS2.ProxyTest1); var configuration2 = Substitute.For<AbstractTypeConfiguration>(); configuration2.Type = typeof(NS2.ProxyTest1); ; ObjectConstructionArgs args2 = new ObjectConstructionArgs(context, abstractTypeCreationContext2, configuration2, service); //Act _task.Execute(args1); _task.Execute(args2); //Assert Assert.IsNotNull(args1.Result); Assert.IsFalse(args1.IsAborted); Assert.IsTrue(args1.Result is NS1.ProxyTest1); Assert.IsFalse(args1.Result.GetType() == typeof(NS1.ProxyTest1)); Assert.IsNotNull(args2.Result); Assert.IsFalse(args2.IsAborted); Assert.IsTrue(args2.Result is NS2.ProxyTest1); Assert.IsFalse(args2.Result.GetType() == typeof(NS2.ProxyTest1)); } [Test] public void Execute_ResultAlreadySet_DoesNoWork() { //Assign Type type = typeof(IStubInterface); var resolver = Substitute.For<IDependencyResolver>(); var service = Substitute.For<IAbstractService>(); Context context = Context.Create(resolver); AbstractTypeCreationContext abstractTypeCreationContext = Substitute.For<AbstractTypeCreationContext>(); abstractTypeCreationContext.RequestedType= typeof(IStubInterface); var configuration = Substitute.For<AbstractTypeConfiguration>(); configuration.Type = type; ObjectConstructionArgs args = new ObjectConstructionArgs(context, abstractTypeCreationContext, configuration, service); args.Result = string.Empty; //Act _task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsFalse(args.IsAborted); Assert.IsTrue(args.Result is string); } #endregion #region Stubs public class StubClass { } public interface IStubInterface { } #endregion } namespace NS1 { public interface ProxyTest1 { } } namespace NS2 { public interface ProxyTest1 { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// PublicIPAddressesOperations operations. /// </summary> internal partial class PublicIPAddressesOperations : IServiceOperations<NetworkManagementClient>, IPublicIPAddressesOperations { /// <summary> /// Initializes a new instance of the PublicIPAddressesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PublicIPAddressesOperations(NetworkManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// The delete publicIpAddress operation deletes the specified publicIpAddress. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, publicIpAddressName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// The delete publicIpAddress operation deletes the specified publicIpAddress. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The Get publicIpAddress operation retrieves information about the /// specified pubicIpAddress /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PublicIPAddress>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update PublicIPAddress operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<PublicIPAddress> _response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, publicIpAddressName, parameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update PublicIPAddress operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PublicIPAddress>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The List publicIpAddress operation retrieves all the publicIpAddresses in /// a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The List publicIpAddress operation retrieves all the publicIpAddresses in /// a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The List publicIpAddress operation retrieves all the publicIpAddresses in /// a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The List publicIpAddress operation retrieves all the publicIpAddresses in /// a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Adult Group Members Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SDGMDataSet : EduHubDataSet<SDGM> { /// <inheritdoc /> public override string Name { get { return "SDGM"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SDGMDataSet(EduHubContext Context) : base(Context) { Index_PERSON_LINK = new Lazy<NullDictionary<string, IReadOnlyList<SDGM>>>(() => this.ToGroupedNullDictionary(i => i.PERSON_LINK)); Index_SDGMKEY = new Lazy<Dictionary<string, IReadOnlyList<SDGM>>>(() => this.ToGroupedDictionary(i => i.SDGMKEY)); Index_TID = new Lazy<Dictionary<int, SDGM>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SDGM" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SDGM" /> fields for each CSV column header</returns> internal override Action<SDGM, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SDGM, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "SDGMKEY": mapper[i] = (e, v) => e.SDGMKEY = v; break; case "PERSON_LINK": mapper[i] = (e, v) => e.PERSON_LINK = v; break; case "START_DATE": mapper[i] = (e, v) => e.START_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "END_DATE": mapper[i] = (e, v) => e.END_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "OTHER_COMMENTS": mapper[i] = (e, v) => e.OTHER_COMMENTS = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SDGM" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SDGM" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SDGM" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SDGM}"/> of entities</returns> internal override IEnumerable<SDGM> ApplyDeltaEntities(IEnumerable<SDGM> Entities, List<SDGM> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SDGMKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.SDGMKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<SDGM>>> Index_PERSON_LINK; private Lazy<Dictionary<string, IReadOnlyList<SDGM>>> Index_SDGMKEY; private Lazy<Dictionary<int, SDGM>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SDGM by PERSON_LINK field /// </summary> /// <param name="PERSON_LINK">PERSON_LINK value used to find SDGM</param> /// <returns>List of related SDGM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDGM> FindByPERSON_LINK(string PERSON_LINK) { return Index_PERSON_LINK.Value[PERSON_LINK]; } /// <summary> /// Attempt to find SDGM by PERSON_LINK field /// </summary> /// <param name="PERSON_LINK">PERSON_LINK value used to find SDGM</param> /// <param name="Value">List of related SDGM entities</param> /// <returns>True if the list of related SDGM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPERSON_LINK(string PERSON_LINK, out IReadOnlyList<SDGM> Value) { return Index_PERSON_LINK.Value.TryGetValue(PERSON_LINK, out Value); } /// <summary> /// Attempt to find SDGM by PERSON_LINK field /// </summary> /// <param name="PERSON_LINK">PERSON_LINK value used to find SDGM</param> /// <returns>List of related SDGM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDGM> TryFindByPERSON_LINK(string PERSON_LINK) { IReadOnlyList<SDGM> value; if (Index_PERSON_LINK.Value.TryGetValue(PERSON_LINK, out value)) { return value; } else { return null; } } /// <summary> /// Find SDGM by SDGMKEY field /// </summary> /// <param name="SDGMKEY">SDGMKEY value used to find SDGM</param> /// <returns>List of related SDGM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDGM> FindBySDGMKEY(string SDGMKEY) { return Index_SDGMKEY.Value[SDGMKEY]; } /// <summary> /// Attempt to find SDGM by SDGMKEY field /// </summary> /// <param name="SDGMKEY">SDGMKEY value used to find SDGM</param> /// <param name="Value">List of related SDGM entities</param> /// <returns>True if the list of related SDGM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySDGMKEY(string SDGMKEY, out IReadOnlyList<SDGM> Value) { return Index_SDGMKEY.Value.TryGetValue(SDGMKEY, out Value); } /// <summary> /// Attempt to find SDGM by SDGMKEY field /// </summary> /// <param name="SDGMKEY">SDGMKEY value used to find SDGM</param> /// <returns>List of related SDGM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDGM> TryFindBySDGMKEY(string SDGMKEY) { IReadOnlyList<SDGM> value; if (Index_SDGMKEY.Value.TryGetValue(SDGMKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SDGM by TID field /// </summary> /// <param name="TID">TID value used to find SDGM</param> /// <returns>Related SDGM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SDGM FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SDGM by TID field /// </summary> /// <param name="TID">TID value used to find SDGM</param> /// <param name="Value">Related SDGM entity</param> /// <returns>True if the related SDGM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SDGM Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SDGM by TID field /// </summary> /// <param name="TID">TID value used to find SDGM</param> /// <returns>Related SDGM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SDGM TryFindByTID(int TID) { SDGM value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SDGM table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SDGM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SDGM]( [TID] int IDENTITY NOT NULL, [SDGMKEY] varchar(12) NOT NULL, [PERSON_LINK] varchar(10) NULL, [START_DATE] datetime NULL, [END_DATE] datetime NULL, [OTHER_COMMENTS] varchar(MAX) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SDGM_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [SDGM_Index_PERSON_LINK] ON [dbo].[SDGM] ( [PERSON_LINK] ASC ); CREATE CLUSTERED INDEX [SDGM_Index_SDGMKEY] ON [dbo].[SDGM] ( [SDGMKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDGM]') AND name = N'SDGM_Index_PERSON_LINK') ALTER INDEX [SDGM_Index_PERSON_LINK] ON [dbo].[SDGM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDGM]') AND name = N'SDGM_Index_TID') ALTER INDEX [SDGM_Index_TID] ON [dbo].[SDGM] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDGM]') AND name = N'SDGM_Index_PERSON_LINK') ALTER INDEX [SDGM_Index_PERSON_LINK] ON [dbo].[SDGM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDGM]') AND name = N'SDGM_Index_TID') ALTER INDEX [SDGM_Index_TID] ON [dbo].[SDGM] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SDGM"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SDGM"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SDGM> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SDGM] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SDGM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SDGM data set</returns> public override EduHubDataSetDataReader<SDGM> GetDataSetDataReader() { return new SDGMDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SDGM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SDGM data set</returns> public override EduHubDataSetDataReader<SDGM> GetDataSetDataReader(List<SDGM> Entities) { return new SDGMDataReader(new EduHubDataSetLoadedReader<SDGM>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SDGMDataReader : EduHubDataSetDataReader<SDGM> { public SDGMDataReader(IEduHubDataSetReader<SDGM> Reader) : base (Reader) { } public override int FieldCount { get { return 9; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // SDGMKEY return Current.SDGMKEY; case 2: // PERSON_LINK return Current.PERSON_LINK; case 3: // START_DATE return Current.START_DATE; case 4: // END_DATE return Current.END_DATE; case 5: // OTHER_COMMENTS return Current.OTHER_COMMENTS; case 6: // LW_DATE return Current.LW_DATE; case 7: // LW_TIME return Current.LW_TIME; case 8: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // PERSON_LINK return Current.PERSON_LINK == null; case 3: // START_DATE return Current.START_DATE == null; case 4: // END_DATE return Current.END_DATE == null; case 5: // OTHER_COMMENTS return Current.OTHER_COMMENTS == null; case 6: // LW_DATE return Current.LW_DATE == null; case 7: // LW_TIME return Current.LW_TIME == null; case 8: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // SDGMKEY return "SDGMKEY"; case 2: // PERSON_LINK return "PERSON_LINK"; case 3: // START_DATE return "START_DATE"; case 4: // END_DATE return "END_DATE"; case 5: // OTHER_COMMENTS return "OTHER_COMMENTS"; case 6: // LW_DATE return "LW_DATE"; case 7: // LW_TIME return "LW_TIME"; case 8: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "SDGMKEY": return 1; case "PERSON_LINK": return 2; case "START_DATE": return 3; case "END_DATE": return 4; case "OTHER_COMMENTS": return 5; case "LW_DATE": return 6; case "LW_TIME": return 7; case "LW_USER": return 8; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }