context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using System.IO;
using GME.MGA;
namespace DynamicsTeamTest.Projects
{
public class MSD_CADFixture : XmeImportFixture
{
protected override string xmeFilename
{
get { return Path.Combine("MSD_CAD", "MSD_CAD.xme"); }
}
}
public partial class MSD_CAD : IUseFixture<MSD_CADFixture>
{
internal string mgaFile { get { return this.fixture.mgaFile; } }
private MSD_CADFixture fixture { get; set; }
public void SetFixture(MSD_CADFixture data)
{
this.fixture = data;
}
//[Fact]
//[Trait("Model", "MSD_CAD")]
//[Trait("ProjectImport/Open", "MSD_CAD")]
//public void ProjectXmeImport()
//{
// Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
//}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("ProjectImport/Open", "MSD_CAD")]
public void ProjectMgaOpen()
{
var mgaReference = "MGA=" + mgaFile;
MgaProject project = new MgaProject();
project.OpenEx(mgaReference, "CyPhyML", null);
project.Close(true);
Assert.True(File.Exists(mgaReference.Substring("MGA=".Length)));
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_extra_mass_with_no_modelica_model()
{
string outputDir = "tbs_MSD_extra_mass_with_no_modelica_model";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_extra_mass_with_no_modelica_model|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_extra_mass_with_unconnected_modelica_model()
{
string outputDir = "tbs_MSD_extra_mass_with_unconnected_modelica_model";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_extra_mass_with_unconnected_modelica_model|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_system_without_dynamic_models()
{
string outputDir = "tbs_MSD_system_without_dynamic_models";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_system_without_dynamic_models|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_system_where_inner_system_only_has_dynamic_models()
{
string outputDir = "tbs_MSD_system_where_inner_system_only_has_dynamic_models";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_system_where_inner_system_only_has_dynamic_models|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_system_without_dynamic_models2()
{
string outputDir = "tbs_MSD_system_without_dynamic_models2";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_system_without_dynamic_models2|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_two_subsystems()
{
string outputDir = "tbs_MSD_two_subsystems";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_two_subsystems|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_two_subsystems_passing_parameter()
{
string outputDir = "tbs_MSD_two_subsystems_passing_parameter";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_two_subsystems_passing_parameter|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_two_subsystems_passing_parameter2()
{
string outputDir = "tbs_MSD_two_subsystems_passing_parameter2";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_two_subsystems_passing_parameter2|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_passing_value_between_components()
{
string outputDir = "tbs_MSD_passing_value_between_components";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_passing_value_between_components|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_passing_value_between_components2()
{
string outputDir = "tbs_MSD_passing_value_between_components2";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_passing_value_between_components2|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_two_subsystems_passing_parameter3()
{
string outputDir = "tbs_MSD_two_subsystems_passing_parameter3";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_two_subsystems_passing_parameter3|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_passing_value_nested_systems()
{
string outputDir = "tbs_MSD_passing_value_nested_systems";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_passing_value_nested_systems|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void tbs_MSD_one_dynamic_one_pure_cad()
{
string outputDir = "tbs_MSD_one_dynamic_one_pure_cad";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@tbs|kind=Testing|relpos=0/@MSD_one_dynamic_one_pure_cad|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
[Fact]
[Trait("Model", "MSD_CAD")]
[Trait("CyPhy2Modelica", "MSD_CAD")]
public void Dynamics_MSD()
{
string outputDir = "Dynamics_MSD";
string testBenchPath = "/@Dynamics|kind=Testing|relpos=0/@MSD|kind=TestBench|relpos=0";
Assert.True(File.Exists(mgaFile), "Failed to generate the mga.");
bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath);
Assert.True(result, "CyPhy2Modelica_v2 failed.");
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Accounts Receivable
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class DR : EduHubEntity
{
#region Navigation Property Cache
private SA Cache_DRTABLEA_SA;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<DRB> Cache_DRKEY_DRB_DR_CODE;
private IReadOnlyList<DRF> Cache_DRKEY_DRF_CODE;
private IReadOnlyList<KNOTE_DR> Cache_DRKEY_KNOTE_DR_CODE;
private IReadOnlyList<SDGM> Cache_DRKEY_SDGM_PERSON_LINK;
private IReadOnlyList<SF> Cache_DRKEY_SF_DEBTOR_ID;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Prime Key
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string DRKEY { get; internal set; }
/// <summary>
/// Debtor name
/// [Alphanumeric (30)]
/// </summary>
public string TITLE { get; internal set; }
/// <summary>
/// Outstanding allocation amount
/// </summary>
public decimal? ALLOCAMT { get; internal set; }
/// <summary>
/// Charges to date
/// </summary>
public decimal? CHARGES { get; internal set; }
/// <summary>
/// Charges this year
/// </summary>
public decimal? CHARGES_YTD { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED01 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED02 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED03 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED04 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED05 { get; internal set; }
/// <summary>
/// Opening balances
/// </summary>
public decimal? OPBAL { get; internal set; }
/// <summary>
/// Last receipt amount
/// </summary>
public decimal? LASTREC { get; internal set; }
/// <summary>
/// Last receipt date
/// </summary>
public DateTime? LASTRECDATE { get; internal set; }
/// <summary>
/// Open item (1) or...
/// Brought forward (0)
/// </summary>
public short? ACCTYPE { get; internal set; }
/// <summary>
/// CONTACT NAME
/// [Alphanumeric (30)]
/// </summary>
public string CONTACT { get; internal set; }
/// <summary>
/// T = Trade Debtor (not used)
/// I = Internal Debtor
/// 1 = AUS Debtor
/// 2 = NSW Debtor
/// 6 = WA Debtor
/// 9 = FRV Debtor
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string DRTYPE { get; internal set; }
/// <summary>
/// Table
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string DRTABLEA { get; internal set; }
/// <summary>
/// Business name
/// [Alphanumeric (30)]
/// </summary>
public string BUSNAME { get; internal set; }
/// <summary>
/// Business address of Debtor
/// [Alphanumeric (30)]
/// </summary>
public string BUSADD01 { get; internal set; }
/// <summary>
/// Business address of Debtor
/// [Alphanumeric (30)]
/// </summary>
public string BUSADD02 { get; internal set; }
/// <summary>
/// Business state
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string BUSSTATE { get; internal set; }
/// <summary>
/// Postcode
/// [Alphanumeric (4)]
/// </summary>
public string POSTCODE { get; internal set; }
/// <summary>
/// Telephone number
/// [Alphanumeric (20)]
/// </summary>
public string TELEPHONE { get; internal set; }
/// <summary>
/// Facsimile
/// [Alphanumeric (20)]
/// </summary>
public string FAX { get; internal set; }
/// <summary>
/// Mobile number
/// [Alphanumeric (20)]
/// </summary>
public string MOBILE { get; internal set; }
/// <summary>
/// Email address for emailing financial statements direct to the Sundry Debtor
/// [Alphanumeric (60)]
/// </summary>
public string BILLING_EMAIL { get; internal set; }
/// <summary>
/// Mailing name
/// [Alphanumeric (30)]
/// </summary>
public string MAILNAME { get; internal set; }
/// <summary>
/// Mailing address
/// [Alphanumeric (30)]
/// </summary>
public string MAILADD01 { get; internal set; }
/// <summary>
/// Mailing address
/// [Alphanumeric (30)]
/// </summary>
public string MAILADD02 { get; internal set; }
/// <summary>
/// Mailing state
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string MAILSTATE { get; internal set; }
/// <summary>
/// Mailing postcode
/// [Alphanumeric (4)]
/// </summary>
public string MAILPOST { get; internal set; }
/// <summary>
/// Delivery name
/// [Alphanumeric (30)]
/// </summary>
public string DELNAME { get; internal set; }
/// <summary>
/// Delivery address
/// [Alphanumeric (30)]
/// </summary>
public string ADDRESS01 { get; internal set; }
/// <summary>
/// Delivery address
/// [Alphanumeric (30)]
/// </summary>
public string ADDRESS02 { get; internal set; }
/// <summary>
/// Delivery postcode
/// [Alphanumeric (4)]
/// </summary>
public string DELIVPOST { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Memo]
/// </summary>
public string REMARK { get; internal set; }
/// <summary>
/// Inventory price level
/// </summary>
public short? PRICELEVEL { get; internal set; }
/// <summary>
/// Y/N flag for memos
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string MEMO_FLAG { get; internal set; }
/// <summary>
/// Notes about this client
/// [Memo]
/// </summary>
public string NOTES { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string DRSHORT { get; internal set; }
/// <summary>
/// Staff customer support rep
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string CSR { get; internal set; }
/// <summary>
/// Debtor group
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string DRGROUP { get; internal set; }
/// <summary>
/// Date first commenced as client
/// </summary>
public DateTime? COMMENCE { get; internal set; }
/// <summary>
/// Number of DRF transactions
/// </summary>
public double? DRFCOUNT { get; internal set; }
/// <summary>
/// Does debtor require tax invoices for GST
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string TAX_INVOICE { get; internal set; }
/// <summary>
/// Seed number for BPAY reference
/// </summary>
public int? BPAY_SEQUENCE { get; internal set; }
/// <summary>
/// BPAY Reference number with check digit
/// [Alphanumeric (20)]
/// </summary>
public string BPAY_REFERENCE { get; internal set; }
/// <summary>
/// Y/N flag for Note
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string KNOTE_FLAG { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last user name
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// SA (Fees) related entity by [DR.DRTABLEA]->[SA.SAKEY]
/// Table
/// </summary>
public SA DRTABLEA_SA
{
get
{
if (DRTABLEA == null)
{
return null;
}
if (Cache_DRTABLEA_SA == null)
{
Cache_DRTABLEA_SA = Context.SA.FindBySAKEY(DRTABLEA);
}
return Cache_DRTABLEA_SA;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// DRB (BPAY Receipts for Sundry Debtors) related entities by [DR.DRKEY]->[DRB.DR_CODE]
/// Prime Key
/// </summary>
public IReadOnlyList<DRB> DRKEY_DRB_DR_CODE
{
get
{
if (Cache_DRKEY_DRB_DR_CODE == null &&
!Context.DRB.TryFindByDR_CODE(DRKEY, out Cache_DRKEY_DRB_DR_CODE))
{
Cache_DRKEY_DRB_DR_CODE = new List<DRB>().AsReadOnly();
}
return Cache_DRKEY_DRB_DR_CODE;
}
}
/// <summary>
/// DRF (DR Transactions) related entities by [DR.DRKEY]->[DRF.CODE]
/// Prime Key
/// </summary>
public IReadOnlyList<DRF> DRKEY_DRF_CODE
{
get
{
if (Cache_DRKEY_DRF_CODE == null &&
!Context.DRF.TryFindByCODE(DRKEY, out Cache_DRKEY_DRF_CODE))
{
Cache_DRKEY_DRF_CODE = new List<DRF>().AsReadOnly();
}
return Cache_DRKEY_DRF_CODE;
}
}
/// <summary>
/// KNOTE_DR (Debtor Notes) related entities by [DR.DRKEY]->[KNOTE_DR.CODE]
/// Prime Key
/// </summary>
public IReadOnlyList<KNOTE_DR> DRKEY_KNOTE_DR_CODE
{
get
{
if (Cache_DRKEY_KNOTE_DR_CODE == null &&
!Context.KNOTE_DR.TryFindByCODE(DRKEY, out Cache_DRKEY_KNOTE_DR_CODE))
{
Cache_DRKEY_KNOTE_DR_CODE = new List<KNOTE_DR>().AsReadOnly();
}
return Cache_DRKEY_KNOTE_DR_CODE;
}
}
/// <summary>
/// SDGM (Adult Group Members) related entities by [DR.DRKEY]->[SDGM.PERSON_LINK]
/// Prime Key
/// </summary>
public IReadOnlyList<SDGM> DRKEY_SDGM_PERSON_LINK
{
get
{
if (Cache_DRKEY_SDGM_PERSON_LINK == null &&
!Context.SDGM.TryFindByPERSON_LINK(DRKEY, out Cache_DRKEY_SDGM_PERSON_LINK))
{
Cache_DRKEY_SDGM_PERSON_LINK = new List<SDGM>().AsReadOnly();
}
return Cache_DRKEY_SDGM_PERSON_LINK;
}
}
/// <summary>
/// SF (Staff) related entities by [DR.DRKEY]->[SF.DEBTOR_ID]
/// Prime Key
/// </summary>
public IReadOnlyList<SF> DRKEY_SF_DEBTOR_ID
{
get
{
if (Cache_DRKEY_SF_DEBTOR_ID == null &&
!Context.SF.TryFindByDEBTOR_ID(DRKEY, out Cache_DRKEY_SF_DEBTOR_ID))
{
Cache_DRKEY_SF_DEBTOR_ID = new List<SF>().AsReadOnly();
}
return Cache_DRKEY_SF_DEBTOR_ID;
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Configuration;
using NUnit.Framework;
using DataPageEvictionMode = Apache.Ignite.Core.Configuration.DataPageEvictionMode;
/// <summary>
/// Tests disk persistence.
/// </summary>
public class PersistenceTest
{
/** Temp dir for WAL. */
private readonly string _tempDir = TestUtils.GetTempDirectoryName();
/// <summary>
/// Sets up the test.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.ClearWorkDir();
}
/// <summary>
/// Tears down the test.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
if (Directory.Exists(_tempDir))
{
Directory.Delete(_tempDir, true);
}
TestUtils.ClearWorkDir();
}
/// <summary>
/// Tests that cache data survives node restart.
/// </summary>
[Test]
public void TestCacheDataSurvivesNodeRestart(
[Values(true, false)] bool withCacheStore,
[Values(true, false)] bool withCustomAffinity)
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = new DataStorageConfiguration
{
StoragePath = Path.Combine(_tempDir, "Store"),
WalPath = Path.Combine(_tempDir, "WalStore"),
WalArchivePath = Path.Combine(_tempDir, "WalArchive"),
MetricsEnabled = true,
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
PageEvictionMode = DataPageEvictionMode.Disabled,
Name = DataStorageConfiguration.DefaultDataRegionName,
PersistenceEnabled = true
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "volatileRegion",
PersistenceEnabled = false
}
}
}
};
const string cacheName = "persistentCache";
const string volatileCacheName = "volatileCache";
// Start Ignite, put data, stop.
using (var ignite = Ignition.Start(cfg))
{
ignite.GetCluster().SetActive(true);
// Create cache with default region (persistence enabled), add data.
var cache = ignite.CreateCache<int, int>(new CacheConfiguration
{
Name = cacheName,
CacheStoreFactory = withCacheStore ? new CustomStoreFactory() : null,
AffinityFunction = withCustomAffinity ? new CustomAffinityFunction() : null
});
cache[1] = 1;
// Check some metrics.
CheckDataStorageMetrics(ignite);
// Create cache with non-persistent region.
var volatileCache = ignite.CreateCache<int, int>(new CacheConfiguration
{
Name = volatileCacheName,
DataRegionName = "volatileRegion"
});
volatileCache[2] = 2;
}
// Verify directories.
Assert.IsTrue(Directory.Exists(cfg.DataStorageConfiguration.StoragePath));
Assert.IsTrue(Directory.Exists(cfg.DataStorageConfiguration.WalPath));
Assert.IsTrue(Directory.Exists(cfg.DataStorageConfiguration.WalArchivePath));
// Start Ignite, verify data survival.
using (var ignite = Ignition.Start(cfg))
{
ignite.GetCluster().SetActive(true);
// Persistent cache already exists and contains data.
var cache = ignite.GetCache<int, int>(cacheName);
Assert.AreEqual(1, cache[1]);
// Non-persistent cache does not exist.
var ex = Assert.Throws<ArgumentException>(() => ignite.GetCache<int, int>(volatileCacheName));
Assert.AreEqual("Cache doesn't exist: volatileCache", ex.Message);
}
// Delete store directory.
Directory.Delete(_tempDir, true);
// Start Ignite, verify data loss.
using (var ignite = Ignition.Start(cfg))
{
ignite.GetCluster().SetActive(true);
Assert.IsFalse(ignite.GetCacheNames().Contains(cacheName));
}
}
/// <summary>
/// Checks that data storage metrics reflect some write operations.
/// </summary>
private static void CheckDataStorageMetrics(IIgnite ignite)
{
var metrics = ignite.GetDataStorageMetrics();
Assert.Greater(metrics.WalLoggingRate, 0);
}
/// <summary>
/// Tests the grid activation with persistence (inactive by default).
/// </summary>
[Test]
public void TestGridActivationWithPersistence()
{
var cfg = GetPersistentConfiguration();
// Default config, inactive by default (IsActiveOnStart is ignored when persistence is enabled).
using (var ignite = Ignition.Start(cfg))
{
CheckIsActive(ignite, false);
ignite.GetCluster().SetActive(true);
CheckIsActive(ignite, true);
ignite.GetCluster().SetActive(false);
CheckIsActive(ignite, false);
}
}
/// <summary>
/// Tests the grid activation without persistence (active by default).
/// </summary>
[Test]
public void TestGridActivationNoPersistence()
{
var cfg = TestUtils.GetTestConfiguration();
Assert.IsTrue(cfg.IsActiveOnStart);
using (var ignite = Ignition.Start(cfg))
{
CheckIsActive(ignite, true);
ignite.GetCluster().SetActive(false);
CheckIsActive(ignite, false);
ignite.GetCluster().SetActive(true);
CheckIsActive(ignite, true);
}
cfg.IsActiveOnStart = false;
using (var ignite = Ignition.Start(cfg))
{
CheckIsActive(ignite, false);
ignite.GetCluster().SetActive(true);
CheckIsActive(ignite, true);
ignite.GetCluster().SetActive(false);
CheckIsActive(ignite, false);
}
}
/// <summary>
/// Tests the baseline topology.
/// </summary>
[Test]
public void TestBaselineTopology()
{
Environment.SetEnvironmentVariable("IGNITE_BASELINE_AUTO_ADJUST_ENABLED", "false");
var cfg1 = new IgniteConfiguration(GetPersistentConfiguration())
{
ConsistentId = "node1"
};
var cfg2 = new IgniteConfiguration(GetPersistentConfiguration())
{
ConsistentId = "node2",
IgniteInstanceName = "2"
};
using (var ignite = Ignition.Start(cfg1))
{
// Start and stop to bump topology version.
Ignition.Start(cfg2);
Ignition.Stop(cfg2.IgniteInstanceName, true);
var cluster = ignite.GetCluster();
Assert.AreEqual(3, cluster.TopologyVersion);
// Can not set baseline while inactive.
var ex = Assert.Throws<IgniteException>(() => cluster.SetBaselineTopology(2));
Assert.AreEqual("Changing BaselineTopology on inactive cluster is not allowed.", ex.Message);
// Set with version.
cluster.SetActive(true);
cluster.SetBaselineTopology(2);
var res = cluster.GetBaselineTopology();
CollectionAssert.AreEquivalent(new[] {"node1", "node2"}, res.Select(x => x.ConsistentId));
cluster.SetBaselineTopology(1);
Assert.AreEqual("node1", cluster.GetBaselineTopology().Single().ConsistentId);
// Set with nodes.
cluster.SetBaselineTopology(res);
res = cluster.GetBaselineTopology();
CollectionAssert.AreEquivalent(new[] { "node1", "node2" }, res.Select(x => x.ConsistentId));
cluster.SetBaselineTopology(cluster.GetTopology(1));
Assert.AreEqual("node1", cluster.GetBaselineTopology().Single().ConsistentId);
// Set to two nodes.
cluster.SetBaselineTopology(cluster.GetTopology(2));
}
// Check auto activation on cluster restart.
using (var ignite = Ignition.Start(cfg1))
using (Ignition.Start(cfg2))
{
var cluster = ignite.GetCluster();
Assert.IsTrue(cluster.IsActive());
var res = cluster.GetBaselineTopology();
CollectionAssert.AreEquivalent(new[] { "node1", "node2" }, res.Select(x => x.ConsistentId));
}
Environment.SetEnvironmentVariable("IGNITE_BASELINE_AUTO_ADJUST_ENABLED", null);
}
/// <summary>
/// Tests the wal disable/enable functionality.
/// </summary>
[Test]
public void TestWalDisableEnable()
{
using (var ignite = Ignition.Start(GetPersistentConfiguration()))
{
var cluster = ignite.GetCluster();
cluster.SetActive(true);
var cache = ignite.CreateCache<int, int>("foo");
Assert.IsTrue(cluster.IsWalEnabled(cache.Name));
cache[1] = 1;
cluster.DisableWal(cache.Name);
Assert.IsFalse(cluster.IsWalEnabled(cache.Name));
cache[2] = 2;
cluster.EnableWal(cache.Name);
Assert.IsTrue(cluster.IsWalEnabled(cache.Name));
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
// Check exceptions.
var ex = Assert.Throws<IgniteException>(() => cluster.IsWalEnabled("bar"));
Assert.AreEqual("Cache not found: bar", ex.Message);
ex = Assert.Throws<IgniteException>(() => cluster.DisableWal("bar"));
Assert.AreEqual("Cache doesn't exist: bar", ex.Message);
ex = Assert.Throws<IgniteException>(() => cluster.EnableWal("bar"));
Assert.AreEqual("Cache doesn't exist: bar", ex.Message);
}
}
/// <summary>
/// Test the configuration of IsBaselineAutoAdjustEnabled flag
/// </summary>
[Test]
public void TestBaselineTopologyAutoAdjustEnabledDisabled()
{
using (var ignite = Ignition.Start(GetPersistentConfiguration()))
{
ICluster cluster = ignite.GetCluster();
cluster.SetActive(true);
bool isEnabled = cluster.IsBaselineAutoAdjustEnabled();
cluster.SetBaselineAutoAdjustEnabledFlag(!isEnabled);
Assert.AreNotEqual(isEnabled, cluster.IsBaselineAutoAdjustEnabled());
}
}
/// <summary>
/// Test the configuration of BaselineAutoAdjustTimeout property
/// </summary>
[Test]
public void TestBaselineTopologyAutoAdjustTimeoutWriteRead()
{
const long newTimeout = 333000;
using (var ignite = Ignition.Start(GetPersistentConfiguration()))
{
ICluster cluster = ignite.GetCluster();
cluster.SetActive(true);
cluster.SetBaselineAutoAdjustTimeout(newTimeout);
Assert.AreEqual(newTimeout, cluster.GetBaselineAutoAdjustTimeout());
}
}
/// <summary>
/// Checks active state.
/// </summary>
private static void CheckIsActive(IIgnite ignite, bool isActive)
{
Assert.AreEqual(isActive, ignite.GetCluster().IsActive());
if (isActive)
{
var cache = ignite.GetOrCreateCache<int, int>("default");
cache[1] = 1;
Assert.AreEqual(1, cache[1]);
}
else
{
var ex = Assert.Throws<IgniteException>(() => ignite.GetOrCreateCache<int, int>("default"));
Assert.AreEqual("Can not perform the operation because the cluster is inactive.",
ex.Message.Substring(0, 62));
}
}
/// <summary>
/// Gets the persistent configuration.
/// </summary>
private static IgniteConfiguration GetPersistentConfiguration()
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = new DataStorageConfiguration
{
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
PersistenceEnabled = true,
Name = "foo"
}
}
};
}
private class CustomStoreFactory : IFactory<ICacheStore>
{
public ICacheStore CreateInstance()
{
return new CustomStore();
}
}
private class CustomStore : CacheStoreAdapter<object, object>
{
public override object Load(object key)
{
return null;
}
public override void Write(object key, object val)
{
// No-op.
}
public override void Delete(object key)
{
// No-op.
}
}
private class CustomAffinityFunction : RendezvousAffinityFunction
{
public override int Partitions
{
get { return 10; }
set { throw new NotSupportedException(); }
}
}
}
}
| |
//
// Copyright (c) 2004-2021 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.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Xml;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.Fakeables;
using NLog.Layouts;
using NLog.Targets;
/// <summary>
/// XML event description compatible with log4j, Chainsaw and NLogViewer.
/// </summary>
[LayoutRenderer("log4jxmlevent")]
[MutableUnsafe]
public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace, IIncludeContext
{
private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid();
private static readonly string dummyNamespaceRemover = " xmlns:log4j=\"" + dummyNamespace + "\"";
private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid();
private static readonly string dummyNLogNamespaceRemover = " xmlns:nlog=\"" + dummyNLogNamespace + "\"";
private readonly ScopeContextNestedStatesLayoutRenderer _scopeNestedLayoutRenderer = new ScopeContextNestedStatesLayoutRenderer();
/// <summary>
/// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class.
/// </summary>
public Log4JXmlEventLayoutRenderer() : this(LogFactory.DefaultAppEnvironment)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class.
/// </summary>
internal Log4JXmlEventLayoutRenderer(IAppEnvironment appEnvironment)
{
#if NETSTANDARD1_3
AppInfo = "NetCore Application";
#else
AppInfo = string.Format(
CultureInfo.InvariantCulture,
"{0}({1})",
appEnvironment.AppDomainFriendlyName,
appEnvironment.CurrentProcessId);
#endif
Parameters = new List<NLogViewerParameterInfo>();
try
{
_machineName = EnvironmentHelper.GetMachineName();
if (string.IsNullOrEmpty(_machineName))
{
InternalLogger.Info("MachineName is not available.");
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error getting machine name.");
if (exception.MustBeRethrown())
{
throw;
}
_machineName = string.Empty;
}
}
/// <inheritdoc/>
protected override void InitializeLayoutRenderer()
{
base.InitializeLayoutRenderer();
_xmlWriterSettings = new XmlWriterSettings
{
Indent = IndentXml,
ConformanceLevel = ConformanceLevel.Fragment,
#if !NET35
NamespaceHandling = NamespaceHandling.OmitDuplicates,
#endif
IndentChars = " ",
};
}
/// <summary>
/// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeNLogData { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the XML should use spaces for indentation.
/// </summary>
/// <docgen category='Layout Options' order='50' />
public bool IndentXml { get; set; }
/// <summary>
/// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public Layout AppInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeCallSite { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeSourceInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")]
public bool IncludeMdc { get => _includeMdc ?? false; set => _includeMdc = value; }
private bool? _includeMdc;
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")]
public bool IncludeMdlc { get => _includeMdlc ?? false; set => _includeMdlc = value; }
private bool? _includeMdlc;
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeNdc. Marked obsolete on NLog 5.0")]
public bool IncludeNdlc { get => _includeNdlc ?? false; set => _includeNdlc = value; }
private bool? _includeNdlc;
/// <summary>
/// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeNdc { get => _includeNdc ?? false; set => _includeNdc = value; }
private bool? _includeNdc;
/// <summary>
/// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeScopeProperties { get => _includeScopeProperties ?? (_includeMdlc == true || _includeMdc == true); set => _includeScopeProperties = value; }
private bool? _includeScopeProperties;
/// <summary>
/// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeScopeNested { get => _includeScopeNested ?? (_includeNdlc == true || _includeNdc == true); set => _includeScopeNested = value; }
private bool? _includeScopeNested;
/// <summary>
/// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public string ScopeNestedSeparator
{
get => _scopeNestedLayoutRenderer.Separator;
set => _scopeNestedLayoutRenderer.Separator = value;
}
/// <summary>
/// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by NdcItemSeparator. Marked obsolete on NLog 5.0")]
public string NdlcItemSeparator { get => ScopeNestedSeparator; set => ScopeNestedSeparator = value; }
/// <summary>
/// Gets or sets the option to include all properties from the log events
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")]
public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; }
/// <summary>
/// Gets or sets the option to include all properties from the log events
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeEventProperties { get; set; }
/// <summary>
/// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public string NdcItemSeparator { get => ScopeNestedSeparator; set => ScopeNestedSeparator = value; }
/// <summary>
/// Gets or sets the log4j:event logger-xml-attribute (Default ${logger})
/// </summary>
/// <docgen category='Layout Options' order='50' />
public Layout LoggerName { get; set; }
/// <summary>
/// Gets or sets whether the log4j:throwable xml-element should be written as CDATA
/// </summary>
/// <docgen category='Layout Options' order='50' />
public bool WriteThrowableCData { get; set; }
private readonly string _machineName;
private XmlWriterSettings _xmlWriterSettings;
/// <inheritdoc/>
StackTraceUsage IUsesStackTrace.StackTraceUsage => (IncludeCallSite || IncludeSourceInfo) ? (StackTraceUsageUtils.GetStackTraceUsage(IncludeSourceInfo, 0, true) | StackTraceUsage.WithCallSiteClassName) : StackTraceUsage.None;
internal IList<NLogViewerParameterInfo> Parameters { get; set; }
/// <inheritdoc/>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
StringBuilder sb = new StringBuilder();
using (XmlWriter xtw = XmlWriter.Create(sb, _xmlWriterSettings))
{
xtw.WriteStartElement("log4j", "event", dummyNamespace);
bool includeNLogCallsite = (IncludeCallSite || IncludeSourceInfo) && logEvent.CallSiteInformation != null;
if (includeNLogCallsite && IncludeNLogData)
{
xtw.WriteAttributeString("xmlns", "nlog", null, dummyNLogNamespace);
}
xtw.WriteAttributeSafeString("logger", LoggerName != null ? LoggerName.Render(logEvent) : logEvent.LoggerName);
xtw.WriteAttributeString("level", logEvent.Level.Name.ToUpperInvariant());
xtw.WriteAttributeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
xtw.WriteAttributeString("thread", AsyncHelpers.GetManagedThreadId().ToString(CultureInfo.InvariantCulture));
xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
if (logEvent.Exception != null)
{
if (WriteThrowableCData)
{
// CDATA correctly preserves newlines and indention, but not all viewers support this
xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
xtw.WriteSafeCData(logEvent.Exception.ToString());
xtw.WriteEndElement();
}
else
{
xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
}
}
AppendScopeContextNestedStates(xtw, logEvent);
if (includeNLogCallsite)
{
AppendCallSite(logEvent, xtw);
}
xtw.WriteStartElement("log4j", "properties", dummyNamespace);
AppendScopeContextProperties("log4j", dummyNamespaceRemover, xtw);
if (IncludeEventProperties)
{
AppendProperties("log4j", dummyNamespaceRemover, xtw, logEvent);
}
AppendParameters(logEvent, xtw);
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeString("name", "log4japp");
xtw.WriteAttributeSafeString("value", AppInfo?.Render(logEvent) ?? string.Empty);
xtw.WriteEndElement();
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeString("name", "log4jmachinename");
xtw.WriteAttributeSafeString("value", _machineName);
xtw.WriteEndElement();
xtw.WriteEndElement(); // properties
xtw.WriteEndElement(); // event
xtw.Flush();
// get rid of 'nlog' and 'log4j' namespace declarations
sb.Replace(dummyNamespaceRemover, string.Empty);
if (includeNLogCallsite && IncludeNLogData)
{
sb.Replace(dummyNLogNamespaceRemover, string.Empty);
}
sb.CopyTo(builder); // StringBuilder.Replace is not good when reusing the StringBuilder
}
}
private void AppendScopeContextProperties(string prefix, string propertiesNamespace, XmlWriter xtw)
{
if (IncludeScopeProperties)
{
using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator())
{
while (scopeEnumerator.MoveNext())
{
var scopeProperty = scopeEnumerator.Current;
if (string.IsNullOrEmpty(scopeProperty.Key))
continue;
string propertyValue = XmlHelper.XmlConvertToStringSafe(scopeProperty.Value);
if (propertyValue is null)
continue;
xtw.WriteStartElement(prefix, "data", propertiesNamespace);
xtw.WriteAttributeSafeString("name", scopeProperty.Key);
xtw.WriteAttributeString("value", propertyValue);
xtw.WriteEndElement();
}
}
}
}
private void AppendScopeContextNestedStates(XmlWriter xtw, LogEventInfo logEvent)
{
if (IncludeScopeNested)
{
var nestedStates = _scopeNestedLayoutRenderer.Render(logEvent);
//NDLC and NDC should be in the same element
xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, nestedStates);
}
}
private void AppendParameters(LogEventInfo logEvent, XmlWriter xtw)
{
for (int i = 0; i < Parameters?.Count; ++i)
{
var parameter = Parameters[i];
if (string.IsNullOrEmpty(parameter?.Name))
continue;
var parameterValue = parameter.Layout?.Render(logEvent) ?? string.Empty;
if (!parameter.IncludeEmptyValue && string.IsNullOrEmpty(parameterValue))
continue;
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", parameter.Name);
xtw.WriteAttributeSafeString("value", parameterValue);
xtw.WriteEndElement();
}
}
private void AppendCallSite(LogEventInfo logEvent, XmlWriter xtw)
{
MethodBase methodBase = logEvent.CallSiteInformation.GetCallerStackFrameMethod(0);
string callerClassName = logEvent.CallSiteInformation.GetCallerClassName(methodBase, true, true, true);
string callerMethodName = logEvent.CallSiteInformation.GetCallerMethodName(methodBase, true, true, true);
xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
if (!string.IsNullOrEmpty(callerClassName))
{
xtw.WriteAttributeSafeString("class", callerClassName);
}
xtw.WriteAttributeSafeString("method", callerMethodName);
if (IncludeSourceInfo)
{
xtw.WriteAttributeSafeString("file", logEvent.CallSiteInformation.GetCallerFilePath(0));
xtw.WriteAttributeString("line", logEvent.CallSiteInformation.GetCallerLineNumber(0).ToString(CultureInfo.InvariantCulture));
}
xtw.WriteEndElement();
if (IncludeNLogData)
{
xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
var type = methodBase?.DeclaringType;
if (type != null)
{
xtw.WriteAttributeSafeString("assembly", type.GetAssembly().FullName);
}
xtw.WriteEndElement();
xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
AppendProperties("nlog", dummyNLogNamespace, xtw, logEvent);
xtw.WriteEndElement();
}
}
private void AppendProperties(string prefix, string propertiesNamespace, XmlWriter xtw, LogEventInfo logEvent)
{
if (logEvent.HasProperties)
{
foreach (var contextProperty in logEvent.Properties)
{
string propertyKey = XmlHelper.XmlConvertToStringSafe(contextProperty.Key);
if (string.IsNullOrEmpty(propertyKey))
continue;
string propertyValue = XmlHelper.XmlConvertToStringSafe(contextProperty.Value);
if (propertyValue is null)
continue;
xtw.WriteStartElement(prefix, "data", propertiesNamespace);
xtw.WriteAttributeString("name", propertyKey);
xtw.WriteAttributeString("value", propertyValue);
xtw.WriteEndElement();
}
}
}
}
}
| |
namespace FriendsDb.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Comment",
c => new
{
CommentId = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
TypeId = c.String(nullable: false, maxLength: 50),
CommentMessage = c.String(nullable: false, maxLength: 50),
Type = c.String(nullable: false, maxLength: 50),
UserId = c.String(nullable: false, maxLength: 50),
CommentTime = c.DateTime(),
})
.PrimaryKey(t => t.CommentId)
.ForeignKey("dbo.UserCredential", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.UserCredential",
c => new
{
UserId = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
Email = c.String(nullable: false, maxLength: 50),
Password = c.String(nullable: false, maxLength: 500),
LastSeen = c.DateTime(nullable: false),
CreatedOn = c.DateTime(nullable: false),
IsActive = c.Int(nullable: false),
})
.PrimaryKey(t => t.UserId);
CreateTable(
"dbo.EventInvited",
c => new
{
Id = c.Int(nullable: false, identity: true),
EventId = c.String(nullable: false, maxLength: 50),
UserId = c.String(nullable: false, maxLength: 50),
Attending = c.Int(),
Time = c.DateTime(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Events", t => t.EventId, cascadeDelete: true)
.ForeignKey("dbo.UserCredential", t => t.UserId, cascadeDelete: true)
.Index(t => t.EventId)
.Index(t => t.UserId);
CreateTable(
"dbo.Events",
c => new
{
EventId = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
EventCode = c.String(nullable: false, maxLength: 10),
EventType = c.Int(nullable: false),
Place = c.String(nullable: false, maxLength: 500),
Purpose = c.String(nullable: false, maxLength: 500),
EventTime = c.DateTime(nullable: false),
DateCreated = c.DateTime(),
CreatedBy = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.EventId)
.ForeignKey("dbo.UserCredential", t => t.CreatedBy, cascadeDelete: true)
.Index(t => t.CreatedBy);
CreateTable(
"dbo.Image",
c => new
{
ImageId = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
Url = c.String(nullable: false, maxLength: 50),
UserId = c.String(nullable: false, maxLength: 50),
Text = c.String(maxLength: 50),
Description = c.String(maxLength: 500),
UploadTime = c.DateTime(),
})
.PrimaryKey(t => t.ImageId)
.ForeignKey("dbo.UserCredential", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.Like",
c => new
{
LikeId = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
TypeId = c.String(nullable: false, maxLength: 50),
Type = c.String(nullable: false, maxLength: 50),
UserId = c.String(nullable: false, maxLength: 50),
LikeType = c.Int(nullable: false),
Time = c.DateTime(),
})
.PrimaryKey(t => t.LikeId)
.ForeignKey("dbo.UserCredential", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.Post",
c => new
{
Pid = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
PostMessage = c.String(nullable: false, maxLength: 500),
Author = c.String(nullable: false, maxLength: 50),
Recipient = c.String(maxLength: 50),
Time = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Pid)
.ForeignKey("dbo.UserCredential", t => t.Author, cascadeDelete: true)
.Index(t => t.Author);
CreateTable(
"dbo.UserProfile",
c => new
{
UserId = c.String(nullable: false, maxLength: 50),
Id = c.Int(nullable: false, identity: true),
FirstName = c.String(nullable: false, maxLength: 50),
LastName = c.String(maxLength: 50),
DOB = c.DateTime(nullable: false),
Gender = c.String(nullable: false, maxLength: 1, fixedLength: true),
About = c.String(maxLength: 2500),
StatusId = c.Int(),
LocationId = c.Int(),
Status = c.String(maxLength: 500),
})
.PrimaryKey(t => t.UserId)
.ForeignKey("dbo.UserCredential", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.UserRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 50),
RoleId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Roles", t => t.RoleId, cascadeDelete: true)
.ForeignKey("dbo.UserCredential", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.Roles",
c => new
{
RoleId = c.Int(nullable: false),
RoleName = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.RoleId);
CreateTable(
"dbo.EventType",
c => new
{
EventTypeId = c.Int(nullable: false),
EventType = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.EventTypeId);
}
public override void Down()
{
DropForeignKey("dbo.Comment", "UserId", "dbo.UserCredential");
DropForeignKey("dbo.UserRoles", "UserId", "dbo.UserCredential");
DropForeignKey("dbo.UserRoles", "RoleId", "dbo.Roles");
DropForeignKey("dbo.UserProfile", "UserId", "dbo.UserCredential");
DropForeignKey("dbo.Post", "Author", "dbo.UserCredential");
DropForeignKey("dbo.Like", "UserId", "dbo.UserCredential");
DropForeignKey("dbo.Image", "UserId", "dbo.UserCredential");
DropForeignKey("dbo.EventInvited", "UserId", "dbo.UserCredential");
DropForeignKey("dbo.EventInvited", "EventId", "dbo.Events");
DropForeignKey("dbo.Events", "CreatedBy", "dbo.UserCredential");
DropIndex("dbo.UserRoles", new[] { "RoleId" });
DropIndex("dbo.UserRoles", new[] { "UserId" });
DropIndex("dbo.UserProfile", new[] { "UserId" });
DropIndex("dbo.Post", new[] { "Author" });
DropIndex("dbo.Like", new[] { "UserId" });
DropIndex("dbo.Image", new[] { "UserId" });
DropIndex("dbo.Events", new[] { "CreatedBy" });
DropIndex("dbo.EventInvited", new[] { "UserId" });
DropIndex("dbo.EventInvited", new[] { "EventId" });
DropIndex("dbo.Comment", new[] { "UserId" });
DropTable("dbo.EventType");
DropTable("dbo.Roles");
DropTable("dbo.UserRoles");
DropTable("dbo.UserProfile");
DropTable("dbo.Post");
DropTable("dbo.Like");
DropTable("dbo.Image");
DropTable("dbo.Events");
DropTable("dbo.EventInvited");
DropTable("dbo.UserCredential");
DropTable("dbo.Comment");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using NQuery.Compilation;
namespace NQuery.Runtime
{
internal static class BuiltInConversions
{
private static object _lock = new object();
private static bool _conversionsLoaded;
private static Dictionary<ConversionKey, MethodInfo> _implicitConversionsTable = new Dictionary<ConversionKey, MethodInfo>();
private static Dictionary<ConversionKey, MethodInfo> _explicitConversionsTable = new Dictionary<ConversionKey, MethodInfo>();
private static void EnsureTablesLoaded()
{
if (!_conversionsLoaded)
{
lock (_lock)
{
if (!_conversionsLoaded)
{
LoadConversionTable(_implicitConversionsTable, typeof(ImplicitConversions));
LoadConversionTable(_explicitConversionsTable, typeof(ExplicitConversions));
_conversionsLoaded = true;
}
}
}
}
private static void LoadConversionTable(IDictionary<ConversionKey, MethodInfo> table, Type type)
{
BindingFlags bindingFlags = BindingFlags.Public |
BindingFlags.Static |
BindingFlags.DeclaredOnly;
MethodInfo[] methods = type.GetMethods(bindingFlags);
Array.Sort(methods, (x, y) => String.Compare(x.ToString(), y.ToString(), StringComparison.Ordinal));
foreach (MethodInfo methodInfo in methods)
{
ConversionKey key = new ConversionKey();
key.SourceType = methodInfo.GetParameters()[0].ParameterType;
key.TargetType = methodInfo.ReturnType;
table.Add(key, methodInfo);
}
}
public static MethodInfo GetConversion(CastingOperatorType castingOperatorType, Type sourceType, Type targetType)
{
EnsureTablesLoaded();
Dictionary<ConversionKey, MethodInfo> conversionTable;
switch (castingOperatorType)
{
case CastingOperatorType.Implicit:
conversionTable = _implicitConversionsTable;
break;
case CastingOperatorType.Explicit:
conversionTable = _explicitConversionsTable;
break;
default:
throw ExceptionBuilder.UnhandledCaseLabel(castingOperatorType);
}
ConversionKey key = new ConversionKey();
key.SourceType = sourceType;
key.TargetType = targetType;
MethodInfo result;
if (conversionTable.TryGetValue(key, out result))
return result;
return null;
}
private struct ConversionKey
{
public Type SourceType;
public Type TargetType;
public override int GetHashCode()
{
return SourceType.GetHashCode() + 29*TargetType.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ConversionKey))
return false;
ConversionKey conversionKey = (ConversionKey) obj;
if (!Equals(SourceType, conversionKey.SourceType))
return false;
if (!Equals(TargetType, conversionKey.TargetType))
return false;
return true;
}
public static bool operator==(ConversionKey left, ConversionKey right)
{
return left.Equals(right);
}
public static bool operator !=(ConversionKey left, ConversionKey right)
{
return !left.Equals(right);
}
}
internal class ImplicitConversions
{
#region FromSByte
public static Int16 FromSByteToInt16(SByte value)
{
return value;
}
public static Int32 FromSByteToInt(SByte value)
{
return value;
}
public static Int64 FromSByteToLong(SByte value)
{
return value;
}
public static Single FromSByteToSingle(SByte value)
{
return value;
}
public static Double FromSByteToDouble(SByte value)
{
return value;
}
public static Decimal FromSByteToDecimal(SByte value)
{
return value;
}
#endregion
#region FromByte
public static Int16 FromByteToInt16(Byte value)
{
return value;
}
public static UInt16 FromByteToUInt16(Byte value)
{
return value;
}
public static Int32 FromByteToInt32(Byte value)
{
return value;
}
public static UInt32 FromByteToUInt32(Byte value)
{
return value;
}
public static Int64 FromByteToInt64(Byte value)
{
return value;
}
public static UInt64 FromByteToUInt64(Byte value)
{
return value;
}
public static Single FromByteToSingle(Byte value)
{
return value;
}
public static Double FromByteToDouble(Byte value)
{
return value;
}
public static Decimal FromByteToDecimal(Byte value)
{
return value;
}
#endregion
#region FromInt16
public static Int32 FromInt16ToInt32(Int16 value)
{
return value;
}
public static Int64 FromInt16ToInt64(Int16 value)
{
return value;
}
public static Single FromInt16ToSingle(Int16 value)
{
return value;
}
public static Double FromInt16ToDouble(Int16 value)
{
return value;
}
public static Decimal FromInt16ToDecimal(Int16 value)
{
return value;
}
#endregion
#region FromUInt16
public static Int32 FromUInt16ToInt32(UInt16 value)
{
return value;
}
public static UInt32 FromUInt16ToUInt32(UInt16 value)
{
return value;
}
public static Int64 FromUInt16ToInt64(UInt16 value)
{
return value;
}
public static UInt64 FromUInt16ToUInt64(UInt16 value)
{
return value;
}
public static Single FromUInt16ToSingle(UInt16 value)
{
return value;
}
public static Double FromUInt16ToDouble(UInt16 value)
{
return value;
}
public static Decimal FromUInt16ToDecimal(UInt16 value)
{
return value;
}
#endregion
#region FromInt32
public static Int64 FromInt32ToInt64(Int32 value)
{
return value;
}
public static Single FromInt32ToSingle(Int32 value)
{
return value;
}
public static Double FromInt32ToDouble(Int32 value)
{
return value;
}
public static Decimal FromInt32ToDecimal(Int32 value)
{
return value;
}
#endregion
#region FromUInt32
public static Int64 FromUInt32ToInt64(UInt32 value)
{
return value;
}
public static UInt64 FromUInt32ToUInt64(UInt32 value)
{
return value;
}
public static Single FromUInt32ToSingle(UInt32 value)
{
return value;
}
public static Double FromUInt32ToDouble(UInt32 value)
{
return value;
}
public static Decimal FromUInt32ToDecimal(UInt32 value)
{
return value;
}
#endregion
#region FromInt64
public static Single FromInt64ToSingle(Int64 value)
{
return value;
}
public static Double FromInt64ToDouble(Int64 value)
{
return value;
}
public static Decimal FromInt64ToDecimal(Int64 value)
{
return value;
}
#endregion
#region FromUInt64
public static Single FromUInt64ToSingle(UInt64 value)
{
return value;
}
public static Double FromUInt64ToDouble(UInt64 value)
{
return value;
}
public static Decimal FromUInt64ToDecimal(UInt64 value)
{
return value;
}
#endregion
#region FromChar
public static UInt16 FromCharToUInt16(Char value)
{
return value;
}
public static Int32 FromCharToInt32(Char value)
{
return value;
}
public static UInt32 FromCharToUInt32(Char value)
{
return value;
}
public static Int64 FromCharToInt64(Char value)
{
return value;
}
public static UInt64 FromCharToUInt64(Char value)
{
return value;
}
public static Single FromCharToSingle(Char value)
{
return value;
}
public static Double FromCharToDouble(Char value)
{
return value;
}
public static Decimal FromCharToDecimal(Char value)
{
return value;
}
#endregion
#region FromSingle
public static Double FromSingleToDouble(Single value)
{
return value;
}
#endregion
}
internal class ExplicitConversions
{
#region FromSByte
public static Byte FromSByteToByte(SByte value)
{
return (Byte) value;
}
public static UInt16 FromSByteToUInt16(SByte value)
{
return (UInt16) value;
}
public static UInt32 FromSByteToUInt32(SByte value)
{
return (UInt32) value;
}
public static UInt64 FromSByteToUInt64(SByte value)
{
return (UInt64) value;
}
public static Char FromSByteToChar(SByte value)
{
return (Char) value;
}
#endregion
#region FromByte
public static SByte FromByteToSByte(Byte value)
{
return (SByte) value;
}
public static Char FromByteToChar(Byte value)
{
return (Char) value;
}
#endregion
#region FromInt16
public static SByte FromInt16ToSByte(Int16 value)
{
return (SByte) value;
}
public static Byte FromInt16ToByte(Int16 value)
{
return (Byte) value;
}
public static UInt16 FromInt16ToUInt16(Int16 value)
{
return (UInt16) value;
}
public static UInt32 FromInt16ToUInt32(Int16 value)
{
return (UInt32) value;
}
public static UInt64 FromInt16ToUInt64(Int16 value)
{
return (UInt64) value;
}
public static Char FromInt16ToChar(Int16 value)
{
return (Char) value;
}
#endregion
#region FromUInt16
public static SByte FromUInt16ToSByte(UInt16 value)
{
return (SByte) value;
}
public static Byte FromUInt16ToByte(UInt16 value)
{
return (Byte) value;
}
public static Int16 FromUInt16ToInt16(UInt16 value)
{
return (Int16) value;
}
public static Char FromUInt16ToChar(UInt16 value)
{
return (Char) value;
}
#endregion
#region FromInt32
public static SByte FromInt32ToSByte(Int32 value)
{
return (SByte) value;
}
public static Byte FromInt32ToByte(Int32 value)
{
return (Byte) value;
}
public static Int16 FromInt32ToInt16(Int32 value)
{
return (Int16) value;
}
public static UInt16 FromInt32ToUInt16(Int32 value)
{
return (UInt16) value;
}
public static UInt32 FromInt32ToUInt32(Int32 value)
{
return (UInt32) value;
}
public static UInt64 FromInt32ToUInt64(Int32 value)
{
return (UInt64) value;
}
public static Char FromInt32ToChar(Int32 value)
{
return (Char) value;
}
#endregion
#region FromUInt32
public static SByte FromUInt32ToSByte(UInt32 value)
{
return (SByte) value;
}
public static Byte FromUInt32ToByte(UInt32 value)
{
return (Byte) value;
}
public static Int16 FromUInt32ToInt16(UInt32 value)
{
return (Int16) value;
}
public static UInt16 FromUInt32ToUInt16(UInt32 value)
{
return (UInt16) value;
}
public static Int32 FromUInt32ToInt32(UInt32 value)
{
return (Int32) value;
}
public static Char FromUInt32ToChar(UInt32 value)
{
return (Char) value;
}
#endregion
#region FromInt64
public static SByte FromInt64ToSByte(Int64 value)
{
return (SByte) value;
}
public static Byte FromInt64ToByte(Int64 value)
{
return (Byte) value;
}
public static Int16 FromInt64ToInt16(Int64 value)
{
return (Int16) value;
}
public static UInt16 FromInt64ToUInt16(Int64 value)
{
return (UInt16) value;
}
public static Int32 FromInt64ToInt32(Int64 value)
{
return (Int32) value;
}
public static UInt32 FromInt64ToUInt32(Int64 value)
{
return (UInt32) value;
}
public static UInt64 FromInt64ToUInt64(Int64 value)
{
return (UInt64) value;
}
public static Char FromInt64ToChar(Int64 value)
{
return (Char) value;
}
#endregion
#region FromUInt64
public static SByte FromUInt64ToSByte(UInt64 value)
{
return (SByte) value;
}
public static Byte FromUInt64ToByte(UInt64 value)
{
return (Byte) value;
}
public static Int16 FromUInt64ToInt16(UInt64 value)
{
return (Int16) value;
}
public static UInt16 FromUInt64ToUInt16(UInt64 value)
{
return (UInt16) value;
}
public static Int32 FromUInt64ToInt32(UInt64 value)
{
return (Int32) value;
}
public static UInt32 FromUInt64ToUInt32(UInt64 value)
{
return (UInt32) value;
}
public static Int64 FromUInt64ToInt64(UInt64 value)
{
return (Int64) value;
}
public static Char FromUInt64ToChar(UInt64 value)
{
return (Char) value;
}
#endregion
#region FromChar
public static SByte FromCharToSByte(Char value)
{
return (SByte) value;
}
public static Byte FromCharToByte(Char value)
{
return (Byte) value;
}
public static Int16 FromCharToInt16(Char value)
{
return (Int16) value;
}
#endregion
#region FromSingle
public static SByte FromSingleToSByte(Single value)
{
return (SByte) value;
}
public static Byte FromSingleToByte(Single value)
{
return (Byte) value;
}
public static Int16 FromSingleToInt16(Single value)
{
return (Int16) value;
}
public static UInt16 FromSingleToUInt16(Single value)
{
return (UInt16) value;
}
public static Int32 FromSingleToInt32(Single value)
{
return (Int32) value;
}
public static UInt32 FromSingleToUInt32(Single value)
{
return (UInt32) value;
}
public static Int64 FromSingleToInt64(Single value)
{
return (Int64) value;
}
public static UInt64 FromSingleToUInt64(Single value)
{
return (UInt64) value;
}
public static Char FromSingleToChar(Single value)
{
return (Char) value;
}
public static Decimal FromSingleToDecimal(Single value)
{
return (Decimal) value;
}
#endregion
#region FromDouble
public static SByte FromDoubleToSByte(Double value)
{
return (SByte) value;
}
public static Byte FromDoubleToByte(Double value)
{
return (Byte) value;
}
public static Int16 FromDoubleToInt16(Double value)
{
return (Int16) value;
}
public static UInt16 FromDoubleToUInt16(Double value)
{
return (UInt16) value;
}
public static Int32 FromDoubleToInt32(Double value)
{
return (Int32) value;
}
public static UInt32 FromDoubleToUInt32(Double value)
{
return (UInt32) value;
}
public static Int64 FromDoubleToInt64(Double value)
{
return (Int64) value;
}
public static UInt64 FromDoubleToUInt64(Double value)
{
return (UInt64) value;
}
public static Char FromDoubleToChar(Double value)
{
return (Char) value;
}
public static Single FromDoubleToSingle(Double value)
{
return (Single) value;
}
public static Decimal FromDoubleToDecimal(Double value)
{
return (Decimal) value;
}
#endregion
#region FromDecimal
public static SByte FromDecimalToSByte(Decimal value)
{
return (SByte) value;
}
public static Byte FromDecimalToByte(Decimal value)
{
return (Byte) value;
}
public static Int16 FromDecimalToInt16(Decimal value)
{
return (Int16) value;
}
public static UInt16 FromDecimalToUInt16(Decimal value)
{
return (UInt16) value;
}
public static Int32 FromDecimalToInt32(Decimal value)
{
return (Int32) value;
}
public static UInt32 FromDecimalToUInt32(Decimal value)
{
return (UInt32) value;
}
public static Int64 FromDecimalToInt64(Decimal value)
{
return (Int64) value;
}
public static UInt64 FromDecimalToUInt64(Decimal value)
{
return (UInt64) value;
}
public static Char FromDecimalToChar(Decimal value)
{
return (Char) value;
}
public static Single FromDecimalToSingle(Decimal value)
{
return (Single) value;
}
public static Double FromDecimalToDouble(Decimal value)
{
return (Double) value;
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Builders;
using Microsoft.Data.Entity.Relational.Migrations;
using Microsoft.Data.Entity.Relational.Migrations.Builders;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Microsoft.Data.Entity.Relational.Migrations.Operations;
using RecipeExpress.Models;
namespace RecipeExpress.Migrations
{
public partial class CreateIdentitySchema : Migration
{
public override void Up(MigrationBuilder migration)
{
migration.CreateTable(
name: "AspNetUsers",
columns: table => new
{
AccessFailedCount = table.Column(type: "int", nullable: false),
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Email = table.Column(type: "nvarchar(max)", nullable: true),
EmailConfirmed = table.Column(type: "bit", nullable: false),
Id = table.Column(type: "nvarchar(450)", nullable: true),
LockoutEnabled = table.Column(type: "bit", nullable: false),
LockoutEnd = table.Column(type: "datetimeoffset", nullable: true),
NormalizedEmail = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedUserName = table.Column(type: "nvarchar(max)", nullable: true),
PasswordHash = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumberConfirmed = table.Column(type: "bit", nullable: false),
SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true),
TwoFactorEnabled = table.Column(type: "bit", nullable: false),
UserName = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migration.CreateTable(
name: "AspNetRoles",
columns: table => new
{
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "nvarchar(450)", nullable: true),
Name = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedName = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migration.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
ClaimType = table.Column(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGeneration", "Identity"),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column(type: "nvarchar(450)", nullable: true),
ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true),
ProviderKey = table.Column(type: "nvarchar(450)", nullable: true),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
ClaimType = table.Column(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGeneration", "Identity"),
RoleId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
columns: x => x.RoleId,
referencedTable: "AspNetRoles",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
RoleId = table.Column(type: "nvarchar(450)", nullable: true),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
columns: x => x.RoleId,
referencedTable: "AspNetRoles",
referencedColumn: "Id");
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
}
public override void Down(MigrationBuilder migration)
{
migration.DropTable("AspNetUserRoles");
migration.DropTable("AspNetRoleClaims");
migration.DropTable("AspNetUserLogins");
migration.DropTable("AspNetUserClaims");
migration.DropTable("AspNetRoles");
migration.DropTable("AspNetUsers");
}
}
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta4"; }
}
public override IModel Target
{
get
{
var builder = new BasicModelBuilder()
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("RecipeExpress.Models.ApplicationUser", b =>
{
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 2);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 3);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("RecipeExpress.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("RecipeExpress.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
b.ForeignKey("RecipeExpress.Models.ApplicationUser", "UserId");
});
return builder.Model;
}
}
}
}
| |
using System;
using VRageMath;
namespace Rynchodon
{
public class LineSegment
{
public static float GetShortestDistanceSquared(LineSegment line1, LineSegment line2)
{
return Line.GetShortestDistanceSquared(line1.m_line, line2.m_line);
}
public static Vector3 GetShortestVector(LineSegment line1, LineSegment line2, out Vector3 res1, out Vector3 res2)
{
return Line.GetShortestVector(ref line1.m_line, ref line2.m_line, out res1, out res2);
}
private Line m_line;
private bool m_calculatedLength;
private bool m_calculatedBox;
public LineSegment() { }
public LineSegment(Vector3 from, Vector3 to)
{
m_line = new Line() { From = from, To = to };
}
public LineSegment(ref Vector3 from, ref Vector3 to)
{
m_line = new Line() { From = from, To = to };
}
public LineSegment Clone()
{
return new LineSegment()
{
m_line = this.m_line,
m_calculatedLength = this.m_calculatedLength,
m_calculatedBox = this.m_calculatedBox
};
}
public Vector3 From
{
get { return m_line.From; }
set
{
if (value == m_line.From)
return;
m_line.From = value;
m_calculatedLength = false;
m_calculatedBox = false;
}
}
public Vector3 To
{
get { return m_line.To; }
set
{
if (value == m_line.To)
return;
m_line.To = value;
m_calculatedLength = false;
m_calculatedBox = false;
}
}
public Vector3 Direction
{
get
{
if (!m_calculatedLength)
CalcLength();
return m_line.Direction;
}
}
public float Length
{
get
{
if (!m_calculatedLength)
CalcLength();
return m_line.Length;
}
}
public BoundingBox BoundingBox
{
get
{
if (!m_calculatedBox)
CalcBox();
return m_line.BoundingBox;
}
}
public float LengthSquared()
{
return Vector3.DistanceSquared(From, To);
}
private void CalcLength()
{
m_line.Length = (float)Math.Sqrt(LengthSquared());
m_line.Direction = m_line.To - m_line.From;
m_line.Direction /= m_line.Length;
m_calculatedLength = true;
}
private void CalcBox()
{
m_line.BoundingBox = new BoundingBox();
m_line.BoundingBox.Include(m_line.From);
m_line.BoundingBox.Include(m_line.To);
m_calculatedBox = true;
}
public void Move(Vector3 shift)
{
Move(ref shift);
}
public void Move(ref Vector3 shift)
{
m_line.From += shift;
m_line.To += shift;
m_calculatedBox = false;
}
/// <summary>
/// Minimum distance squared between a line and a point.
/// </summary>
/// <remarks>
/// based on http://stackoverflow.com/a/1501725
/// </remarks>
/// <returns>The minimum distance squared between the line and the point</returns>
public float DistanceSquared(Vector3 point)
{
return DistanceSquared(ref point);
}
/// <summary>
/// Minimum distance squared between a line and a point.
/// </summary>
/// <remarks>
/// based on http://stackoverflow.com/a/1501725
/// </remarks>
/// <returns>The minimum distance squared between the line and the point</returns>
public float DistanceSquared(ref Vector3 point)
{
if (From == To)
return Vector3.DistanceSquared(From, point);
Vector3 line_disp = To - From;
float fraction = Vector3.Dot(point - From, line_disp) / LengthSquared(); // projection as a fraction of line_disp
if (fraction < 0) // extends past From
return Vector3.DistanceSquared(point, From);
else if (fraction > 1) // extends past To
return Vector3.DistanceSquared(point, To);
Vector3 closestPoint = From + fraction * line_disp; // closest point on the line
return Vector3.DistanceSquared(point, closestPoint);
}
/// <summary>
/// Determines whether a point lies within a cylinder described by this line and a radius.
/// </summary>
/// <param name="radius">The radius of the cylinder.</param>
/// <param name="point">The point to test.</param>
/// <returns>True iff the point lies within the cylinder</returns>
public bool PointInCylinder(float radius, Vector3 point)
{
return PointInCylinder(radius, ref point);
}
/// <summary>
/// Determines whether a point lies within a cylinder described by this line and a radius.
/// </summary>
/// <param name="radius">The radius of the cylinder.</param>
/// <param name="point">The point to test.</param>
/// <returns>True iff the point lies within the cylinder</returns>
public bool PointInCylinder(float radius, ref Vector3 point)
{
radius *= radius;
if (From == To)
return Vector3.DistanceSquared(From, point) < radius;
Vector3 line_disp = To - From;
float fraction = Vector3.Dot(point - From, line_disp) / LengthSquared(); // projection as a fraction of line_disp
if (fraction < 0) // extends past From
return false;
else if (fraction > 1) // extends past To
return false;
Vector3 closestPoint = From + fraction * line_disp; // closest point on the line
return Vector3.DistanceSquared(point, closestPoint) < radius;
}
/// <summary>
/// Closest point on a line to specified coordinates
/// </summary>
/// <remarks>
/// based on http://stackoverflow.com/a/1501725
/// </remarks>
public Vector3 ClosestPoint(Vector3 coordinates)
{
Vector3 point;
ClosestPoint(ref coordinates, out point);
return point;
}
/// <summary>
/// Closest point on a line to specified coordinates
/// </summary>
/// <remarks>
/// based on http://stackoverflow.com/a/1501725
/// </remarks>
public void ClosestPoint(ref Vector3 coordinates, out Vector3 point)
{
if (From == To)
{
point = From;
return;
}
Vector3 line_disp = To - From;
float fraction = Vector3.Dot(coordinates - From, line_disp) / LengthSquared(); // projection as a fraction of line_disp
if (fraction < 0) // extends past From
{
point = From;
return;
}
else if (fraction > 1) // extends past To
{
point = To;
return;
}
point = From + fraction * line_disp; // closest point on the line
}
/// <summary>
/// Minimum distance between a line and a point.
/// </summary>
/// <returns>Minimum distance between a line and a point.</returns>
public float Distance(Vector3 point)
{
return Distance(ref point);
}
/// <summary>
/// Minimum distance between a line and a point.
/// </summary>
/// <returns>Minimum distance between a line and a point.</returns>
public float Distance(ref Vector3 point)
{
return (float)Math.Sqrt(DistanceSquared(point));
}
/// <summary>
/// Tests that the distance between line and point is less than or equal to supplied distance
/// </summary>
public bool DistanceLessEqual(Vector3 point, float distance)
{
return DistanceLessEqual(ref point, distance);
}
/// <summary>
/// Tests that the distance between line and point is less than or equal to supplied distance
/// </summary>
public bool DistanceLessEqual(ref Vector3 point, float distance)
{
distance *= distance;
return DistanceSquared(point) <= distance;
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2014 - 2017 XLR8 Development Team /
// ---------------------------------------------------------------------------------- /
// 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.Reflection;
using System.Reflection.Emit;
namespace XLR8.CGLib
{
/// <summary>
/// Provides access to property information and creates dynamic method to access
/// properties rather than relying upon reflection.
/// </summary>
public class FastProperty : FastBase
{
/// <summary>
/// Class object that this method belongs to.
/// </summary>
private readonly FastClass fastClass;
/// <summary>
/// Property that is being proxied
/// </summary>
private readonly PropertyInfo targetProperty;
/// <summary>
/// Dynamic method that is constructed for invocation.
/// </summary>
private DynamicMethod dynamicGetMethod;
private DynamicMethod dynamicSetMethod;
private Getter getInvoker;
private Setter setInvoker;
/// <summary>
/// Gets the target property.
/// </summary>
/// <value>The target property.</value>
public PropertyInfo Target
{
get { return targetProperty; }
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public String Name
{
get { return targetProperty.Name; }
}
/// <summary>
/// Gets the property type.
/// </summary>
/// <value>The property type</value>
public Type PropertyType
{
get { return targetProperty.PropertyType; }
}
/// <summary>
/// Gets the type of the declaring.
/// </summary>
/// <value>The type of the declaring.</value>
public FastClass DeclaringType
{
get { return fastClass; }
}
/// <summary>
/// Constructs a wrapper around the target property.
/// </summary>
/// <param name="_fastClass">The _fast class.</param>
/// <param name="property">The property.</param>
internal FastProperty(FastClass _fastClass, PropertyInfo property)
{
// Store the class that spawned us
fastClass = _fastClass;
// Property we will be get/setting
targetProperty = property;
CreateDynamicGetMethod(property);
CreateDynamicSetMethod(property);
}
/// <summary>
/// Creates the dynamic get method.
/// </summary>
/// <param name="property">The property.</param>
private void CreateDynamicGetMethod(PropertyInfo property)
{
MethodInfo getMethod = property.GetGetMethod(false);
if (getMethod == null)
{
return;
}
Module module = targetProperty.Module;
// Create a unique name for the method
String dynamicMethodName = "_CGLibPG_" + fastClass.Id + "_" + property.Name;
// Generate the method
dynamicGetMethod = new DynamicMethod(
dynamicMethodName,
//MethodAttributes.Public | MethodAttributes.Static,
//CallingConventions.Standard,
typeof(Object),
new Type[]{ typeof(Object) },
module,
true);
EmitGetMethod(getMethod, dynamicGetMethod.GetILGenerator());
getInvoker = (Getter) dynamicGetMethod.CreateDelegate(typeof (Getter));
}
private static void EmitGetMethod(MethodInfo getMethod, ILGenerator il)
{
il.DeclareLocal(typeof(object));
// Is this calling an instance method; if so, load 'this'
if (!getMethod.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, getMethod.DeclaringType);
}
if (getMethod.IsVirtual)
{
il.Emit(OpCodes.Callvirt, getMethod);
}
else
{
il.Emit(OpCodes.Call, getMethod);
}
// Emit code for return value
if (getMethod.ReturnType.IsValueType)
{
il.Emit(OpCodes.Box, getMethod.ReturnType); //Box if necessary
}
//il.Emit(OpCodes.Stloc_0);
//il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
}
/// <summary>
/// Creates the dynamic set method.
/// </summary>
/// <param name="property">The property.</param>
private void CreateDynamicSetMethod(PropertyInfo property)
{
MethodInfo setMethod = property.GetSetMethod(false);
if (setMethod == null)
{
return;
}
Module module = targetProperty.Module;
// Create a unique name for the method
String dynamicMethodName = "_CGLibPS_" + fastClass.Id + "_" + property.Name;
// Generate the method
dynamicSetMethod = new DynamicMethod(
dynamicMethodName,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
typeof(void),
new Type[]{ typeof(Object), typeof(Object) },
module,
true);
EmitSetMethod(property, setMethod, dynamicSetMethod.GetILGenerator());
setInvoker = (Setter)dynamicSetMethod.CreateDelegate(typeof(Setter));
}
private static void EmitSetMethod(PropertyInfo property, MethodInfo setMethod, ILGenerator il)
{
il.DeclareLocal(typeof(object));
// Is this calling an instance method; if so, load 'this'
if (!setMethod.IsStatic)
{
// Load the object instance
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, setMethod.DeclaringType);
}
// Load the value
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Unbox_Any, property.PropertyType);
// Call the set method
il.Emit(OpCodes.Callvirt, setMethod);
il.Emit(OpCodes.Ret);
}
public Getter GetGetInvoker()
{
return getInvoker;
}
/// <summary>
/// Gets the value of the property
/// </summary>
/// <param name="target">The target.</param>
/// <returns></returns>
public Object Get(Object target)
{
return getInvoker(target);
}
/// <summary>
/// Gets the value of a static property
/// </summary>
/// <returns></returns>
public Object GetStatic()
{
return getInvoker(null);
}
/// <summary>
/// Sets the value of an instance property.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public void Set(Object target, Object value)
{
setInvoker(target, value);
}
/// <summary>
/// Sets the value of a static property.
/// </summary>
/// <param name="value">The value.</param>
public void SetStatic(Object value)
{
setInvoker(null, value);
}
}
}
| |
#if !NETCOREAPP
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Orleans;
using Orleans.CodeGeneration;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using Orleans.Utilities;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using TestExtensions;
using TestVersionGrainInterfaces;
using TestVersionGrains;
using Xunit;
namespace Tester.HeterogeneousSilosTests.UpgradeTests
{
public abstract class UpgradeTestsBase : IDisposable, IAsyncLifetime
{
private static readonly TimeSpan RefreshInterval = TimeSpan.FromMilliseconds(200);
private TimeSpan waitDelay;
protected IClusterClient Client => this.cluster.Client;
protected IManagementGrain ManagementGrain => this.cluster.Client.GetGrain<IManagementGrain>(0);
#if DEBUG
private const string BuildConfiguration = "Debug";
#else
private const string BuildConfiguration = "Release";
#endif
private const string CommonParentDirectory = "test";
private const string BinDirectory = "bin";
private const string VersionsProjectDirectory = "Grains";
private const string GrainsV1ProjectName = "TestVersionGrains";
private const string GrainsV2ProjectName = "TestVersionGrains2";
private const string VersionTestBinaryName = "TestVersionGrains.dll";
private readonly DirectoryInfo assemblyGrainsV1Dir;
private readonly DirectoryInfo assemblyGrainsV2Dir;
private readonly List<SiloHandle> deployedSilos = new List<SiloHandle>();
private int siloIdx = 0;
private TestClusterBuilder builder;
private TestCluster cluster;
protected abstract Type VersionSelectorStrategy { get; }
protected abstract Type CompatibilityStrategy { get; }
protected virtual short SiloCount => 2;
protected UpgradeTestsBase()
{
var testDirectory = new DirectoryInfo(GetType().Assembly.Location);
while (String.Compare(testDirectory.Name, CommonParentDirectory, StringComparison.OrdinalIgnoreCase) != 0 || testDirectory.Parent == null)
{
testDirectory = testDirectory.Parent;
}
if (testDirectory.Parent == null)
{
throw new InvalidOperationException($"Cannot locate 'test' directory starting from '{GetType().Assembly.Location}'");
}
assemblyGrainsV1Dir = GetVersionTestDirectory(testDirectory, GrainsV1ProjectName);
assemblyGrainsV2Dir = GetVersionTestDirectory(testDirectory, GrainsV2ProjectName);
}
private DirectoryInfo GetVersionTestDirectory(DirectoryInfo testDirectory, string directoryName)
{
var projectDirectory = Path.Combine(testDirectory.FullName, VersionsProjectDirectory, directoryName, BinDirectory);
var directories = Directory.GetDirectories(projectDirectory, BuildConfiguration, SearchOption.AllDirectories);
if (directories.Length != 1)
{
throw new InvalidOperationException($"Number of directories found for pattern: '{BuildConfiguration}' under {testDirectory.FullName}: {directories.Length}");
}
var files = Directory.GetFiles(directories[0], VersionTestBinaryName, SearchOption.AllDirectories)
#if NETCOREAPP
.Where(f => f.Contains("netcoreapp"))
#else
.Where(f => !f.Contains("netcoreapp"))
#endif
.ToArray();
if (files.Length != 1)
{
throw new InvalidOperationException($"Number of files found for pattern: '{VersionTestBinaryName}' under {testDirectory.FullName}: {files.Length}");
}
return new DirectoryInfo(Path.GetDirectoryName(files[0]));
}
protected async Task Step1_StartV1Silo_Step2_StartV2Silo_Step3_StopV2Silo(int step2Version)
{
const int numberOfGrains = 100;
await StartSiloV1();
// Only V1 exist for now
for (var i = 0; i < numberOfGrains; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(1, await grain.GetVersion());
}
// Start a new silo with V2
var siloV2 = await StartSiloV2();
for (var i = 0; i < numberOfGrains; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(1, await grain.GetVersion());
}
for (var i = numberOfGrains; i < numberOfGrains * 2; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(step2Version, await grain.GetVersion());
}
// Stop the V2 silo
await StopSilo(siloV2);
// Now all activation should be V1
for (var i = 0; i < numberOfGrains * 3; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(1, await grain.GetVersion());
}
}
protected async Task ProxyCallNoPendingRequest(int expectedVersion)
{
await StartSiloV1();
// Only V1 exist for now
var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0);
Assert.Equal(1, await grain0.GetVersion());
await StartSiloV2();
// New activation should be V2
var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1);
Assert.Equal(2, await grain1.GetVersion());
Assert.Equal(1, await grain0.GetVersion());
Assert.Equal(expectedVersion, await grain1.ProxyGetVersion(grain0));
Assert.Equal(expectedVersion, await grain0.GetVersion());
}
protected async Task ProxyCallWithPendingRequest(int expectedVersion)
{
await StartSiloV1();
// Only V1 exist for now
var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0);
Assert.Equal(1, await grain0.GetVersion());
// Start a new silo with V2
await StartSiloV2();
// New activation should be V2
var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1);
Assert.Equal(2, await grain1.GetVersion());
var waitingTask = grain0.LongRunningTask(TimeSpan.FromSeconds(5));
var callBeforeUpgrade = grain0.GetVersion();
await Task.Delay(100); // Make sure requests are not sent out of order
var callProvokingUpgrade = grain1.ProxyGetVersion(grain0);
await waitingTask;
Assert.Equal(1, await callBeforeUpgrade);
Assert.Equal(expectedVersion, await callProvokingUpgrade);
}
protected async Task<SiloHandle> StartSiloV1()
{
var handle = await StartSilo(assemblyGrainsV1Dir);
await Task.Delay(waitDelay);
return handle;
}
protected async Task<SiloHandle> StartSiloV2()
{
var handle = await StartSilo(assemblyGrainsV2Dir);
await Task.Delay(waitDelay);
return handle;
}
private async Task<SiloHandle> StartSilo(DirectoryInfo rootDir)
{
SiloHandle silo;
if (this.siloIdx == 0)
{
// Setup configuration
this.builder = new TestClusterBuilder(1)
{
CreateSiloAsync = AppDomainSiloHandle.Create
};
TestDefaultConfiguration.ConfigureTestCluster(this.builder);
builder.Options.ApplicationBaseDirectory = rootDir.FullName;
builder.AddSiloBuilderConfigurator<VersionGrainsSiloBuilderConfigurator>();
builder.AddClientBuilderConfigurator<VersionGrainsClientConfigurator>();
builder.Properties[nameof(SiloCount)] = this.SiloCount.ToString();
builder.Properties[nameof(RefreshInterval)] = RefreshInterval.ToString();
builder.Properties[nameof(VersionSelectorStrategy)] = this.VersionSelectorStrategy.Name;
builder.Properties[nameof(CompatibilityStrategy)] = this.CompatibilityStrategy.Name;
waitDelay = TestCluster.GetLivenessStabilizationTime(new ClusterMembershipOptions(), didKill: false);
this.cluster = builder.Build();
await this.cluster.DeployAsync();
silo = this.cluster.Primary;
}
else
{
var configBuilder = new ConfigurationBuilder();
foreach (var source in cluster.ConfigurationSources) configBuilder.Add(source);
var testClusterOptions = new TestClusterOptions();
configBuilder.Build().Bind(testClusterOptions);
// Override the root directory.
var sources = new IConfigurationSource[]
{
new MemoryConfigurationSource {InitialData = new Dictionary<string, string>{ [nameof(TestClusterOptions.ApplicationBaseDirectory)] = rootDir.FullName } }
};
silo = await TestCluster.StartSiloAsync(cluster, siloIdx, testClusterOptions, sources);
}
this.deployedSilos.Add(silo);
this.siloIdx++;
return silo;
}
protected async Task StopSilo(SiloHandle handle)
{
await handle?.StopSiloAsync(true);
this.deployedSilos.Remove(handle);
await Task.Delay(waitDelay);
}
public void Dispose()
{
try
{
if (!deployedSilos.Any()) return;
var primarySilo = this.deployedSilos[0];
foreach (var silo in this.deployedSilos.Skip(1))
{
silo.Dispose();
}
primarySilo.Dispose();
this.Client?.Dispose();
}
finally
{
this.cluster?.Dispose();
}
}
public Task InitializeAsync()
{
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
var primarySilo = this.deployedSilos[0];
foreach (var silo in this.deployedSilos.Skip(1))
{
await silo.StopSiloAsync(true);
silo.Dispose();
}
await primarySilo.StopSiloAsync(true);
primarySilo.Dispose();
if (this.Client != null) await this.Client.Close();
this.Client?.Dispose();
}
}
}
#endif
| |
/*
TODO:
Better error messages
LASM (Lua Assembly) is used to write Lua bytecode.
Controls:
[] - Optional
.const Value
Value = "String", true/false/nil, Number
.local Name <StartPC, EndPC = 0, 0>
.upval Name
.upvalue Name
.stacksize Value
.maxstacksize value
.vararg <Vararg int value>
.name Name
.options
.func [name]
.function [name]
.end
Opcodes:
<code> <arg> <arg> [<arg>]
The 'C' (3rd) arg is optional, and defaults to 0
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SharpLua.LASM
{
public class LasmParser
{
LuaFile file;
int index, lineNumber;
Chunk func;
Stack<Chunk> funcStack;
string text = "";
void parseControl(string line)
{
string ll = line.ToLower();
if (ll.Substring(0, 6) == ".const")
{
string l = line.Substring(6);
l = l.Trim();
object value = readValue(l);
if (value == null)
func.Constants.Add(new Constant(ConstantType.Nil, null));
else if (value is bool)
func.Constants.Add(new Constant(ConstantType.Bool, (bool)value));
else if (value is double)
func.Constants.Add(new Constant(ConstantType.Number, (double)value));
else if (value is string)
func.Constants.Add(new Constant(ConstantType.String, (string)value));
}
else if (ll.Substring(0, 5) == ".name")
{
/// Im lazy :P
string l = line.Substring(5);
l = l.Trim();
if (l[0] == '"')
func.Name = (string)readValue(l);
else
func.Name = l;
}
else if (ll.Substring(0, 8) == ".options")
{
string l = line.Substring(8);
l = l.Trim();
List<int> nums = new List<int>();
// Pattern matching time!
Regex r = new Regex("\\d+");
foreach (Match m in r.Matches(l))
nums.Add(int.Parse(m.Value));
func.UpvalueCount = nums.Count > 0 ? nums[0] : func.UpvalueCount;
func.ArgumentCount = nums.Count > 1 ? nums[1] : func.ArgumentCount;
func.Vararg = nums.Count > 2 ? nums[2] : func.Vararg;
func.MaxStackSize = nums.Count > 3 ? (uint)nums[3] : func.MaxStackSize;
}
else if (ll.Substring(0, 6) == ".local")
{
string l = line.Substring(6).Trim();
if (l[0] == '"')
func.Locals.Add(new Local((string)readValue(l), 0, 0));
else
func.Locals.Add(new Local(l, 0, 0));
}
else if (ll.Substring(0, 6) == ".upval")
{
string l = line.Substring(6).Trim();
if (l[0] == '"')
func.Upvalues.Add(new Upvalue((string)readValue(l)));
else
func.Upvalues.Add(new Upvalue(l));
}
else if (ll.Substring(0, 8) == ".upvalue")
{
string l = line.Substring(8).Trim();
if (l[0] == '"')
func.Upvalues.Add(new Upvalue((string)readValue(l)));
else
func.Upvalues.Add(new Upvalue(l));
}
else if (ll.Substring(0, 10) == ".stacksize")
{
string l = line.Substring(10).Trim();
uint n = uint.Parse(l);
func.MaxStackSize = n;
}
else if (ll.Substring(0, 13) == ".maxstacksize")
{
string l = line.Substring(13).Trim();
uint n = uint.Parse(l);
func.MaxStackSize = n;
}
else if (ll.Substring(0, 7) == ".vararg")
{
string l = line.Substring(7).Trim();
int n = int.Parse(l);
func.Vararg = n;
}
else if (ll.Substring(0, 9) == ".function")
{
string l = line.Substring(9).Trim();
Chunk n = new Chunk();
n.FirstLine = (uint)lineNumber;
if (l.Length > 0)
if (l[0] == '"')
n.Name = (string)readValue(l);
else
n.Name = l;
func.Protos.Add(n);
funcStack.Push(func);
func = n;
}
else if (ll.Substring(0, 5) == ".func")
{
string l = line.Substring(5).Trim();
Chunk n = new Chunk();
n.FirstLine = (uint)lineNumber;
if (l.Length > 0)
if (l[0] == '"')
n.Name = (string)readValue(l);
else
n.Name = l;
func.Protos.Add(n);
funcStack.Push(func);
func = n;
}
else if (ll.Substring(0, 4) == ".end")
{
Chunk f = funcStack.Pop();
func.LastLine = (ulong)lineNumber;
Instruction instr1 = func.Instructions.Count > 0 ? func.Instructions[func.Instructions.Count - 1] : null;
Instruction instr2 = new Instruction("RETURN");
instr2.A = 0;
instr2.B = 1;
instr2.C = 0;
if (instr1 != null && instr1.Opcode == Instruction.LuaOpcode.RETURN)
{ } //func.Instructions.Add(instr2);
else
func.Instructions.Add(instr2);
func = f;
}
else
throw new Exception("Invalid Control Label");
}
int tonumber(string s)
{
if (s[0] == '$'
|| char.ToLower(s[0]) == 'r'
|| char.ToLower(s[0]) == 'k')
s = s.Substring(1);
return int.Parse(s);
}
Instruction parseOpcode(string line)
{
string op = "";
int i = 0;
string l = line.ToLower();
while (true)
{
if (i >= l.Length)
break;
if (!char.IsLetter(l[i]))
break;
else
op += l[i++];
}
Instruction instr = new Instruction(op, 0);
line = line.Substring(i).Trim();
i = 0;
switch (instr.OpcodeType)
{
case OpcodeType.ABC:
string a = "", b = "", c = "";
bool inA = true, inB = false;
while (true)
{
if (line.Length <= i)
break;
char ch = line[i];
if (ch == '\t' || ch == ' ')
if (inA)
{
inB = true;
inA = false;
}
else if (inB)
inB = false;
else
break;
else
if (inA)
a = a + ch;
else if (inB)
b = b + ch;
else
c = c + ch;
i++;
}
c = c == "" ? "0" : c;
instr.A = tonumber(a);
instr.B = tonumber(b);
instr.C = tonumber(c);
break;
case OpcodeType.ABx:
string bx = "";
a = "";
inA = true;
while (true)
{
if (line.Length <= i)
break;
char ch = line[i];
if (ch == '\t' || ch == ' ')
if (inA)
inA = false;
else
break;
else
if (inA)
a = a + ch;
else
bx = bx + ch;
i++;
}
instr.A = tonumber(a);
instr.Bx = tonumber(bx);
break;
case OpcodeType.AsBx:
string sbx = "";
a = "";
inA = true;
while (true)
{
if (line.Length <= i)
break;
char ch = line[i];
if (ch == '\t' || ch == ' ')
if (inA)
inA = false;
else
break;
else
if (inA)
a = a + ch;
else
sbx = sbx + ch;
i++;
}
instr.A = tonumber(a);
instr.sBx = tonumber(sbx);
break;
default:
break;
}
return instr;
}
//string readVarName()
//{
// local varPattern = "([%w_]*)" -- Any letter, number, or underscore
// local varName = string.match(text, varPattern, index)
// if not varName then
// error("Invalid variable name!")
// end
// index = index + varName:len()
// return varName
//}
void readComment()
{
if (text[index] == ';')
{
while (true)
{
if (text.Length <= index)
break;
char c = text[index];
if (c == '\r')
{
index++;
if (text[index] == '\n')
index++;
break;
}
else if (c == '\n')
{
index++;
break;
}
else
{
}
index++;
}
}
}
object readValue(string text)
{
int index = 0;
if (text[index] == '"')
{
string s = "";
index++;
while (true)
{
char c = text[index];
if (c == '\\')
{
char c2 = text[index + 1];
if (c2 == 'n')
s += "\n";
else if (c2 == 'r')
s += "\r";
else if (c2 == 't')
s += "\t";
else if (c2 == '\\')
s += "\\";
else if (c2 == '"')
s += "\"";
else if (c2 == '\'')
s += "'";
else if (c2 == 'a')
s += "\a";
else if (c2 == 'b')
s += "\b";
else if (c2 == 'f')
s += "\f";
else if (c2 == 'v')
s += "\v";
else if (char.IsNumber(c2))
{
string ch = text[index + 1].ToString();
if (char.IsNumber(text[index + 2]))
{
index++;
ch += text[index + 1];
if (char.IsNumber(text[index + 2]))
{
index++;
ch += text[index + 2];
}
}
s += int.Parse(ch);
}
else
throw new Exception("Unknown escape sequence: " + c2);
index += 2;
}
else if (c == '"')
break;
else
{
index++;
s += c;
}
}
return s;
}
else if (text.StartsWith("true"))
return true;
else if (text.StartsWith("false"))
return false;
else if (text.StartsWith("nil"))
return null;
else
{
// number
int x;
if (!int_TryParse(text.Trim(), out x))
throw new Exception("Unable to read value '" + text + "'");
else
return x;
}
}
static bool int_TryParse(string s, out int x)
{
#if WindowsCE
x = default(int);
if (string.IsNullOrEmpty(s)) return false;
try { x = int.Parse(s); return true; }
catch (FormatException) { return false; }
#else
return int.TryParse(s, out x);
#endif
}
void readWhitespace()
{
char c = text[index];
while (true)
{
readComment();
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
index++;
else
break;
if (text.Length <= index)
break;
c = text[index];
}
}
public LuaFile Parse(string t)
{
this.text = t;
file = new LuaFile();
index = 0;
lineNumber = 1;
func = file.Main;
file.Main.Vararg = 2;
file.Main.Name = "LASM Chunk";
funcStack = new Stack<Chunk>();
readWhitespace();
while (text.Length > index)
{
readWhitespace();
string line = "";
while (true)
{
if (text.Length <= index)
break;
char c = text[index];
if (c == '\r')
{
index++;
if (text[index] == '\n')
index++;
break;
}
else if (c == '\n')
{
index++;
break;
}
else
line += c;
index++;
}
line = line.Trim();
if (string.IsNullOrEmpty(line) || line[0] == ';')
{ } // do nothing.
else if (line[0] == '.')
parseControl(line);
else
{
Instruction op = parseOpcode(line);
op.LineNumber = lineNumber;
func.Instructions.Add(op);
}
lineNumber++;
}
Instruction instr1 = func.Instructions.Count > 0 ? func.Instructions[func.Instructions.Count - 1] : null;
Instruction instr2 = new Instruction("RETURN");
instr2.A = 0;
instr2.B = 1;
instr2.C = 0;
//getmetatable(func.Instructions).__newindex(func.Instructions, func.Instructions.Count, op)
if (instr1 == null || instr1.Opcode != Instruction.LuaOpcode.RETURN)
func.Instructions.Add(instr2);
return file;
}
}
/*
if false then -- Testing.
local p = Parser:new()
local file = p:Parse[[
.const "print"
.const "Hello"
getglobal 0 0
loadk 1 1
call 0 2 1
return 0 1
]]
local code = file:Compile()
local f = io.open("lasm.out", "wb")
f:write(code)
f:close()
local funcX = { loadstring(code) }
print(funcX[1], funcX[2])
if funcX[1] then
funcX[1]()
end
--table.foreach(file.Main.Instructions, function(x) pcall(function() print(x) end) end)
--funcX()
end
*/
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Tests.Utilities;
using NUnit.Framework;
namespace Azure.Search.Documents.Tests
{
public class SearchIndexerClientTests : SearchTestBase
{
public SearchIndexerClientTests(bool async, SearchClientOptions.ServiceVersion serviceVersion)
: base(async, serviceVersion, null /* RecordedTestMode.Record /* to re-record */)
{
}
[Test]
public void Constructor()
{
var serviceName = "my-svc-name";
var endpoint = new Uri($"https://{serviceName}.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
Assert.NotNull(service);
Assert.AreEqual(endpoint, service.Endpoint);
Assert.AreEqual(serviceName, service.ServiceName);
Assert.Throws<ArgumentNullException>(() => new SearchIndexerClient(null, new AzureKeyCredential("fake")));
Assert.Throws<ArgumentNullException>(() => new SearchIndexerClient(endpoint, null));
Assert.Throws<ArgumentException>(() => new SearchIndexerClient(new Uri("http://bing.com"), null));
}
[Test]
public void DiagnosticsAreUnique()
{
// Make sure we're not repeating Header/Query names already defined
// in the base ClientOptions
SearchClientOptions options = new SearchClientOptions();
Assert.IsEmpty(GetDuplicates(options.Diagnostics.LoggedHeaderNames));
Assert.IsEmpty(GetDuplicates(options.Diagnostics.LoggedQueryParameters));
// CollectionAssert.Unique doesn't give you the duplicate values
// which is less helpful than it could be
static string GetDuplicates(IEnumerable<string> values)
{
List<string> duplicates = new List<string>();
HashSet<string> unique = new HashSet<string>();
foreach (string value in values)
{
if (!unique.Add(value))
{
duplicates.Add(value);
}
}
return string.Join(", ", duplicates);
}
}
[Test]
public async Task CreateAzureBlobIndexer()
{
await using SearchResources resources = await SearchResources.CreateWithBlobStorageAndIndexAsync(this, populate: true);
SearchIndexerClient serviceClient = resources.GetIndexerClient();
// Create the Azure Blob data source and indexer.
SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection(
Recording.Random.GetName(),
SearchIndexerDataSourceType.AzureBlob,
resources.StorageAccountConnectionString,
new SearchIndexerDataContainer(resources.BlobContainerName));
SearchIndexerDataSourceConnection actualSource = await serviceClient.CreateDataSourceConnectionAsync(
dataSource);
SearchIndexer indexer = new SearchIndexer(
Recording.Random.GetName(),
dataSource.Name,
resources.IndexName);
SearchIndexer actualIndexer = await serviceClient.CreateIndexerAsync(
indexer);
// Update the indexer.
actualIndexer.Description = "Updated description";
await serviceClient.CreateOrUpdateIndexerAsync(
actualIndexer,
onlyIfUnchanged: true);
await WaitForIndexingAsync(serviceClient, actualIndexer.Name);
// Run the indexer.
await serviceClient.RunIndexerAsync(
indexer.Name);
await WaitForIndexingAsync(serviceClient, actualIndexer.Name);
// Query the index.
SearchClient client = resources.GetSearchClient();
long count = await client.GetDocumentCountAsync();
// This should be equal, but sometimes reports double despite logs showing no shared resources.
Assert.That(count, Is.GreaterThanOrEqualTo(SearchResources.TestDocuments.Length));
}
[Test]
[SyncOnly]
public void CreateDataSourceConnectionParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateDataSourceConnection(null));
Assert.AreEqual("dataSourceConnection", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateDataSourceConnectionAsync(null));
Assert.AreEqual("dataSourceConnection", ex.ParamName);
}
[Test]
[SyncOnly]
public void CreateOrUpdateDataSourceConnectionParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateOrUpdateDataSourceConnection(null));
Assert.AreEqual("dataSourceConnection", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateOrUpdateDataSourceConnectionAsync(null));
Assert.AreEqual("dataSourceConnection", ex.ParamName);
}
[Test]
[SyncOnly]
public void GetDataSourceConnectionParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.GetDataSourceConnection(null));
Assert.AreEqual("dataSourceConnectionName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.GetDataSourceConnectionAsync(null));
Assert.AreEqual("dataSourceConnectionName", ex.ParamName);
}
[Test]
[SyncOnly]
public void DeleteDataSourceConnectionParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.DeleteDataSourceConnection((string)null));
Assert.AreEqual("dataSourceConnectionName", ex.ParamName);
ex = Assert.Throws<ArgumentNullException>(() => service.DeleteDataSourceConnection((SearchIndexerDataSourceConnection)null));
Assert.AreEqual("dataSourceConnection", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteDataSourceConnectionAsync((string)null));
Assert.AreEqual("dataSourceConnectionName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteDataSourceConnectionAsync((SearchIndexerDataSourceConnection)null));
Assert.AreEqual("dataSourceConnection", ex.ParamName);
}
[Test]
public async Task CrudDataSourceConnection()
{
await using SearchResources resources = await SearchResources.CreateWithBlobStorageAndIndexAsync(this);
SearchIndexerClient client = resources.GetIndexerClient();
string connectionName = Recording.Random.GetName();
SearchIndexerDataSourceConnection connection = new SearchIndexerDataSourceConnection(
connectionName,
SearchIndexerDataSourceType.AzureBlob,
resources.StorageAccountConnectionString,
new SearchIndexerDataContainer(resources.BlobContainerName));
// Create the connection.
SearchIndexerDataSourceConnection createdConnection = await client.CreateDataSourceConnectionAsync(connection);
try
{
Assert.That(createdConnection, Is.EqualTo(connection).Using(SearchIndexerDataSourceConnectionComparer.Shared));
Assert.IsNull(createdConnection.ConnectionString); // Should not be returned since it contains sensitive information.
// Update the connection.
createdConnection.Description = "Updated description";
SearchIndexerDataSourceConnection updatedConnection = await client.CreateOrUpdateDataSourceConnectionAsync(createdConnection, onlyIfUnchanged: true);
Assert.That(updatedConnection, Is.EqualTo(createdConnection).Using(SearchIndexerDataSourceConnectionComparer.Shared));
Assert.IsNull(updatedConnection.ConnectionString); // Should not be returned since it contains sensitive information.
Assert.AreNotEqual(createdConnection.ETag, updatedConnection.ETag);
// Get the connection.
connection = await client.GetDataSourceConnectionAsync(connectionName);
Assert.That(connection, Is.EqualTo(updatedConnection).Using(SearchIndexerDataSourceConnectionComparer.Shared));
Assert.IsNull(connection.ConnectionString); // Should not be returned since it contains sensitive information.
Assert.AreEqual(updatedConnection.ETag, connection.ETag);
// Delete the connection.
await client.DeleteDataSourceConnectionAsync(connection, onlyIfUnchanged: true);
Response<IReadOnlyList<string>> names = await client.GetDataSourceConnectionNamesAsync();
CollectionAssert.DoesNotContain(names.Value, connectionName);
}
catch
{
if (Recording.Mode != RecordedTestMode.Playback)
{
await client.DeleteDataSourceConnectionAsync(connectionName);
}
throw;
}
}
[Test]
[SyncOnly]
public void CreateIndexParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateIndexer(null));
Assert.AreEqual("indexer", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateIndexerAsync(null));
Assert.AreEqual("indexer", ex.ParamName);
}
[Test]
[SyncOnly]
public void CreateOrUpdateIndexerParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateOrUpdateIndexer(null));
Assert.AreEqual("indexer", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateOrUpdateIndexerAsync(null));
Assert.AreEqual("indexer", ex.ParamName);
}
[Test]
[SyncOnly]
public void GetIndexerParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.GetIndexer(null));
Assert.AreEqual("indexerName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.GetIndexerAsync(null));
Assert.AreEqual("indexerName", ex.ParamName);
}
[Test]
[SyncOnly]
public void DeleteIndexerParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.DeleteIndexer((string)null));
Assert.AreEqual("indexerName", ex.ParamName);
ex = Assert.Throws<ArgumentNullException>(() => service.DeleteIndexer((SearchIndexer)null));
Assert.AreEqual("indexer", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteIndexerAsync((string)null));
Assert.AreEqual("indexerName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteIndexerAsync((SearchIndexer)null));
Assert.AreEqual("indexer", ex.ParamName);
}
[Test]
[SyncOnly]
public void ResetIndexerParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.ResetIndexer(null));
Assert.AreEqual("indexerName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.ResetIndexerAsync(null));
Assert.AreEqual("indexerName", ex.ParamName);
}
[Test]
[SyncOnly]
public void RunIndexerParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.RunIndexer(null));
Assert.AreEqual("indexerName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.RunIndexerAsync(null));
Assert.AreEqual("indexerName", ex.ParamName);
}
[Test]
[SyncOnly]
public void CreateSkillsetParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateSkillset(null));
Assert.AreEqual("skillset", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateSkillsetAsync(null));
Assert.AreEqual("skillset", ex.ParamName);
}
[Test]
[SyncOnly]
public void CreateOrUpdateSkillsetParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateOrUpdateSkillset(null));
Assert.AreEqual("skillset", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateOrUpdateSkillsetAsync(null));
Assert.AreEqual("skillset", ex.ParamName);
}
[Test]
[SyncOnly]
public void GetSkillsetParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.GetSkillset(null));
Assert.AreEqual("skillsetName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.GetSkillsetAsync(null));
Assert.AreEqual("skillsetName", ex.ParamName);
}
[Test]
[SyncOnly]
public void DeleteSkillsetParameterValidation()
{
var endpoint = new Uri($"https://my-svc-name.search.windows.net");
var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake"));
ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.DeleteSkillset((string)null));
Assert.AreEqual("skillsetName", ex.ParamName);
ex = Assert.Throws<ArgumentNullException>(() => service.DeleteSkillset((SearchIndexerSkillset)null));
Assert.AreEqual("skillset", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteSkillsetAsync((string)null));
Assert.AreEqual("skillsetName", ex.ParamName);
ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteSkillsetAsync((SearchIndexerSkillset)null));
Assert.AreEqual("skillset", ex.ParamName);
}
[Test]
public async Task CrudSkillset()
{
await using SearchResources resources = await SearchResources.CreateWithBlobStorageAndIndexAsync(this);
SearchIndexerClient client = resources.GetIndexerClient();
string skillsetName = Recording.Random.GetName();
// Skills based on https://github.com/Azure-Samples/azure-search-sample-data/blob/master/hotelreviews/HotelReviews_skillset.json.
SearchIndexerSkill skill1 = new SplitSkill(
new[]
{
new InputFieldMappingEntry("text") { Source = "/document/reviews_text" },
new InputFieldMappingEntry("languageCode") { Source = "/document/Language" },
},
new[]
{
new OutputFieldMappingEntry("textItems") { TargetName = "pages" },
})
{
Context = "/document/reviews_text",
DefaultLanguageCode = SplitSkillLanguage.En,
TextSplitMode = TextSplitMode.Pages,
MaximumPageLength = 5000,
};
SearchIndexerSkill skill2 = new SentimentSkill(
new[]
{
new InputFieldMappingEntry("text") { Source = "/documents/reviews_text/pages/*" },
new InputFieldMappingEntry("languageCode") { Source = "/document/Language" },
},
new[]
{
new OutputFieldMappingEntry("score") { TargetName = "Sentiment" },
})
{
Context = "/document/reviews_text/pages/*",
DefaultLanguageCode = SentimentSkillLanguage.En,
};
SearchIndexerSkill skill3 = new LanguageDetectionSkill(
new[]
{
new InputFieldMappingEntry("text") { Source = "/document/reviews_text" },
},
new[]
{
new OutputFieldMappingEntry("languageCode") { TargetName = "Language" },
})
{
Context = "/document",
};
SearchIndexerSkill skill4 = new KeyPhraseExtractionSkill(
new[]
{
new InputFieldMappingEntry("text") { Source = "/documents/reviews_Text/pages/*" },
new InputFieldMappingEntry("languageCode") { Source = "/document/Language" },
},
new[]
{
new OutputFieldMappingEntry("keyPhrases") { TargetName = "Keyphrases" },
})
{
Context = "/document/reviews_text/pages/*",
DefaultLanguageCode = KeyPhraseExtractionSkillLanguage.En,
};
SearchIndexerSkill skill5 = new ShaperSkill(
new[]
{
new InputFieldMappingEntry("name") { Source = "/document/name" },
new InputFieldMappingEntry("reviews_date") { Source = "/document/reviews_date" },
new InputFieldMappingEntry("reviews_rating") { Source = "/documents/reviews_rating" },
new InputFieldMappingEntry("reviews_text") { Source = "/documents/reviews_text" },
new InputFieldMappingEntry("reviews_title") { Source = "/document/reviews_title" },
new InputFieldMappingEntry("AzureSearch_DocumentKey") { Source = "/document/AzureSearch_DocumentKey" },
new InputFieldMappingEntry("pages")
{
SourceContext = "/document/reviews_text/pages/*",
Inputs =
{
new InputFieldMappingEntry("SentimentScore") { Source = "/document/reviews_text/pages/*/Sentiment" },
new InputFieldMappingEntry("LanguageCode") { Source = "/document/Language" },
new InputFieldMappingEntry("Page") { Source = "/document/reviews_text/pages/*" },
new InputFieldMappingEntry("keyphrase")
{
SourceContext = "/document/reviews_text/pages/*/Keyphrases/*",
Inputs =
{
new InputFieldMappingEntry("Keyphrases") { Source = "/document/reviews_text/pages/*/Keyphrases/*" },
},
},
},
},
},
new[]
{
new OutputFieldMappingEntry("output") { TargetName = "tableprojection" },
})
{
Context = "/document",
};
SearchIndexerSkillset skillset = new SearchIndexerSkillset(skillsetName, new[] { skill1, skill2, skill3, skill4, skill5 })
{
CognitiveServicesAccount = new DefaultCognitiveServicesAccount(),
};
// Create the skillset.
SearchIndexerSkillset createdSkillset = await client.CreateSkillsetAsync(skillset);
try
{
Assert.That(createdSkillset, Is.EqualTo(skillset).Using(SearchIndexerSkillsetComparer.Shared));
// Update the skillset.
createdSkillset.Description = "Update description";
SearchIndexerSkillset updatedSkillset = await client.CreateOrUpdateSkillsetAsync(createdSkillset, onlyIfUnchanged: true);
Assert.That(updatedSkillset, Is.EqualTo(createdSkillset).Using(SearchIndexerSkillsetComparer.Shared));
Assert.AreNotEqual(createdSkillset.ETag, updatedSkillset.ETag);
// Get the skillset
skillset = await client.GetSkillsetAsync(skillsetName);
Assert.That(skillset, Is.EqualTo(updatedSkillset).Using(SearchIndexerSkillsetComparer.Shared));
Assert.AreEqual(updatedSkillset.ETag, skillset.ETag);
// Delete the skillset.
await client.DeleteSkillsetAsync(skillset, onlyIfUnchanged: true);
Response<IReadOnlyList<string>> names = await client.GetSkillsetNamesAsync();
CollectionAssert.DoesNotContain(names.Value, skillsetName);
}
catch
{
if (Recording.Mode != RecordedTestMode.Playback)
{
await client.DeleteSkillsetAsync(skillsetName);
}
throw;
}
}
[Test]
public async Task RoundtripAllSkills()
{
// BUGBUG: https://github.com/Azure/azure-sdk-for-net/issues/15108
await using SearchResources resources = SearchResources.CreateWithNoIndexes(this);
SearchIndexerClient client = resources.GetIndexerClient();
string skillsetName = Recording.Random.GetName();
// Enumerate all skills and create them with consistently fake input to test for nullability during deserialization.
SearchIndexerSkill CreateSkill(Type t, string[] inputNames, string[] outputNames)
{
var inputs = inputNames.Select(input => new InputFieldMappingEntry(input) { Source = "/document/content" } ).ToList();
var outputs = outputNames.Select(output => new OutputFieldMappingEntry(output, targetName: Recording.Random.GetName())).ToList();
return t switch
{
// TODO: Should TextSplitMode be added to constructor (required input)?
Type _ when t == typeof(SplitSkill) => new SplitSkill(inputs, outputs) { TextSplitMode = TextSplitMode.Pages },
Type _ when t == typeof(TextTranslationSkill) => new TextTranslationSkill(inputs, outputs, TextTranslationSkillLanguage.En),
Type _ when t == typeof(WebApiSkill) => new WebApiSkill(inputs, outputs, "https://microsoft.com"),
_ => (SearchIndexerSkill)Activator.CreateInstance(t, new object[] { inputs, outputs }),
};
}
List<SearchIndexerSkill> skills = typeof(SearchIndexerSkill).Assembly.GetExportedTypes()
.Where(t => t != typeof(SearchIndexerSkill) && typeof(SearchIndexerSkill).IsAssignableFrom(t))
.Select(t => t switch
{
Type _ when t == typeof(ConditionalSkill) => CreateSkill(t, new[] { "condition", "whenTrue", "whenFalse" }, new[] { "output" }),
Type _ when t == typeof(EntityRecognitionSkill) => CreateSkill(t, new[] { "languageCode", "text" }, new[] { "persons" }),
Type _ when t == typeof(ImageAnalysisSkill) => CreateSkill(t, new[] { "image" }, new[] { "categories" }),
Type _ when t == typeof(KeyPhraseExtractionSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "keyPhrases" }),
Type _ when t == typeof(LanguageDetectionSkill) => CreateSkill(t, new[] { "text" }, new[] { "languageCode", "languageName", "score" }),
Type _ when t == typeof(MergeSkill) => CreateSkill(t, new[] { "text", "itemsToInsert", "offsets" }, new[] { "mergedText" }),
Type _ when t == typeof(OcrSkill) => CreateSkill(t, new[] { "image" }, new[] { "text", "layoutText" }),
Type _ when t == typeof(SentimentSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "score" }),
Type _ when t == typeof(ShaperSkill) => CreateSkill(t, new[] { "text" }, new[] { "output" }),
Type _ when t == typeof(SplitSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "textItems" }),
Type _ when t == typeof(TextTranslationSkill) => CreateSkill(t, new[] { "text", "toLanguageCode", "fromLanguageCode" }, new[] { "translatedText", "translatedToLanguageCode", "translatedFromLanguageCode" }),
Type _ when t == typeof(WebApiSkill) => CreateSkill(t, new[] { "input" }, new[] { "output" }),
_ => throw new NotSupportedException(),
})
.ToList();
SearchIndexerSkillset specifiedSkillset = new SearchIndexerSkillset(skillsetName, skills)
{
CognitiveServicesAccount = new DefaultCognitiveServicesAccount(),
};
try
{
SearchIndexerSkillset createdSkillset = await client.CreateSkillsetAsync(specifiedSkillset);
Assert.AreEqual(skillsetName, createdSkillset.Name);
Assert.AreEqual(skills.Count, createdSkillset.Skills.Count);
}
catch
{
if (Recording.Mode != RecordedTestMode.Playback)
{
await client.DeleteSkillsetAsync(skillsetName);
}
throw;
}
}
}
}
| |
namespace CodeHub.Data.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using CodeHub.Common;
using CodeHub.Common.RandomGenerator;
using CodeHub.Common.RandomGenerator.Contracts;
using CodeHub.Data.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
internal sealed class Configuration : DbMigrationsConfiguration<CodeHubDbContext>
{
private readonly IList<User> users;
private readonly IList<Comment> comments;
private readonly IDictionary<string, string> pastesData;
private readonly IRandomProvider randomProvider;
private IList<Syntax> syntaxes;
private IList<Paste> pastes;
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
this.users = new List<User>();
this.comments = new List<Comment>();
this.pastesData = new Dictionary<string, string>();
this.randomProvider = RandomProvider.Instance;
}
protected override void Seed(CodeHubDbContext context)
{
if (!context.Roles.Any(r => r.Name == GlobalConstants.AdminRole))
{
this.SeedRoles(context);
context.SaveChanges();
}
if (!context.Users.Any())
{
this.SeedUsers(context);
context.SaveChanges();
}
if (!context.Syntaxes.Any())
{
this.SeedSyntaxes(context);
context.SaveChanges();
}
if (!context.Pastes.Any())
{
this.SeedPastes(context);
context.SaveChanges();
}
if (!context.Comments.Any())
{
this.SeedComments(context);
context.SaveChanges();
}
if (!context.Repos.Any())
{
this.SeedRepo(context);
context.SaveChanges();
}
}
private void SeedRepo(CodeHubDbContext context)
{
User currentOwner = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)];
context.Repos.Add(
new Repo()
{
Name = this.randomProvider.GetRandomLengthString(5, 30),
Owner = currentOwner,
Pastes = currentOwner.Pastes
});
}
private void SeedComments(CodeHubDbContext context)
{
List<Paste> pastesToDb = context.Pastes.ToList();
int numberOfComments = this.randomProvider.GetRandomInt(5, 10);
for (int i = 0; i < numberOfComments; i++)
{
this.comments.Add(
new Comment()
{
Author = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)],
Content = this.randomProvider.GetRandomString(150),
Paste = pastesToDb[this.randomProvider.GetRandomInt(0, pastesToDb.Count - 1)]
});
}
foreach (Comment comment in this.comments)
{
context.Comments.Add(comment);
}
}
private void SeedPastes(CodeHubDbContext context)
{
this.ReadPastesFromFile();
this.pastes = new List<Paste>()
{
new Paste
{
Author = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)],
Title = "Find Catalan's numbers problem",
Content = this.pastesData["C#"],
Description = this.pastesData["description"],
Syntax = this.syntaxes[0]
},
new Paste
{
Author = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)],
Title = "HTML5 Example",
Content = this.pastesData["HTML"],
Description = this.pastesData["description"],
Syntax = this.syntaxes[2]
},
new Paste
{
Author = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)],
Title = "jQuery plugin with CoffeeScript",
Content = this.pastesData["CoffeeScript"],
Description = this.pastesData["description"],
Syntax = this.syntaxes[5]
},
new Paste
{
Author = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)],
Title = "JavaScript source code example",
Content = this.pastesData["JavaScript"],
Description = this.pastesData["description"],
Syntax = this.syntaxes[8]
},
new Paste
{
Author = this.users[this.randomProvider.GetRandomInt(0, this.users.Count - 1)],
Title = "CSS source code example",
Content = this.pastesData["CSS"],
Description = this.pastesData["description"],
Syntax = this.syntaxes[3]
}
};
foreach (Paste paste in this.pastes)
{
context.Pastes.Add(paste);
}
}
private void ReadPastesFromFile()
{
string codeBase = Assembly.GetCallingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
string ddlPath = Path.GetDirectoryName(path);
using (var reader = new StreamReader(string.Format("{0}\\SeedData\\CatalanNumber.cs", ddlPath), Encoding.UTF8))
{
this.pastesData["C#"] = reader.ReadToEnd();
}
using (var reader = new StreamReader(string.Format("{0}\\SeedData\\index.html", ddlPath), Encoding.UTF8))
{
this.pastesData["HTML"] = reader.ReadToEnd();
}
using (var reader = new StreamReader(string.Format("{0}\\SeedData\\scripts.coffee", ddlPath), Encoding.UTF8))
{
this.pastesData["CoffeeScript"] = reader.ReadToEnd();
}
using (var reader = new StreamReader(string.Format("{0}\\SeedData\\scripts.js", ddlPath), Encoding.UTF8))
{
this.pastesData["JavaScript"] = reader.ReadToEnd();
}
using (var reader = new StreamReader(string.Format("{0}\\SeedData\\styles.css", ddlPath), Encoding.UTF8))
{
this.pastesData["CSS"] = reader.ReadToEnd();
}
using (var reader = new StreamReader(string.Format("{0}\\SeedData\\lorem.txt", ddlPath), Encoding.UTF8))
{
this.pastesData["description"] = reader.ReadToEnd();
}
}
private void SeedUsers(CodeHubDbContext context)
{
this.SeedAdmins(context);
for (int i = 0; i < 3; i++)
{
var store = new UserStore<User>(context);
var manager = new UserManager<User>(store);
var user = new User { UserName = string.Format("pesho{0}", i) };
manager.Create(user, "asdasd");
context.SaveChanges();
this.users.Add(user);
}
}
private void SeedAdmins(CodeHubDbContext context)
{
if (!context.Users.Any(u => u.UserName == "admin@admin.bg"))
{
var store = new UserStore<User>(context);
var manager = new UserManager<User>(store);
var user = new User { UserName = "admin" };
manager.Create(user, "asdasd");
context.SaveChanges();
manager.AddToRole(user.Id, GlobalConstants.AdminRole);
context.SaveChanges();
}
}
private void SeedRoles(CodeHubDbContext context)
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = GlobalConstants.AdminRole };
manager.Create(role);
}
private void SeedSyntaxes(CodeHubDbContext context)
{
this.syntaxes = new List<Syntax>()
{
new Syntax { Name = "C#", SyntaxMode = "text/x-csharp" },
new Syntax { Name = "C++", SyntaxMode = "text/x-c++src" },
new Syntax { Name = "HTML", SyntaxMode = "text/html" },
new Syntax { Name = "CSS", SyntaxMode = "text/css" },
new Syntax { Name = "SQL", SyntaxMode = "text/x-mssql" },
new Syntax { Name = "CoffeeScript", SyntaxMode = "text/x-coffeescript" },
new Syntax { Name = "Java", SyntaxMode = "text/x-java" },
new Syntax { Name = "Ruby", SyntaxMode = "text/x-ruby" },
new Syntax { Name = "JavaScript", SyntaxMode = "text/javascript" },
new Syntax { Name = "TypeScript", SyntaxMode = "text/typescript" }
};
foreach (Syntax syntax in this.syntaxes)
{
context.Syntaxes.Add(syntax);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLConditionalFormat : XLStylizedBase, IXLConditionalFormat, IXLStylized
{
private sealed class FullEqualityComparer : IEqualityComparer<IXLConditionalFormat>
{
private readonly bool _compareRange;
private readonly DictionaryComparer<int, XLColor> _colorsComparer = new DictionaryComparer<int, XLColor>();
private readonly EnumerableComparer<string> _listComparer = new EnumerableComparer<string>();
private readonly DictionaryComparer<int, XLCFContentType> _contentsTypeComparer = new DictionaryComparer<int, XLCFContentType>();
private readonly DictionaryComparer<int, XLCFIconSetOperator> _iconSetTypeComparer = new DictionaryComparer<int, XLCFIconSetOperator>();
public FullEqualityComparer(bool compareRange)
{
_compareRange = compareRange;
}
public bool Equals(IXLConditionalFormat x, IXLConditionalFormat y)
{
var xx = (XLConditionalFormat)x;
var yy = (XLConditionalFormat)y;
if (ReferenceEquals(xx, yy)) return true;
if (ReferenceEquals(xx, null)) return false;
if (ReferenceEquals(yy, null)) return false;
if (xx.GetType() != yy.GetType()) return false;
var xxValues = xx.Values.Values.Where(v => v == null || !v.IsFormula).Select(v => v?.Value);
var yyValues = yy.Values.Values.Where(v => v == null || !v.IsFormula).Select(v => v?.Value);
var xxFormulas = x.Ranges.Count > 0 ? xx.Values.Values.Where(v => v != null && v.IsFormula).Select(f => ((XLCell)x.Ranges.First().FirstCell()).GetFormulaR1C1(f.Value)) : null;
var yyFormulas = y.Ranges.Count > 0 ? yy.Values.Values.Where(v => v != null && v.IsFormula).Select(f => ((XLCell)y.Ranges.First().FirstCell()).GetFormulaR1C1(f.Value)) : null;
var xStyle = xx.StyleValue;
var yStyle = yy.StyleValue;
return Equals(xStyle, yStyle)
&& xx.CopyDefaultModify == yy.CopyDefaultModify
&& xx.ConditionalFormatType == yy.ConditionalFormatType
&& xx.TimePeriod == yy.TimePeriod
&& xx.IconSetStyle == yy.IconSetStyle
&& xx.Operator == yy.Operator
&& xx.Bottom == yy.Bottom
&& xx.Percent == yy.Percent
&& xx.ReverseIconOrder == yy.ReverseIconOrder
&& xx.StopIfTrue == yy.StopIfTrue
&& xx.ShowIconOnly == yy.ShowIconOnly
&& xx.ShowBarOnly == yy.ShowBarOnly
&& _listComparer.Equals(xxValues, yyValues)
&& _listComparer.Equals(xxFormulas, yyFormulas)
&& _colorsComparer.Equals(xx.Colors, yy.Colors)
&& _contentsTypeComparer.Equals(xx.ContentTypes, yy.ContentTypes)
&& _iconSetTypeComparer.Equals(xx.IconSetOperators, yy.IconSetOperators)
&& (!_compareRange || XLRanges.Equals(xx.Ranges, yy.Ranges));
}
public int GetHashCode(IXLConditionalFormat obj)
{
var xx = (XLConditionalFormat)obj;
var xStyle = (obj.Style as XLStyle).Value;
var xValues = xx.Values.Values.Where(v => !v.IsFormula).Select(v => v.Value);
if (obj.Ranges.Count > 0)
xValues = xValues
.Union(xx.Values.Values.Where(v => v.IsFormula).Select(f => ((XLCell)obj.Ranges.First().FirstCell()).GetFormulaR1C1(f.Value)));
unchecked
{
var hashCode = xStyle.GetHashCode();
hashCode = (hashCode * 397) ^ xx.StyleValue.GetHashCode();
hashCode = (hashCode * 397) ^ xx.CopyDefaultModify.GetHashCode();
hashCode = (hashCode * 397) ^ xValues.GetHashCode();
hashCode = (hashCode * 397) ^ (xx.Colors != null ? xx.Colors.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (xx.ContentTypes != null ? xx.ContentTypes.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (xx.IconSetOperators != null ? xx.IconSetOperators.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (_compareRange && xx.Ranges != null ? xx.Ranges.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (int)xx.ConditionalFormatType;
hashCode = (hashCode * 397) ^ (int)xx.TimePeriod;
hashCode = (hashCode * 397) ^ (int)xx.IconSetStyle;
hashCode = (hashCode * 397) ^ (int)xx.Operator;
hashCode = (hashCode * 397) ^ xx.Bottom.GetHashCode();
hashCode = (hashCode * 397) ^ xx.Percent.GetHashCode();
hashCode = (hashCode * 397) ^ xx.ReverseIconOrder.GetHashCode();
hashCode = (hashCode * 397) ^ xx.ShowIconOnly.GetHashCode();
hashCode = (hashCode * 397) ^ xx.ShowBarOnly.GetHashCode();
hashCode = (hashCode * 397) ^ xx.StopIfTrue.GetHashCode();
return hashCode;
}
}
}
internal void AdjustFormulas(XLCell baseCell, XLCell targetCell)
{
var keys = Values.Keys.ToList();
foreach (var key in keys)
{
if (Values[key] == null || !Values[key].IsFormula)
continue;
var r1c1 = baseCell.GetFormulaR1C1(Values[key].Value);
Values[key] = new XLFormula { _value = targetCell.GetFormulaA1(r1c1), IsFormula = true };
}
}
private static readonly IEqualityComparer<IXLConditionalFormat> FullComparerInstance = new FullEqualityComparer(true);
public static IEqualityComparer<IXLConditionalFormat> FullComparer
{
get { return FullComparerInstance; }
}
private static readonly IEqualityComparer<IXLConditionalFormat> NoRangeComparerInstance = new FullEqualityComparer(false);
public static IEqualityComparer<IXLConditionalFormat> NoRangeComparer
{
get { return NoRangeComparerInstance; }
}
#region Constructors
private XLConditionalFormat(XLStyleValue style)
: base(XLStyle.Default.Value)
{
Id = Guid.NewGuid();
Ranges = new XLRanges();
Values = new XLDictionary<XLFormula>();
Colors = new XLDictionary<XLColor>();
ContentTypes = new XLDictionary<XLCFContentType>();
IconSetOperators = new XLDictionary<XLCFIconSetOperator>();
}
public XLConditionalFormat(XLRange range, Boolean copyDefaultModify = false)
: this(XLStyle.Default.Value)
{
if (range != null)
Ranges.Add(range);
CopyDefaultModify = copyDefaultModify;
}
public XLConditionalFormat(IEnumerable<XLRange> ranges, Boolean copyDefaultModify = false)
: this(XLStyle.Default.Value)
{
ranges?.ForEach(range => Ranges.Add(range));
CopyDefaultModify = copyDefaultModify;
}
public XLConditionalFormat(XLConditionalFormat conditionalFormat, IXLRange targetRange)
: this(conditionalFormat, new[] { targetRange })
{
}
public XLConditionalFormat(XLConditionalFormat conditionalFormat, IEnumerable<IXLRange> targetRanges)
: this(conditionalFormat.StyleValue)
{
targetRanges?.ForEach(range => Ranges.Add(range));
CopyFrom(conditionalFormat);
}
#endregion Constructors
public Guid Id { get; internal set; }
internal Int32 OriginalPriority { get; set; }
public Boolean CopyDefaultModify { get; set; }
public override IEnumerable<IXLStyle> Styles
{
get
{
yield return Style;
}
}
protected override IEnumerable<XLStylizedBase> Children
{
get { yield break; }
}
public override IXLRanges RangesUsed
{
get { return new XLRanges(); }
}
public XLDictionary<XLFormula> Values { get; private set; }
public XLDictionary<XLColor> Colors { get; private set; }
public XLDictionary<XLCFContentType> ContentTypes { get; private set; }
public XLDictionary<XLCFIconSetOperator> IconSetOperators { get; private set; }
public IXLRange Range
{
get { return Ranges.FirstOrDefault(); }
set
{
Ranges.RemoveAll();
Ranges.Add(value);
}
}
public IXLRanges Ranges { get; private set; }
public XLConditionalFormatType ConditionalFormatType { get; set; }
public XLTimePeriod TimePeriod { get; set; }
public XLIconSetStyle IconSetStyle { get; set; }
public XLCFOperator Operator { get; set; }
public Boolean Bottom { get; set; }
public Boolean Percent { get; set; }
public Boolean ReverseIconOrder { get; set; }
public Boolean ShowIconOnly { get; set; }
public Boolean ShowBarOnly { get; set; }
public Boolean StopIfTrue { get; set; }
public IXLConditionalFormat SetStopIfTrue()
{
return SetStopIfTrue(true);
}
public IXLConditionalFormat SetStopIfTrue(bool value)
{
this.StopIfTrue = value;
return this;
}
public IXLConditionalFormat CopyTo(IXLWorksheet targetSheet)
{
if (targetSheet == Range?.Worksheet)
throw new InvalidOperationException("Cannot copy conditional format to the worksheet it already belongs to.");
var targetRanges = Ranges.Select(r => targetSheet.Range(((XLRangeAddress)r.RangeAddress).WithoutWorksheet()));
var newCf = new XLConditionalFormat(this, targetRanges);
targetSheet.ConditionalFormats.Add(newCf);
return newCf;
}
public void CopyFrom(IXLConditionalFormat other)
{
InnerStyle = other.Style;
ConditionalFormatType = other.ConditionalFormatType;
TimePeriod = other.TimePeriod;
IconSetStyle = other.IconSetStyle;
Operator = other.Operator;
Bottom = other.Bottom;
Percent = other.Percent;
ReverseIconOrder = other.ReverseIconOrder;
ShowIconOnly = other.ShowIconOnly;
ShowBarOnly = other.ShowBarOnly;
StopIfTrue = other.StopIfTrue;
Values.Clear();
other.Values.ForEach(kp => Values.Add(kp.Key, new XLFormula(kp.Value)));
//CopyDictionary(Values, other.Values);
CopyDictionary(Colors, other.Colors);
CopyDictionary(ContentTypes, other.ContentTypes);
CopyDictionary(IconSetOperators, other.IconSetOperators);
}
private void CopyDictionary<T>(XLDictionary<T> target, XLDictionary<T> source)
{
target.Clear();
source.ForEach(kp => target.Add(kp.Key, kp.Value));
}
public IXLStyle WhenIsBlank()
{
ConditionalFormatType = XLConditionalFormatType.IsBlank;
return Style;
}
public IXLStyle WhenNotBlank()
{
ConditionalFormatType = XLConditionalFormatType.NotBlank;
return Style;
}
public IXLStyle WhenIsError()
{
ConditionalFormatType = XLConditionalFormatType.IsError;
return Style;
}
public IXLStyle WhenNotError()
{
ConditionalFormatType = XLConditionalFormatType.NotError;
return Style;
}
public IXLStyle WhenDateIs(XLTimePeriod timePeriod)
{
TimePeriod = timePeriod;
ConditionalFormatType = XLConditionalFormatType.TimePeriod;
return Style;
}
public IXLStyle WhenContains(String value)
{
Values.Initialize(new XLFormula { Value = value });
ConditionalFormatType = XLConditionalFormatType.ContainsText;
Operator = XLCFOperator.Contains;
return Style;
}
public IXLStyle WhenNotContains(String value)
{
Values.Initialize(new XLFormula { Value = value });
ConditionalFormatType = XLConditionalFormatType.NotContainsText;
Operator = XLCFOperator.NotContains;
return Style;
}
public IXLStyle WhenStartsWith(String value)
{
Values.Initialize(new XLFormula { Value = value });
ConditionalFormatType = XLConditionalFormatType.StartsWith;
Operator = XLCFOperator.StartsWith;
return Style;
}
public IXLStyle WhenEndsWith(String value)
{
Values.Initialize(new XLFormula { Value = value });
ConditionalFormatType = XLConditionalFormatType.EndsWith;
Operator = XLCFOperator.EndsWith;
return Style;
}
public IXLStyle WhenEquals(String value)
{
Values.Initialize(new XLFormula { Value = value });
Operator = XLCFOperator.Equal;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenNotEquals(String value)
{
Values.Initialize(new XLFormula { Value = value });
Operator = XLCFOperator.NotEqual;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenGreaterThan(String value)
{
Values.Initialize(new XLFormula { Value = value });
Operator = XLCFOperator.GreaterThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenLessThan(String value)
{
Values.Initialize(new XLFormula { Value = value });
Operator = XLCFOperator.LessThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenEqualOrGreaterThan(String value)
{
Values.Initialize(new XLFormula { Value = value });
Operator = XLCFOperator.EqualOrGreaterThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenEqualOrLessThan(String value)
{
Values.Initialize(new XLFormula { Value = value });
Operator = XLCFOperator.EqualOrLessThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenBetween(String minValue, String maxValue)
{
Values.Initialize(new XLFormula { Value = minValue });
Values.Add(new XLFormula { Value = maxValue });
Operator = XLCFOperator.Between;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenNotBetween(String minValue, String maxValue)
{
Values.Initialize(new XLFormula { Value = minValue });
Values.Add(new XLFormula { Value = maxValue });
Operator = XLCFOperator.NotBetween;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenEquals(Double value)
{
Values.Initialize(new XLFormula(value));
Operator = XLCFOperator.Equal;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenNotEquals(Double value)
{
Values.Initialize(new XLFormula(value));
Operator = XLCFOperator.NotEqual;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenGreaterThan(Double value)
{
Values.Initialize(new XLFormula(value));
Operator = XLCFOperator.GreaterThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenLessThan(Double value)
{
Values.Initialize(new XLFormula(value));
Operator = XLCFOperator.LessThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenEqualOrGreaterThan(Double value)
{
Values.Initialize(new XLFormula(value));
Operator = XLCFOperator.EqualOrGreaterThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenEqualOrLessThan(Double value)
{
Values.Initialize(new XLFormula(value));
Operator = XLCFOperator.EqualOrLessThan;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenBetween(Double minValue, Double maxValue)
{
Values.Initialize(new XLFormula(minValue));
Values.Add(new XLFormula(maxValue));
Operator = XLCFOperator.Between;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenNotBetween(Double minValue, Double maxValue)
{
Values.Initialize(new XLFormula(minValue));
Values.Add(new XLFormula(maxValue));
Operator = XLCFOperator.NotBetween;
ConditionalFormatType = XLConditionalFormatType.CellIs;
return Style;
}
public IXLStyle WhenIsDuplicate()
{
ConditionalFormatType = XLConditionalFormatType.IsDuplicate;
return Style;
}
public IXLStyle WhenIsUnique()
{
ConditionalFormatType = XLConditionalFormatType.IsUnique;
return Style;
}
public IXLStyle WhenIsTrue(String formula)
{
String f = formula.TrimStart()[0] == '=' ? formula : "=" + formula;
Values.Initialize(new XLFormula { Value = f });
ConditionalFormatType = XLConditionalFormatType.Expression;
return Style;
}
public IXLStyle WhenIsTop(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items)
{
Values.Initialize(new XLFormula(value));
Percent = topBottomType == XLTopBottomType.Percent;
ConditionalFormatType = XLConditionalFormatType.Top10;
Bottom = false;
return Style;
}
public IXLStyle WhenIsBottom(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items)
{
Values.Initialize(new XLFormula(value));
Percent = topBottomType == XLTopBottomType.Percent;
ConditionalFormatType = XLConditionalFormatType.Top10;
Bottom = true;
return Style;
}
public IXLCFColorScaleMin ColorScale()
{
ConditionalFormatType = XLConditionalFormatType.ColorScale;
return new XLCFColorScaleMin(this);
}
public IXLCFDataBarMin DataBar(XLColor color, Boolean showBarOnly = false)
{
Colors.Initialize(color);
ShowBarOnly = showBarOnly;
ConditionalFormatType = XLConditionalFormatType.DataBar;
return new XLCFDataBarMin(this);
}
public IXLCFDataBarMin DataBar(XLColor positiveColor, XLColor negativeColor, Boolean showBarOnly = false)
{
Colors.Initialize(positiveColor);
Colors.Add(negativeColor);
ShowBarOnly = showBarOnly;
ConditionalFormatType = XLConditionalFormatType.DataBar;
return new XLCFDataBarMin(this);
}
public IXLCFIconSet IconSet(XLIconSetStyle iconSetStyle, Boolean reverseIconOrder = false, Boolean showIconOnly = false)
{
IconSetOperators.Clear();
Values.Clear();
ContentTypes.Clear();
ConditionalFormatType = XLConditionalFormatType.IconSet;
IconSetStyle = iconSetStyle;
ReverseIconOrder = reverseIconOrder;
ShowIconOnly = showIconOnly;
return new XLCFIconSet(this);
}
}
internal class DictionaryComparer<TKey, TValue> :
IEqualityComparer<Dictionary<TKey, TValue>>
{
private readonly IEqualityComparer<TValue> _valueComparer;
public DictionaryComparer(IEqualityComparer<TValue> valueComparer = null)
{
this._valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
}
public bool Equals(Dictionary<TKey, TValue> x, Dictionary<TKey, TValue> y)
{
if (x.Count != y.Count)
return false;
if (x.Keys.Except(y.Keys).Any())
return false;
if (y.Keys.Except(x.Keys).Any())
return false;
foreach (var pair in x)
if (!_valueComparer.Equals(pair.Value, y[pair.Key]))
return false;
return true;
}
public int GetHashCode(Dictionary<TKey, TValue> obj)
{
throw new NotImplementedException();
}
}
internal class EnumerableComparer<T> : IEqualityComparer<IEnumerable<T>>
{
private readonly IEqualityComparer<T> _valueComparer;
public EnumerableComparer(IEqualityComparer<T> valueComparer = null)
{
this._valueComparer = valueComparer ?? EqualityComparer<T>.Default;
}
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
return SetEquals(x, y, _valueComparer);
}
public int GetHashCode(IEnumerable<T> obj)
{
throw new NotImplementedException();
}
public static bool SetEquals(IEnumerable<T> first, IEnumerable<T> second,
IEqualityComparer<T> comparer)
{
return new HashSet<T>(second, comparer ?? EqualityComparer<T>.Default)
.SetEquals(first);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// ASCIIEncoding
//
// Note that ASCIIEncoding is optomized with no best fit and ? for fallback.
// It doesn't come in other flavors.
//
// Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit).
//
// Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd
// use fallbacks, and we cannot guarantee that fallbacks are normalized.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ASCIIEncoding : Encoding
{
public ASCIIEncoding() : base(Encoding.CodePageASCII)
{
}
internal override void SetDefaultFallbacks()
{
// For ASCIIEncoding we just use default replacement fallback
this.encoderFallback = EncoderFallback.ReplacementFallback;
this.decoderFallback = DecoderFallback.ReplacementFallback;
}
//
// WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...)
// WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted,
// WARNING: or it'll break VB's way of calling these.
//
// The following methods are copied from EncodingNLS.cs.
// Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here.
// These should be kept in sync for the following classes:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
//
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(String chars)
{
// Validate input
if (chars==null)
throw new ArgumentNullException("chars");
Contract.EndContractBlock();
fixed (char* pChars = chars)
return GetByteCount(pChars, chars.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(String chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
// Fixed doesn't like empty byte arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = chars)
fixed ( byte* pBytes = bytes)
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
// Fixed doesn't like empty byte arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// If no input just return 0, fixed doesn't like 0 length arrays
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// If no input, return 0 & avoid fixed problem
if (byteCount == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
// Fixed doesn't like empty char arrays
if (chars.Length == 0)
chars = new char[1];
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe String GetString(byte[] bytes, int byteIndex, int byteCount)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid problems with empty input buffer
if (byteCount == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + byteIndex, byteCount, this);
}
//
// End of standard methods copied from EncodingNLS.cs
//
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
// Start by assuming default count, then +/- for fallback characters
char* charEnd = chars + charCount;
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
this.EncodingName, encoder.Fallback.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
}
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
// if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
// throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
// this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallback = this.EncoderFallback as EncoderReplacementFallback;
}
// If we have an encoder AND we aren't using default fallback,
// then we may have a complicated count.
if (fallback != null && fallback.MaxCharCount == 1)
{
// Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always
// same as input size.
// Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy.
// We could however have 1 extra byte if the last call had an encoder and a funky fallback and
// if we don't use the funky fallback this time.
// Do we have an extra char left over from last time?
if (charLeftOver > 0)
charCount++;
return (charCount);
}
// Count is more complicated if you have a funky fallback
// For fallback we may need a fallback buffer, we know we're not default fallback
int byteCount = 0;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for fallback, this'll catch surrogate pairs too.
// no chars >= 0x80 are allowed.
if (ch > 0x7f)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
if (encoder == null)
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false);
}
// Get Fallback
fallbackBuffer.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
}
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
char* charEnd = chars + charCount;
byte* byteStart = bytes;
char* charStart = chars;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
fallback = encoder.Fallback as EncoderReplacementFallback;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
this.EncodingName, encoder.Fallback.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
// encoder.FallbackBuffer.Remaining > 0)
// throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
// this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallback = this.EncoderFallback as EncoderReplacementFallback;
}
// See if we do the fast default or slightly slower fallback
if (fallback != null && fallback.MaxCharCount == 1)
{
// Fast version
char cReplacement = fallback.DefaultString[0];
// Check for replacements in range, otherwise fall back to slow version.
if (cReplacement <= (char)0x7f)
{
// We should have exactly as many output bytes as input bytes, unless there's a left
// over character, in which case we may need one more.
// If we had a left over character will have to add a ? (This happens if they had a funky
// fallback last time, but not this time.) (We can't spit any out though
// because with fallback encoder each surrogate is treated as a seperate code point)
if (charLeftOver > 0)
{
// Have to have room
// Throw even if doing no throw version because this is just 1 char,
// so buffer will never be big enough
if (byteCount == 0)
ThrowBytesOverflow(encoder, true);
// This'll make sure we still have more room and also make sure our return value is correct.
*(bytes++) = (byte)cReplacement;
byteCount--; // We used one of the ones we were counting.
}
// This keeps us from overrunning our output buffer
if (byteCount < charCount)
{
// Throw or make buffer smaller?
ThrowBytesOverflow(encoder, byteCount < 1);
// Just use what we can
charEnd = chars + byteCount;
}
// We just do a quick copy
while (chars < charEnd)
{
char ch2 = *(chars++);
if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement;
else *(bytes++) = unchecked((byte)(ch2));
}
// Clear encoder
if (encoder != null)
{
encoder.charLeftOver = (char)0;
encoder.m_charsUsed = (int)(chars-charStart);
}
return (int)(bytes - byteStart);
}
}
// Slower version, have to do real fallback.
// prepare our end
byte* byteEnd = bytes + byteCount;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
// Initialize the buffer
Contract.Assert(encoder != null,
"[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
// This will fallback a pair if *chars is a low surrogate
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for fallback, this'll catch surrogate pairs too.
// All characters >= 0x80 must fall back.
if (ch > 0x7f)
{
// Initialize the buffer
if (fallbackBuffer == null)
{
if (encoder == null)
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Get Fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Go ahead & continue (& do the fallback)
continue;
}
// We'll use this one
// Bounds check
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
Contract.Assert(chars > charStart || bytes == byteStart,
"[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious();
// Are we throwing or using buffer?
ThrowBytesOverflow(encoder, bytes == byteStart); // throw?
break; // don't throw, stop
}
// Go ahead and add it
*bytes = unchecked((byte)ch);
bytes++;
}
// Need to do encoder stuff
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
(encoder != null && !encoder.m_throwOnOverflow ),
"[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
if (decoder == null)
fallback = this.DecoderFallback as DecoderReplacementFallback;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
}
if (fallback != null && fallback.MaxCharCount == 1)
{
// Just return length, SBCS stay the same length because they don't map to surrogate
// pairs and we don't have a decoder fallback.
return count;
}
// Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII
DecoderFallbackBuffer fallbackBuffer = null;
// Have to do it the hard way.
// Assume charCount will be == count
int charCount = count;
byte[] byteBuffer = new byte[1];
// Do it our fast way
byte* byteEnd = bytes + count;
// Quick loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
byte b = *bytes;
bytes++;
// If unknown we have to do fallback count
if (b >= 0x80)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - count, null);
}
// Use fallback buffer
byteBuffer[0] = b;
charCount--; // Have to unreserve the one we already allocated for b
charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
}
}
// Fallback buffer must be empty
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
// Converted sequence is same length as input
return charCount;
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
// Do it fast way if using ? replacement fallback
byte* byteEnd = bytes + byteCount;
byte* byteStart = bytes;
char* charStart = chars;
// Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f
// Only need decoder fallback buffer if not using ? fallback.
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
if (decoder == null)
fallback = this.DecoderFallback as DecoderReplacementFallback;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
}
if (fallback != null && fallback.MaxCharCount == 1)
{
// Try it the fast way
char replacementChar = fallback.DefaultString[0];
// Need byteCount chars, otherwise too small buffer
if (charCount < byteCount)
{
// Need at least 1 output byte, throw if must throw
ThrowCharsOverflow(decoder, charCount < 1);
// Not throwing, use what we can
byteEnd = bytes + charCount;
}
// Quick loop, just do '?' replacement because we don't have fallbacks for decodings.
while (bytes < byteEnd)
{
byte b = *(bytes++);
if (b >= 0x80)
// This is an invalid byte in the ASCII encoding.
*(chars++) = replacementChar;
else
*(chars++) = unchecked((char)b);
}
// bytes & chars used are the same
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
return (int)(chars - charStart);
}
// Slower way's going to need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
byte[] byteBuffer = new byte[1];
char* charEnd = chars + charCount;
// Not quite so fast loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
byte b = *(bytes);
bytes++;
if (b >= 0x80)
{
// This is an invalid byte in the ASCII encoding.
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Use fallback buffer
byteBuffer[0] = b;
// Note that chars won't get updated unless this succeeds
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get this byte
Contract.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
bytes--; // unused byte
fallbackBuffer.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, chars == charStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Make sure we have buffer space
if (chars >= charEnd)
{
Contract.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, chars == charStart); // throw?
break; // don't throw, but stop loop
}
*(chars) = unchecked((char)b);
chars++;
}
}
// Might have had decoder fallback stuff.
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
long charCount = (long)byteCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
// True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
[System.Runtime.InteropServices.ComVisible(false)]
public override bool IsSingleByte
{
get
{
return true;
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override Decoder GetDecoder()
{
return new DecoderNLS(this);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) Punit Todi
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Xunit;
namespace System.Data.Tests
{
public class DataRelationCollectionTest : IDisposable
{
private DataSet _dataset;
private DataTable _tblparent, _tblchild;
private DataRelation _relation;
public DataRelationCollectionTest()
{
_dataset = new DataSet();
_tblparent = new DataTable("Customer");
_tblchild = new DataTable("Order");
_dataset.Tables.Add(_tblchild);
_dataset.Tables.Add(_tblparent);
_dataset.Tables.Add("Item");
_dataset.Tables["Customer"].Columns.Add("custid");
_dataset.Tables["Customer"].Columns.Add("custname");
_dataset.Tables["Order"].Columns.Add("oid");
_dataset.Tables["Order"].Columns.Add("custid");
_dataset.Tables["Order"].Columns.Add("itemid");
_dataset.Tables["Order"].Columns.Add("desc");
_dataset.Tables["Item"].Columns.Add("itemid");
_dataset.Tables["Item"].Columns.Add("desc");
}
public void Dispose()
{
_dataset.Relations.Clear();
}
[Fact]
public void Add()
{
DataRelationCollection drcol = _dataset.Relations;
DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"];
DataColumn childCol = _dataset.Tables["Order"].Columns["custid"];
DataRelation dr = new DataRelation("CustOrder", parentCol, childCol);
drcol.Add(dr);
Assert.Equal("CustOrder", drcol[0].RelationName);
drcol.Clear();
drcol.Add(parentCol, childCol);
Assert.Equal(1, drcol.Count);
drcol.Clear();
drcol.Add("NewRelation", parentCol, childCol);
Assert.Equal("NewRelation", drcol[0].RelationName);
drcol.Clear();
drcol.Add("NewRelation", parentCol, childCol, false);
Assert.Equal(1, drcol.Count);
drcol.Clear();
drcol.Add("NewRelation", parentCol, childCol, true);
Assert.Equal(1, drcol.Count);
drcol.Clear();
}
[Fact]
public void AddException2()
{
Assert.Throws<ArgumentException>(() =>
{
DataRelationCollection drcol = _dataset.Relations;
DataRelation dr1 = new DataRelation("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add(dr1);
drcol.Add(dr1);
});
}
[Fact]
public void AddException3()
{
Assert.Throws<DuplicateNameException>(() =>
{
DataRelationCollection drcol = _dataset.Relations;
DataRelation dr1 = new DataRelation("DuplicateName"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataRelation dr2 = new DataRelation("DuplicateName"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add(dr1);
drcol.Add(dr2);
});
}
[Fact]
public void AddRange()
{
DataRelationCollection drcol = _dataset.Relations;
DataRelation dr1 = new DataRelation("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataRelation dr2 = new DataRelation("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.AddRange(new DataRelation[] { dr1, dr2 });
Assert.Equal("CustOrder", drcol[0].RelationName);
Assert.Equal("ItemOrder", drcol[1].RelationName);
}
[Fact]
public void CanRemove()
{
DataRelationCollection drcol = _dataset.Relations;
DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"];
DataColumn childCol = _dataset.Tables["Order"].Columns["custid"];
DataRelation dr = new DataRelation("CustOrder", parentCol, childCol);
drcol.Add(dr);
Assert.True(drcol.CanRemove(dr));
Assert.False(drcol.CanRemove(null));
DataRelation dr2 = new DataRelation("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
Assert.False(drcol.CanRemove(dr2));
}
[Fact]
public void Clear()
{
DataRelationCollection drcol = _dataset.Relations;
DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"];
DataColumn childCol = _dataset.Tables["Order"].Columns["custid"];
drcol.Add(new DataRelation("CustOrder", parentCol, childCol));
drcol.Add("ItemOrder", _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["itemid"]);
drcol.Clear();
Assert.Equal(0, drcol.Count);
}
[Fact]
public void Contains()
{
DataRelationCollection drcol = _dataset.Relations;
DataColumn parentCol = _dataset.Tables["Customer"].Columns["custid"];
DataColumn childCol = _dataset.Tables["Order"].Columns["custid"];
DataRelation dr = new DataRelation("CustOrder", parentCol, childCol);
drcol.Add(dr);
Assert.True(drcol.Contains(dr.RelationName));
string drnull = "";
Assert.False(drcol.Contains(drnull));
dr = new DataRelation("newRelation", childCol, parentCol);
Assert.False(drcol.Contains("NoSuchRelation"));
}
[Fact]
public void CopyTo()
{
DataRelationCollection drcol = _dataset.Relations;
drcol.Add("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataRelation[] array = new DataRelation[2];
drcol.CopyTo(array, 0);
Assert.Equal(2, array.Length);
Assert.Equal("CustOrder", array[0].RelationName);
Assert.Equal("ItemOrder", array[1].RelationName);
DataRelation[] array1 = new DataRelation[4];
drcol.CopyTo(array1, 2);
Assert.Null(array1[0]);
Assert.Null(array1[1]);
Assert.Equal("CustOrder", array1[2].RelationName);
Assert.Equal("ItemOrder", array1[3].RelationName);
}
[Fact]
public void Equals()
{
DataRelationCollection drcol = _dataset.Relations;
drcol.Add("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataSet newds = new DataSet();
DataRelationCollection drcol1 = newds.Relations;
DataRelationCollection drcol2 = _dataset.Relations;
Assert.True(drcol.Equals(drcol));
Assert.True(drcol.Equals(drcol2));
Assert.False(drcol1.Equals(drcol));
Assert.False(drcol.Equals(drcol1));
Assert.True(object.Equals(drcol, drcol2));
Assert.False(object.Equals(drcol, drcol1));
}
[Fact]
public void IndexOf()
{
DataRelationCollection drcol = _dataset.Relations;
DataRelation dr1 = new DataRelation("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataRelation dr2 = new DataRelation("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add(dr1);
drcol.Add(dr2);
Assert.Equal(0, drcol.IndexOf(dr1));
Assert.Equal(1, drcol.IndexOf(dr2));
Assert.Equal(0, drcol.IndexOf("CustOrder"));
Assert.Equal(1, drcol.IndexOf("ItemOrder"));
Assert.Equal(0, drcol.IndexOf(drcol[0]));
Assert.Equal(1, drcol.IndexOf(drcol[1]));
Assert.Equal(-1, drcol.IndexOf("_noRelation_"));
DataRelation newdr = new DataRelation("newdr"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
Assert.Equal(-1, drcol.IndexOf(newdr));
}
[Fact]
public void Remove()
{
DataRelationCollection drcol = _dataset.Relations;
DataRelation dr1 = new DataRelation("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataRelation dr2 = new DataRelation("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add(dr1);
drcol.Add(dr2);
drcol.Remove(dr1);
Assert.False(drcol.Contains(dr1.RelationName));
drcol.Add(dr1);
drcol.Remove("CustOrder");
Assert.False(drcol.Contains("CustOrder"));
drcol.Add(dr1);
DataRelation drnull = null;
drcol.Remove(drnull);
DataRelation newdr = new DataRelation("newdr"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
Assert.Throws<ArgumentException>(() => drcol.Remove(newdr));
}
[Fact]
public void RemoveAt()
{
DataRelationCollection drcol = _dataset.Relations;
DataRelation dr1 = new DataRelation("CustOrder"
, _dataset.Tables["Customer"].Columns["custid"]
, _dataset.Tables["Order"].Columns["custid"]);
DataRelation dr2 = new DataRelation("ItemOrder"
, _dataset.Tables["Item"].Columns["itemid"]
, _dataset.Tables["Order"].Columns["custid"]);
drcol.Add(dr1);
drcol.Add(dr2);
try
{
drcol.RemoveAt(-1);
Assert.False(true);
}
catch (IndexOutOfRangeException e)
{
}
try
{
drcol.RemoveAt(101);
Assert.False(true);
}
catch (IndexOutOfRangeException e)
{
}
drcol.RemoveAt(1);
Assert.False(drcol.Contains(dr2.RelationName));
drcol.RemoveAt(0);
Assert.False(drcol.Contains(dr1.RelationName));
}
}
}
| |
namespace XenAdmin.Wizards
{
partial class XenWizardBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(XenWizardBase));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panelTop = new System.Windows.Forms.TableLayoutPanel();
this.pictureBoxWizard = new System.Windows.Forms.PictureBox();
this.labelWizard = new System.Windows.Forms.Label();
this.XSHelpButton = new XenAdmin.Controls.HelpButton();
this.wizardProgress = new XenAdmin.Wizards.WizardProgress();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.xenTabControlBody = new XenAdmin.Controls.XenTabControl();
this.deprecationBanner = new XenAdmin.Controls.DeprecationBanner();
this.buttonPrevious = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.tableLayoutPanelNavigation = new System.Windows.Forms.TableLayoutPanel();
this.buttonNext = new System.Windows.Forms.Button();
this.panelGeneralInformationMessage = new System.Windows.Forms.Panel();
this.labelGeneralInformationMessage = new System.Windows.Forms.Label();
this.pictureBoxGeneralInformationMessage = new System.Windows.Forms.PictureBox();
this.tableLayoutPanel1.SuspendLayout();
this.panelTop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWizard)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.XSHelpButton)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.tableLayoutPanelNavigation.SuspendLayout();
this.panelGeneralInformationMessage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxGeneralInformationMessage)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.panelTop, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.wizardProgress, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 1, 1);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// panelTop
//
this.panelTop.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(251)))), ((int)(((byte)(251)))), ((int)(((byte)(251)))));
resources.ApplyResources(this.panelTop, "panelTop");
this.tableLayoutPanel1.SetColumnSpan(this.panelTop, 2);
this.panelTop.Controls.Add(this.pictureBoxWizard, 0, 0);
this.panelTop.Controls.Add(this.labelWizard, 1, 0);
this.panelTop.Controls.Add(this.XSHelpButton, 2, 0);
this.panelTop.Name = "panelTop";
//
// pictureBoxWizard
//
this.pictureBoxWizard.Image = global::XenAdmin.Properties.Resources._000_CreateVM_h32bit_32;
resources.ApplyResources(this.pictureBoxWizard, "pictureBoxWizard");
this.pictureBoxWizard.Name = "pictureBoxWizard";
this.pictureBoxWizard.TabStop = false;
//
// labelWizard
//
this.labelWizard.AutoEllipsis = true;
resources.ApplyResources(this.labelWizard, "labelWizard");
this.labelWizard.ForeColor = System.Drawing.Color.Black;
this.labelWizard.Name = "labelWizard";
//
// XSHelpButton
//
resources.ApplyResources(this.XSHelpButton, "XSHelpButton");
this.XSHelpButton.Name = "XSHelpButton";
this.XSHelpButton.TabStop = false;
this.XSHelpButton.Click += new System.EventHandler(this.HelpButton_Click);
//
// wizardProgress
//
resources.ApplyResources(this.wizardProgress, "wizardProgress");
this.wizardProgress.Name = "wizardProgress";
this.wizardProgress.TabStop = false;
this.wizardProgress.LeavingStep += new System.EventHandler<XenAdmin.Wizards.WizardProgressEventArgs>(this.WizardProgress_LeavingStep);
this.wizardProgress.EnteringStep += new System.EventHandler<XenAdmin.Wizards.WizardProgressEventArgs>(this.WizardProgress_EnteringStep);
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.xenTabControlBody, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.deprecationBanner, 0, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// xenTabControlBody
//
resources.ApplyResources(this.xenTabControlBody, "xenTabControlBody");
this.xenTabControlBody.Name = "xenTabControlBody";
this.xenTabControlBody.SelectedIndex = -1;
this.xenTabControlBody.SelectedTab = null;
this.xenTabControlBody.TabStop = false;
//
// deprecationBanner
//
resources.ApplyResources(this.deprecationBanner, "deprecationBanner");
this.deprecationBanner.BackColor = System.Drawing.Color.LightCoral;
this.deprecationBanner.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.deprecationBanner.Name = "deprecationBanner";
//
// buttonPrevious
//
resources.ApplyResources(this.buttonPrevious, "buttonPrevious");
this.buttonPrevious.Name = "buttonPrevious";
this.buttonPrevious.UseVisualStyleBackColor = true;
this.buttonPrevious.Click += new System.EventHandler(this.buttonPrevious_Click);
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// tableLayoutPanelNavigation
//
resources.ApplyResources(this.tableLayoutPanelNavigation, "tableLayoutPanelNavigation");
this.tableLayoutPanelNavigation.Controls.Add(this.buttonPrevious, 2, 0);
this.tableLayoutPanelNavigation.Controls.Add(this.buttonNext, 3, 0);
this.tableLayoutPanelNavigation.Controls.Add(this.buttonCancel, 4, 0);
this.tableLayoutPanelNavigation.Controls.Add(this.panelGeneralInformationMessage, 0, 0);
this.tableLayoutPanelNavigation.Name = "tableLayoutPanelNavigation";
//
// buttonNext
//
resources.ApplyResources(this.buttonNext, "buttonNext");
this.buttonNext.Name = "buttonNext";
this.buttonNext.UseVisualStyleBackColor = true;
this.buttonNext.Click += new System.EventHandler(this.buttonNext_Click);
//
// panelGeneralInformationMessage
//
this.tableLayoutPanelNavigation.SetColumnSpan(this.panelGeneralInformationMessage, 2);
this.panelGeneralInformationMessage.Controls.Add(this.labelGeneralInformationMessage);
this.panelGeneralInformationMessage.Controls.Add(this.pictureBoxGeneralInformationMessage);
resources.ApplyResources(this.panelGeneralInformationMessage, "panelGeneralInformationMessage");
this.panelGeneralInformationMessage.Name = "panelGeneralInformationMessage";
//
// labelGeneralInformationMessage
//
resources.ApplyResources(this.labelGeneralInformationMessage, "labelGeneralInformationMessage");
this.labelGeneralInformationMessage.Name = "labelGeneralInformationMessage";
//
// pictureBoxGeneralInformationMessage
//
this.pictureBoxGeneralInformationMessage.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16;
resources.ApplyResources(this.pictureBoxGeneralInformationMessage, "pictureBoxGeneralInformationMessage");
this.pictureBoxGeneralInformationMessage.Name = "pictureBoxGeneralInformationMessage";
this.pictureBoxGeneralInformationMessage.TabStop = false;
//
// XenWizardBase
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.tableLayoutPanelNavigation);
this.DoubleBuffered = true;
this.KeyPreview = true;
this.MaximizeBox = false;
this.Name = "XenWizardBase";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.XenWizardBase_FormClosing);
this.Load += new System.EventHandler(this.XenWizardBase_Load);
this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.XenWizardBase_HelpRequested);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.XenWizardBase_KeyPress);
this.tableLayoutPanel1.ResumeLayout(false);
this.panelTop.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWizard)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.XSHelpButton)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tableLayoutPanelNavigation.ResumeLayout(false);
this.tableLayoutPanelNavigation.PerformLayout();
this.panelGeneralInformationMessage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxGeneralInformationMessage)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label labelWizard;
protected System.Windows.Forms.PictureBox pictureBoxWizard;
private XenAdmin.Controls.XenTabControl xenTabControlBody;
protected XenAdmin.Controls.HelpButton XSHelpButton;
private System.Windows.Forms.Button buttonPrevious;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelNavigation;
private System.Windows.Forms.Button buttonNext;
private WizardProgress wizardProgress;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private XenAdmin.Controls.DeprecationBanner deprecationBanner;
private System.Windows.Forms.TableLayoutPanel panelTop;
private System.Windows.Forms.Panel panelGeneralInformationMessage;
private System.Windows.Forms.Label labelGeneralInformationMessage;
private System.Windows.Forms.PictureBox pictureBoxGeneralInformationMessage;
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.Models
{
/// <summary>
/// A provincial-wide Equipment Type, the related Blue Book Chapter Section and related usage attributes.
/// </summary>
[MetaDataExtension (Description = "A provincial-wide Equipment Type, the related Blue Book Chapter Section and related usage attributes.")]
public partial class EquipmentType : AuditableEntity, IEquatable<EquipmentType>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public EquipmentType()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="EquipmentType" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for an EquipmentName (required).</param>
/// <param name="Name">The generic name of an equipment type - e.g. Dump Truck, Excavator and so on. (required).</param>
/// <param name="IsDumpTruck">True if the Equipment Type is a Dump Truck. Equipment of this type will have a related Dump Truck record containing dump truck-related attributes. (required).</param>
/// <param name="BlueBookSection">The section of the Blue Book that is related to equipment types of this name. (required).</param>
/// <param name="NumberOfBlocks">The number of blocks defined for the equipment of this name and Blue Book section. In general Dump Truck-class equipment types have 3 blocks, while non-Dump Truck equipment types have 2 blocks. (required).</param>
/// <param name="BlueBookRateNumber">The rate number in the Blue Book that is related to equipment types of this name..</param>
/// <param name="MaximumHours">The maximum number of hours per year that equipment types of this name&#x2F;Blue Book section can work in a year.</param>
/// <param name="ExtendHours">The number of extended hours per year that equipment types of this name&#x2F;Blue Book section can work..</param>
/// <param name="MaxHoursSub">The number of substitute hours per year that equipment types of this name&#x2F;Blue Book section can work..</param>
public EquipmentType(int Id, string Name, bool IsDumpTruck, float? BlueBookSection, int NumberOfBlocks, float? BlueBookRateNumber = null, float? MaximumHours = null, float? ExtendHours = null, float? MaxHoursSub = null)
{
this.Id = Id;
this.Name = Name;
this.IsDumpTruck = IsDumpTruck;
this.BlueBookSection = BlueBookSection;
this.NumberOfBlocks = NumberOfBlocks;
this.BlueBookRateNumber = BlueBookRateNumber;
this.MaximumHours = MaximumHours;
this.ExtendHours = ExtendHours;
this.MaxHoursSub = MaxHoursSub;
}
/// <summary>
/// A system-generated unique identifier for an EquipmentName
/// </summary>
/// <value>A system-generated unique identifier for an EquipmentName</value>
[MetaDataExtension (Description = "A system-generated unique identifier for an EquipmentName")]
public int Id { get; set; }
/// <summary>
/// The generic name of an equipment type - e.g. Dump Truck, Excavator and so on.
/// </summary>
/// <value>The generic name of an equipment type - e.g. Dump Truck, Excavator and so on.</value>
[MetaDataExtension (Description = "The generic name of an equipment type - e.g. Dump Truck, Excavator and so on.")]
[MaxLength(50)]
public string Name { get; set; }
/// <summary>
/// True if the Equipment Type is a Dump Truck. Equipment of this type will have a related Dump Truck record containing dump truck-related attributes.
/// </summary>
/// <value>True if the Equipment Type is a Dump Truck. Equipment of this type will have a related Dump Truck record containing dump truck-related attributes.</value>
[MetaDataExtension (Description = "True if the Equipment Type is a Dump Truck. Equipment of this type will have a related Dump Truck record containing dump truck-related attributes.")]
public bool IsDumpTruck { get; set; }
/// <summary>
/// The section of the Blue Book that is related to equipment types of this name.
/// </summary>
/// <value>The section of the Blue Book that is related to equipment types of this name.</value>
[MetaDataExtension (Description = "The section of the Blue Book that is related to equipment types of this name.")]
public float? BlueBookSection { get; set; }
/// <summary>
/// The number of blocks defined for the equipment of this name and Blue Book section. In general Dump Truck-class equipment types have 3 blocks, while non-Dump Truck equipment types have 2 blocks.
/// </summary>
/// <value>The number of blocks defined for the equipment of this name and Blue Book section. In general Dump Truck-class equipment types have 3 blocks, while non-Dump Truck equipment types have 2 blocks.</value>
[MetaDataExtension (Description = "The number of blocks defined for the equipment of this name and Blue Book section. In general Dump Truck-class equipment types have 3 blocks, while non-Dump Truck equipment types have 2 blocks.")]
public int NumberOfBlocks { get; set; }
/// <summary>
/// The rate number in the Blue Book that is related to equipment types of this name.
/// </summary>
/// <value>The rate number in the Blue Book that is related to equipment types of this name.</value>
[MetaDataExtension (Description = "The rate number in the Blue Book that is related to equipment types of this name.")]
public float? BlueBookRateNumber { get; set; }
/// <summary>
/// The maximum number of hours per year that equipment types of this name/Blue Book section can work in a year
/// </summary>
/// <value>The maximum number of hours per year that equipment types of this name/Blue Book section can work in a year</value>
[MetaDataExtension (Description = "The maximum number of hours per year that equipment types of this name/Blue Book section can work in a year")]
public float? MaximumHours { get; set; }
/// <summary>
/// The number of extended hours per year that equipment types of this name/Blue Book section can work.
/// </summary>
/// <value>The number of extended hours per year that equipment types of this name/Blue Book section can work.</value>
[MetaDataExtension (Description = "The number of extended hours per year that equipment types of this name/Blue Book section can work.")]
public float? ExtendHours { get; set; }
/// <summary>
/// The number of substitute hours per year that equipment types of this name/Blue Book section can work.
/// </summary>
/// <value>The number of substitute hours per year that equipment types of this name/Blue Book section can work.</value>
[MetaDataExtension (Description = "The number of substitute hours per year that equipment types of this name/Blue Book section can work.")]
public float? MaxHoursSub { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EquipmentType {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" IsDumpTruck: ").Append(IsDumpTruck).Append("\n");
sb.Append(" BlueBookSection: ").Append(BlueBookSection).Append("\n");
sb.Append(" NumberOfBlocks: ").Append(NumberOfBlocks).Append("\n");
sb.Append(" BlueBookRateNumber: ").Append(BlueBookRateNumber).Append("\n");
sb.Append(" MaximumHours: ").Append(MaximumHours).Append("\n");
sb.Append(" ExtendHours: ").Append(ExtendHours).Append("\n");
sb.Append(" MaxHoursSub: ").Append(MaxHoursSub).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((EquipmentType)obj);
}
/// <summary>
/// Returns true if EquipmentType instances are equal
/// </summary>
/// <param name="other">Instance of EquipmentType to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EquipmentType other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.IsDumpTruck == other.IsDumpTruck ||
this.IsDumpTruck.Equals(other.IsDumpTruck)
) &&
(
this.BlueBookSection == other.BlueBookSection ||
this.BlueBookSection != null &&
this.BlueBookSection.Equals(other.BlueBookSection)
) &&
(
this.NumberOfBlocks == other.NumberOfBlocks ||
this.NumberOfBlocks.Equals(other.NumberOfBlocks)
) &&
(
this.BlueBookRateNumber == other.BlueBookRateNumber ||
this.BlueBookRateNumber != null &&
this.BlueBookRateNumber.Equals(other.BlueBookRateNumber)
) &&
(
this.MaximumHours == other.MaximumHours ||
this.MaximumHours != null &&
this.MaximumHours.Equals(other.MaximumHours)
) &&
(
this.ExtendHours == other.ExtendHours ||
this.ExtendHours != null &&
this.ExtendHours.Equals(other.ExtendHours)
) &&
(
this.MaxHoursSub == other.MaxHoursSub ||
this.MaxHoursSub != null &&
this.MaxHoursSub.Equals(other.MaxHoursSub)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null)
{
hash = hash * 59 + this.Name.GetHashCode();
}
hash = hash * 59 + this.IsDumpTruck.GetHashCode();
if (this.BlueBookSection != null)
{
hash = hash * 59 + this.BlueBookSection.GetHashCode();
}
hash = hash * 59 + this.NumberOfBlocks.GetHashCode(); if (this.BlueBookRateNumber != null)
{
hash = hash * 59 + this.BlueBookRateNumber.GetHashCode();
}
if (this.MaximumHours != null)
{
hash = hash * 59 + this.MaximumHours.GetHashCode();
}
if (this.ExtendHours != null)
{
hash = hash * 59 + this.ExtendHours.GetHashCode();
}
if (this.MaxHoursSub != null)
{
hash = hash * 59 + this.MaxHoursSub.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(EquipmentType left, EquipmentType right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(EquipmentType left, EquipmentType right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.IO;
using System.Xml.Linq;
using System.Collections;
using System.Xml.XPath;
using System.Xml;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO.Compression;
namespace Template10.MSBUILD
{
/// <summary>
/// A custom MS BUILD Task that generates a Project Template ZIP file
/// and copies to the specified location. This is used to covert the existing
/// Template 10 projects into project templates for deployment via the
/// the VSIX.
/// </summary>
public class VSTemplateBuildTask : Microsoft.Build.Utilities.Task
{
#region ---- Private Variables ----------------
private string tempFolder;
private ItemFolder topFolder;
bool helpFileReferenceExists = false;
#endregion
#region ---- public properties -------
/// <summary>
/// Gets or sets the csproj file.
/// </summary>
/// <value>
/// The csproj file.
/// </value>
[Required]
public string CsprojFile { get; set; }
/// <summary>
/// Gets or sets the name of the zip.
/// </summary>
/// <value>
/// The name of the zip.
/// </value>
[Required]
public string ZipName { get; set; }
/// <summary>
/// Gets or sets the help URL.
/// </summary>
/// <value>
/// The help URL.
/// </value>
[Required]
public string HelpUrl { get; set; }
/// <summary>
/// Gets or sets the project description.
/// </summary>
/// <value>
/// The project description.
/// </value>
[Required]
public string ProjectDescription { get; set; }
/// <summary>
/// Gets or sets the preview image path.
/// </summary>
/// <value>
/// The preview image path.
/// </value>
[Required]
public string PreviewImagePath { get; set; }
/// <summary>
/// Gets or sets the name of the project friendly.
/// </summary>
/// <value>
/// The name of the project friendly.
/// </value>
[Required]
public string ProjectFriendlyName { get; set; }
/// <summary>
/// Gets or sets the source dir.
/// </summary>
/// <value>
/// The source dir.
/// </value>
[Required]
public string SourceDir { get; set; }
/// <summary>
/// Gets or sets the target dir.
/// </summary>
/// <value>
/// The target dir.
/// </value>
public string TargetDir { get; set; }
#endregion
/// <summary>
/// Executes this instance.
/// </summary>
/// <returns></returns>
public override bool Execute()
{
helpFileReferenceExists = false;
tempFolder = Path.Combine(TargetDir, Constants.TEMPFOLDER);
if (Directory.Exists(tempFolder))
{
Directory.Delete(tempFolder, true);
}
string projectFolder = Path.GetDirectoryName(CsprojFile);
CopyProjectFilesToTempFolder(projectFolder, tempFolder);
ReplaceNamespace(tempFolder);
FileHelper.DeleteKey(tempFolder);
ProcessVSTemplate(tempFolder);
OperateOnCsProj(tempFolder, CsprojFile);
OperateOnManifest(Path.Combine(tempFolder, "Package.appxmanifest"));
CopyEmbeddedFilesToOutput(tempFolder);
string jsonProj = Path.Combine(tempFolder, Constants.PROJECTJSON);
AddTemplate10Nuget(jsonProj);
SetupHelpFile(Path.Combine(tempFolder, Constants.HELPHTML), HelpUrl);
ZipFiles(tempFolder, ZipName, TargetDir);
return true;
}
/// <summary>
/// Replaces the namespace.
/// </summary>
/// <param name="tempFolder">The temporary folder.</param>
private void ReplaceNamespace(string tempFolder)
{
string csprojXml = FileHelper.ReadFile(CsprojFile);
string rootNamespace = GetExistingRootNamespace(csprojXml);
var ext = new List<string> { ".cs", ".xaml"};
var files = Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories).Where(s => ext.Any(e => s.EndsWith(e)));
foreach (var file in files)
{
string text = FileHelper.ReadFile(file);
//TODO: think about a safer way to do this... what if there is another use of RootNamespace string elsewhere... this will break the generated project.
text = text.Replace(rootNamespace, "$safeprojectname$");
FileHelper.WriteFile(file, text);
}
}
/// <summary>
/// Operates the on manifest.
/// </summary>
/// <param name="manifestFile">The manifest file.</param>
private void OperateOnManifest(string manifestFile)
{
string manifestText = FileHelper.ReadFile(manifestFile);
var replacements = new List<FindReplaceItem>();
replacements.Add(new FindReplaceItem() { Pattern = "<mp:PhoneIdentity(.*?)/>", Replacement = @"<mp:PhoneIdentity PhoneProductId=""$$guid9$$"" PhonePublisherId=""00000000-0000-0000-0000-000000000000""/>" });
replacements.Add(new FindReplaceItem() { Pattern = "<DisplayName>(.*?)</DisplayName>", Replacement = @"<DisplayName>$$projectname$$</DisplayName>" });
replacements.Add(new FindReplaceItem() { Pattern = "<PublisherDisplayName>(.*?)</PublisherDisplayName>", Replacement = @"<PublisherDisplayName>$$XmlEscapedPublisher$$</PublisherDisplayName>" });
replacements.Add(new FindReplaceItem() { Pattern = @"Executable=""(.*?)""", Replacement = @"Executable=""$$targetnametoken$$.exe""" });
replacements.Add(new FindReplaceItem() { Pattern = @"EntryPoint=""(.*?)""", Replacement = @"EntryPoint=""$$safeprojectname$$.App""" });
replacements.Add(new FindReplaceItem() { Pattern = @"DisplayName=""(.*?)""", Replacement = @"DisplayName=""$$projectname$$.App""" });
replacements.Add(new FindReplaceItem() { Pattern = @"EntryPoint=""(.*?)""", Replacement = @"EntryPoint=""$$projectname$$.App""" });
foreach (var item in replacements)
{
manifestText = Regex.Replace(manifestText, item.Pattern, item.Replacement);
}
manifestText = ReplaceIdentityNode(manifestText);
FileHelper.WriteFile(manifestFile, manifestText);
}
/// <summary>
/// Adds the template10 nuget.
/// </summary>
/// <param name="jsonProj">The json proj.</param>
private void AddTemplate10Nuget(string jsonProj)
{
string txt = FileHelper.ReadFile(jsonProj);
if (txt.Contains(Constants.TEMPLATE10))
{
return;
}
string template10Txt = Constants.TEMPLATE10PROJECTJSON;
string newtonsoft = Constants.NEWTONSOFT_PROJECTJSON;
txt = txt.Insert(txt.IndexOf(newtonsoft) + newtonsoft.Length, ",\n\r" + template10Txt);
FileHelper.WriteFile(jsonProj, txt);
}
/// <summary>
/// Sets up the help file, basically changing the redirect.
/// </summary>
/// <param name="helpFile">The help file.</param>
/// <param name="helpUrl">The help URL.</param>
private void SetupHelpFile(string helpFile, string helpUrl)
{
if (!File.Exists(helpFile))
return;
string helpText = FileHelper.ReadFile(helpFile);
helpText = helpText.Replace(Constants.HELPURL, helpUrl);
FileHelper.WriteFile(helpFile, helpText);
}
/// <summary>
/// Copies the project files to temporary folder.
/// </summary>
/// <param name="projectFolder">The project folder.</param>
/// <param name="tempFolder">The temporary folder.</param>
private void CopyProjectFilesToTempFolder(string projectFolder, string tempFolder)
{
FileHelper.DirectoryCopy(projectFolder, tempFolder, true);
}
/// <summary>
/// Processes the vs template.
/// </summary>
/// <param name="tempFolder">The temporary folder.</param>
private void ProcessVSTemplate(string tempFolder)
{
string xml = FileHelper.ReadFile(CsprojFile);
string projectName = Path.GetFileName(CsprojFile);
string projXml = GetProjectNode(xml, projectName);
xml = Constants.VSTEMPLATETEXT.Replace(Constants.PROJECTNODE, projXml);
xml = xml.Replace(Constants.TEMPLATENAME, ProjectFriendlyName);
xml = xml.Replace(Constants.TEMPLATEDESCRIPTION, ProjectDescription);
string previewFileName = Path.GetFileName(PreviewImagePath);
xml = xml.Replace(Constants.PREVIEWIMAGEFILE, previewFileName);
string filePath = Path.Combine(tempFolder, Constants.VSTEMPLATENAME);
FileHelper.WriteFile(filePath, xml);
}
/// <summary>
/// Zips the files.
/// </summary>
/// <param name="tempFolder">The temporary folder.</param>
/// <param name="zipName">Name of the zip.</param>
/// <param name="targetDir">The target dir.</param>
private void ZipFiles(string tempFolder, string zipName, string targetDir)
{
string zipFileName = Path.Combine(targetDir, ZipName);
if (File.Exists(zipFileName))
{
File.Delete(zipFileName);
}
ZipFile.CreateFromDirectory(tempFolder, zipFileName);
//-- clean up the temporary folder
Directory.Delete(tempFolder, true);
}
/// <summary>
/// Copies the embedded files to output.
/// </summary>
/// <param name="targetDir">The target dir.</param>
private void CopyEmbeddedFilesToOutput(string targetDir)
{
string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (var item in names)
{
using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(item))
{
var targetFile = Path.Combine(targetDir, Path.GetFileName(item.Substring(item.LastIndexOf("EmbeddedFiles.") + 14)));
using (var fileStream = File.Create(targetFile))
{
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(fileStream);
}
}
}
}
/// <summary>
/// Operates the on cs proj.
/// </summary>
/// <param name="tempFolder">The temporary folder.</param>
/// <param name="csprojFile">The csproj file.</param>
private void OperateOnCsProj(string tempFolder, string csprojFile)
{
string fileName = Path.GetFileName(CsprojFile);
string targetPath = Path.Combine(tempFolder, fileName);
File.Copy(CsprojFile, targetPath, true);
string csprojText = FileHelper.ReadFile(targetPath);
var replacements = new List<FindReplaceItem>();
replacements.Add(new FindReplaceItem() { Pattern = @"<PackageCertificateKeyFile>(.*?)</PackageCertificateKeyFile>", Replacement = @"<PackageCertificateKeyFile>$$projectname$$_TemporaryKey.pfx</PackageCertificateKeyFile>" });
replacements.Add(new FindReplaceItem() { Pattern = "<RootNamespace>(.*?)</RootNamespace>", Replacement = "<RootNamespace>$$safeprojectname$$</RootNamespace>" });
replacements.Add(new FindReplaceItem() { Pattern = "<AssemblyName>(.*?)</AssemblyName>", Replacement = "<AssemblyName>$$safeprojectname$$</AssemblyName>" });
replacements.Add(new FindReplaceItem() { Pattern = @"<None Include=""(.*?)_TemporaryKey.pfx"" />", Replacement = @"<None Include=""$$projectname$$_TemporaryKey.pfx"" />" });
replacements.Add(new FindReplaceItem() { Pattern = @"<ProjectGuid>(.*?)</ProjectGuid>", Replacement = @"<ProjectGuid>$guid1$</ProjectGuid>" });
foreach (var item in replacements)
{
csprojText = Regex.Replace(csprojText, item.Pattern, item.Replacement);
}
csprojText = RemoveItemNodeAround(@"csproj", csprojText);
csprojText = AddHelpToCSProj(csprojText);
FileHelper.WriteFile(targetPath, csprojText);
}
/// <summary>
/// Adds the help to cs proj.
/// </summary>
/// <param name="csprojText">The csproj text.</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private string AddHelpToCSProj(string csprojText)
{
//<Content Include="Help.htm" />
// <Content Include="Properties\Default.rd.xml" />
if (csprojText.ToLower().Contains("help.htm"))
{
return csprojText;
}
string findText = @"<Content Include=""Properties\Default.rd.xml"" />";
string helpText = @"<Content Include=""Help.htm"" />";
csprojText = csprojText.Replace(findText, helpText + findText);
return csprojText;
}
/// <summary>
/// Gets the existing root namespace.
/// </summary>
/// <param name="csprojxml">The csprojxml.</param>
/// <returns></returns>
private string GetExistingRootNamespace(string csprojxml)
{
XDocument xdoc;
using (StringReader sr = new StringReader(csprojxml))
{
xdoc = XDocument.Load(sr, LoadOptions.None);
}
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
return xdoc.Descendants(ns + "RootNamespace").FirstOrDefault().Value;
}
/// <summary>
/// Removes the item node around the specified text. This is used to remove the csproj reference in the csproj file which will be replaced by a project.json NuGet reference instead.
/// </summary>
/// <param name="findText">The find text.</param>
/// <param name="csprojText">The csproj text.</param>
/// <returns></returns>
private string RemoveItemNodeAround(string findText, string csprojText)
{
if (!csprojText.Contains(findText))
{
return csprojText;
}
int findTextIndex, start, end;
string firstHalf, lastHalf;
findTextIndex = csprojText.IndexOf(findText);
start = csprojText.Substring(0, findTextIndex).LastIndexOf("<ItemGroup>");
end = csprojText.IndexOf("</ItemGroup>", findTextIndex);
firstHalf = csprojText.Substring(0, start);
lastHalf = csprojText.Substring(end + 12);
return firstHalf + lastHalf;
}
/// <summary>
/// Replaces the identity node.
/// </summary>
/// <param name="manifestText">The manifest text.</param>
/// <returns></returns>
private string ReplaceIdentityNode(string manifestText)
{
string findText = @"<Identity";
if (!manifestText.Contains(findText))
{
return manifestText;
}
string identityReplacementText = @"<Identity
Name=""$guid9$""
Publisher = ""$XmlEscapedPublisherDistinguishedName$""
Version = ""1.0.0.0"" /> ";
int findTextIndex, start, end;
string firstHalf, lastHalf;
findTextIndex = manifestText.IndexOf(findText);
start = findTextIndex;
end = manifestText.IndexOf("/>", findTextIndex);
firstHalf = manifestText.Substring(0, start);
lastHalf = manifestText.Substring(end + 2);
return firstHalf + identityReplacementText + lastHalf;
}
/// <summary>
/// Gets the project node.
/// </summary>
/// <param name="csprojxml">The csprojxml.</param>
/// <param name="projectFileName">Name of the project file.</param>
/// <returns></returns>
public string GetProjectNode(string csprojxml, string projectFileName)
{
string projectNodeStart = @"<Project TargetFileName=""$projectName"" File=""$projectName"" ReplaceParameters=""true"">";
projectNodeStart = projectNodeStart.Replace("$projectName", projectFileName);
//string projectName = GetProjectName(csprojxml);
List<string> projectItems = GetProjectItems(csprojxml);
//-- sorting for directories
projectItems = SortProjectItems(projectItems);
GetItemFolder(projectItems);
string foldersString = SerializeFolder(topFolder);
if (!helpFileReferenceExists)
{
foldersString = InsertHelp(foldersString);
}
using (StringWriter writer = new StringWriter())
{
writer.WriteLine(projectNodeStart);
writer.WriteLine(foldersString);
writer.WriteLine("</Project>");
return writer.ToString();
}
}
/// <summary>
/// Inserts the help.
/// </summary>
/// <param name="foldersString">The folders string.</param>
/// <returns></returns>
private string InsertHelp(string foldersString)
{
string helpString = @"<ProjectItem ReplaceParameters=""false"" TargetFileName=""help.htm"" OpenInWebBrowser=""true"">help.htm</ProjectItem>";
return helpString + foldersString;
}
/// <summary>
/// Serializes the folder.
/// </summary>
/// <param name="topFolder">The top folder.</param>
/// <returns></returns>
private string SerializeFolder(ItemFolder topFolder)
{
string folderString = string.Empty;
string projItemNodeTemplate = @"<ProjectItem ReplaceParameters = ""true"" TargetFileName=""$filename"">$filename</ProjectItem>";
string folderItemNodeTemplate = @"<Folder Name=""$folderName"" TargetFolderName=""$folderName"" >";
if (topFolder.FolderName != null)
{
folderString = folderItemNodeTemplate.Replace("$folderName", topFolder.FolderName);
}
foreach (var item in topFolder.Items)
{
if (IsHelpItem(item))
{
folderString = folderString + @"<ProjectItem ReplaceParameters=""false"" TargetFileName=""help.htm"" OpenInWebBrowser=""true"">help.htm</ProjectItem>";
helpFileReferenceExists = true;
}
else if (IsKeyProjectItemNode(item))
folderString = folderString + @"<ProjectItem ReplaceParameters=""false"" TargetFileName=""$projectname$_TemporaryKey.pfx"" BlendDoNotCreate=""true"">Application_TemporaryKey.pfx</ProjectItem>";
else
{
//-- now writing item.
if (!string.IsNullOrEmpty(item) && !item.Contains("csproj") && !item.Contains(".."))
{
folderString = folderString + projItemNodeTemplate.Replace("$filename", item);
}
}
}
foreach (var folderItem in topFolder.Folders)
{
folderString = folderString + SerializeFolder(folderItem);
}
if (topFolder.FolderName != null)
{
folderString = folderString + "</Folder>";
}
return folderString;
}
/// <summary>
/// Determines whether [is help item] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
private bool IsHelpItem(string item)
{
return item.ToLower().Contains("help.htm");
}
/// <summary>
/// Gets the item folder.
/// </summary>
/// <param name="projectItems">The project items.</param>
private void GetItemFolder(List<string> projectItems)
{
topFolder = new ItemFolder();
string[] stringSeparator = new string[] { @"\" };
foreach (var item in projectItems)
{
var parts = item.Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries);
AddPartsToTopFolder(parts);
}
}
/// <summary>
/// Adds the parts to top folder.
/// </summary>
/// <param name="parts">The parts.</param>
private void AddPartsToTopFolder(string[] parts)
{
AddPartsToFolder(topFolder, parts, 0);
}
/// <summary>
/// Adds the parts to folder.
/// </summary>
/// <param name="currentFolder">The current folder.</param>
/// <param name="parts">The parts.</param>
/// <param name="partIndex">Index of the part.</param>
private void AddPartsToFolder(ItemFolder currentFolder, string[] parts, int partIndex)
{
//-- empty folder
if (partIndex >= parts.Length)
return;
string part = parts[partIndex];
if (!IsFolder(part))
{
currentFolder.Items.Add(part);
return;
}
var folder = currentFolder.Folders.FirstOrDefault(e => e.FolderName == part);
if (folder == null)
{
folder = new ItemFolder() { FolderName = part };
currentFolder.Folders.Add(folder);
}
AddPartsToFolder(folder, parts, ++partIndex);
}
/// <summary>
/// Determines whether the specified part is folder.
/// </summary>
/// <param name="part">The part.</param>
/// <returns></returns>
private bool IsFolder(string part)
{
return !part.Contains(".");
}
/// <summary>
/// Sorts the project items.
/// </summary>
/// <param name="projectItems">The project items.</param>
/// <returns></returns>
private List<string> SortProjectItems(List<string> projectItems)
{
projectItems.Sort();
var l2 = new List<string>();
foreach (var item in projectItems)
{
if (!item.Contains(@"\"))
l2.Insert(0, item);
else
l2.Add(item);
}
projectItems = l2;
return projectItems;
}
/// <summary>
/// Gets the name of the folder.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
private string GetFolderName(string item)
{
int startIndex = item.IndexOf(@"\");
return item.Substring(0, startIndex);
}
/// <summary>
/// Determines whether [is key project item node] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
private bool IsKeyProjectItemNode(string item)
{
return item.Contains(".pfx");
}
/// <summary>
/// Gets the project items.
/// </summary>
/// <param name="csprojxml">The csprojxml.</param>
/// <returns></returns>
private List<string> GetProjectItems(string csprojxml)
{
List<string> files = new List<string>(); ;
XDocument xdoc;
using (StringReader sr = new StringReader(csprojxml))
{
xdoc = XDocument.Load(sr, LoadOptions.None);
}
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var items = xdoc.Descendants(ns + "ItemGroup");
string itemString = string.Empty;
foreach (var itemG in items)
{
foreach (var item in itemG.Elements())
{
itemString = item.Attribute("Include").Value;
if (!string.IsNullOrEmpty(itemString) && !itemString.Contains("=") && !itemString.Contains(","))
{
files.Add(itemString);
}
}
}
return files;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup
{
internal partial class EventHookupCommandHandler : ICommandHandler<TabKeyCommandArgs>
{
public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup))
{
nextHandler();
return;
}
if (EventHookupSessionManager.CurrentSession == null)
{
nextHandler();
return;
}
// Handling tab is currently uncancellable.
HandleTabWorker(args.TextView, args.SubjectBuffer, nextHandler, CancellationToken.None);
}
public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (EventHookupSessionManager.CurrentSession != null)
{
return CommandState.Available;
}
else
{
return nextHandler();
}
}
private void HandleTabWorker(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, CancellationToken cancellationToken)
{
AssertIsForeground();
// For test purposes only!
if (EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex != null)
{
try
{
EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex.ReleaseMutex();
}
catch (ApplicationException)
{
}
}
// Blocking wait (if necessary) to determine whether to consume the tab and
// generate the event handler.
EventHookupSessionManager.CurrentSession.GetEventNameTask.Wait(cancellationToken);
string eventHandlerMethodName = null;
if (EventHookupSessionManager.CurrentSession.GetEventNameTask.Status == TaskStatus.RanToCompletion)
{
eventHandlerMethodName = EventHookupSessionManager.CurrentSession.GetEventNameTask.WaitAndGetResult(cancellationToken);
}
if (eventHandlerMethodName == null ||
EventHookupSessionManager.CurrentSession.TextView != textView)
{
nextHandler();
EventHookupSessionManager.CancelAndDismissExistingSessions();
return;
}
// If QuickInfoSession is null, then Tab was pressed before the background task
// finished (that is, the Wait call above actually needed to wait). Since we know an
// event hookup was found, we should set everything up now because the background task
// will not have a chance to set things up until after this Tab has been handled, and
// by then it's too late. When the background task alerts that it found an event hookup
// nothing will change because QuickInfoSession will already be set.
EventHookupSessionManager.EventHookupFoundInSession(EventHookupSessionManager.CurrentSession);
// This tab means we should generate the event handler method. Begin the code
// generation process.
GenerateAndAddEventHandler(textView, subjectBuffer, eventHandlerMethodName, nextHandler, cancellationToken);
}
private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectBuffer, string eventHandlerMethodName, Action nextHandler, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.EventHookup_Generate_Handler, cancellationToken))
{
EventHookupSessionManager.CancelAndDismissExistingSessions();
var workspace = textView.TextSnapshot.TextBuffer.GetWorkspace();
if (workspace == null)
{
nextHandler();
EventHookupSessionManager.CancelAndDismissExistingSessions();
return;
}
Document document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
Contract.Fail("Event Hookup could not find the document for the IBufferView.");
}
var position = textView.GetCaretPoint(subjectBuffer).Value.Position;
var solutionWithEventHandler = CreateSolutionWithEventHandler(
document,
eventHandlerMethodName,
position,
out var plusEqualTokenEndPosition,
cancellationToken);
if (solutionWithEventHandler == null)
{
Contract.Fail("Event Hookup could not create solution with event handler.");
}
// The new solution is created, so start user observable changes
if (!workspace.TryApplyChanges(solutionWithEventHandler))
{
Contract.Fail("Event Hookup could not update the solution.");
}
// The += token will not move during this process, so it is safe to use that
// position as a location from which to find the identifier we're renaming.
BeginInlineRename(workspace, textView, subjectBuffer, plusEqualTokenEndPosition, cancellationToken);
}
}
private Solution CreateSolutionWithEventHandler(
Document document,
string eventHandlerMethodName,
int position,
out int plusEqualTokenEndPosition,
CancellationToken cancellationToken)
{
AssertIsForeground();
// Mark the += token with an annotation so we can find it after formatting
var plusEqualsTokenAnnotation = new SyntaxAnnotation();
var documentWithNameAndAnnotationsAdded = AddMethodNameAndAnnotationsToSolution(document, eventHandlerMethodName, position, plusEqualsTokenAnnotation, cancellationToken);
var semanticDocument = SemanticDocument.CreateAsync(documentWithNameAndAnnotationsAdded, cancellationToken).WaitAndGetResult(cancellationToken);
var updatedRoot = AddGeneratedHandlerMethodToSolution(semanticDocument, eventHandlerMethodName, plusEqualsTokenAnnotation, cancellationToken);
if (updatedRoot == null)
{
plusEqualTokenEndPosition = 0;
return null;
}
var simplifiedDocument = Simplifier.ReduceAsync(documentWithNameAndAnnotationsAdded.WithSyntaxRoot(updatedRoot), Simplifier.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
var formattedDocument = Formatter.FormatAsync(simplifiedDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
var newRoot = formattedDocument.GetSyntaxRootSynchronously(cancellationToken);
plusEqualTokenEndPosition = newRoot.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation)
.Single().Span.End;
return document.Project.Solution.WithDocumentText(
formattedDocument.Id, formattedDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken));
}
private Document AddMethodNameAndAnnotationsToSolution(
Document document,
string eventHandlerMethodName,
int position,
SyntaxAnnotation plusEqualsTokenAnnotation,
CancellationToken cancellationToken)
{
// First find the event hookup to determine if we are in a static context.
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var plusEqualsToken = root.FindTokenOnLeftOfPosition(position);
var eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>();
var textToInsert = eventHandlerMethodName + ";";
if (!eventHookupExpression.IsInStaticContext())
{
// This will be simplified later if it's not needed.
textToInsert = "this." + textToInsert;
}
// Next, perform a textual insertion of the event handler method name.
var textChange = new TextChange(new TextSpan(position, 0), textToInsert);
var newText = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).WithChanges(textChange);
var documentWithNameAdded = document.WithText(newText);
// Now find the event hookup again to add the appropriate annotations.
root = documentWithNameAdded.GetSyntaxRootSynchronously(cancellationToken);
plusEqualsToken = root.FindTokenOnLeftOfPosition(position);
eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>();
var updatedEventHookupExpression = eventHookupExpression
.ReplaceToken(plusEqualsToken, plusEqualsToken.WithAdditionalAnnotations(plusEqualsTokenAnnotation))
.WithRight(eventHookupExpression.Right.WithAdditionalAnnotations(Simplifier.Annotation))
.WithAdditionalAnnotations(Formatter.Annotation);
var rootWithUpdatedEventHookupExpression = root.ReplaceNode(eventHookupExpression, updatedEventHookupExpression);
return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression);
}
private SyntaxNode AddGeneratedHandlerMethodToSolution(
SemanticDocument document,
string eventHandlerMethodName,
SyntaxAnnotation plusEqualsTokenAnnotation,
CancellationToken cancellationToken)
{
var root = document.Root as SyntaxNode;
var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor<AssignmentExpressionSyntax>();
var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken);
if (generatedMethodSymbol == null)
{
return null;
}
var typeDecl = eventHookupExpression.GetAncestor<TypeDeclarationSyntax>();
var typeDeclWithMethodAdded = CodeGenerator.AddMethodDeclaration(typeDecl, generatedMethodSymbol, document.Project.Solution.Workspace, new CodeGenerationOptions(afterThisLocation: eventHookupExpression.GetLocation()));
return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded);
}
private IMethodSymbol GetMethodSymbol(
SemanticDocument document,
string eventHandlerMethodName,
AssignmentExpressionSyntax eventHookupExpression,
CancellationToken cancellationToken)
{
var semanticModel = document.SemanticModel as SemanticModel;
var symbolInfo = semanticModel.GetSymbolInfo(eventHookupExpression.Left, cancellationToken);
var symbol = symbolInfo.Symbol;
if (symbol == null || symbol.Kind != SymbolKind.Event)
{
return null;
}
var typeInference = document.Project.LanguageServices.GetService<ITypeInferenceService>();
var delegateType = typeInference.InferDelegateType(semanticModel, eventHookupExpression.Right, cancellationToken);
if (delegateType == null || delegateType.DelegateInvokeMethod == null)
{
return null;
}
var syntaxFactory = document.Project.LanguageServices.GetService<SyntaxGenerator>();
return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: null,
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()),
returnType: delegateType.DelegateInvokeMethod.ReturnType,
explicitInterfaceSymbol: null,
name: eventHandlerMethodName,
typeParameters: null,
parameters: delegateType.DelegateInvokeMethod.Parameters,
statements: new List<SyntaxNode>
{
CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, document, "System.NotImplementedException", cancellationToken)
});
}
private void BeginInlineRename(Workspace workspace, ITextView textView, ITextBuffer subjectBuffer, int plusEqualTokenEndPosition, CancellationToken cancellationToken)
{
AssertIsForeground();
if (_inlineRenameService.ActiveSession == null)
{
var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
// In the middle of a user action, cannot cancel.
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var token = root.FindTokenOnRightOfPosition(plusEqualTokenEndPosition);
var editSpan = token.Span;
var memberAccessExpression = token.GetAncestor<MemberAccessExpressionSyntax>();
if (memberAccessExpression != null)
{
// the event hookup might look like `MyEvent += this.GeneratedHandlerName;`
editSpan = memberAccessExpression.Name.Span;
}
_inlineRenameService.StartInlineSession(document, editSpan, cancellationToken);
textView.SetSelection(editSpan.ToSnapshotSpan(textView.TextSnapshot));
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
namespace M2SA.AppGenome.Threading
{
/// <summary>
///
/// </summary>
public interface ISTPPerformanceCountersReader
{
/// <summary>
///
/// </summary>
long InUseThreads { get; }
/// <summary>
///
/// </summary>
long ActiveThreads { get; }
/// <summary>
///
/// </summary>
long WorkItemsQueued { get; }
/// <summary>
///
/// </summary>
long WorkItemsProcessed { get; }
}
}
namespace M2SA.AppGenome.Threading.Internal
{
/// <summary>
///
/// </summary>
internal interface ISTPInstancePerformanceCounters : IDisposable
{
void Close();
void SampleThreads(long activeThreads, long inUseThreads);
void SampleWorkItems(long workItemsQueued, long workItemsProcessed);
void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime);
void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime);
}
#if !(_WINDOWS_CE) && !(_SILVERLIGHT)
internal enum STPPerformanceCounterType
{
// Fields
ActiveThreads = 0,
InUseThreads = 1,
OverheadThreads = 2,
OverheadThreadsPercent = 3,
OverheadThreadsPercentBase = 4,
WorkItems = 5,
WorkItemsInQueue = 6,
WorkItemsProcessed = 7,
WorkItemsQueuedPerSecond = 8,
WorkItemsProcessedPerSecond = 9,
AvgWorkItemWaitTime = 10,
AvgWorkItemWaitTimeBase = 11,
AvgWorkItemProcessTime = 12,
AvgWorkItemProcessTimeBase = 13,
WorkItemsGroups = 14,
LastCounter = 14,
}
/// <summary>
/// Summary description for STPPerformanceCounter.
/// </summary>
internal class STPPerformanceCounter
{
// Fields
private readonly PerformanceCounterType _pcType;
protected string _counterHelp;
protected string _counterName;
// Methods
public STPPerformanceCounter(
string counterName,
string counterHelp,
PerformanceCounterType pcType)
{
_counterName = counterName;
_counterHelp = counterHelp;
_pcType = pcType;
}
public void AddCounterToCollection(CounterCreationDataCollection counterData)
{
CounterCreationData counterCreationData = new CounterCreationData(
_counterName,
_counterHelp,
_pcType);
counterData.Add(counterCreationData);
}
// Properties
public string Name
{
get
{
return _counterName;
}
}
}
internal class STPPerformanceCounters
{
// Fields
internal STPPerformanceCounter[] _stpPerformanceCounters;
private static readonly STPPerformanceCounters _instance;
internal const string _stpCategoryHelp = "SmartThreadPool performance counters";
internal const string _stpCategoryName = "SmartThreadPool";
// Methods
static STPPerformanceCounters()
{
_instance = new STPPerformanceCounters();
}
private STPPerformanceCounters()
{
STPPerformanceCounter[] stpPerformanceCounters = new STPPerformanceCounter[]
{
new STPPerformanceCounter("Active threads", "The current number of available in the thread pool.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("In use threads", "The current number of threads that execute a work item.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Overhead threads", "The current number of threads that are active, but are not in use.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("% overhead threads", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawFraction),
new STPPerformanceCounter("% overhead threads base", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawBase),
new STPPerformanceCounter("Work Items", "The number of work items in the Smart Thread Pool. Both queued and processed.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items in queue", "The current number of work items in the queue", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items processed", "The number of work items already processed", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items queued/sec", "The number of work items queued per second", PerformanceCounterType.RateOfCountsPerSecond32),
new STPPerformanceCounter("Work Items processed/sec", "The number of work items processed per second", PerformanceCounterType.RateOfCountsPerSecond32),
new STPPerformanceCounter("Avg. Work Item wait time/sec", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageCount64),
new STPPerformanceCounter("Avg. Work Item wait time base", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageBase),
new STPPerformanceCounter("Avg. Work Item process time/sec", "The average time it takes to process a work item.", PerformanceCounterType.AverageCount64),
new STPPerformanceCounter("Avg. Work Item process time base", "The average time it takes to process a work item.", PerformanceCounterType.AverageBase),
new STPPerformanceCounter("Work Items Groups", "The current number of work item groups associated with the Smart Thread Pool.", PerformanceCounterType.NumberOfItems32),
};
_stpPerformanceCounters = stpPerformanceCounters;
SetupCategory();
}
private void SetupCategory()
{
if (!PerformanceCounterCategory.Exists(_stpCategoryName))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
for (int i = 0; i < _stpPerformanceCounters.Length; i++)
{
_stpPerformanceCounters[i].AddCounterToCollection(counters);
}
PerformanceCounterCategory.Create(
_stpCategoryName,
_stpCategoryHelp,
PerformanceCounterCategoryType.MultiInstance,
counters);
}
}
// Properties
public static STPPerformanceCounters Instance
{
get
{
return _instance;
}
}
}
internal class STPInstancePerformanceCounter : IDisposable
{
// Fields
private bool _isDisposed;
private PerformanceCounter _pcs;
// Methods
protected STPInstancePerformanceCounter()
{
_isDisposed = false;
}
public STPInstancePerformanceCounter(
string instance,
STPPerformanceCounterType spcType) : this()
{
STPPerformanceCounters counters = STPPerformanceCounters.Instance;
_pcs = new PerformanceCounter(
STPPerformanceCounters._stpCategoryName,
counters._stpPerformanceCounters[(int) spcType].Name,
instance,
false);
_pcs.RawValue = _pcs.RawValue;
}
public void Close()
{
if (_pcs != null)
{
_pcs.RemoveInstance();
_pcs.Close();
_pcs = null;
}
}
public void Dispose()
{
Dispose(true);
}
public virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
}
}
_isDisposed = true;
}
public virtual void Increment()
{
_pcs.Increment();
}
public virtual void IncrementBy(long val)
{
_pcs.IncrementBy(val);
}
public virtual void Set(long val)
{
_pcs.RawValue = val;
}
}
internal class STPInstanceNullPerformanceCounter : STPInstancePerformanceCounter
{
// Methods
public override void Increment() {}
public override void IncrementBy(long value) {}
public override void Set(long val) {}
}
internal class STPInstancePerformanceCounters : ISTPInstancePerformanceCounters
{
private bool _isDisposed;
// Fields
private STPInstancePerformanceCounter[] _pcs;
private static readonly STPInstancePerformanceCounter _stpInstanceNullPerformanceCounter;
// Methods
static STPInstancePerformanceCounters()
{
_stpInstanceNullPerformanceCounter = new STPInstanceNullPerformanceCounter();
}
public STPInstancePerformanceCounters(string instance)
{
_isDisposed = false;
_pcs = new STPInstancePerformanceCounter[(int)STPPerformanceCounterType.LastCounter];
// Call the STPPerformanceCounters.Instance so the static constructor will
// intialize the STPPerformanceCounters singleton.
STPPerformanceCounters.Instance.GetHashCode();
for (int i = 0; i < _pcs.Length; i++)
{
if (instance != null)
{
_pcs[i] = new STPInstancePerformanceCounter(
instance,
(STPPerformanceCounterType) i);
}
else
{
_pcs[i] = _stpInstanceNullPerformanceCounter;
}
}
}
public void Close()
{
if (null != _pcs)
{
for (int i = 0; i < _pcs.Length; i++)
{
if (null != _pcs[i])
{
_pcs[i].Dispose();
}
}
_pcs = null;
}
}
public void Dispose()
{
Dispose(true);
}
public virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
}
}
_isDisposed = true;
}
private STPInstancePerformanceCounter GetCounter(STPPerformanceCounterType spcType)
{
return _pcs[(int) spcType];
}
public void SampleThreads(long activeThreads, long inUseThreads)
{
GetCounter(STPPerformanceCounterType.ActiveThreads).Set(activeThreads);
GetCounter(STPPerformanceCounterType.InUseThreads).Set(inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreads).Set(activeThreads-inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreadsPercentBase).Set(activeThreads-inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreadsPercent).Set(inUseThreads);
}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed)
{
GetCounter(STPPerformanceCounterType.WorkItems).Set(workItemsQueued+workItemsProcessed);
GetCounter(STPPerformanceCounterType.WorkItemsInQueue).Set(workItemsQueued);
GetCounter(STPPerformanceCounterType.WorkItemsProcessed).Set(workItemsProcessed);
GetCounter(STPPerformanceCounterType.WorkItemsQueuedPerSecond).Set(workItemsQueued);
GetCounter(STPPerformanceCounterType.WorkItemsProcessedPerSecond).Set(workItemsProcessed);
}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime)
{
GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTime).IncrementBy((long)workItemWaitTime.TotalMilliseconds);
GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTimeBase).Increment();
}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime)
{
GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTime).IncrementBy((long)workItemProcessTime.TotalMilliseconds);
GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTimeBase).Increment();
}
}
#endif
internal class NullSTPInstancePerformanceCounters : ISTPInstancePerformanceCounters, ISTPPerformanceCountersReader
{
private static readonly NullSTPInstancePerformanceCounters _instance = new NullSTPInstancePerformanceCounters();
public static NullSTPInstancePerformanceCounters Instance
{
get { return _instance; }
}
public void Close() {}
public void Dispose() {}
public void SampleThreads(long activeThreads, long inUseThreads) {}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed) {}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime) {}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime) {}
public long InUseThreads
{
get { return 0; }
}
public long ActiveThreads
{
get { return 0; }
}
public long WorkItemsQueued
{
get { return 0; }
}
public long WorkItemsProcessed
{
get { return 0; }
}
}
internal class LocalSTPInstancePerformanceCounters : ISTPInstancePerformanceCounters, ISTPPerformanceCountersReader
{
public void Close() { }
public void Dispose() { }
private long _activeThreads;
private long _inUseThreads;
private long _workItemsQueued;
private long _workItemsProcessed;
public long InUseThreads
{
get { return _inUseThreads; }
}
public long ActiveThreads
{
get { return _activeThreads; }
}
public long WorkItemsQueued
{
get { return _workItemsQueued; }
}
public long WorkItemsProcessed
{
get { return _workItemsProcessed; }
}
public void SampleThreads(long activeThreads, long inUseThreads)
{
_activeThreads = activeThreads;
_inUseThreads = inUseThreads;
}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed)
{
_workItemsQueued = workItemsQueued;
_workItemsProcessed = workItemsProcessed;
}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime)
{
// Not supported
}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime)
{
// Not supported
}
}
}
| |
//
// DefaultSecureMimeContext.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Pkix;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.Smime;
using Org.BouncyCastle.X509.Store;
namespace MimeKit.Cryptography {
/// <summary>
/// A default <see cref="SecureMimeContext"/> implementation that uses
/// an SQLite database as a certificate and private key store.
/// </summary>
/// <remarks>
/// The default S/MIME context is designed to be usable on any platform
/// where there exists a .NET runtime by storing certificates, CRLs, and
/// (encrypted) private keys in a SQLite database.
/// </remarks>
public class DefaultSecureMimeContext : SecureMimeContext
{
const X509CertificateRecordFields CmsRecipientFields = X509CertificateRecordFields.Algorithms | X509CertificateRecordFields.Certificate;
const X509CertificateRecordFields CmsSignerFields = X509CertificateRecordFields.Certificate | X509CertificateRecordFields.PrivateKey;
const X509CertificateRecordFields AlgorithmFields = X509CertificateRecordFields.Id | X509CertificateRecordFields.Algorithms | X509CertificateRecordFields.AlgorithmsUpdated;
const X509CertificateRecordFields ImportPkcs12Fields = AlgorithmFields | X509CertificateRecordFields.Trusted | X509CertificateRecordFields.PrivateKey;
/// <summary>
/// The default database path for certificates, private keys and CRLs.
/// </summary>
/// <remarks>
/// <para>On Microsoft Windows-based systems, this path will be something like <c>C:\Users\UserName\AppData\Roaming\mimekit\smime.db</c>.</para>
/// <para>On Unix systems such as Linux and Mac OS X, this path will be <c>~/.mimekit/smime.db</c>.</para>
/// </remarks>
public static readonly string DefaultDatabasePath;
readonly IX509CertificateDatabase dbase;
static DefaultSecureMimeContext ()
{
string path;
#if !COREFX
if (Path.DirectorySeparatorChar == '\\') {
var appData = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
path = Path.Combine (appData, "Roaming\\mimekit");
} else {
var home = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
path = Path.Combine (home, ".mimekit");
}
#else
path = ".mimekit";
#endif
if (!Directory.Exists (path))
Directory.CreateDirectory (path);
DefaultDatabasePath = Path.Combine (path, "smime.db");
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.DefaultSecureMimeContext"/> class.
/// </summary>
/// <remarks>
/// <para>Allows the program to specify its own location for the SQLite database. If the file does not exist,
/// it will be created and the necessary tables and indexes will be constructed.</para>
/// <para>Requires linking with Mono.Data.Sqlite.</para>
/// </remarks>
/// <param name="fileName">The path to the SQLite database.</param>
/// <param name="password">The password used for encrypting and decrypting the private keys.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="fileName"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The specified file path is empty.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// Mono.Data.Sqlite is not available.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to read the specified file.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the file.
/// </exception>
public DefaultSecureMimeContext (string fileName, string password)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (password == null)
throw new ArgumentNullException ("password");
var dir = Path.GetDirectoryName (fileName);
var exists = File.Exists (fileName);
if (!string.IsNullOrEmpty (dir) && !Directory.Exists (dir))
Directory.CreateDirectory (dir);
if (SqliteCertificateDatabase.IsAvailable)
dbase = new SqliteCertificateDatabase (fileName, password);
else
throw new NotSupportedException ("Mono.Data.Sqlite is not available.");
if (!exists) {
// TODO: initialize our dbase with some root CA certificates.
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.DefaultSecureMimeContext"/> class.
/// </summary>
/// <remarks>
/// <para>Allows the program to specify its own password for the default database.</para>
/// <para>Requires linking with Mono.Data.Sqlite.</para>
/// </remarks>
/// <param name="password">The password used for encrypting and decrypting the private keys.</param>
/// <exception cref="System.NotImplementedException">
/// Mono.Data.Sqlite is not available.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to read the database at the default location.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the database at the default location.
/// </exception>
public DefaultSecureMimeContext (string password) : this (DefaultDatabasePath, password)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.DefaultSecureMimeContext"/> class.
/// </summary>
/// <remarks>
/// <para>Not recommended for production use as the password to unlock the private keys is hard-coded.</para>
/// <para>Requires linking with Mono.Data.Sqlite.</para>
/// </remarks>
/// <exception cref="System.NotImplementedException">
/// Mono.Data.Sqlite is not available.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to read the database at the default location.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the database at the default location.
/// </exception>
public DefaultSecureMimeContext () : this (DefaultDatabasePath, "no.secret")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.DefaultSecureMimeContext"/> class.
/// </summary>
/// <remarks>
/// This constructor is useful for supplying a custom <see cref="IX509CertificateDatabase"/>.
/// </remarks>
/// <param name="database">The certificate database.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="database"/> is <c>null</c>.
/// </exception>
public DefaultSecureMimeContext (IX509CertificateDatabase database)
{
if (database == null)
throw new ArgumentNullException ("database");
dbase = database;
}
#region implemented abstract members of SecureMimeContext
/// <summary>
/// Gets the X.509 certificate matching the specified selector.
/// </summary>
/// <remarks>
/// Gets the first certificate that matches the specified selector.
/// </remarks>
/// <returns>The certificate on success; otherwise <c>null</c>.</returns>
/// <param name="selector">The search criteria for the certificate.</param>
protected override X509Certificate GetCertificate (IX509Selector selector)
{
return dbase.FindCertificates (selector).FirstOrDefault ();
}
/// <summary>
/// Gets the private key for the certificate matching the specified selector.
/// </summary>
/// <remarks>
/// Gets the private key for the first certificate that matches the specified selector.
/// </remarks>
/// <returns>The private key on success; otherwise <c>null</c>.</returns>
/// <param name="selector">The search criteria for the private key.</param>
protected override AsymmetricKeyParameter GetPrivateKey (IX509Selector selector)
{
return dbase.FindPrivateKeys (selector).FirstOrDefault ();
}
/// <summary>
/// Gets the trusted anchors.
/// </summary>
/// <remarks>
/// A trusted anchor is a trusted root-level X.509 certificate,
/// generally issued by a Certificate Authority (CA).
/// </remarks>
/// <returns>The trusted anchors.</returns>
protected override Org.BouncyCastle.Utilities.Collections.HashSet GetTrustedAnchors ()
{
var anchors = new Org.BouncyCastle.Utilities.Collections.HashSet ();
var selector = new X509CertStoreSelector ();
var keyUsage = new bool[9];
keyUsage[(int) X509KeyUsageBits.KeyCertSign] = true;
selector.KeyUsage = keyUsage;
foreach (var record in dbase.Find (selector, true, X509CertificateRecordFields.Certificate)) {
anchors.Add (new TrustAnchor (record.Certificate, null));
}
return anchors;
}
/// <summary>
/// Gets the intermediate certificates.
/// </summary>
/// <remarks>
/// An intermediate certificate is any certificate that exists between the root
/// certificate issued by a Certificate Authority (CA) and the certificate at
/// the end of the chain.
/// </remarks>
/// <returns>The intermediate certificates.</returns>
protected override IX509Store GetIntermediateCertificates ()
{
return dbase;
}
/// <summary>
/// Gets the certificate revocation lists.
/// </summary>
/// <remarks>
/// A Certificate Revocation List (CRL) is a list of certificate serial numbers issued
/// by a particular Certificate Authority (CA) that have been revoked, either by the CA
/// itself or by the owner of the revoked certificate.
/// </remarks>
/// <returns>The certificate revocation lists.</returns>
protected override IX509Store GetCertificateRevocationLists ()
{
return dbase.GetCrlStore ();
}
static EncryptionAlgorithm[] DecodeEncryptionAlgorithms (byte[] rawData)
{
using (var memory = new MemoryStream (rawData, false)) {
using (var asn1 = new Asn1InputStream (memory)) {
var algorithms = new List<EncryptionAlgorithm> ();
var sequence = asn1.ReadObject () as Asn1Sequence;
if (sequence == null)
return null;
for (int i = 0; i < sequence.Count; i++) {
var identifier = AlgorithmIdentifier.GetInstance (sequence[i]);
EncryptionAlgorithm algorithm;
if (TryGetEncryptionAlgorithm (identifier, out algorithm))
algorithms.Add (algorithm);
}
return algorithms.ToArray ();
}
}
}
/// <summary>
/// Gets the <see cref="CmsRecipient"/> for the specified mailbox.
/// </summary>
/// <remarks>
/// <para>Constructs a <see cref="CmsRecipient"/> with the appropriate certificate and
/// <see cref="CmsRecipient.EncryptionAlgorithms"/> for the specified mailbox.</para>
/// <para>If the mailbox is a <see cref="SecureMailboxAddress"/>, the
/// <see cref="SecureMailboxAddress.Fingerprint"/> property will be used instead of
/// the mailbox address for database lookups.</para>
/// </remarks>
/// <returns>A <see cref="CmsRecipient"/>.</returns>
/// <param name="mailbox">The mailbox.</param>
/// <exception cref="CertificateNotFoundException">
/// A certificate for the specified <paramref name="mailbox"/> could not be found.
/// </exception>
protected override CmsRecipient GetCmsRecipient (MailboxAddress mailbox)
{
foreach (var record in dbase.Find (mailbox, DateTime.UtcNow, false, CmsRecipientFields)) {
if (record.KeyUsage != 0 && (record.KeyUsage & X509KeyUsageFlags.KeyEncipherment) == 0)
continue;
var recipient = new CmsRecipient (record.Certificate);
if (record.Algorithms == null) {
var capabilities = record.Certificate.GetExtensionValue (SmimeAttributes.SmimeCapabilities);
if (capabilities != null) {
var algorithms = DecodeEncryptionAlgorithms (capabilities.GetOctets ());
if (algorithms != null)
recipient.EncryptionAlgorithms = algorithms;
}
} else {
recipient.EncryptionAlgorithms = record.Algorithms;
}
return recipient;
}
throw new CertificateNotFoundException (mailbox, "A valid certificate could not be found.");
}
/// <summary>
/// Gets the <see cref="CmsSigner"/> for the specified mailbox.
/// </summary>
/// <remarks>
/// <para>Constructs a <see cref="CmsSigner"/> with the appropriate signing certificate
/// for the specified mailbox.</para>
/// <para>If the mailbox is a <see cref="SecureMailboxAddress"/>, the
/// <see cref="SecureMailboxAddress.Fingerprint"/> property will be used instead of
/// the mailbox address for database lookups.</para>
/// </remarks>
/// <returns>A <see cref="CmsSigner"/>.</returns>
/// <param name="mailbox">The mailbox.</param>
/// <param name="digestAlgo">The preferred digest algorithm.</param>
/// <exception cref="CertificateNotFoundException">
/// A certificate for the specified <paramref name="mailbox"/> could not be found.
/// </exception>
protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
{
foreach (var record in dbase.Find (mailbox, DateTime.UtcNow, true, CmsSignerFields)) {
if (record.KeyUsage != X509KeyUsageFlags.None && (record.KeyUsage & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
continue;
var signer = new CmsSigner (record.Certificate, record.PrivateKey);
signer.DigestAlgorithm = digestAlgo;
return signer;
}
throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found.");
}
/// <summary>
/// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
/// </summary>
/// <remarks>
/// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
/// </remarks>
/// <param name="certificate">The certificate.</param>
/// <param name="algorithms">The encryption algorithm capabilities of the client (in preferred order).</param>
/// <param name="timestamp">The timestamp in coordinated universal time (UTC).</param>
protected override void UpdateSecureMimeCapabilities (X509Certificate certificate, EncryptionAlgorithm[] algorithms, DateTime timestamp)
{
X509CertificateRecord record;
if ((record = dbase.Find (certificate, AlgorithmFields)) == null) {
record = new X509CertificateRecord (certificate);
record.AlgorithmsUpdated = timestamp;
record.Algorithms = algorithms;
dbase.Add (record);
} else if (timestamp > record.AlgorithmsUpdated) {
record.AlgorithmsUpdated = timestamp;
record.Algorithms = algorithms;
dbase.Update (record, AlgorithmFields);
}
}
/// <summary>
/// Imports a certificate.
/// </summary>
/// <remarks>
/// Imports the specified certificate into the database.
/// </remarks>
/// <param name="certificate">The certificate.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificate"/> is <c>null</c>.
/// </exception>
public override void Import (X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (dbase.Find (certificate, X509CertificateRecordFields.Id) == null)
dbase.Add (new X509CertificateRecord (certificate));
}
/// <summary>
/// Imports a certificate revocation list.
/// </summary>
/// <remarks>
/// Imports the specified certificate revocation list.
/// </remarks>
/// <param name="crl">The certificate revocation list.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="crl"/> is <c>null</c>.
/// </exception>
public override void Import (X509Crl crl)
{
if (crl == null)
throw new ArgumentNullException ("crl");
// check for an exact match...
if (dbase.Find (crl, X509CrlRecordFields.Id) != null)
return;
const X509CrlRecordFields fields = ~X509CrlRecordFields.Crl;
var obsolete = new List<X509CrlRecord> ();
var delta = crl.IsDelta ();
// scan over our list of CRLs by the same issuer to check if this CRL obsoletes any
// older CRLs or if there are any newer CRLs that obsolete that obsolete this one.
foreach (var record in dbase.Find (crl.IssuerDN, fields)) {
if (!record.IsDelta && record.ThisUpdate >= crl.ThisUpdate) {
// we have a complete CRL that obsoletes this CRL
return;
}
if (!delta)
obsolete.Add (record);
}
// remove any obsoleted CRLs
foreach (var record in obsolete)
dbase.Remove (record);
dbase.Add (new X509CrlRecord (crl));
}
/// <summary>
/// Imports certificates and keys from a pkcs12-encoded stream.
/// </summary>
/// <remarks>
/// Imports all of the certificates and keys from the pkcs12-encoded stream.
/// </remarks>
/// <param name="stream">The raw certificate and key data.</param>
/// <param name="password">The password to unlock the data.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public override void Import (Stream stream, string password)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (password == null)
throw new ArgumentNullException ("password");
var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ());
var enabledAlgorithms = EnabledEncryptionAlgorithms;
X509CertificateRecord record;
foreach (string alias in pkcs12.Aliases) {
if (pkcs12.IsKeyEntry (alias)) {
var chain = pkcs12.GetCertificateChain (alias);
var entry = pkcs12.GetKey (alias);
int startIndex = 0;
if (entry.Key.IsPrivate) {
if ((record = dbase.Find (chain[0].Certificate, ImportPkcs12Fields)) == null) {
record = new X509CertificateRecord (chain[0].Certificate, entry.Key);
record.AlgorithmsUpdated = DateTime.UtcNow;
record.Algorithms = enabledAlgorithms;
record.IsTrusted = true;
dbase.Add (record);
} else {
record.AlgorithmsUpdated = DateTime.UtcNow;
record.Algorithms = enabledAlgorithms;
if (record.PrivateKey == null)
record.PrivateKey = entry.Key;
record.IsTrusted = true;
dbase.Update (record, ImportPkcs12Fields);
}
startIndex = 1;
}
for (int i = startIndex; i < chain.Length; i++) {
if ((record = dbase.Find (chain[i].Certificate, X509CertificateRecordFields.Id)) == null)
dbase.Add (new X509CertificateRecord (chain[i].Certificate));
}
} else if (pkcs12.IsCertificateEntry (alias)) {
var entry = pkcs12.GetCertificate (alias);
if ((record = dbase.Find (entry.Certificate, X509CertificateRecordFields.Id)) == null)
dbase.Add (new X509CertificateRecord (entry.Certificate));
}
}
}
#endregion
/// <summary>
/// Imports a DER-encoded certificate stream.
/// </summary>
/// <remarks>
/// Imports all of the certificates in the DER-encoded stream.
/// </remarks>
/// <param name="stream">The raw certificate(s).</param>
/// <param name="trusted"><c>true</c> if the certificates are trusted.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
public void Import (Stream stream, bool trusted)
{
if (stream == null)
throw new ArgumentNullException ("stream");
var parser = new X509CertificateParser ();
foreach (X509Certificate certificate in parser.ReadCertificates (stream)) {
if (dbase.Find (certificate, X509CertificateRecordFields.Id) != null)
continue;
var record = new X509CertificateRecord (certificate);
record.IsTrusted = trusted;
dbase.Add (record);
}
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="DefaultSecureMimeContext"/> and
/// optionally releases the managed resources.
/// </summary>
/// <remarks>
/// Releases the unmanaged resources used by the <see cref="DefaultSecureMimeContext"/> and
/// optionally releases the managed resources.
/// </remarks>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only the unmanaged resources.</param>
protected override void Dispose (bool disposing)
{
dbase.Dispose ();
base.Dispose (disposing);
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Documents;
using System;
using System.Diagnostics;
using MS.Internal;
namespace System.Windows.Controls.Primitives
{
/// <summary>
/// ToolBarOverflowPanel
/// </summary>
public class ToolBarOverflowPanel : Panel
{
#region Properties
/// <summary>
/// WrapWidth Property
/// </summary>
public static readonly DependencyProperty WrapWidthProperty =
DependencyProperty.Register(
"WrapWidth",
typeof(double),
typeof(ToolBarOverflowPanel),
new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure),
new ValidateValueCallback(IsWrapWidthValid));
/// <summary>
/// WrapWidth Property
/// </summary>
public double WrapWidth
{
get { return (double)GetValue(WrapWidthProperty); }
set { SetValue(WrapWidthProperty, value); }
}
private static bool IsWrapWidthValid(object value)
{
double v = (double)value;
return (DoubleUtil.IsNaN(v)) || (DoubleUtil.GreaterThanOrClose(v, 0d) && !Double.IsPositiveInfinity(v));
}
#endregion Properties
#region Override methods
/// <summary>
/// Measure the content and store the desired size of the content
/// </summary>
/// <param name="constraint"></param>
/// <returns></returns>
protected override Size MeasureOverride(Size constraint)
{
Size curLineSize = new Size();
_panelSize = new Size();
_wrapWidth = double.IsNaN(WrapWidth) ? constraint.Width : WrapWidth;
UIElementCollection children = InternalChildren;
int childrenCount = children.Count;
// Add ToolBar items which have IsOverflowItem = true
ToolBarPanel toolBarPanel = ToolBarPanel;
if (toolBarPanel != null)
{
// Go through the generated items collection and add to the children collection
// any that are marked IsOverFlowItem but aren't already in the children collection.
//
// The order of both collections matters.
//
// It is assumed that any children that were removed from generated items will have
// already been removed from the children collection.
List<UIElement> generatedItemsCollection = toolBarPanel.GeneratedItemsCollection;
int generatedItemsCount = (generatedItemsCollection != null) ? generatedItemsCollection.Count : 0;
int childrenIndex = 0;
for (int i = 0; i < generatedItemsCount; i++)
{
UIElement child = generatedItemsCollection[i];
if ((child != null) && ToolBar.GetIsOverflowItem(child) && !(child is Separator))
{
if (childrenIndex < childrenCount)
{
if (children[childrenIndex] != child)
{
children.Insert(childrenIndex, child);
childrenCount++;
}
}
else
{
children.Add(child);
childrenCount++;
}
childrenIndex++;
}
}
Debug.Assert(childrenIndex == childrenCount, "ToolBarOverflowPanel.Children count mismatch after transferring children from GeneratedItemsCollection.");
}
// Measure all children to determine if we need to increase desired wrapWidth
for (int i = 0; i < childrenCount; i++)
{
UIElement child = children[i] as UIElement;
child.Measure(constraint);
Size childDesiredSize = child.DesiredSize;
if (DoubleUtil.GreaterThan(childDesiredSize.Width, _wrapWidth))
{
_wrapWidth = childDesiredSize.Width;
}
}
// wrapWidth should not be bigger than constraint.Width
_wrapWidth = Math.Min(_wrapWidth, constraint.Width);
for (int i = 0; i < children.Count; i++)
{
UIElement child = children[i] as UIElement;
Size sz = child.DesiredSize;
if (DoubleUtil.GreaterThan(curLineSize.Width + sz.Width, _wrapWidth)) //need to switch to another line
{
_panelSize.Width = Math.Max(curLineSize.Width, _panelSize.Width);
_panelSize.Height += curLineSize.Height;
curLineSize = sz;
if (DoubleUtil.GreaterThan(sz.Width, _wrapWidth)) //the element is wider then the constraint - give it a separate line
{
_panelSize.Width = Math.Max(sz.Width, _panelSize.Width);
_panelSize.Height += sz.Height;
curLineSize = new Size();
}
}
else //continue to accumulate a line
{
curLineSize.Width += sz.Width;
curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);
}
}
//the last line size, if any should be added
_panelSize.Width = Math.Max(curLineSize.Width, _panelSize.Width);
_panelSize.Height += curLineSize.Height;
return _panelSize;
}
/// <summary>
/// Content arrangement.
/// </summary>
/// <param name="arrangeBounds"></param>
/// <returns></returns>
protected override Size ArrangeOverride(Size arrangeBounds)
{
int firstInLine = 0;
Size curLineSize = new Size();
double accumulatedHeight = 0d;
_wrapWidth = Math.Min(_wrapWidth, arrangeBounds.Width);
UIElementCollection children = this.Children;
for (int i = 0; i < children.Count; i++)
{
Size sz = children[i].DesiredSize;
if (DoubleUtil.GreaterThan(curLineSize.Width + sz.Width, _wrapWidth)) //need to switch to another line
{
// Arrange the items in the current line not including the current
arrangeLine(accumulatedHeight, curLineSize.Height, firstInLine, i);
accumulatedHeight += curLineSize.Height;
// Current item will be first on the next line
firstInLine = i;
curLineSize = sz;
}
else //continue to accumulate a line
{
curLineSize.Width += sz.Width;
curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);
}
}
arrangeLine(accumulatedHeight, curLineSize.Height, firstInLine, children.Count);
return _panelSize;
}
/// <summary>
/// Creates a new UIElementCollection. Panel-derived class can create its own version of
/// UIElementCollection -derived class to add cached information to every child or to
/// intercept any Add/Remove actions (for example, for incremental layout update)
/// </summary>
protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent)
{
// we ignore the Logical Parent (this) if we have ToolBar as our TemplatedParent
return new UIElementCollection(this, TemplatedParent == null ? logicalParent : null);
}
private void arrangeLine(double y, double lineHeight, int start, int end)
{
double x = 0;
UIElementCollection children = this.Children;
for (int i = start; i < end; i++)
{
UIElement child = children[i];
child.Arrange(new Rect(x, y, child.DesiredSize.Width, lineHeight));
x += child.DesiredSize.Width;
}
}
#endregion Override methods
#region private implementation
private ToolBar ToolBar
{
get { return TemplatedParent as ToolBar; }
}
private ToolBarPanel ToolBarPanel
{
get
{
ToolBar tb = ToolBar;
return tb == null ? null : tb.ToolBarPanel;
}
}
#endregion private implementation
#region private data
private double _wrapWidth; // calculated in MeasureOverride and used in ArrangeOverride
private Size _panelSize;
#endregion private data
}
}
| |
// 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 PermuteVar8x32Single()
{
var test = new SimpleBinaryOpTest__PermuteVar8x32Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 SimpleBinaryOpTest__PermuteVar8x32Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Int32[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = 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.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__PermuteVar8x32Single testClass)
{
var result = Avx2.PermuteVar8x32(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__PermuteVar8x32Single testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.PermuteVar8x32(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__PermuteVar8x32Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleBinaryOpTest__PermuteVar8x32Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.PermuteVar8x32(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.PermuteVar8x32(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.PermuteVar8x32(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.PermuteVar8x32), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.PermuteVar8x32), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.PermuteVar8x32), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.PermuteVar8x32(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.PermuteVar8x32(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.PermuteVar8x32(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.PermuteVar8x32(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.PermuteVar8x32(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__PermuteVar8x32Single();
var result = Avx2.PermuteVar8x32(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__PermuteVar8x32Single();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx2.PermuteVar8x32(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.PermuteVar8x32(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.PermuteVar8x32(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.PermuteVar8x32(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.PermuteVar8x32(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _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(Vector256<Single> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Int32[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(left[(right[0] & 7)]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[(right[i] & 7)]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.PermuteVar8x32)}<Single>(Vector256<Single>, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;
namespace Internal.TypeSystem
{
[Flags]
public enum MethodSignatureFlags
{
None = 0x0000,
// TODO: Generic, etc.
UnmanagedCallingConventionMask = 0x000F,
UnmanagedCallingConventionCdecl = 0x0001,
UnmanagedCallingConventionStdCall = 0x0002,
UnmanagedCallingConventionThisCall = 0x0003,
Static = 0x0010,
}
/// <summary>
/// Represents the parameter types, the return type, and flags of a method.
/// </summary>
public sealed partial class MethodSignature
{
internal MethodSignatureFlags _flags;
internal int _genericParameterCount;
internal TypeDesc _returnType;
internal TypeDesc[] _parameters;
public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters)
{
_flags = flags;
_genericParameterCount = genericParameterCount;
_returnType = returnType;
_parameters = parameters;
Debug.Assert(parameters != null, "Parameters must not be null");
}
public MethodSignatureFlags Flags
{
get
{
return _flags;
}
}
public bool IsStatic
{
get
{
return (_flags & MethodSignatureFlags.Static) != 0;
}
}
public int GenericParameterCount
{
get
{
return _genericParameterCount;
}
}
public TypeDesc ReturnType
{
get
{
return _returnType;
}
}
/// <summary>
/// Gets the parameter type at the specified index.
/// </summary>
[IndexerName("Parameter")]
public TypeDesc this[int index]
{
get
{
return _parameters[index];
}
}
/// <summary>
/// Gets the number of parameters of this method signature.
/// </summary>
public int Length
{
get
{
return _parameters.Length;
}
}
public bool Equals(MethodSignature otherSignature)
{
// TODO: Generics, etc.
if (this._flags != otherSignature._flags)
return false;
if (this._genericParameterCount != otherSignature._genericParameterCount)
return false;
if (this._returnType != otherSignature._returnType)
return false;
if (this._parameters.Length != otherSignature._parameters.Length)
return false;
for (int i = 0; i < this._parameters.Length; i++)
{
if (this._parameters[i] != otherSignature._parameters[i])
return false;
}
return true;
}
public override bool Equals(object obj)
{
return obj is MethodSignature && Equals((MethodSignature)obj);
}
public override int GetHashCode()
{
return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters);
}
}
/// <summary>
/// Helper structure for building method signatures by cloning an existing method signature.
/// </summary>
/// <remarks>
/// This can potentially avoid array allocation costs for allocating the parameter type list.
/// </remarks>
public struct MethodSignatureBuilder
{
private MethodSignature _template;
private MethodSignatureFlags _flags;
private int _genericParameterCount;
private TypeDesc _returnType;
private TypeDesc[] _parameters;
public MethodSignatureBuilder(MethodSignature template)
{
_template = template;
_flags = template._flags;
_genericParameterCount = template._genericParameterCount;
_returnType = template._returnType;
_parameters = template._parameters;
}
public MethodSignatureFlags Flags
{
set
{
_flags = value;
}
}
public TypeDesc ReturnType
{
set
{
_returnType = value;
}
}
[System.Runtime.CompilerServices.IndexerName("Parameter")]
public TypeDesc this[int index]
{
set
{
if (_parameters[index] == value)
return;
if (_template != null && _parameters == _template._parameters)
{
TypeDesc[] parameters = new TypeDesc[_parameters.Length];
for (int i = 0; i < parameters.Length; i++)
parameters[i] = _parameters[i];
_parameters = parameters;
}
_parameters[index] = value;
}
}
public int Length
{
set
{
_parameters = new TypeDesc[value];
_template = null;
}
}
public MethodSignature ToSignature()
{
if (_template == null ||
_flags != _template._flags ||
_genericParameterCount != _template._genericParameterCount ||
_returnType != _template._returnType ||
_parameters != _template._parameters)
{
_template = new MethodSignature(_flags, _genericParameterCount, _returnType, _parameters);
}
return _template;
}
}
/// <summary>
/// Represents the fundamental base type for all methods within the type system.
/// </summary>
public abstract partial class MethodDesc : TypeSystemEntity
{
public static readonly MethodDesc[] EmptyMethods = new MethodDesc[0];
private int _hashcode;
/// <summary>
/// Allows a performance optimization that skips the potentially expensive
/// construction of a hash code if a hash code has already been computed elsewhere.
/// Use to allow objects to have their hashcode computed
/// independently of the allocation of a MethodDesc object
/// For instance, compute the hashcode when looking up the object,
/// then when creating the object, pass in the hashcode directly.
/// The hashcode specified MUST exactly match the algorithm implemented
/// on this type normally.
/// </summary>
protected void SetHashCode(int hashcode)
{
_hashcode = hashcode;
Debug.Assert(hashcode == ComputeHashCode());
}
public sealed override int GetHashCode()
{
if (_hashcode != 0)
return _hashcode;
return AcquireHashCode();
}
private int AcquireHashCode()
{
_hashcode = ComputeHashCode();
return _hashcode;
}
/// <summary>
/// Compute HashCode. Should only be overriden by a MethodDesc that represents an instantiated method.
/// </summary>
protected virtual int ComputeHashCode()
{
return TypeHashingAlgorithms.ComputeMethodHashCode(OwningType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name));
}
public override bool Equals(Object o)
{
// Its only valid to compare two MethodDescs in the same context
Debug.Assert(Object.ReferenceEquals(o, null) || !(o is MethodDesc) || Object.ReferenceEquals(((MethodDesc)o).Context, this.Context));
return Object.ReferenceEquals(this, o);
}
/// <summary>
/// Gets the type that owns this method. This will be a <see cref="DefType"/> or
/// an <see cref="ArrayType"/>.
/// </summary>
public abstract TypeDesc OwningType
{
get;
}
/// <summary>
/// Gets the signature of the method.
/// </summary>
public abstract MethodSignature Signature
{
get;
}
/// <summary>
/// Gets the generic instantiation information of this method.
/// For generic definitions, retrieves the generic parameters of the method.
/// For generic instantiation, retrieves the generic arguments of the method.
/// </summary>
public virtual Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
/// <summary>
/// Gets a value indicating whether this method has a generic instantiation.
/// This will be true for generic method instantiations and generic definitions.
/// </summary>
public bool HasInstantiation
{
get
{
return this.Instantiation.Length != 0;
}
}
/// <summary>
/// Gets a value indicating whether this method is an instance constructor.
/// </summary>
public bool IsConstructor
{
get
{
// TODO: Precise check
// TODO: Cache?
return this.Name == ".ctor";
}
}
/// <summary>
/// Gets a value indicating whether this is a public parameterless instance constructor
/// on a non-abstract type.
/// </summary>
public virtual bool IsDefaultConstructor
{
get
{
return OwningType.GetDefaultConstructor() == this;
}
}
/// <summary>
/// Gets a value indicating whether this method is a static constructor.
/// </summary>
public bool IsStaticConstructor
{
get
{
return this == this.OwningType.GetStaticConstructor();
}
}
/// <summary>
/// Gets the name of the method as specified in the metadata.
/// </summary>
public virtual string Name
{
get
{
return null;
}
}
/// <summary>
/// Gets a value indicating whether the method is virtual.
/// </summary>
public virtual bool IsVirtual
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method should not override any
/// virtual methods defined in any of the base classes.
/// </summary>
public virtual bool IsNewSlot
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method needs to be overriden
/// by all non-abstract classes deriving from the method's owning type.
/// </summary>
public virtual bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating that this method cannot be overriden.
/// </summary>
public virtual bool IsFinal
{
get
{
return false;
}
}
public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName);
/// <summary>
/// Retrieves the uninstantiated form of the method on the method's <see cref="OwningType"/>.
/// For generic methods, this strips method instantiation. For non-generic methods, returns 'this'.
/// To also strip instantiation of the owning type, use <see cref="GetTypicalMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a method definition. This property
/// is true for non-generic methods and for uninstantiated generic methods.
/// </summary>
public bool IsMethodDefinition
{
get
{
return GetMethodDefinition() == this;
}
}
/// <summary>
/// Retrieves the generic definition of the method on the generic definition of the owning type.
/// To only uninstantiate the method without uninstantiating the owning type, use <see cref="GetMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetTypicalMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a typical definition. This property is true
/// if neither the owning type, nor the method are instantiated.
/// </summary>
public bool IsTypicalMethodDefinition
{
get
{
return GetTypicalMethodDefinition() == this;
}
}
public bool IsFinalizer
{
get
{
return OwningType.GetFinalizer() == this || OwningType.IsObject && Name == "Finalize";
}
}
public virtual MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
Instantiation instantiation = Instantiation;
TypeDesc[] clone = null;
for (int i = 0; i < instantiation.Length; i++)
{
TypeDesc uninst = instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = instantiation[j];
}
}
clone[i] = inst;
}
}
MethodDesc method = this;
TypeDesc owningType = method.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
{
method = Context.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)instantiatedOwningType);
if (clone == null && instantiation.Length != 0)
return Context.GetInstantiatedMethod(method, instantiation);
}
return (clone == null) ? method : Context.GetInstantiatedMethod(method.GetMethodDefinition(), new Instantiation(clone));
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The valid values for the -PathType parameter for test-path
/// </summary>
public enum TestPathType
{
/// <summary>
/// If the item at the path exists, true will be returned.
/// </summary>
Any,
/// <summary>
/// If the item at the path exists and is a container, true will be returned.
/// </summary>
Container,
/// <summary>
/// If the item at the path exists and is not a container, true will be returned.
/// </summary>
Leaf
}
/// <summary>
/// A command to determine if an item exists at a specified path
/// </summary>
[Cmdlet(VerbsDiagnostic.Test, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113418")]
[OutputType(typeof(bool))]
public class TestPathCommand : CoreCommandWithCredentialsBase
{
#region Parameters
/// <summary>
/// Gets or sets the path parameter to the command
/// </summary>
[Parameter(Position = 0, ParameterSetName = "Path",
Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
public string[] Path
{
get { return _paths; }
set { _paths = value; }
}
/// <summary>
/// Gets or sets the literal path parameter to the command
/// </summary>
[Parameter(ParameterSetName = "LiteralPath",
Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath")]
public string[] LiteralPath
{
get { return _paths; }
set
{
base.SuppressWildcardExpansion = true;
_paths = value;
}
}
/// <summary>
/// Gets or sets the filter property
/// </summary>
[Parameter]
public override string Filter
{
get { return base.Filter; }
set { base.Filter = value; }
}
/// <summary>
/// Gets or sets the include property
/// </summary>
[Parameter]
public override string[] Include
{
get { return base.Include; }
set { base.Include = value; }
}
/// <summary>
/// Gets or sets the exclude property
/// </summary>
[Parameter]
public override string[] Exclude
{
get { return base.Exclude; }
set { base.Exclude = value; }
}
/// <summary>
/// Gets or sets the isContainer property
/// </summary>
[Parameter]
[Alias("Type")]
public TestPathType PathType { get; set; } = TestPathType.Any;
/// <summary>
/// Gets or sets the IsValid parameter
/// </summary>
[Parameter]
public SwitchParameter IsValid { get; set; } = new SwitchParameter();
/// <summary>
/// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets
/// that require dynamic parameters should override this method and return the
/// dynamic parameter object.
/// </summary>
///
/// <param name="context">
/// The context under which the command is running.
/// </param>
///
/// <returns>
/// An object representing the dynamic parameters for the cmdlet or null if there
/// are none.
/// </returns>
///
internal override object GetDynamicParameters(CmdletProviderContext context)
{
object result = null;
if (this.PathType == TestPathType.Any && !IsValid)
{
if (Path != null && Path.Length > 0)
{
result = InvokeProvider.Item.ItemExistsDynamicParameters(Path[0], context);
}
else
{
result = InvokeProvider.Item.ItemExistsDynamicParameters(".", context);
}
}
return result;
} // GetDynamicParameters
#endregion Parameters
#region parameter data
/// <summary>
/// The path to the item to ping
/// </summary>
private string[] _paths;
#endregion parameter data
#region Command code
/// <summary>
/// Determines if an item at the specified path exists.
/// </summary>
protected override void ProcessRecord()
{
CmdletProviderContext currentContext = CmdletProviderContext;
foreach (string path in _paths)
{
bool result = false;
try
{
if (IsValid)
{
result = SessionState.Path.IsValid(path, currentContext);
}
else
{
if (this.PathType == TestPathType.Container)
{
result = InvokeProvider.Item.IsContainer(path, currentContext);
}
else if (this.PathType == TestPathType.Leaf)
{
result =
InvokeProvider.Item.Exists(path, currentContext) &&
!InvokeProvider.Item.IsContainer(path, currentContext);
}
else
{
result = InvokeProvider.Item.Exists(path, currentContext);
}
}
}
// Any of the known exceptions means the path does not exist.
catch (PSNotSupportedException)
{
}
catch (DriveNotFoundException)
{
}
catch (ProviderNotFoundException)
{
}
catch (ItemNotFoundException)
{
}
WriteObject(result);
}
} // ProcessRecord
#endregion Command code
} // PingPathCommand
} // namespace Microsoft.PowerShell.Commands
| |
//------------------------------------------------------------------------------
// <copyright file="SimpleType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data {
using System;
using System.Xml;
using System.Xml.Schema;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Globalization;
using System.Collections;
using System.Data.Common;
/// <devdoc>
/// </devdoc>
[Serializable]
internal sealed class SimpleType : ISerializable {
string baseType = null; // base type name
SimpleType baseSimpleType = null;
// object xmlBaseType = null; // Qualified name of Basetype
XmlQualifiedName xmlBaseType = null; // Qualified name of Basetype
string name = "";
int length = -1;
int minLength = -1;
int maxLength = -1;
string pattern = "";
string ns = ""; // my ns
//
string maxExclusive = "";
string maxInclusive = "";
string minExclusive = "";
string minInclusive = "";
//REMOVED: encoding due to [....] 2001 XDS changes
//
internal string enumeration = "";
internal SimpleType (string baseType) { // anonymous simpletype
this.baseType = baseType;
}
internal SimpleType (XmlSchemaSimpleType node) { // named simpletype
name = node.Name;
ns = (node.QualifiedName != null) ? node.QualifiedName.Namespace : "";
LoadTypeValues(node);
}
private SimpleType(SerializationInfo info, StreamingContext context) {
this.baseType = info.GetString("SimpleType.BaseType");
this.baseSimpleType = (SimpleType)info.GetValue("SimpleType.BaseSimpleType", typeof(SimpleType));
if (info.GetBoolean("SimpleType.XmlBaseType.XmlQualifiedNameExists")) {
string xmlQNName = info.GetString("SimpleType.XmlBaseType.Name");
string xmlQNNamespace = info.GetString("SimpleType.XmlBaseType.Namespace");
this.xmlBaseType = new XmlQualifiedName(xmlQNName, xmlQNNamespace);
}
else {
this.xmlBaseType = null;
}
this.name = info.GetString("SimpleType.Name");
this.ns = info.GetString("SimpleType.NS");
this.maxLength = info.GetInt32("SimpleType.MaxLength");
this.length = info.GetInt32("SimpleType.Length");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("SimpleType.BaseType", this.baseType);
info.AddValue("SimpleType.BaseSimpleType", this.baseSimpleType);
XmlQualifiedName xmlQN = (xmlBaseType as XmlQualifiedName);
info.AddValue("SimpleType.XmlBaseType.XmlQualifiedNameExists", xmlQN != null ? true : false);
info.AddValue("SimpleType.XmlBaseType.Name", xmlQN != null ? xmlQN.Name : null);
info.AddValue("SimpleType.XmlBaseType.Namespace", xmlQN != null ? xmlQN.Namespace : null);
info.AddValue("SimpleType.Name", this.name);
info.AddValue("SimpleType.NS", this.ns);
info.AddValue("SimpleType.MaxLength", this.maxLength);
info.AddValue("SimpleType.Length", this.length);
}
internal void LoadTypeValues (XmlSchemaSimpleType node) {
if ((node.Content is XmlSchemaSimpleTypeList) ||
(node.Content is XmlSchemaSimpleTypeUnion))
throw ExceptionBuilder.SimpleTypeNotSupported();
if (node.Content is XmlSchemaSimpleTypeRestriction) {
XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction) node.Content;
XmlSchemaSimpleType ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType;
if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) { // I'm assuming that built-in types don't have a name!
// Console.WriteLine("In simpleNode, ancestor.Name = '{0}'", ancestor.Name);
baseSimpleType = new SimpleType(node.BaseXmlSchemaType as XmlSchemaSimpleType);
// baseSimpleType = new SimpleType(node);
}
// do we need to put qualified name?
// for user defined simpletype, always go with qname
if (content.BaseTypeName.Namespace == Keywords.XSDNS)
baseType = content.BaseTypeName.Name;
else
baseType = content.BaseTypeName.ToString();
if (baseSimpleType != null && baseSimpleType.Name != null && baseSimpleType.Name.Length > 0) {
xmlBaseType = baseSimpleType.XmlBaseType;// SimpleTypeQualifiedName;
}
else {
xmlBaseType = content.BaseTypeName;
}
if (baseType == null || baseType.Length == 0) {
// Console.WriteLine("baseType == null, setting it to ", content.BaseType.Name);
baseType = content.BaseType.Name;
xmlBaseType = null;
}
if (baseType == "NOTATION")
baseType = "string";
foreach(XmlSchemaFacet facet in content.Facets) {
if (facet is XmlSchemaLengthFacet)
length = Convert.ToInt32(facet.Value, null);
if (facet is XmlSchemaMinLengthFacet)
minLength = Convert.ToInt32(facet.Value, null);
if (facet is XmlSchemaMaxLengthFacet)
maxLength = Convert.ToInt32(facet.Value, null);
if (facet is XmlSchemaPatternFacet)
pattern = facet.Value;
if (facet is XmlSchemaEnumerationFacet)
enumeration = !Common.ADP.IsEmpty(enumeration) ? enumeration + " " + facet.Value : facet.Value;
if (facet is XmlSchemaMinExclusiveFacet)
minExclusive = facet.Value;
if (facet is XmlSchemaMinInclusiveFacet)
minInclusive = facet.Value;
if (facet is XmlSchemaMaxExclusiveFacet)
maxExclusive = facet.Value;
if (facet is XmlSchemaMaxInclusiveFacet)
maxInclusive = facet.Value;
}
}
string tempStr = XSDSchema.GetMsdataAttribute(node, Keywords.TARGETNAMESPACE);
if (tempStr != null)
ns = tempStr;
}
internal bool IsPlainString() {
return (
XSDSchema.QualifiedName(this.baseType) == XSDSchema.QualifiedName("string") &&
Common.ADP.IsEmpty(this.name) &&
this.length == -1 &&
this.minLength == -1 &&
this.maxLength == -1 &&
Common.ADP.IsEmpty(this.pattern) &&
Common.ADP.IsEmpty(this.maxExclusive) &&
Common.ADP.IsEmpty(this.maxInclusive) &&
Common.ADP.IsEmpty(this.minExclusive) &&
Common.ADP.IsEmpty(this.minInclusive) &&
Common.ADP.IsEmpty(this.enumeration)
);
}
internal string BaseType {
get {
return baseType;
}
}
internal XmlQualifiedName XmlBaseType {
get {
return (XmlQualifiedName)xmlBaseType;
}
}
internal string Name {
get {
return name;
}
}
internal string Namespace {
get {
return ns;
}
}
internal int Length {
get {
return length;
}
}
internal int MaxLength {
get {
return maxLength;
}
set {
maxLength = value;
}
}
internal SimpleType BaseSimpleType {
get {
return baseSimpleType;
}
}
// return qualified name of this simple type
public string SimpleTypeQualifiedName {
get {
if (ns.Length == 0)
return name;
return (ns + ":" + name);
}
}
internal string QualifiedName(string name) {
int iStart = name.IndexOf(':');
if (iStart == -1)
return Keywords.XSD_PREFIXCOLON + name;
else
return name;
}
/*
internal XmlNode ToNode(XmlDocument dc) {
return ToNode(dc, null, false);
}
*/
internal XmlNode ToNode(XmlDocument dc, Hashtable prefixes, bool inRemoting) {
XmlElement typeNode = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SIMPLETYPE, Keywords.XSDNS);
if (name != null && name.Length != 0) {
// this is a global type :
typeNode.SetAttribute(Keywords.NAME, name);
if (inRemoting) {
typeNode.SetAttribute(Keywords.TARGETNAMESPACE, Keywords.MSDNS, this.Namespace);
}
}
XmlElement type = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_RESTRICTION, Keywords.XSDNS);
if (!inRemoting) {
if (baseSimpleType != null) {
if (baseSimpleType.Namespace != null && baseSimpleType.Namespace.Length > 0) {
string prefix = (prefixes!=null)?(string) prefixes[baseSimpleType.Namespace]:null;
if (prefix != null) {
type.SetAttribute(Keywords.BASE, (prefix +":"+ baseSimpleType.Name));
}
else {
type.SetAttribute(Keywords.BASE, baseSimpleType.Name);
}
}
else { // [....]
type.SetAttribute(Keywords.BASE, baseSimpleType.Name);
}
}
else {
type.SetAttribute(Keywords.BASE, QualifiedName(baseType)); // has to be xs:SomePrimitiveType
}
}
else{
type.SetAttribute(Keywords.BASE, (baseSimpleType != null) ? baseSimpleType.Name : QualifiedName(baseType));
}
XmlElement constraint;
if (length >= 0) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_LENGTH, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, length.ToString(CultureInfo.InvariantCulture));
type.AppendChild(constraint);
}
if (maxLength >= 0) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MAXLENGTH, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, maxLength.ToString(CultureInfo.InvariantCulture));
type.AppendChild(constraint);
}
/* // removed due to MDAC bug 83892
// will be reactivated in whidbey with the proper handling
if (pattern != null && pattern.Length > 0) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_PATTERN, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, pattern);
type.AppendChild(constraint);
}
if (minLength >= 0) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MINLENGTH, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, minLength.ToString());
type.AppendChild(constraint);
}
if (minInclusive != null && minInclusive.Length > 0) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MININCLUSIVE, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, minInclusive);
type.AppendChild(constraint);
}
if (minExclusive != null && minExclusive.Length > 0) {
constraint =dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MINEXCLUSIVE, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, minExclusive);
type.AppendChild(constraint);
}
if (maxInclusive != null && maxInclusive.Length > 0) {
constraint =dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MAXINCLUSIVE, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, maxInclusive);
type.AppendChild(constraint);
}
if (maxExclusive != null && maxExclusive.Length > 0) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MAXEXCLUSIVE, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, maxExclusive);
type.AppendChild(constraint);
}
if (enumeration.Length > 0) {
string[] list = enumeration.TrimEnd(null).Split(null);
for (int i = 0; i < list.Length; i++) {
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ENUMERATION, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, list[i]);
type.AppendChild(constraint);
}
}
*/
typeNode.AppendChild(type);
return typeNode;
}
//
internal static SimpleType CreateEnumeratedType(string values) {
SimpleType enumType = new SimpleType("string");
enumType.enumeration = values;
return enumType;
}
internal static SimpleType CreateByteArrayType(string encoding) {
SimpleType byteArrayType = new SimpleType("base64Binary");
return byteArrayType;
}
internal static SimpleType CreateLimitedStringType(int length) {
SimpleType limitedString = new SimpleType("string");
limitedString.maxLength = length;
return limitedString;
}
internal static SimpleType CreateSimpleType(StorageType typeCode, Type type) {
if ((typeCode == StorageType.Char) && (type == typeof(Char))) {
return new SimpleType("string") { length = 1 };
}
return null;
}
// Assumption is otherSimpleType and current ST name and NS matches.
// if existing simpletype is being redefined with different facets, then it will return no-empty string defining the error
internal string HasConflictingDefinition(SimpleType otherSimpleType) {
if (otherSimpleType == null)
return "otherSimpleType";
if (this.MaxLength != otherSimpleType.MaxLength)
return ("MaxLength");
if (string.Compare(this.BaseType, otherSimpleType.BaseType, StringComparison.Ordinal) != 0)
return ("BaseType");
if ((this.BaseSimpleType == null && otherSimpleType.BaseSimpleType != null) &&
(this.BaseSimpleType.HasConflictingDefinition(otherSimpleType.BaseSimpleType)).Length != 0)
return ("BaseSimpleType");
return string.Empty;
}
// only string types can have MaxLength
internal bool CanHaveMaxLength() {
SimpleType rootType = this;
while (rootType.BaseSimpleType != null) {
rootType = rootType.BaseSimpleType;
}
if (string.Compare(rootType.BaseType, "string", StringComparison.OrdinalIgnoreCase) == 0)
return true;
return false;
}
internal void ConvertToAnnonymousSimpleType() {
this.name = null;
this.ns = string.Empty;
SimpleType tmpSimpleType = this;
while (tmpSimpleType.baseSimpleType != null) {
tmpSimpleType = tmpSimpleType.baseSimpleType;
}
baseType = tmpSimpleType.baseType;
baseSimpleType = tmpSimpleType.baseSimpleType;
xmlBaseType = tmpSimpleType.xmlBaseType;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Threading
{
using System;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using Microsoft.Win32.SafeHandles;
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void TimerCallback(Object state);
//
// TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM,
// to schedule all managed timers in the AppDomain.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, but we can live
// with linear traversal times when firing timers.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers.
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
get { return s_queue; }
}
private TimerQueue()
{
// empty private constructor to ensure we remain a singleton.
}
#endregion
#region interface to native per-AppDomain timer
//
// We need to keep our notion of time synchronized with the calls to SleepEx that drive
// the underlying native timer. In Win8, SleepEx does not count the time the machine spends
// sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time,
// so we will get out of sync with SleepEx if we use that method.
//
// So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent
// in sleep/hibernate mode.
//
private static int TickCount
{
[SecuritySafeCritical]
get
{
#if !FEATURE_PAL
if (Environment.IsWindows8OrAbove)
{
ulong time100ns;
bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns);
if (!result)
throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
// convert to 100ns to milliseconds, and truncate to 32 bits.
return (int)(uint)(time100ns / 10000);
}
else
#endif
{
return Environment.TickCount;
}
}
}
//
// We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded.
//
[SecurityCritical]
class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public AppDomainTimerSafeHandle()
: base(true)
{
}
[SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected override bool ReleaseHandle()
{
return DeleteAppDomainTimer(handle);
}
}
[SecurityCritical]
AppDomainTimerSafeHandle m_appDomainTimer;
bool m_isAppDomainTimerScheduled;
int m_currentAppDomainTimerStartTicks;
uint m_currentAppDomainTimerDuration;
[SecuritySafeCritical]
private bool EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// The VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
//
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (m_isAppDomainTimerScheduled)
{
uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks);
if (elapsed >= m_currentAppDomainTimerDuration)
return true; //the timer's about to fire
uint remainingDuration = m_currentAppDomainTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return true; //the timer will fire earlier than this request
}
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
if(m_pauseTicks != 0)
{
Contract.Assert(!m_isAppDomainTimerScheduled);
Contract.Assert(m_appDomainTimer == null);
return true;
}
if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
{
Contract.Assert(!m_isAppDomainTimerScheduled);
m_appDomainTimer = CreateAppDomainTimer(actualDuration);
if (!m_appDomainTimer.IsInvalid)
{
m_isAppDomainTimerScheduled = true;
m_currentAppDomainTimerStartTicks = TickCount;
m_currentAppDomainTimerDuration = actualDuration;
return true;
}
else
{
return false;
}
}
else
{
if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration))
{
m_isAppDomainTimerScheduled = true;
m_currentAppDomainTimerStartTicks = TickCount;
m_currentAppDomainTimerDuration = actualDuration;
return true;
}
else
{
return false;
}
}
}
//
// The VM calls this when the native timer fires.
//
[SecuritySafeCritical]
internal static void AppDomainTimerCallback()
{
Instance.FireNextTimers();
}
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static extern bool DeleteAppDomainTimer(IntPtr handle);
#endregion
#region Firing timers
//
// The list of timers
//
TimerQueueTimer m_timers;
volatile int m_pauseTicks = 0; // Time when Pause was called
[SecurityCritical]
internal void Pause()
{
lock(this)
{
// Delete the native timer so that no timers are fired in the Pause zone
if(m_appDomainTimer != null && !m_appDomainTimer.IsInvalid)
{
m_appDomainTimer.Dispose();
m_appDomainTimer = null;
m_isAppDomainTimerScheduled = false;
m_pauseTicks = TickCount;
}
}
}
[SecurityCritical]
internal void Resume()
{
//
// Update timers to adjust their due-time to accomodate Pause/Resume
//
lock (this)
{
// prevent ThreadAbort while updating state
try { }
finally
{
int pauseTicks = m_pauseTicks;
m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled
int resumedTicks = TickCount;
int pauseDuration = resumedTicks - pauseTicks;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
Contract.Assert(resumedTicks >= timer.m_startTicks);
uint elapsed; // How much of the timer dueTime has already elapsed
// Timers started before the paused event has to be sufficiently delayed to accomodate
// for the Pause time. However, timers started after the Paused event shouldnt be adjusted.
// E.g. ones created by the app in its Activated event should fire when it was designated.
// The Resumed event which is where this routine is executing is after this Activated and hence
// shouldn't delay this timer
if(timer.m_startTicks <= pauseTicks)
elapsed = (uint)(pauseTicks - timer.m_startTicks);
else
elapsed = (uint)(resumedTicks - timer.m_startTicks);
// Handling the corner cases where a Timer was already due by the time Resume is happening,
// We shouldn't delay those timers.
// Example is a timer started in App's Activated event with a very small duration
timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0;;
timer.m_startTicks = resumedTicks; // re-baseline
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
timer = timer.m_next;
}
if (haveTimerToSchedule)
{
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
}
}
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
//
private void FireNextTimers()
{
//
// we fire the first timer on this thread; any other timers that might have fired are queued
// to the ThreadPool.
//
TimerQueueTimer timerToFireOnThisThread = null;
lock (this)
{
// prevent ThreadAbort while updating state
try { }
finally
{
//
// since we got here, that means our previous timer has fired.
//
m_isAppDomainTimerScheduled = false;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
//
// Sweep through all timers. The ones that have reached their due time
// will fire. We will calculate the next native timer due time from the
// other timers.
//
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
{
//
// Remember the next timer in case we delete this one
//
TimerQueueTimer nextTimer = timer.m_next;
if (timer.m_period != Timeout.UnsignedInfinite)
{
timer.m_startTicks = nowTicks;
timer.m_dueTime = timer.m_period;
//
// This is a repeating timer; schedule it to run again.
//
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
}
else
{
//
// Not repeating; remove it from the queue
//
DeleteTimer(timer);
}
//
// If this is the first timer, we'll fire it on this thread. Otherwise, queue it
// to the ThreadPool.
//
if (timerToFireOnThisThread == null)
timerToFireOnThisThread = timer;
else
QueueTimerCompletion(timer);
timer = nextTimer;
}
else
{
//
// This timer hasn't fired yet. Just update the next time the native timer fires.
//
uint remaining = timer.m_dueTime - elapsed;
if (remaining < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = remaining;
}
timer = timer.m_next;
}
}
if (haveTimerToSchedule)
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
//
// Fire the user timer outside of the lock!
//
if (timerToFireOnThisThread != null)
timerToFireOnThisThread.Fire();
}
[SecuritySafeCritical]
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
if (callback == null)
s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion);
// Can use "unsafe" variant because we take care of capturing and restoring
// the ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(callback, timer);
}
private static WaitCallback s_fireQueuedTimerCompletion;
private static void FireQueuedTimerCompletion(object state)
{
((TimerQueueTimer)state).Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
if (timer.m_dueTime == Timeout.UnsignedInfinite)
{
// the timer is not in the list; add it (as the head of the list).
timer.m_next = m_timers;
timer.m_prev = null;
if (timer.m_next != null)
timer.m_next.m_prev = timer;
m_timers = timer;
}
timer.m_dueTime = dueTime;
timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period;
timer.m_startTicks = TickCount;
return EnsureAppDomainTimerFiresBy(dueTime);
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer.m_dueTime != Timeout.UnsignedInfinite)
{
if (timer.m_next != null)
timer.m_next.m_prev = timer.m_prev;
if (timer.m_prev != null)
timer.m_prev.m_next = timer.m_next;
if (m_timers == timer)
m_timers = timer.m_next;
timer.m_dueTime = Timeout.UnsignedInfinite;
timer.m_period = Timeout.UnsignedInfinite;
timer.m_startTicks = 0;
timer.m_prev = null;
timer.m_next = null;
}
}
#endregion
}
//
// A timer in our TimerQueue.
//
sealed class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
//
// The first four fields are maintained by TimerQueue itself.
//
internal TimerQueueTimer m_next;
internal TimerQueueTimer m_prev;
//
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
//
internal int m_startTicks;
//
// Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire.
//
internal uint m_dueTime;
//
// Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval.
//
internal uint m_period;
//
// Info about the user's callback
//
readonly TimerCallback m_timerCallback;
readonly Object m_state;
readonly ExecutionContext m_executionContext;
//
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set m_canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning
// reaches zero.
//
int m_callbacksRunning;
volatile bool m_canceled;
volatile WaitHandle m_notifyWhenNoCallbacksRunning;
[SecurityCritical]
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark)
{
m_timerCallback = timerCallback;
m_state = state;
m_dueTime = Timeout.UnsignedInfinite;
m_period = Timeout.UnsignedInfinite;
if (!ExecutionContext.IsFlowSuppressed())
{
m_executionContext = ExecutionContext.Capture(
ref stackMark,
ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
}
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
//
if (dueTime != Timeout.UnsignedInfinite)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
lock (TimerQueue.Instance)
{
if (m_canceled)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic"));
// prevent ThreadAbort while updating state
try { }
finally
{
m_period = period;
if (dueTime == Timeout.UnsignedInfinite)
{
TimerQueue.Instance.DeleteTimer(this);
success = true;
}
else
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true);
success = TimerQueue.Instance.UpdateTimer(this, dueTime, period);
}
}
}
return success;
}
public void Close()
{
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (!m_canceled)
{
m_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
}
}
public bool Close(WaitHandle toSignal)
{
bool success;
bool shouldSignal = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (m_canceled)
{
success = false;
}
else
{
m_canceled = true;
m_notifyWhenNoCallbacksRunning = toSignal;
TimerQueue.Instance.DeleteTimer(this);
if (m_callbacksRunning == 0)
shouldSignal = true;
success = true;
}
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
return success;
}
internal void Fire()
{
bool canceled = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
canceled = m_canceled;
if (!canceled)
m_callbacksRunning++;
}
}
if (canceled)
return;
CallCallback();
bool shouldSignal = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
m_callbacksRunning--;
if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null)
shouldSignal = true;
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
}
[SecuritySafeCritical]
internal void SignalNoCallbacksRunning()
{
Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle);
}
[SecuritySafeCritical]
internal void CallCallback()
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty);
// call directly if EC flow is suppressed
if (m_executionContext == null)
{
m_timerCallback(m_state);
}
else
{
using (ExecutionContext executionContext =
m_executionContext.IsPreAllocatedDefault ? m_executionContext : m_executionContext.CreateCopy())
{
ContextCallback callback = s_callCallbackInContext;
if (callback == null)
s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext);
ExecutionContext.Run(
executionContext,
callback,
this, // state
true); // ignoreSyncCtx
}
}
}
[SecurityCritical]
private static ContextCallback s_callCallbackInContext;
[SecurityCritical]
private static void CallCallbackInContext(object state)
{
TimerQueueTimer t = (TimerQueueTimer)state;
t.m_timerCallback(t.m_state);
}
}
//
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
public TimerHolder(TimerQueueTimer timer)
{
m_timer = timer;
}
~TimerHolder()
{
//
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
//
// Similarly, we should not close the timer during AD-unload's live-object finalization phase.
// A rude abort may have prevented us from releasing the lock.
//
// Note that in either case, the Timer still won't fire, because ThreadPool threads won't be
// allowed to run in this AppDomain.
//
if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload())
return;
m_timer.Close();
}
public void Close()
{
m_timer.Close();
GC.SuppressFinalize(this);
}
public bool Close(WaitHandle notifyObject)
{
bool result = m_timer.Close(notifyObject);
GC.SuppressFinalize(this);
return result;
}
}
[HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
#if FEATURE_REMOTING
public sealed class Timer : MarshalByRefObject, IDisposable
#else // FEATURE_REMOTING
public sealed class Timer : IDisposable
#endif // FEATURE_REMOTING
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
private TimerHolder m_timer;
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
int dueTime,
int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1 )
throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark);
}
[CLSCompliant(false)]
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,dueTime,period,ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
long dueTime,
long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback)
{
int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call
int period = -1; // Change after a timer instance is created. This is to avoid the potential
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark);
}
[SecurityCritical]
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period,
ref StackCrawlMark stackMark)
{
if (callback == null)
throw new ArgumentNullException("TimerCallback");
Contract.EndContractBlock();
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark));
}
[SecurityCritical]
internal static void Pause()
{
TimerQueue.Instance.Pause();
}
[SecurityCritical]
internal static void Resume()
{
TimerQueue.Instance.Resume();
}
public bool Change(int dueTime, int period)
{
if (dueTime < -1 )
throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds);
}
[CLSCompliant(false)]
public bool Change(UInt32 dueTime, UInt32 period)
{
return m_timer.m_timer.Change(dueTime, period);
}
public bool Change(long dueTime, long period)
{
if (dueTime < -1 )
throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Dispose(WaitHandle notifyObject)
{
if (notifyObject==null)
throw new ArgumentNullException("notifyObject");
Contract.EndContractBlock();
return m_timer.Close(notifyObject);
}
public void Dispose()
{
m_timer.Close();
}
internal void KeepRootedWhileScheduled()
{
GC.SuppressFinalize(m_timer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;
using Tester;
using Orleans.Hosting;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Microsoft.Extensions.Configuration;
using Orleans.Providers.Streams.AzureQueue;
namespace UnitTests.StreamingTests
{
[TestCategory("Streaming"), TestCategory("Cleanup")]
public class StreamLifecycleTests : TestClusterPerTest
{
public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
protected Guid StreamId;
protected string StreamProviderName;
protected string StreamNamespace;
private readonly ITestOutputHelper output;
private IActivateDeactivateWatcherGrain watcher;
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
TestUtils.CheckForAzureStorage();
builder.AddSiloBuilderConfigurator<MySiloBuilderConfigurator>();
builder.AddClientBuilderConfigurator<MyClientBuilderConfigurator>();
}
private class MyClientBuilderConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder
.AddSimpleMessageStreamProvider(SmsStreamProviderName)
.AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName,
options =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
});
}
}
private class MySiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder
.AddSimpleMessageStreamProvider(SmsStreamProviderName)
.AddSimpleMessageStreamProvider("SMSProviderDoNotOptimizeForImmutableData", options => options.OptimizeForImmutableData = false)
.AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.ServiceId = silo.Value.ServiceId.ToString();
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.DeleteStateOnClear = true;
}))
.AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.ServiceId = silo.Value.ServiceId.ToString();
options.DeleteStateOnClear = true;
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
}))
.AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName,
options =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
})
.AddAzureQueueStreams<AzureQueueDataAdapterV2>("AzureQueueProvider2",
options =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
})
.AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1);
}
}
public StreamLifecycleTests(ITestOutputHelper output)
{
this.output = output;
this.watcher = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
StreamId = Guid.NewGuid();
StreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
StreamNamespace = StreamTestsConstants.StreamLifecycleTestsNamespace;
}
public override void Dispose()
{
watcher.Clear().WaitWithThrow(TimeSpan.FromSeconds(15));
base.Dispose();
}
[SkippableFact, TestCategory("Functional")]
public async Task StreamCleanup_Deactivate()
{
await DoStreamCleanupTest_Deactivate(false, false);
}
[SkippableFact, TestCategory("Functional")]
public async Task StreamCleanup_BadDeactivate()
{
await DoStreamCleanupTest_Deactivate(true, false);
}
[SkippableFact, TestCategory("Functional")]
public async Task StreamCleanup_UseAfter_Deactivate()
{
await DoStreamCleanupTest_Deactivate(false, true);
}
[SkippableFact, TestCategory("Functional")]
public async Task StreamCleanup_UseAfter_BadDeactivate()
{
await DoStreamCleanupTest_Deactivate(true, true);
}
[SkippableFact, TestCategory("Functional")]
public async Task Stream_Lifecycle_AddRemoveProducers()
{
string testName = "Stream_Lifecycle_AddRemoveProducers";
StreamTestUtils.LogStartTest(testName, StreamId, StreamProviderName, logger, HostedCluster);
int numProducers = 10;
var consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName);
var producers = new IStreamLifecycleProducerInternalGrain[numProducers];
for (int i = 1; i <= producers.Length; i++)
{
var producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid());
producers[i - 1] = producer;
}
int expectedReceived = 0;
string when = "round 1";
await IncrementalAddProducers(producers, when);
expectedReceived += numProducers;
Assert.Equal(expectedReceived, await consumer.GetReceivedCount());
for (int i = producers.Length; i > 0; i--)
{
var producer = producers[i - 1];
// Force Remove
await producer.TestInternalRemoveProducer(StreamId, StreamProviderName);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "producer #" + i + " remove", (i - 1), 1,
StreamId, StreamProviderName, StreamNamespace);
}
when = "round 2";
await IncrementalAddProducers(producers, when);
expectedReceived += numProducers;
Assert.Equal(expectedReceived, await consumer.GetReceivedCount());
List<Task> promises = new List<Task>();
for (int i = producers.Length; i > 0; i--)
{
var producer = producers[i - 1];
// Remove when Deactivate
promises.Add(producer.DoDeactivateNoClose());
}
await Task.WhenAll(promises);
await WaitForDeactivation();
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "all producers deactivated", 0, 1,
StreamId, StreamProviderName, StreamNamespace);
when = "round 3";
await IncrementalAddProducers(producers, when);
expectedReceived += numProducers;
Assert.Equal(expectedReceived, await consumer.GetReceivedCount());
}
private async Task IncrementalAddProducers(IStreamLifecycleProducerGrain[] producers, string when)
{
for (int i = 1; i <= producers.Length; i++)
{
var producer = producers[i - 1];
await producer.BecomeProducer(StreamId, StreamNamespace, StreamProviderName);
// These Producers test grains always send first message when they register
await StreamTestUtils.CheckPubSubCounts(
this.InternalClient,
output,
string.Format("producer #{0} create - {1}", i, when),
i, 1,
StreamId, StreamProviderName, StreamNamespace);
}
}
// ---------- Test support methods ----------
private async Task DoStreamCleanupTest_Deactivate(bool uncleanShutdown, bool useStreamAfterDeactivate, [CallerMemberName]string testName = null)
{
StreamTestUtils.LogStartTest(testName, StreamId, StreamProviderName, logger, HostedCluster);
var producer1 = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid());
var producer2 = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid());
var consumer1 = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid());
var consumer2 = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid());
await consumer1.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName);
await producer1.BecomeProducer(StreamId, StreamNamespace, StreamProviderName);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after first producer added", 1, 1,
StreamId, StreamProviderName, StreamNamespace);
Assert.Equal(1, await producer1.GetSendCount()); // "SendCount after first send"
var activations = await watcher.GetActivateCalls();
var deactivations = await watcher.GetDeactivateCalls();
Assert.Equal(2, activations.Length);
Assert.Empty(deactivations);
int expectedNumProducers;
if (uncleanShutdown)
{
expectedNumProducers = 1; // Will not cleanup yet
await producer1.DoBadDeactivateNoClose();
}
else
{
expectedNumProducers = 0; // Should immediately cleanup on Deactivate
await producer1.DoDeactivateNoClose();
}
await WaitForDeactivation();
deactivations = await watcher.GetDeactivateCalls();
Assert.Single(deactivations);
// Test grains that did unclean shutdown will not have cleaned up yet, so PubSub counts are unchanged here for them
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after deactivate first producer", expectedNumProducers, 1,
StreamId, StreamProviderName, StreamNamespace);
// Add another consumer - which forces cleanup of dead producers and PubSub counts should now always be correct
await consumer2.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName);
// Runtime should have cleaned up after next consumer added
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after add second consumer", 0, 2,
StreamId, StreamProviderName, StreamNamespace);
if (useStreamAfterDeactivate)
{
// Add new producer
await producer2.BecomeProducer(StreamId, StreamNamespace, StreamProviderName);
// These Producer test grains always send first message when they BecomeProducer, so should be registered with PubSub
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after add second producer", 1, 2,
StreamId, StreamProviderName, StreamNamespace);
Assert.Equal(1, await producer1.GetSendCount()); // "SendCount (Producer#1) after second publisher added");
Assert.Equal(1, await producer2.GetSendCount()); // "SendCount (Producer#2) after second publisher added");
Assert.Equal(2, await consumer1.GetReceivedCount()); // "ReceivedCount (Consumer#1) after second publisher added");
Assert.Equal(1, await consumer2.GetReceivedCount()); // "ReceivedCount (Consumer#2) after second publisher added");
await producer2.SendItem(3);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after second producer send", 1, 2,
StreamId, StreamProviderName, StreamNamespace);
Assert.Equal(3, await consumer1.GetReceivedCount()); // "ReceivedCount (Consumer#1) after second publisher send");
Assert.Equal(2, await consumer2.GetReceivedCount()); // "ReceivedCount (Consumer#2) after second publisher send");
}
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task WaitForDeactivation()
{
var delay = TimeSpan.FromSeconds(1);
logger.Info("Waiting for {0} to allow time for grain deactivation to occur", delay);
await Task.Delay(delay); // Allow time for Deactivate
logger.Info("Awake again.");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OLEDB.Test.ModuleCore;
using Xunit;
namespace System.Xml.Tests
{
public partial class WrappedReaderTest : CGenericTestModule
{
private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/async";
RunTestCase(testCaseGenerator);
}
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new WrappedReaderTest();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
RunTestCase(testCaseGenerator);
RunTestCaseAsync(testCaseGenerator);
}
[Fact]
[OuterLoop]
public static void ErrorConditionReader()
{
RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XMLExceptionReader()
{
RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void LinePosReader()
{
RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void DepthReader()
{
RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void NamespaceReader()
{
RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void LookupNamespaceReader()
{
RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void HasValueReader()
{
RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void IsEmptyElementReader()
{
RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlSpaceReader()
{
RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlLangReader()
{
RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void SkipReader()
{
RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void InvalidXMLReader()
{
RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeAccessReader()
{
RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ThisNameReader()
{
RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeReader()
{
RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeOrdinalReader()
{
RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeNameReader()
{
RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ThisOrdinalReader()
{
RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeOrdinalReader()
{
RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToFirstAttributeReader()
{
RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToNextAttributeReader()
{
RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeTestReader()
{
RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeXmlDeclarationReader()
{
RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration DCR52258", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsReader()
{
RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsPrefixReader()
{
RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadInnerXmlReader()
{
RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToContentReader()
{
RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void IsStartElementReader()
{
RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStartElementReader()
{
RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadEndElementReader()
{
RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ResolveEntityReader()
{
RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadAttributeValueReader()
{
RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadReader()
{
RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToElementReader()
{
RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void DisposeReader()
{
RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void BufferBoundariesReader()
{
RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterClose()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileBeforeRead()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
}
[Fact]
[OuterLoop]
public static void ReadSubtreeReader()
{
RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToDescendantReader()
{
RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToNextSiblingReader()
{
RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadValueReader()
{
RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBase64Reader()
{
RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBase64Reader()
{
RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBinHexReader()
{
RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBinHexReader()
{
RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToFollowingReader()
{
RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "WrappedReader" } });
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for TableRowCtl.
/// </summary>
internal class TableRowCtl : System.Windows.Forms.UserControl, IProperty
{
private XmlNode _TableRow;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fHidden, fToggle, fHeight;
private System.Windows.Forms.GroupBox grpBoxVisibility;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbHidden;
private System.Windows.Forms.ComboBox cbToggle;
private System.Windows.Forms.Button bHidden;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbRowHeight;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal TableRowCtl(DesignXmlDraw dxDraw, XmlNode tr)
{
_TableRow = tr;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(tr);
}
private void InitValues(XmlNode node)
{
// Handle Width definition
this.tbRowHeight.Text = _Draw.GetElementValue(node, "Height", "");
// Handle Visiblity definition
XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility");
if (visNode != null)
{
this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", "");
this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", "");
}
IEnumerable list = _Draw.GetReportItems("//Textbox");
if (list != null)
{
foreach (XmlNode tNode in list)
{
XmlAttribute name = tNode.Attributes["Name"];
if (name != null && name.Value != null && name.Value.Length > 0)
cbToggle.Items.Add(name.Value);
}
}
// nothing has changed now
fHeight = fHidden = fToggle = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.grpBoxVisibility = new System.Windows.Forms.GroupBox();
this.bHidden = new System.Windows.Forms.Button();
this.cbToggle = new System.Windows.Forms.ComboBox();
this.tbHidden = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbRowHeight = new System.Windows.Forms.TextBox();
this.grpBoxVisibility.SuspendLayout();
this.SuspendLayout();
//
// grpBoxVisibility
//
this.grpBoxVisibility.Controls.Add(this.bHidden);
this.grpBoxVisibility.Controls.Add(this.cbToggle);
this.grpBoxVisibility.Controls.Add(this.tbHidden);
this.grpBoxVisibility.Controls.Add(this.label3);
this.grpBoxVisibility.Controls.Add(this.label2);
this.grpBoxVisibility.Location = new System.Drawing.Point(8, 8);
this.grpBoxVisibility.Name = "grpBoxVisibility";
this.grpBoxVisibility.Size = new System.Drawing.Size(432, 80);
this.grpBoxVisibility.TabIndex = 1;
this.grpBoxVisibility.TabStop = false;
this.grpBoxVisibility.Text = "Visibility";
//
// bHidden
//
this.bHidden.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bHidden.Location = new System.Drawing.Point(400, 24);
this.bHidden.Name = "bHidden";
this.bHidden.Size = new System.Drawing.Size(24, 21);
this.bHidden.TabIndex = 1;
this.bHidden.Tag = "visibility";
this.bHidden.Text = "fx";
this.bHidden.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bHidden.Click += new System.EventHandler(this.bExpr_Click);
//
// cbToggle
//
this.cbToggle.Location = new System.Drawing.Point(168, 48);
this.cbToggle.Name = "cbToggle";
this.cbToggle.Size = new System.Drawing.Size(152, 21);
this.cbToggle.TabIndex = 2;
this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
//
// tbHidden
//
this.tbHidden.Location = new System.Drawing.Point(168, 24);
this.tbHidden.Name = "tbHidden";
this.tbHidden.Size = new System.Drawing.Size(224, 20);
this.tbHidden.TabIndex = 0;
this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(152, 23);
this.label3.TabIndex = 1;
this.label3.Text = "Toggle Item (Textbox name)";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 23);
this.label2.TabIndex = 0;
this.label2.Text = "Hidden (initial visibility)";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 104);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Row Height";
//
// tbRowHeight
//
this.tbRowHeight.Location = new System.Drawing.Point(88, 104);
this.tbRowHeight.Name = "tbRowHeight";
this.tbRowHeight.Size = new System.Drawing.Size(100, 20);
this.tbRowHeight.TabIndex = 3;
this.tbRowHeight.TextChanged += new System.EventHandler(this.tbRowHeight_TextChanged);
//
// TableRowCtl
//
this.Controls.Add(this.tbRowHeight);
this.Controls.Add(this.label1);
this.Controls.Add(this.grpBoxVisibility);
this.Name = "TableRowCtl";
this.Size = new System.Drawing.Size(472, 288);
this.grpBoxVisibility.ResumeLayout(false);
this.grpBoxVisibility.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
try
{
if (fHeight)
DesignerUtility.ValidateSize(this.tbRowHeight.Text, true, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Height is Invalid");
return false;
}
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
{
if (vh.StartsWith("="))
{}
else
{
vh = vh.ToLower();
switch (vh)
{
case "true":
case "false":
break;
default:
MessageBox.Show(String.Format("{0} must be an expression or 'true' or 'false'", tbHidden.Text), "Hidden is Invalid");
return false;
}
}
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
ApplyChanges(this._TableRow);
// nothing has changed now
fHeight = fHidden = fToggle = false;
}
private void ApplyChanges(XmlNode rNode)
{
if (fHidden || fToggle)
{
XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null);
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
_Draw.SetElement(visNode, "Hidden", vh);
else
_Draw.RemoveElement(visNode, "Hidden");
}
if (fToggle)
_Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text);
}
if (fHeight) // already validated
_Draw.SetElement(rNode, "Height", this.tbRowHeight.Text);
}
private void tbHidden_TextChanged(object sender, System.EventArgs e)
{
fHidden = true;
}
private void tbRowHeight_TextChanged(object sender, System.EventArgs e)
{
fHeight = true;
}
private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fToggle = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "visibility":
c = tbHidden;
break;
}
if (c == null)
return;
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _TableRow))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
return;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using Python.Runtime.StateSerialization;
namespace Python.Runtime
{
/// <summary>
/// The ClassManager is responsible for creating and managing instances
/// that implement the Python type objects that reflect managed classes.
/// Each managed type reflected to Python is represented by an instance
/// of a concrete subclass of ClassBase. Each instance is associated with
/// a generated Python type object, whose slots point to static methods
/// of the managed instance's class.
/// </summary>
internal class ClassManager
{
// Binding flags to determine which members to expose in Python.
// This is complicated because inheritance in Python is name
// based. We can't just find DeclaredOnly members, because we
// could have a base class A that defines two overloads of a
// method and a class B that defines two more. The name-based
// descriptor Python will find needs to know about inherited
// overloads as well as those declared on the sub class.
internal static readonly BindingFlags BindingFlags = BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic;
internal static Dictionary<MaybeType, ReflectedClrType> cache = new(capacity: 128);
private static readonly Type dtype;
private ClassManager()
{
}
static ClassManager()
{
// SEE: https://msdn.microsoft.com/en-us/library/96b1ayy4(v=vs.100).aspx
// ""All delegates inherit from MulticastDelegate, which inherits from Delegate.""
// Was Delegate, which caused a null MethodInfo returned from GetMethode("Invoke")
// and crashed on Linux under Mono.
dtype = typeof(MulticastDelegate);
}
public static void Reset()
{
cache.Clear();
}
internal static void RemoveClasses()
{
foreach (var @class in cache.Values)
{
@class.Dispose();
}
cache.Clear();
}
internal static ClassManagerState SaveRuntimeData()
{
var contexts = new Dictionary<ReflectedClrType, Dictionary<string, object?>>();
foreach (var cls in cache)
{
var cb = (ClassBase)ManagedType.GetManagedObject(cls.Value)!;
var context = cb.Save(cls.Value);
if (context is not null)
{
contexts[cls.Value] = context;
}
// Remove all members added in InitBaseClass.
// this is done so that if domain reloads and a member of a
// reflected dotnet class is removed, it is removed from the
// Python object's dictionary tool; thus raising an AttributeError
// instead of a TypeError.
// Classes are re-initialized on in RestoreRuntimeData.
using var dict = Runtime.PyObject_GenericGetDict(cls.Value);
foreach (var member in cb.dotNetMembers)
{
if ((Runtime.PyDict_DelItemString(dict.Borrow(), member) == -1) &&
(Exceptions.ExceptionMatches(Exceptions.KeyError)))
{
// Trying to remove a key that's not in the dictionary
// raises an error. We don't care about it.
Runtime.PyErr_Clear();
}
else if (Exceptions.ErrorOccurred())
{
throw PythonException.ThrowLastAsClrException();
}
}
// We modified the Type object, notify it we did.
Runtime.PyType_Modified(cls.Value);
}
return new()
{
Contexts = contexts,
Cache = cache,
};
}
internal static void RestoreRuntimeData(ClassManagerState storage)
{
cache = storage.Cache;
var invalidClasses = new List<KeyValuePair<MaybeType, ReflectedClrType>>();
var contexts = storage.Contexts;
foreach (var pair in cache)
{
var context = contexts[pair.Value];
if (pair.Key.Valid)
{
pair.Value.Restore(context);
}
else
{
invalidClasses.Add(pair);
var cb = new UnloadedClass(pair.Key.Name);
cb.Load(pair.Value, context);
pair.Value.Restore(cb);
}
}
}
/// <summary>
/// Return the ClassBase-derived instance that implements a particular
/// reflected managed type, creating it if it doesn't yet exist.
/// </summary>
internal static ReflectedClrType GetClass(Type type) => ReflectedClrType.GetOrCreate(type);
internal static ClassBase GetClassImpl(Type type)
{
var pyType = GetClass(type);
var impl = (ClassBase)ManagedType.GetManagedObject(pyType)!;
Debug.Assert(impl is not null);
return impl!;
}
/// <summary>
/// Create a new ClassBase-derived instance that implements a reflected
/// managed type. The new object will be associated with a generated
/// Python type object.
/// </summary>
internal static ClassBase CreateClass(Type type)
{
// Next, select the appropriate managed implementation class.
// Different kinds of types, such as array types or interface
// types, want to vary certain implementation details to make
// sure that the type semantics are consistent in Python.
ClassBase impl;
// Check to see if the given type extends System.Exception. This
// lets us check once (vs. on every lookup) in case we need to
// wrap Exception-derived types in old-style classes
if (type.ContainsGenericParameters)
{
impl = new GenericType(type);
}
else if (type.IsSubclassOf(dtype))
{
impl = new DelegateObject(type);
}
else if (type.IsArray)
{
impl = new ArrayObject(type);
}
else if (type.IsInterface)
{
impl = new InterfaceObject(type);
}
else if (type == typeof(Exception) ||
type.IsSubclassOf(typeof(Exception)))
{
impl = new ExceptionClassObject(type);
}
#pragma warning disable CS0618 // Type or member is obsolete. OK for internal use.
else if (null != PythonDerivedType.GetPyObjField(type))
#pragma warning restore CS0618 // Type or member is obsolete
{
impl = new ClassDerivedObject(type);
}
else
{
impl = new ClassObject(type);
}
return impl;
}
internal static void InitClassBase(Type type, ClassBase impl, ReflectedClrType pyType)
{
// First, we introspect the managed type and build some class
// information, including generating the member descriptors
// that we'll be putting in the Python class __dict__.
ClassInfo info = GetClassInfo(type, impl);
impl.indexer = info.indexer;
impl.richcompare.Clear();
// Finally, initialize the class __dict__ and return the object.
using var newDict = Runtime.PyObject_GenericGetDict(pyType.Reference);
BorrowedReference dict = newDict.Borrow();
foreach (var iter in info.members)
{
var item = iter.Value;
var name = iter.Key;
impl.dotNetMembers.Add(name);
Runtime.PyDict_SetItemString(dict, name, item);
if (ClassBase.CilToPyOpMap.TryGetValue(name, out var pyOp)
// workaround for unintialized types crashing in GetManagedObject
&& item is not ReflectedClrType
&& ManagedType.GetManagedObject(item) is MethodObject method)
{
impl.richcompare.Add(pyOp, method);
}
}
// If class has constructors, generate an __doc__ attribute.
NewReference doc = default;
Type marker = typeof(DocStringAttribute);
var attrs = (Attribute[])type.GetCustomAttributes(marker, false);
if (attrs.Length != 0)
{
var attr = (DocStringAttribute)attrs[0];
string docStr = attr.DocString;
doc = Runtime.PyString_FromString(docStr);
Runtime.PyDict_SetItem(dict, PyIdentifier.__doc__, doc.Borrow());
}
var co = impl as ClassObject;
// If this is a ClassObject AND it has constructors, generate a __doc__ attribute.
// required that the ClassObject.ctors be changed to internal
if (co != null)
{
if (co.NumCtors > 0 && !co.HasCustomNew())
{
// Implement Overloads on the class object
if (!CLRModule._SuppressOverloads)
{
// HACK: __init__ points to instance constructors.
// When unbound they fully instantiate object, so we get overloads for free from MethodBinding.
var init = info.members["__init__"];
// TODO: deprecate __overloads__ soon...
Runtime.PyDict_SetItem(dict, PyIdentifier.__overloads__, init);
Runtime.PyDict_SetItem(dict, PyIdentifier.Overloads, init);
}
// don't generate the docstring if one was already set from a DocStringAttribute.
if (!CLRModule._SuppressDocs && doc.IsNull())
{
doc = co.GetDocString();
Runtime.PyDict_SetItem(dict, PyIdentifier.__doc__, doc.Borrow());
}
}
}
doc.Dispose();
// The type has been modified after PyType_Ready has been called
// Refresh the type
Runtime.PyType_Modified(pyType.Reference);
}
internal static bool ShouldBindMethod(MethodBase mb)
{
return (mb.IsPublic || mb.IsFamily || mb.IsFamilyOrAssembly);
}
internal static bool ShouldBindField(FieldInfo fi)
{
return (fi.IsPublic || fi.IsFamily || fi.IsFamilyOrAssembly);
}
internal static bool ShouldBindProperty(PropertyInfo pi)
{
MethodInfo? mm;
try
{
mm = pi.GetGetMethod(true);
if (mm == null)
{
mm = pi.GetSetMethod(true);
}
}
catch (SecurityException)
{
// GetGetMethod may try to get a method protected by
// StrongNameIdentityPermission - effectively private.
return false;
}
if (mm == null)
{
return false;
}
return ShouldBindMethod(mm);
}
internal static bool ShouldBindEvent(EventInfo ei)
{
return ShouldBindMethod(ei.GetAddMethod(true));
}
private static ClassInfo GetClassInfo(Type type, ClassBase impl)
{
var ci = new ClassInfo();
var methods = new Dictionary<string, List<MethodBase>>();
MethodInfo meth;
ExtensionType ob;
string name;
Type tp;
int i, n;
MemberInfo[] info = type.GetMembers(BindingFlags);
var local = new HashSet<string>();
var items = new List<MemberInfo>();
MemberInfo m;
// Loop through once to find out which names are declared
for (i = 0; i < info.Length; i++)
{
m = info[i];
if (m.DeclaringType == type)
{
local.Add(m.Name);
}
}
if (type.IsEnum)
{
var opsImpl = typeof(EnumOps<>).MakeGenericType(type);
foreach (var op in opsImpl.GetMethods(OpsHelper.BindingFlags))
{
local.Add(op.Name);
}
info = info.Concat(opsImpl.GetMethods(OpsHelper.BindingFlags)).ToArray();
// only [Flags] enums support bitwise operations
if (type.IsFlagsEnum())
{
opsImpl = typeof(FlagEnumOps<>).MakeGenericType(type);
foreach (var op in opsImpl.GetMethods(OpsHelper.BindingFlags))
{
local.Add(op.Name);
}
info = info.Concat(opsImpl.GetMethods(OpsHelper.BindingFlags)).ToArray();
}
}
// Now again to filter w/o losing overloaded member info
for (i = 0; i < info.Length; i++)
{
m = info[i];
if (local.Contains(m.Name))
{
items.Add(m);
}
}
if (type.IsInterface)
{
// Interface inheritance seems to be a different animal:
// more contractual, less structural. Thus, a Type that
// represents an interface that inherits from another
// interface does not return the inherited interface's
// methods in GetMembers. For example ICollection inherits
// from IEnumerable, but ICollection's GetMemebers does not
// return GetEnumerator.
//
// Not sure if this is the correct way to fix this, but it
// seems to work. Thanks to Bruce Dodson for the fix.
Type[] inheritedInterfaces = type.GetInterfaces();
for (i = 0; i < inheritedInterfaces.Length; ++i)
{
Type inheritedType = inheritedInterfaces[i];
MemberInfo[] imembers = inheritedType.GetMembers(BindingFlags);
for (n = 0; n < imembers.Length; n++)
{
m = imembers[n];
if (!local.Contains(m.Name))
{
items.Add(m);
}
}
}
// All interface implementations inherit from Object,
// but GetMembers don't return them either.
var objFlags = BindingFlags.Public | BindingFlags.Instance;
foreach (var mi in typeof(object).GetMembers(objFlags))
{
if (!local.Contains(mi.Name) && mi is not ConstructorInfo)
{
items.Add(mi);
}
}
}
for (i = 0; i < items.Count; i++)
{
var mi = (MemberInfo)items[i];
switch (mi.MemberType)
{
case MemberTypes.Method:
meth = (MethodInfo)mi;
if (!ShouldBindMethod(meth))
{
continue;
}
name = meth.Name;
//TODO mangle?
if (name == "__init__" && !impl.HasCustomNew())
continue;
if (!methods.TryGetValue(name, out var methodList))
{
methodList = methods[name] = new List<MethodBase>();
}
methodList.Add(meth);
continue;
case MemberTypes.Constructor when !impl.HasCustomNew():
var ctor = (ConstructorInfo)mi;
if (ctor.IsStatic)
{
continue;
}
name = "__init__";
if (!methods.TryGetValue(name, out methodList))
{
methodList = methods[name] = new List<MethodBase>();
}
methodList.Add(ctor);
continue;
case MemberTypes.Property:
var pi = (PropertyInfo)mi;
if(!ShouldBindProperty(pi))
{
continue;
}
// Check for indexer
ParameterInfo[] args = pi.GetIndexParameters();
if (args.GetLength(0) > 0)
{
Indexer? idx = ci.indexer;
if (idx == null)
{
ci.indexer = new Indexer();
idx = ci.indexer;
}
idx.AddProperty(pi);
continue;
}
ob = new PropertyObject(pi);
ci.members[pi.Name] = ob.AllocObject();
continue;
case MemberTypes.Field:
var fi = (FieldInfo)mi;
if (!ShouldBindField(fi))
{
continue;
}
ob = new FieldObject(fi);
ci.members[mi.Name] = ob.AllocObject();
continue;
case MemberTypes.Event:
var ei = (EventInfo)mi;
if (!ShouldBindEvent(ei))
{
continue;
}
ob = ei.AddMethod.IsStatic
? new EventBinding(ei)
: new EventObject(ei);
ci.members[ei.Name] = ob.AllocObject();
continue;
case MemberTypes.NestedType:
tp = (Type)mi;
if (!(tp.IsNestedPublic || tp.IsNestedFamily ||
tp.IsNestedFamORAssem))
{
continue;
}
// Note the given instance might be uninitialized
var pyType = GetClass(tp);
// make a copy, that could be disposed later
ci.members[mi.Name] = new ReflectedClrType(pyType);
continue;
}
}
foreach (var iter in methods)
{
name = iter.Key;
var mlist = iter.Value.ToArray();
ob = new MethodObject(type, name, mlist);
ci.members[name] = ob.AllocObject();
if (mlist.Any(OperatorMethod.IsOperatorMethod))
{
string pyName = OperatorMethod.GetPyMethodName(name);
string pyNameReverse = OperatorMethod.ReversePyMethodName(pyName);
OperatorMethod.FilterMethods(mlist, out var forwardMethods, out var reverseMethods);
// Only methods where the left operand is the declaring type.
if (forwardMethods.Length > 0)
ci.members[pyName] = new MethodObject(type, name, forwardMethods).AllocObject();
// Only methods where only the right operand is the declaring type.
if (reverseMethods.Length > 0)
ci.members[pyNameReverse] = new MethodObject(type, name, reverseMethods).AllocObject();
}
}
if (ci.indexer == null && type.IsClass)
{
// Indexer may be inherited.
var parent = type.BaseType;
while (parent != null && ci.indexer == null)
{
foreach (var prop in parent.GetProperties()) {
var args = prop.GetIndexParameters();
if (args.GetLength(0) > 0)
{
ci.indexer = new Indexer();
ci.indexer.AddProperty(prop);
break;
}
}
parent = parent.BaseType;
}
}
return ci;
}
/// <summary>
/// This class owns references to PyObjects in the `members` member.
/// The caller has responsibility to DECREF them.
/// </summary>
private class ClassInfo
{
public Indexer? indexer;
public readonly Dictionary<string, PyObject> members = new();
internal ClassInfo()
{
indexer = null;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using QuantConnect.Brokerages;
using QuantConnect.Configuration;
namespace QuantConnect.ToolBox.CoinApi
{
/// <summary>
/// Provides the mapping between Lean symbols and CoinAPI symbols.
/// </summary>
/// <remarks>For now we only support mapping for CoinbasePro (GDAX) and Bitfinex</remarks>
public class CoinApiSymbolMapper : ISymbolMapper
{
private const string RestUrl = "https://rest.coinapi.io";
private readonly string _apiKey = Config.Get("coinapi-api-key");
private readonly bool _useLocalSymbolList = Config.GetBool("coinapi-use-local-symbol-list");
private readonly FileInfo _coinApiSymbolsListFile = new FileInfo(
Config.Get("coinapi-default-symbol-list-file", "CoinApiSymbols.json"));
// LEAN market <-> CoinAPI exchange id maps
private static readonly Dictionary<string, string> MapMarketsToExchangeIds = new Dictionary<string, string>
{
{ Market.GDAX, "COINBASE" },
{ Market.Bitfinex, "BITFINEX" },
{ Market.Binance, "BINANCE" }
};
private static readonly Dictionary<string, string> MapExchangeIdsToMarkets =
MapMarketsToExchangeIds.ToDictionary(x => x.Value, x => x.Key);
private static readonly Dictionary<string, Dictionary<string, string>> CoinApiToLeanCurrencyMappings =
new Dictionary<string, Dictionary<string, string>>
{
{
Market.Bitfinex,
new Dictionary<string, string>
{
{ "ABS", "ABYSS"},
{ "AIO", "AION"},
{ "ALG", "ALGO"},
{ "AMP", "AMPL"},
{ "ATO", "ATOM"},
{ "BCHABC", "BCH"},
{ "BCHSV", "BSV"},
{ "CSX", "CS"},
{ "CTX", "CTXC"},
{ "DOG", "MDOGE"},
{ "DRN", "DRGN"},
{ "DTX", "DT"},
{ "EDO", "PNT"},
{ "EUS", "EURS"},
{ "EUT", "EURT"},
{ "GSD", "GUSD"},
{ "HOPL", "HOT"},
{ "IOS", "IOST"},
{ "IOT", "IOTA"},
{ "LOO", "LOOM"},
{ "MIT", "MITH"},
{ "NCA", "NCASH"},
{ "OMN", "OMNI"},
{ "ORS", "ORST"},
{ "PAS", "PASS"},
{ "PKGO", "GOT"},
{ "POY", "POLY"},
{ "QSH", "QASH"},
{ "REP", "REP2"},
{ "SCR", "XD"},
{ "SNG", "SNGLS"},
{ "SPK", "SPANK"},
{ "STJ", "STORJ"},
{ "TSD", "TUSD"},
{ "UDC", "USDC"},
{ "ULTRA", "UOS"},
{ "USK", "USDK"},
{ "UTN", "UTNP"},
{ "VSY", "VSYS"},
{ "WBT", "WBTC"},
{ "XCH", "XCHF"},
{ "YGG", "YEED"}
}
}
};
// map LEAN symbols to CoinAPI symbol ids
private Dictionary<Symbol, string> _symbolMap = new Dictionary<Symbol, string>();
/// <summary>
/// Creates a new instance of the <see cref="CoinApiSymbolMapper"/> class
/// </summary>
public CoinApiSymbolMapper()
{
LoadSymbolMap(MapMarketsToExchangeIds.Values.ToArray());
}
/// <summary>
/// Converts a Lean symbol instance to a CoinAPI symbol id
/// </summary>
/// <param name="symbol">A Lean symbol instance</param>
/// <returns>The CoinAPI symbol id</returns>
public string GetBrokerageSymbol(Symbol symbol)
{
string symbolId;
if (!_symbolMap.TryGetValue(symbol, out symbolId))
{
throw new Exception($"CoinApiSymbolMapper.GetBrokerageSymbol(): Symbol not found: {symbol}");
}
return symbolId;
}
/// <summary>
/// Converts a CoinAPI symbol id to a Lean symbol instance
/// </summary>
/// <param name="brokerageSymbol">The CoinAPI symbol id</param>
/// <param name="securityType">The security type</param>
/// <param name="market">The market</param>
/// <param name="expirationDate">Expiration date of the security (if applicable)</param>
/// <param name="strike">The strike of the security (if applicable)</param>
/// <param name="optionRight">The option right of the security (if applicable)</param>
/// <returns>A new Lean Symbol instance</returns>
public Symbol GetLeanSymbol(string brokerageSymbol, SecurityType securityType, string market,
DateTime expirationDate = new DateTime(), decimal strike = 0, OptionRight optionRight = OptionRight.Call)
{
var parts = brokerageSymbol.Split('_');
if (parts.Length != 4 || parts[1] != "SPOT")
{
throw new Exception($"CoinApiSymbolMapper.GetLeanSymbol(): Unsupported SymbolId: {brokerageSymbol}");
}
string symbolMarket;
if (!MapExchangeIdsToMarkets.TryGetValue(parts[0], out symbolMarket))
{
throw new Exception($"CoinApiSymbolMapper.GetLeanSymbol(): Unsupported ExchangeId: {parts[0]}");
}
var baseCurrency = ConvertCoinApiCurrencyToLeanCurrency(parts[2], symbolMarket);
var quoteCurrency = ConvertCoinApiCurrencyToLeanCurrency(parts[3], symbolMarket);
var ticker = baseCurrency + quoteCurrency;
return Symbol.Create(ticker, SecurityType.Crypto, symbolMarket);
}
/// <summary>
/// Returns the CoinAPI exchange id for the given market
/// </summary>
/// <param name="market">The Lean market</param>
/// <returns>The CoinAPI exchange id</returns>
public string GetExchangeId(string market)
{
string exchangeId;
MapMarketsToExchangeIds.TryGetValue(market, out exchangeId);
return exchangeId;
}
private void LoadSymbolMap(string[] exchangeIds)
{
var list = string.Join(",", exchangeIds);
var json = string.Empty;
if (_useLocalSymbolList)
{
if (!_coinApiSymbolsListFile.Exists)
{
throw new Exception($"CoinApiSymbolMapper.LoadSymbolMap(): File not found: {_coinApiSymbolsListFile.FullName}, please " +
$"download the latest symbol list from CoinApi.");
}
json = File.ReadAllText(_coinApiSymbolsListFile.FullName);
}
else
{
json = $"{RestUrl}/v1/symbols?filter_symbol_id={list}&apiKey={_apiKey}".DownloadData();
}
var result = JsonConvert.DeserializeObject<List<CoinApiSymbol>>(json);
// There were cases of entries in the CoinApiSymbols list with the following pattern:
// <Exchange>_SPOT_<BaseCurrency>_<QuoteCurrency>_<ExtraSuffix>
// Those cases should be ignored for SPOT prices.
_symbolMap = result
.Where(x => x.SymbolType == "SPOT" &&
x.SymbolId.Split('_').Length == 4 &&
// exclude Bitfinex BCH pre-2018-fork as for now we don't have historical mapping data
(x.ExchangeId != "BITFINEX" || x.AssetIdBase != "BCH" && x.AssetIdQuote != "BCH")
// solves the cases where we request 'binance' and get 'binanceus'
&& MapExchangeIdsToMarkets.ContainsKey(x.ExchangeId))
.ToDictionary(
x =>
{
var market = MapExchangeIdsToMarkets[x.ExchangeId];
return Symbol.Create(
ConvertCoinApiCurrencyToLeanCurrency(x.AssetIdBase, market) +
ConvertCoinApiCurrencyToLeanCurrency(x.AssetIdQuote, market),
SecurityType.Crypto,
market);
},
x => x.SymbolId);
}
private static string ConvertCoinApiCurrencyToLeanCurrency(string currency, string market)
{
Dictionary<string, string> mappings;
if (CoinApiToLeanCurrencyMappings.TryGetValue(market, out mappings))
{
string mappedCurrency;
if (mappings.TryGetValue(currency, out mappedCurrency))
{
currency = mappedCurrency;
}
}
return currency;
}
}
}
| |
/*
** $Id: loadlib.c,v 1.52.1.3 2008/08/06 13:29:28 roberto Exp $
** Dynamic library loader for Lua
** See Copyright Notice in lua.h
**
** This module contains an implementation of loadlib for Unix systems
** that have dlfcn, an implementation for Darwin (Mac OS X), an
** implementation for Windows, and a stub for other systems.
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace SharpLua
{
public partial class Lua
{
/* prefix for open functions in C libraries */
public const string LUA_POF = "luaopen_";
/* separator for open functions in C libraries */
public const string LUA_OFSEP = "_";
public const string LIBPREFIX = "LOADLIB: ";
public const string POF = LUA_POF;
public const string LIB_FAIL = "open";
/* error codes for ll_loadfunc */
public const int ERRLIB = 1;
public const int ERRFUNC = 2;
//public static void setprogdir(lua_State L) { }
public static void setprogdir(LuaState L)
{
CharPtr buff = Directory.GetCurrentDirectory();
luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
lua_remove(L, -2); /* remove original string */
}
#if LUA_DL_DLOPEN
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.
** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
** as an emulation layer on top of native functions.
** =========================================================================
*/
//#include <dlfcn.h>
static void ll_unloadlib (void *lib) {
dlclose(lib);
}
static void *ll_load (lua_State L, readonly CharPtr path) {
void *lib = dlopen(path, RTLD_NOW);
if (lib == null) lua_pushstring(L, dlerror());
return lib;
}
static lua_CFunction ll_sym (lua_State L, void *lib, readonly CharPtr sym) {
lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
if (f == null) lua_pushstring(L, dlerror());
return f;
}
/* }====================================================== */
//#elif defined(LUA_DL_DLL)
/*
** {======================================================================
** This is an implementation of loadlib for Windows using native functions.
** =======================================================================
*/
//#include <windows.h>
//#undef setprogdir
static void setprogdir (lua_State L) {
char buff[MAX_PATH + 1];
char *lb;
DWORD nsize = sizeof(buff)/GetUnmanagedSize(typeof(char));
DWORD n = GetModuleFileNameA(null, buff, nsize);
if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == null)
luaL_error(L, "unable to get ModuleFileName");
else {
*lb = '\0';
luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
lua_remove(L, -2); /* remove original string */
}
}
static void pusherror (lua_State L) {
int error = GetLastError();
char buffer[128];
if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
null, error, 0, buffer, sizeof(buffer), null))
lua_pushstring(L, buffer);
else
lua_pushfstring(L, "system error %d\n", error);
}
static void ll_unloadlib (void *lib) {
FreeLibrary((HINSTANCE)lib);
}
static void *ll_load (lua_State L, readonly CharPtr path) {
HINSTANCE lib = LoadLibraryA(path);
if (lib == null) pusherror(L);
return lib;
}
static lua_CFunction ll_sym (lua_State L, void *lib, readonly CharPtr sym) {
lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
if (f == null) pusherror(L);
return f;
}
/* }====================================================== */
#elif LUA_DL_DYLD
/*
** {======================================================================
** Native Mac OS X / Darwin Implementation
** =======================================================================
*/
//#include <mach-o/dyld.h>
/* Mac appends a `_' before C function names */
//#undef POF
//#define POF "_" LUA_POF
static void pusherror (lua_State L) {
CharPtr err_str;
CharPtr err_file;
NSLinkEditErrors err;
int err_num;
NSLinkEditError(err, err_num, err_file, err_str);
lua_pushstring(L, err_str);
}
static CharPtr errorfromcode (NSObjectFileImageReturnCode ret) {
switch (ret) {
case NSObjectFileImageInappropriateFile:
return "file is not a bundle";
case NSObjectFileImageArch:
return "library is for wrong CPU type";
case NSObjectFileImageFormat:
return "bad format";
case NSObjectFileImageAccess:
return "cannot access file";
case NSObjectFileImageFailure:
default:
return "unable to load library";
}
}
static void ll_unloadlib (void *lib) {
NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
}
static void *ll_load (lua_State L, readonly CharPtr path) {
NSObjectFileImage img;
NSObjectFileImageReturnCode ret;
/* this would be a rare case, but prevents crashing if it happens */
if(!_dyld_present()) {
lua_pushliteral(L, "dyld not present");
return null;
}
ret = NSCreateObjectFileImageFromFile(path, img);
if (ret == NSObjectFileImageSuccess) {
NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE |
NSLINKMODULE_OPTION_RETURN_ON_ERROR);
NSDestroyObjectFileImage(img);
if (mod == null) pusherror(L);
return mod;
}
lua_pushstring(L, errorfromcode(ret));
return null;
}
static lua_CFunction ll_sym (lua_State L, void *lib, readonly CharPtr sym) {
NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
if (nss == null) {
lua_pushfstring(L, "symbol " + LUA_QS + " not found", sym);
return null;
}
return (lua_CFunction)NSAddressOfSymbol(nss);
}
/* }====================================================== */
#else
/*
** {======================================================
** Fallback for other systems
** =======================================================
*/
//#undef LIB_FAIL
//#define LIB_FAIL "absent"
public const string DLMSG = "SharpLua does not support loading C modules"; //"dynamic libraries not enabled; check your Lua installation";
public static void ll_unloadlib(object lib)
{
//(void)lib; /* to avoid warnings */
}
public static object ll_load(LuaState L, CharPtr path)
{
//(void)path; /* to avoid warnings */
lua_pushliteral(L, DLMSG);
return null;
}
public static lua_CFunction ll_sym(LuaState L, object lib, CharPtr sym)
{
//(void)lib; (void)sym; /* to avoid warnings */
lua_pushliteral(L, DLMSG);
return null;
}
/* }====================================================== */
#endif
private static object ll_register(LuaState L, CharPtr path)
{
// todo: the whole usage of plib here is wrong, fix it - mjf
//void **plib;
object plib = null;
lua_pushfstring(L, "%s%s", LIBPREFIX, path);
lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
if (!lua_isnil(L, -1)) /* is there an entry? */
plib = lua_touserdata(L, -1);
else
{ /* no entry yet; create one */
lua_pop(L, 1);
//plib = lua_newuserdata(L, (uint)Marshal.SizeOf(plib));
//plib[0] = null;
luaL_getmetatable(L, "_LOADLIB");
lua_setmetatable(L, -2);
lua_pushfstring(L, "%s%s", LIBPREFIX, path);
lua_pushvalue(L, -2);
lua_settable(L, LUA_REGISTRYINDEX);
}
return plib;
}
/*
** __gc tag method: calls library's `ll_unloadlib' function with the lib
** handle
*/
private static int gctm(LuaState L)
{
object lib = luaL_checkudata(L, 1, "_LOADLIB");
if (lib != null) ll_unloadlib(lib);
lib = null; /* mark library as closed */
return 0;
}
private static int ll_loadfunc(LuaState L, CharPtr path, CharPtr sym)
{
object reg = ll_register(L, path);
if (reg == null)
reg = ll_load(L, path);
if (reg == null)
return ERRLIB; /* unable to load library */
else
{
lua_CFunction f = ll_sym(L, reg, sym);
if (f == null)
return ERRFUNC; /* unable to find function */
lua_pushcfunction(L, f);
return 0; /* return function */
}
}
private static int ll_loadlib(LuaState L)
{
CharPtr path = luaL_checkstring(L, 1);
CharPtr init = luaL_checkstring(L, 2);
int stat = ll_loadfunc(L, path, init);
if (stat == 0) /* no errors? */
return 1; /* return the loaded function */
else
{ /* error; error message is on stack top */
lua_pushnil(L);
lua_insert(L, -2);
lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
return 3; /* return nil, error message, and where */
}
}
/*
** {======================================================
** 'require' function
** =======================================================
*/
private static int readable(CharPtr filename)
{
Stream f = fopen(filename, "r"); /* try to open file */
if (f == null) return 0; /* open failed */
fclose(f);
return 1;
}
private static CharPtr pushnexttemplate(LuaState L, CharPtr path)
{
CharPtr l;
while (path[0] == LUA_PATHSEP[0]) path = path.next(); /* skip separators */
if (path[0] == '\0') return null; /* no more templates */
l = strchr(path, LUA_PATHSEP[0]); /* find next separator */
if (l == null) l = path + strlen(path);
lua_pushlstring(L, path, (uint)(l - path)); /* template */
return l;
}
private static CharPtr findfile(LuaState L, CharPtr name,
CharPtr pname)
{
CharPtr path;
name = luaL_gsub(L, name, ".", LUA_DIRSEP);
lua_getfield(L, LUA_ENVIRONINDEX, pname);
path = lua_tostring(L, -1);
if (path == null)
luaL_error(L, LUA_QL("package.%s") + " must be a string", pname);
lua_pushliteral(L, ""); /* error accumulator */
while ((path = pushnexttemplate(L, path)) != null)
{
CharPtr filename;
filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name);
lua_remove(L, -2); /* remove path template */
if (readable(filename) != 0) /* does file exist and is readable? */
return filename; /* return that file name */
lua_pushfstring(L, "\n\tno file " + LUA_QS, filename);
lua_remove(L, -2); /* remove file name */
lua_concat(L, 2); /* add entry to possible error message */
}
return null; /* not found */
}
private static void loaderror(LuaState L, CharPtr filename)
{
luaL_error(L, "error loading module " + LUA_QS + " from file " + LUA_QS + ":\n\t%s",
lua_tostring(L, 1), filename, lua_tostring(L, -1));
}
private static int loader_Lua(LuaState L)
{
CharPtr filename;
CharPtr name = luaL_checkstring(L, 1);
filename = findfile(L, name, "path");
if (filename == null) return 1; /* library not found in this path */
if (luaL_loadfile(L, filename) != 0)
loaderror(L, filename);
return 1; /* library loaded successfully */
}
private static CharPtr mkfuncname(LuaState L, CharPtr modname)
{
CharPtr funcname;
CharPtr mark = strchr(modname, LUA_IGMARK[0]);
if (mark != null) modname = mark + 1;
funcname = luaL_gsub(L, modname, ".", LUA_OFSEP);
funcname = lua_pushfstring(L, POF + "%s", funcname);
lua_remove(L, -2); /* remove 'gsub' result */
return funcname;
}
private static int loader_C(LuaState L)
{
CharPtr funcname;
CharPtr name = luaL_checkstring(L, 1);
CharPtr filename = findfile(L, name, "cpath");
if (filename == null) return 1; /* library not found in this path */
funcname = mkfuncname(L, name);
if (ll_loadfunc(L, filename, funcname) != 0)
loaderror(L, filename);
return 1; /* library loaded successfully */
}
private static int loader_CLRModule(LuaState L)
{
CharPtr name = luaL_checkstring(L, 1);
CharPtr filename = findfile(L, name, "cpath");
if (filename == null)
return 1; /* library not found in this path */
Assembly a = Assembly.LoadFrom(filename);
string sfn = System.IO.Path.GetFileNameWithoutExtension(filename);
int i = 0;
foreach (Type t in a.GetTypes())
{
if (t.IsClass == true && t.GetCustomAttributes(typeof(LuaModuleAttribute), false).Length > 0)
{
i++;
//L.Interface.RegisterModule(t);
lua_pushcfunction(L, (l) =>
{
LuaTable tbl = l.Interface.RegisterModule(t);
tbl.push(l);
return 1;
});
}
else if (t.IsClass)
{
MethodInfo mi = t.GetMethod("luaopen_" + sfn, BindingFlags.Static | BindingFlags.Public);
if (mi != null)
{
i++;
lua_pushcfunction(L, (l) =>
{
return (int)mi.Invoke(null, new object[] { l });
});
}
}
}
return i;
}
private static int loader_Croot(LuaState L)
{
CharPtr funcname;
CharPtr filename;
CharPtr name = luaL_checkstring(L, 1);
CharPtr p = strchr(name, '.');
int stat;
if (p == null) return 0; /* is root */
lua_pushlstring(L, name, (uint)(p - name));
filename = findfile(L, lua_tostring(L, -1), "cpath");
if (filename == null) return 1; /* root not found */
funcname = mkfuncname(L, name);
if ((stat = ll_loadfunc(L, filename, funcname)) != 0)
{
if (stat != ERRFUNC) loaderror(L, filename); /* real error */
lua_pushfstring(L, "\n\tno module " + LUA_QS + " in file " + LUA_QS,
name, filename);
return 1; /* function not found */
}
return 1;
}
private static int loader_preload(LuaState L)
{
CharPtr name = luaL_checkstring(L, 1);
lua_getfield(L, LUA_ENVIRONINDEX, "preload");
if (!lua_istable(L, -1))
luaL_error(L, LUA_QL("package.preload") + " must be a table");
lua_getfield(L, -1, name);
if (lua_isnil(L, -1)) /* not found? */
lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
return 1;
}
public static object sentinel = new object();
public static int ll_require(LuaState L)
{
CharPtr name = luaL_checkstring(L, 1);
int i;
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, name);
if (lua_toboolean(L, -1) != 0)
{ /* is it there? */
if (lua_touserdata(L, -1) == sentinel) /* check loops */
luaL_error(L, "loop or previous error loading module " + LUA_QS, name);
return 1; /* package is already loaded */
}
/* else must load it; iterate over available loaders */
lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
if (!lua_istable(L, -1))
luaL_error(L, LUA_QL("package.loaders") + " must be a table");
lua_pushliteral(L, ""); /* error message accumulator */
for (i = 1; ; i++)
{
lua_rawgeti(L, -2, i); /* get a loader */
if (lua_isnil(L, -1))
luaL_error(L, "module " + LUA_QS + " not found:%s",
name, lua_tostring(L, -2));
lua_pushstring(L, name);
lua_call(L, 1, 1); /* call it */
if (lua_isfunction(L, -1)) /* did it find module? */
break; /* module loaded successfully */
else if (lua_isstring(L, -1) != 0) /* loader returned error message? */
lua_concat(L, 2); /* accumulate it */
else
lua_pop(L, 1);
}
lua_pushlightuserdata(L, sentinel);
lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
lua_pushstring(L, name); /* pass name as argument to module */
lua_call(L, 1, 1); /* run loaded module */
if (!lua_isnil(L, -1)) /* non-nil return? */
lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
lua_getfield(L, 2, name);
if (lua_touserdata(L, -1) == sentinel)
{ /* module did not set a value? */
lua_pushboolean(L, 1); /* use true as result */
lua_pushvalue(L, -1); /* extra copy to be returned */
lua_setfield(L, 2, name); /* _LOADED[name] = true */
}
return 1;
}
/* }====================================================== */
/*
** {======================================================
** 'module' function
** =======================================================
*/
private static void setfenv(LuaState L)
{
lua_Debug ar = new lua_Debug();
if (lua_getstack(L, 1, ar) == 0 ||
lua_getinfo(L, "f", ar) == 0 || /* get calling function */
lua_iscfunction(L, -1))
luaL_error(L, LUA_QL("module") + " not called from a Lua function");
lua_pushvalue(L, -2);
lua_setfenv(L, -2);
lua_pop(L, 1);
}
private static void dooptions(LuaState L, int n)
{
int i;
for (i = 2; i <= n; i++)
{
lua_pushvalue(L, i); /* get option (a function) */
lua_pushvalue(L, -2); /* module */
lua_call(L, 1, 0);
}
}
private static void modinit(LuaState L, CharPtr modname)
{
CharPtr dot;
lua_pushvalue(L, -1);
lua_setfield(L, -2, "_M"); /* module._M = module */
lua_pushstring(L, modname);
lua_setfield(L, -2, "_NAME");
dot = strrchr(modname, '.'); /* look for last dot in module name */
if (dot == null) dot = modname;
else dot = dot.next();
/* set _PACKAGE as package name (full module name minus last part) */
lua_pushlstring(L, modname, (uint)(dot - modname));
lua_setfield(L, -2, "_PACKAGE");
}
private static int ll_module(LuaState L)
{
CharPtr modname = luaL_checkstring(L, 1);
int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
if (!lua_istable(L, -1))
{ /* not found? */
lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */
if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != null)
return luaL_error(L, "name conflict for module " + LUA_QS, modname);
lua_pushvalue(L, -1);
lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
}
/* check whether table already has a _NAME field */
lua_getfield(L, -1, "_NAME");
if (!lua_isnil(L, -1)) /* is table an initialized module? */
lua_pop(L, 1);
else
{ /* no; initialize it */
lua_pop(L, 1);
modinit(L, modname);
}
lua_pushvalue(L, -1);
setfenv(L);
dooptions(L, loaded - 1);
return 0;
}
private static int ll_seeall(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
if (lua_getmetatable(L, 1) == 0)
{
lua_createtable(L, 0, 1); /* create new metatable */
lua_pushvalue(L, -1);
lua_setmetatable(L, 1);
}
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_setfield(L, -2, "__index"); /* mt.__index = _G */
return 0;
}
/* }====================================================== */
/* auxiliary mark (for internal use) */
public readonly static string AUXMARK = String.Format("{0}", (char)1);
private static void setpath(LuaState L, CharPtr fieldname, CharPtr envname,
CharPtr def)
{
CharPtr path = getenv(envname);
if (path == null) /* no environment variable? */
lua_pushstring(L, def); /* use default */
else
{
/* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
path = luaL_gsub(L, path, LUA_PATHSEP + LUA_PATHSEP,
LUA_PATHSEP + AUXMARK + LUA_PATHSEP);
luaL_gsub(L, path, AUXMARK, def);
lua_remove(L, -2);
}
setprogdir(L);
lua_setfield(L, -2, fieldname);
}
private readonly static luaL_Reg[] pk_funcs = {
new luaL_Reg("loadlib", ll_loadlib),
new luaL_Reg("seeall", ll_seeall),
new luaL_Reg(null, null)
};
private readonly static luaL_Reg[] ll_funcs = {
new luaL_Reg("module", ll_module),
new luaL_Reg("require", ll_require),
new luaL_Reg(null, null)
};
public readonly static lua_CFunction[] loaders = {
loader_preload,
loader_Lua,
loader_CLRModule,
loader_C,
loader_Croot,
null
};
public static int luaopen_package(LuaState L)
{
int i;
/* create new type _LOADLIB */
luaL_newmetatable(L, "_LOADLIB");
lua_pushcfunction(L, gctm);
lua_setfield(L, -2, "__gc");
/* create `package' table */
luaL_register(L, LUA_LOADLIBNAME, pk_funcs);
#if LUA_COMPAT_LOADLIB
lua_getfield(L, -1, "loadlib");
lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
#endif
lua_pushvalue(L, -1);
lua_replace(L, LUA_ENVIRONINDEX);
/* create `loaders' table */
//lua_createtable(L, 0, loaders.Length - 1);
lua_createtable(L, loaders.Length - 1, 0);
//lua_createtable(L, sizeof(loaders) / sizeof(loaders[0]) - 1, 0);
/* fill it with pre-defined loaders */
for (i = 0; loaders[i] != null; i++)
{
lua_pushcfunction(L, loaders[i]);
lua_rawseti(L, -2, i + 1);
}
lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
string lpath = Environment.GetEnvironmentVariable(LUA_PATH);
if (lpath != null && !string.IsNullOrWhiteSpace(lpath))
lpath = lpath + ";" + LUA_PATH_DEFAULT;
else
lpath = LUA_PATH_DEFAULT;
setpath(L, "path", LUA_PATH, lpath); /* set field `path' */
string cpath = Environment.GetEnvironmentVariable(LUA_CPATH);
if (cpath != null && !string.IsNullOrWhiteSpace(cpath))
cpath = cpath + ";" + LUA_CPATH_DEFAULT;
else
cpath = LUA_CPATH_DEFAULT;
setpath(L, "cpath", LUA_CPATH, cpath); /* set field `cpath' */
/* store config information */
lua_pushliteral(L, LUA_DIRSEP + "\n" + LUA_PATHSEP + "\n" + LUA_PATH_MARK + "\n" +
LUA_EXECDIR + "\n" + LUA_IGMARK);
lua_setfield(L, -2, "config");
/* set field `loaded' */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2);
lua_setfield(L, -2, "loaded");
/* set field `preload' */
lua_newtable(L);
lua_setfield(L, -2, "preload");
lua_pushvalue(L, LUA_GLOBALSINDEX);
luaL_register(L, null, ll_funcs); /* open lib into global table */
lua_pop(L, 1);
return 1; /* return 'package' table */
}
}
}
| |
using System;
using System.Runtime.Serialization;
using Tweetsharp;
using Newtonsoft.Json;
namespace TweetSharp
{
/*
<list>
<id>2029636</id>
<name>firemen</name>
<full_name>@twitterapidocs/firemen</full_name>
<slug>firemen</slug>
<subscriber_count>0</subscriber_count>
<member_count>0</member_count>
<uri>/twitterapidocs/firemen</uri>
<mode>public</mode>
<user/>
</list>
*/
/// <summary>
/// Represents a user-curated list of Twitter members,
/// that other users can subscribe to and see the aggregated
/// list of member tweets in a dedicated timeline.
/// </summary>
#if !Smartphone && !NET20
[DataContract]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterList : PropertyChangedBase, ITwitterModel
{
private long _id;
private string _name;
private string _fullName;
private string _slug;
private string _description;
private int _subscriberCount;
private int _memberCount;
private string _uri;
private string _mode;
private TwitterUser _user;
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the ID of the list.
/// </summary>
/// <value>The list ID.</value>
[DataMember]
#endif
public virtual long Id
{
get { return _id; }
set
{
if (_id == value)
{
return;
}
_id = value;
OnPropertyChanged("Id");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the descriptive name of the list.
/// </summary>
/// <value>The name.</value>
[DataMember]
#endif
public virtual string Name
{
get { return _name; }
set
{
if (_name == value)
{
return;
}
_name = value;
OnPropertyChanged("Name");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the full name of the list including the list owner.
/// </summary>
/// <value>The full name of the list.</value>
[DataMember]
#endif
public virtual string FullName
{
get { return _fullName; }
set
{
if (_fullName == value)
{
return;
}
_fullName = value;
OnPropertyChanged("FullName");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the user-supplied list description.
/// </summary>
/// <value>The list description.</value>
[DataMember]
#endif
public virtual string Description
{
get { return _description; }
set
{
if (_description == value)
{
return;
}
_description = value;
OnPropertyChanged("Description");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the list URL slug.
/// </summary>
/// <value>The list slug.</value>
[DataMember]
#endif
public virtual string Slug
{
get { return _slug; }
set
{
if (_slug == value)
{
return;
}
_slug = value;
OnPropertyChanged("Slug");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the subscriber count.
/// A subscriber follows the list's updates.
/// </summary>
/// <value>The subscriber count.</value>
[DataMember]
#endif
public virtual int SubscriberCount
{
get { return _subscriberCount; }
set
{
if (_subscriberCount == value)
{
return;
}
_subscriberCount = value;
OnPropertyChanged("SubscriberCount");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the member count.
/// A member's updates appear in the list.
/// </summary>
/// <value>The member count.</value>
[DataMember]
#endif
public virtual int MemberCount
{
get { return _memberCount; }
set
{
if (_memberCount == value)
{
return;
}
_memberCount = value;
OnPropertyChanged("MemberCount");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the URI of the list.
/// </summary>
/// <value>The URI of the list.</value>
[DataMember]
#endif
public virtual string Uri
{
get { return _uri; }
set
{
if (_uri == value)
{
return;
}
_uri = value;
OnPropertyChanged("Uri");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the mode.
/// The list can be "public", visible to everyone,
/// or "private", visible only to the authenticating user.
/// </summary>
/// <value>The mode.</value>
[DataMember]
#endif
public virtual string Mode
{
get { return _mode; }
set
{
if (_mode == value)
{
return;
}
_mode = value;
OnPropertyChanged("Mode");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the user who created the list.
/// </summary>
/// <value>The user.</value>
[DataMember]
#endif
public virtual TwitterUser User
{
get { return _user; }
set
{
if (_user == value)
{
return;
}
_user = value;
OnPropertyChanged("User");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string RawSource { get; set; }
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
namespace Cinemachine.Editor
{
public static class CinemachineMenu
{
public const string kCinemachineRootMenu = "Assets/Create/Cinemachine/";
[MenuItem(kCinemachineRootMenu + "Blender/Settings")]
private static void CreateBlenderSettingAsset()
{
ScriptableObjectUtility.Create<CinemachineBlenderSettings>();
}
[MenuItem(kCinemachineRootMenu + "Noise/Settings")]
private static void CreateNoiseSettingAsset()
{
ScriptableObjectUtility.Create<NoiseSettings>();
}
[MenuItem("Cinemachine/Create Virtual Camera", false, 1)]
public static CinemachineVirtualCamera CreateVirtualCamera()
{
return InternalCreateVirtualCamera(
"CM vcam", true, typeof(CinemachineComposer), typeof(CinemachineTransposer));
}
[MenuItem("Cinemachine/Create FreeLook Camera", false, 1)]
private static void CreateFreeLookCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineFreeLook), "CM FreeLook"));
Undo.RegisterCreatedObjectUndo(go, "create FreeLook");
Undo.AddComponent<CinemachineFreeLook>(go);
Selection.activeGameObject = go;
}
[MenuItem("Cinemachine/Create Blend List Camera", false, 1)]
private static void CreateBlendListCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineBlendListCamera), "CM BlendListCamera"));
Undo.RegisterCreatedObjectUndo(go, "create Blend List camera");
var vcam = Undo.AddComponent<CinemachineBlendListCamera>(go);
Selection.activeGameObject = go;
// Give it a couple of children
var child1 = CreateDefaultVirtualCamera();
Undo.SetTransformParent(child1.transform, go.transform, "create BlendListCam child");
var child2 = CreateDefaultVirtualCamera();
child2.m_Lens.FieldOfView = 10;
Undo.SetTransformParent(child2.transform, go.transform, "create BlendListCam child");
// Set up initial instruction set
vcam.m_Instructions = new CinemachineBlendListCamera.Instruction[2];
vcam.m_Instructions[0].m_VirtualCamera = child1;
vcam.m_Instructions[0].m_Hold = 1f;
vcam.m_Instructions[1].m_VirtualCamera = child2;
vcam.m_Instructions[1].m_Blend.m_Style = CinemachineBlendDefinition.Style.EaseInOut;
vcam.m_Instructions[1].m_Blend.m_Time = 2f;
}
[MenuItem("Cinemachine/Create State-Driven Camera", false, 1)]
private static void CreateStateDivenCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineStateDrivenCamera), "CM StateDrivenCamera"));
Undo.RegisterCreatedObjectUndo(go, "create state driven camera");
Undo.AddComponent<CinemachineStateDrivenCamera>(go);
Selection.activeGameObject = go;
// Give it a child
Undo.SetTransformParent(CreateDefaultVirtualCamera().transform, go.transform, "create state driven camera");
}
[MenuItem("Cinemachine/Create ClearShot Camera", false, 1)]
private static void CreateClearShotVirtualCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineClearShot), "CM ClearShot"));
Undo.RegisterCreatedObjectUndo(go, "create ClearShot camera");
Undo.AddComponent<CinemachineClearShot>(go);
Selection.activeGameObject = go;
// Give it a child
var child = CreateDefaultVirtualCamera();
Undo.SetTransformParent(child.transform, go.transform, "create ClearShot camera");
var collider = Undo.AddComponent<CinemachineCollider>(child.gameObject);
collider.m_AvoidObstacles = false;
Undo.RecordObject(collider, "create ClearShot camera");
}
[MenuItem("Cinemachine/Create Dolly Camera with Track", false, 1)]
private static void CreateDollyCameraWithPath()
{
CinemachineVirtualCamera vcam = InternalCreateVirtualCamera(
"CM vcam", true, typeof(CinemachineComposer), typeof(CinemachineTrackedDolly));
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineSmoothPath), "DollyTrack"));
Undo.RegisterCreatedObjectUndo(go, "create track");
CinemachineSmoothPath path = Undo.AddComponent<CinemachineSmoothPath>(go);
var dolly = vcam.GetCinemachineComponent<CinemachineTrackedDolly>();
Undo.RecordObject(dolly, "create track");
dolly.m_Path = path;
}
[MenuItem("Cinemachine/Create Target Group Camera", false, 1)]
private static void CreateTargetGroupCamera()
{
CinemachineVirtualCamera vcam = InternalCreateVirtualCamera(
"CM vcam", true, typeof(CinemachineGroupComposer), typeof(CinemachineTransposer));
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineTargetGroup), "TargetGroup"),
typeof(CinemachineTargetGroup));
Undo.RegisterCreatedObjectUndo(go, "create target group");
vcam.LookAt = go.transform;
vcam.Follow = go.transform;
}
[MenuItem("Cinemachine/Create Mixing Camera", false, 1)]
private static void CreateMixingCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineMixingCamera), "CM MixingCamera"));
Undo.RegisterCreatedObjectUndo(go, "create MixingCamera camera");
Undo.AddComponent<CinemachineMixingCamera>(go);
Selection.activeGameObject = go;
// Give it a couple of children
Undo.SetTransformParent(CreateDefaultVirtualCamera().transform, go.transform, "create MixedCamera child");
Undo.SetTransformParent(CreateDefaultVirtualCamera().transform, go.transform, "create MixingCamera child");
}
[MenuItem("Cinemachine/Create 2D Camera", false, 1)]
private static void Create2DCamera()
{
InternalCreateVirtualCamera("CM vcam", true, typeof(CinemachineFramingTransposer));
}
[MenuItem("Cinemachine/Create Dolly Track with Cart", false, 1)]
private static void CreateDollyTrackWithCart()
{
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineSmoothPath), "DollyTrack"));
Undo.RegisterCreatedObjectUndo(go, "create track");
CinemachineSmoothPath path = Undo.AddComponent<CinemachineSmoothPath>(go);
Selection.activeGameObject = go;
go = new GameObject(GenerateUniqueObjectName(typeof(CinemachineDollyCart), "DollyCart"));
Undo.RegisterCreatedObjectUndo(go, "create cart");
CinemachineDollyCart cart = Undo.AddComponent<CinemachineDollyCart>(go);
Undo.RecordObject(cart, "create track");
cart.m_Path = path;
}
[MenuItem("Cinemachine/Import Example Asset Package")]
private static void ImportExamplePackage()
{
string pkgFile = ScriptableObjectUtility.CinemachineInstallPath
+ "/CinemachineExamples.unitypackage";
if (!File.Exists(pkgFile))
Debug.LogError("Missing file " + pkgFile);
else
AssetDatabase.ImportPackage(pkgFile, true);
}
/// <summary>
/// Create a default Virtual Camera, with standard components
/// </summary>
public static CinemachineVirtualCamera CreateDefaultVirtualCamera()
{
return InternalCreateVirtualCamera(
"CM vcam", false, typeof(CinemachineComposer), typeof(CinemachineTransposer));
}
/// <summary>
/// Create a Virtual Camera, with components
/// </summary>
static CinemachineVirtualCamera InternalCreateVirtualCamera(
string name, bool selectIt, params Type[] components)
{
// Create a new virtual camera
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineVirtualCamera), name));
Undo.RegisterCreatedObjectUndo(go, "create " + name);
CinemachineVirtualCamera vcam = Undo.AddComponent<CinemachineVirtualCamera>(go);
GameObject componentOwner = vcam.GetComponentOwner().gameObject;
foreach (Type t in components)
Undo.AddComponent(componentOwner, t);
vcam.InvalidateComponentPipeline();
if (selectIt)
Selection.activeObject = go;
return vcam;
}
/// <summary>
/// If there is no CinemachineBrain in the scene, try to create one on the main camera
/// </summary>
public static void CreateCameraBrainIfAbsent()
{
CinemachineBrain[] brains = UnityEngine.Object.FindObjectsOfType(
typeof(CinemachineBrain)) as CinemachineBrain[];
if (brains == null || brains.Length == 0)
{
Camera cam = Camera.main;
if (cam == null)
{
Camera[] cams = UnityEngine.Object.FindObjectsOfType(
typeof(Camera)) as Camera[];
if (cams != null && cams.Length > 0)
cam = cams[0];
}
if (cam != null)
{
Undo.AddComponent<CinemachineBrain>(cam.gameObject);
}
}
}
/// <summary>
/// Generate a unique name with the given prefix by adding a suffix to it
/// </summary>
public static string GenerateUniqueObjectName(Type type, string prefix)
{
int count = 0;
UnityEngine.Object[] all = Resources.FindObjectsOfTypeAll(type);
foreach (UnityEngine.Object o in all)
{
if (o != null && o.name.StartsWith(prefix))
{
string suffix = o.name.Substring(prefix.Length);
int i;
if (Int32.TryParse(suffix, out i) && i > count)
count = i;
}
}
return prefix + (count + 1);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Text;
using System.IO;
using NUnit.Framework;
namespace OpenStack.Swift.Functional.Tests
{
[TestFixture]
public class TestClient
{
private readonly string user_name = ConfigurationManager.AppSettings["FunctionalTestUserName"];
private readonly string api_key = ConfigurationManager.AppSettings["FunctionalTestApiKey"];
private readonly string auth_url = ConfigurationManager.AppSettings["FunctionalTestAuthUrl"];
private const string snet_pattern = "://snet-";
private const string prefix = ".csharp_swift";
private const string object_content = "unit";
private const string auth_storage_url_header = "x-storage-url";
private const string auth_storage_token_header = "x-storage-token";
private const string auth_auth_token_header = "x-auth-token";
private readonly string[] auth_headers = {auth_storage_url_header, auth_storage_token_header, auth_auth_token_header};
private const string container_name_key = "name";
private const string container_bytes_used_key = "bytes";
private const string container_object_count_key = "count";
private readonly string[] container_listing_keys = {container_name_key, container_bytes_used_key, container_object_count_key};
private const string account_object_count_header = "x-account-object-count";
private const string account_container_count_header = "x-account-container-count";
private const string account_bytes_used_header = "x-account-bytes-used";
private readonly string[] account_headers = {account_object_count_header, account_container_count_header, account_bytes_used_header};
private const string container_object_count_header = "x-container-object-count";
private const string container_bytes_used_header = "x-container-bytes-used";
private readonly string[] container_headers = {container_object_count_header, container_bytes_used_header};
private const string folder_object_name = "folder/blah";
private const string subdir_name_key = "subdir";
private readonly string[] subdir_listing_keys = {subdir_name_key};
private const string account_metadata_prefix = "x-account-meta-";
private const string container_metadata_prefix = "x-container-meta-";
private const string object_metadata_prefix = "x-object-meta-";
private const string metadata_key = "unit";
private const string metadata_value = "unit";
private const string object_name_key = "name";
private const string object_hash_key = "hash";
private const string object_bytes_key = "bytes";
private const string object_content_type_key = "content_type";
private const string object_last_modified_key = "last_modified";
private readonly string[] object_listing_keys = {object_name_key, object_hash_key, object_bytes_key, object_bytes_key, object_content_type_key, object_last_modified_key};
private const string object_last_modified_header = "last-modified";
private const string object_etag_header = "etag";
private const string object_content_length_header = "content-length";
private const string object_content_type_header = "content-type";
private readonly string[] object_header_keys = {object_last_modified_header, object_etag_header, object_content_length_header, object_content_type_header};
private string auth_token;
private string storage_url;
private readonly Dictionary<string, string> teardown_query = new Dictionary<string, string>();
private List<Dictionary<string, string>> created_objects = new List<Dictionary<string, string>>();
private List<string> created_containers = new List<string>();
private SwiftClient client = new SwiftClient();
[SetUp]
public void setup()
{
created_containers = new List<string>();
created_objects = new List<Dictionary<string, string>>();
client = new SwiftClient();
var res = client.GetAuth(auth_url, user_name, api_key, new Dictionary<string, string>(), new Dictionary<string, string>(), false);
auth_token = res.Headers["x-auth-token"];
storage_url = res.Headers["x-storage-url"];
}
[TearDown]
public void teardown()
{
teardown_query["prefix"] = prefix;
try
{
foreach (var container_info in client.GetAccount(storage_url, auth_token, new Dictionary<string, string>(), teardown_query, false).Containers)
{
foreach (var object_info in client.GetContainer(storage_url, auth_token, container_info["name"], new Dictionary<string, string>(), new Dictionary<string, string>(), false).Objects)
{
client.DeleteObject(storage_url, auth_token, container_info["name"],
container_info.ContainsKey("name") ? object_info["name"] : object_info["subdir"],
new Dictionary<string, string>(), new Dictionary<string, string>());
}
client.DeleteContainer(storage_url, auth_token, container_info["name"], new Dictionary<string, string>(), new Dictionary<string, string>());
}
}
catch(ClientException)
{
}
}
[Test]
public void test_get_auth()
{
var res = client.GetAuth(auth_url, user_name, api_key, new Dictionary<string, string>(), new Dictionary<string, string>(), false);
foreach (var header in auth_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header), "Header: " + header);
}
Assert.IsTrue(res.Status < 300 || res.Status > 199);
res = client.GetAuth(auth_url, user_name, api_key, new Dictionary<string, string>(), new Dictionary<string, string>(), true);
foreach (var header in auth_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header), "Header: " + header);
}
Assert.IsTrue(res.Status < 300 && res.Status > 199);
var index = res.Headers["x-storage-url"].IndexOf(snet_pattern, StringComparison.Ordinal);
//Make Sure snet- was added to the right part of the url
Assert.IsTrue(index > 3 && index < 6);
Assert.IsTrue(index != -1);
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_get_auth_fail()
{
client.GetAuth(auth_url, user_name, "sdf", new Dictionary<string, string>(), new Dictionary<string, string>(), false);
}
[Test]
public void test_get_account()
{
created_containers.Add((prefix + Guid.NewGuid().ToString()));
created_containers.Add((prefix + Guid.NewGuid().ToString()));
foreach (string container_name in created_containers)
{
client.PutContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
}
var query = new Dictionary<string, string>();
query["prefix"] = prefix;
var res = client.GetAccount(storage_url, auth_token, new Dictionary<string, string>(), query, true);
foreach (var container_dictionary in res.Containers)
{
foreach (var key in container_listing_keys)
{
Assert.IsTrue(container_dictionary.ContainsKey(key));
}
}
foreach (var header in account_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
}
[ExpectedException(typeof(ClientException))]
[Test]
public void test_get_account_fail()
{
client.GetAccount(storage_url, "asdf", new Dictionary<string, string>(), new Dictionary<string, string>(), false);
}
[Test]
public void test_head_account()
{
AccountResponse res = client.HeadAccount(storage_url, auth_token, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsTrue(res.Status > 199 && res.Status < 300);
foreach (string header in account_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
res = client.HeadAccount(storage_url, auth_token, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsTrue(res.Status > 199 && res.Status < 300);
foreach (string header in account_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_head_account_fail()
{
client.HeadAccount(storage_url, "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_post_account()
{
var headers = new Dictionary<string, string> {{account_metadata_prefix + metadata_key, metadata_value}};
client.PostAccount(storage_url, auth_token, headers, new Dictionary<string, string>());
var res = client.HeadAccount(storage_url, auth_token, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsTrue(res.Headers.ContainsKey(account_metadata_prefix + metadata_key));
Assert.IsTrue(res.Headers[account_metadata_prefix + metadata_key] == metadata_value);
client.PostAccount(storage_url, auth_token, headers, new Dictionary<string, string>());
res = client.HeadAccount(storage_url, auth_token, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsTrue(res.Headers.ContainsKey(account_metadata_prefix +
metadata_key));
Assert.IsTrue(res.Headers[account_metadata_prefix + metadata_key] == metadata_value);
headers[account_metadata_prefix + metadata_key] = "";
client.PostAccount(storage_url, auth_token, headers, new Dictionary<string, string>());
res = client.HeadAccount(storage_url, auth_token, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsFalse(res.Headers.ContainsKey(account_metadata_prefix + metadata_key));
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_post_account_fail()
{
client.PostAccount(storage_url, "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_get_container()
{
string container_name = (prefix + Guid.NewGuid().ToString());
created_containers.Add(container_name);
var obj_cont_pair = new Dictionary<string, string>
{{"container", container_name}, {"object", prefix + Guid.NewGuid().ToString()}};
created_objects.Add(obj_cont_pair);
obj_cont_pair = new Dictionary<string, string>
{{"container", container_name}, {"object", prefix + Guid.NewGuid().ToString()}};
client.PutContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
created_objects.Add(obj_cont_pair);
foreach (var obj_dict in created_objects)
{
var encoder = new UTF8Encoding();
byte[] byte_array = encoder.GetBytes(object_content);
var stream = new MemoryStream(byte_array);
client.PutObject(storage_url, auth_token, obj_dict["container"], obj_dict["object"], stream, new Dictionary<string, string>(), new Dictionary<string, string>());
}
var query = new Dictionary<string, string> {{"prefix", prefix}};
var res = client.GetContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), query, false);
foreach (var header in container_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header), "Header: " + header);
}
foreach (var object_hash in res.Objects)
{
if (object_hash.ContainsKey("subdir"))
{
foreach (string key in subdir_listing_keys)
{
Assert.IsTrue(object_hash.ContainsKey(key));
}
}
else
{
foreach (var key in object_listing_keys)
{
Assert.IsTrue(object_hash.ContainsKey(key));
}
}
}
query.Add("limit", "1");
obj_cont_pair = new Dictionary<string, string> {{"container", container_name}, {"object", folder_object_name}};
created_objects.Add(obj_cont_pair);
var coder = new UTF8Encoding();
var byte_array2 = coder.GetBytes(object_content);
var stream2 = new MemoryStream(byte_array2);
client.PutObject(storage_url, auth_token, container_name, folder_object_name, stream2, new Dictionary<string, string>(), new Dictionary<string, string>());
foreach (var header in container_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header), "Header: " + header);
}
foreach (var object_hash in res.Objects)
{
if (object_hash.ContainsKey("subdir"))
{
foreach (var key in subdir_listing_keys)
{
Assert.IsTrue(object_hash.ContainsKey(key));
}
}
else
{
foreach (string key in object_listing_keys)
{
Assert.IsTrue(object_hash.ContainsKey(key));
}
}
}
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_get_container_fail()
{
client.GetContainer(storage_url, "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>(), false);
}
[Test]
public void test_head_container()
{
var container_name = prefix + Guid.NewGuid().ToString();
created_containers.Add(container_name);
client.PutContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
var res = client.HeadContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
foreach (var header in container_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header),
"Header: " + header);
}
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_head_container_fail()
{
client.HeadContainer(storage_url, "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_post_container()
{
var headers = new Dictionary<string, string> {{container_metadata_prefix + metadata_key, metadata_value}};
var container_name = prefix + Guid.NewGuid().ToString();
created_containers.Add(container_name);
client.PutContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
client.PostContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>());
var res = client.HeadContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsTrue(res.Headers.ContainsKey(container_metadata_prefix + metadata_key));
Assert.IsTrue(res.Headers[container_metadata_prefix + metadata_key] == metadata_value);
foreach (var header in container_headers)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
headers[container_metadata_prefix + metadata_key] = "";
client.PostContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>());
res = client.HeadContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsFalse(res.Headers.ContainsKey(container_metadata_prefix + metadata_key));
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_post_container_fail()
{
client.PostContainer(storage_url, "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_put_container()
{
var query = new Dictionary<string, string> {{"prefix", prefix}};
var headers = new Dictionary<string, string>();
var container_name = prefix + Guid.NewGuid().ToString();
created_containers.Add(container_name);
client.PutContainer(storage_url, auth_token, container_name, headers, new Dictionary<string, string>());
var res = client.GetAccount(storage_url, auth_token, new Dictionary<string, string>(), query, false);
Assert.IsTrue(res.Containers.Count > 0 && res.Containers.Count < 2, res.Containers.Count.ToString(CultureInfo.InvariantCulture));
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_put_container_fail()
{
client.PutContainer(storage_url, "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_delete_container()
{
string container_name = prefix + Guid.NewGuid().ToString();
var query = new Dictionary<string, string> {{"prefix", prefix}};
client.PutContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
var res = client.GetAccount(storage_url, auth_token, new Dictionary<string, string>(), query, false);
Assert.IsTrue(res.Containers.Count > 0 && res.Containers.Count < 2);
client.DeleteContainer(storage_url, auth_token, container_name, new Dictionary<string, string>(), new Dictionary<string, string>());
res = client.GetAccount(storage_url, auth_token, new Dictionary<string, string>(), query, false);
Assert.IsTrue(res.Containers.Count == 0);
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_delete_container_fail()
{
client.DeleteContainer(storage_url, "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_get_object()
{
string name = prefix + Guid.NewGuid().ToString();
created_containers.Add(name);
client.PutContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>());
var encoder = new UTF8Encoding();
byte[] byte_array = encoder.GetBytes(object_content);
var stream = new MemoryStream(byte_array);
client.PutObject(storage_url, auth_token, name, name, stream, new Dictionary<string, string>(), new Dictionary<string, string>());
var res = client.GetObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
byte_array = new byte[object_content.Length];
res.ObjectData.Read(byte_array, 0, object_content.Length);
var content = Encoding.UTF8.GetString(byte_array);
Assert.IsTrue(content == object_content);
foreach (var header in object_header_keys)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_get_object_fail()
{
client.GetObject(storage_url, "asdf", "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_head_object()
{
string name = prefix + Guid.NewGuid().ToString();
created_containers.Add(name);
var obj_cont_pair = new Dictionary<string, string> {{"container", name}, {"object", name}};
client.PutContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>());
created_objects.Add(obj_cont_pair);
var encoder = new UTF8Encoding();
byte[] byte_array = encoder.GetBytes(object_content);
var stream = new MemoryStream(byte_array);
client.PutObject(storage_url, auth_token, name, name, stream, new Dictionary<string, string>(), new Dictionary<string, string>());
var res = client.HeadObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
foreach (string header in object_header_keys)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_head_object_fail()
{
client.HeadObject(storage_url, "asdf", "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_post_object()
{
var headers = new Dictionary<string, string> {{object_metadata_prefix + metadata_key, metadata_value}};
var name = prefix + Guid.NewGuid().ToString();
created_containers.Add(name);
var obj_cont_pair = new Dictionary<string, string> {{"container", name}, {"object", name}};
created_objects.Add(obj_cont_pair);
client.PutContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>());
var encoder = new UTF8Encoding();
byte[] byte_array = encoder.GetBytes(object_content);
var stream = new MemoryStream(byte_array);
client.PutObject(storage_url, auth_token, name, name, stream, new Dictionary<string, string>(), new Dictionary<string, string>());
client.PostObject(storage_url, auth_token, name, name, headers, new Dictionary<string, string>());
var res = client.HeadObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsTrue(res.Headers.ContainsKey(object_metadata_prefix + metadata_key));
Assert.IsTrue(res.Headers[object_metadata_prefix + metadata_key] == metadata_value);
client.PostObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
res = client.HeadObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
Assert.IsFalse(res.Headers.ContainsKey(object_metadata_prefix + metadata_key));
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_post_object_fail()
{
client.PostObject(storage_url, "asdf", "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_put_object()
{
var name = prefix + Guid.NewGuid();
created_containers.Add(name);
var obj_cont_pair = new Dictionary<string, string> {{"container", name}, {"object", name}};
client.PutContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>());
created_objects.Add(obj_cont_pair);
var encoder = new UTF8Encoding();
var byte_array = encoder.GetBytes(object_content);
var byte_array_length_before_put = byte_array.Length;
var stream = new MemoryStream(byte_array);
client.PutObject(storage_url, auth_token, name, name, stream, new Dictionary<string, string>(), new Dictionary<string, string>());
var res = client.GetObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
byte_array = ReadFully(res.ObjectData);
long byte_array_length_after_get = byte_array.Length;
Assert.That(byte_array_length_after_get, Is.EqualTo(byte_array_length_before_put));
res.ObjectData.Read(byte_array, 0, object_content.Length);
var content = Encoding.UTF8.GetString(byte_array);
Assert.That(content, Is.EqualTo(object_content));
foreach (var header in object_header_keys)
{
Assert.IsTrue(res.Headers.ContainsKey(header));
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_put_object_fail()
{
client.PutObject(storage_url, "asdf", "asdf", "asdf", new MemoryStream(), new Dictionary<string, string>(), new Dictionary<string, string>());
}
[Test]
public void test_delete_object()
{
var name = prefix + Guid.NewGuid().ToString();
created_containers.Add(name);
var obj_cont_pair = new Dictionary<string, string> {{"container", name}, {"object", name}};
client.PutContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>());
created_objects.Add(obj_cont_pair);
var encoder = new UTF8Encoding();
byte[] byte_array = encoder.GetBytes(object_content);
var stream = new MemoryStream(byte_array);
client.PutObject(storage_url, auth_token, name, name, stream, new Dictionary<string, string>(), new Dictionary<string, string>());
var res = client.GetContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>(), false);
Assert.IsTrue(res.Objects.Count == 1);
client.DeleteObject(storage_url, auth_token, name, name, new Dictionary<string, string>(), new Dictionary<string, string>());
res = client.GetContainer(storage_url, auth_token, name, new Dictionary<string, string>(), new Dictionary<string, string>(), false);
Assert.IsTrue(res.Objects.Count == 0);
}
[Test]
[ExpectedException(typeof(ClientException))]
public void test_delete_object_fail()
{
client.DeleteObject(storage_url, "asdf", "asdf", "asdf", new Dictionary<string, string>(), new Dictionary<string, string>());
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using EventStore.BufferManagement;
using EventStore.Common.Locks;
using EventStore.Common.Log;
using EventStore.Common.Utils;
namespace EventStore.Transport.Tcp
{
public class TcpConnection : TcpConnectionBase, ITcpConnection
{
internal const int MaxSendPacketSize = 64 * 1024;
internal static readonly BufferManager BufferManager = new BufferManager(TcpConfiguration.BufferChunksCount, TcpConfiguration.SocketBufferSize);
private static readonly ILogger Log = LogManager.GetLoggerFor<TcpConnection>();
private static readonly SocketArgsPool SocketArgsPool = new SocketArgsPool("TcpConnection.SocketArgsPool",
TcpConfiguration.SendReceivePoolSize,
() => new SocketAsyncEventArgs());
public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId,
IPEndPoint remoteEndPoint,
TcpClientConnector connector,
TimeSpan connectionTimeout,
Action<ITcpConnection> onConnectionEstablished,
Action<ITcpConnection, SocketError> onConnectionFailed,
bool verbose)
{
var connection = new TcpConnection(connectionId, remoteEndPoint, verbose);
// ReSharper disable ImplicitlyCapturedClosure
connector.InitConnect(remoteEndPoint,
(_, socket) =>
{
connection.InitSocket(socket);
if (onConnectionEstablished != null)
onConnectionEstablished(connection);
},
(_, socketError) =>
{
if (onConnectionFailed != null)
onConnectionFailed(connection, socketError);
}, connection, connectionTimeout);
// ReSharper restore ImplicitlyCapturedClosure
return connection;
}
public static ITcpConnection CreateAcceptedTcpConnection(Guid connectionId, IPEndPoint remoteEndPoint, Socket socket, bool verbose)
{
var connection = new TcpConnection(connectionId, remoteEndPoint, verbose);
connection.InitSocket(socket);
return connection;
}
public event Action<ITcpConnection, SocketError> ConnectionClosed;
public Guid ConnectionId { get { return _connectionId; } }
public int SendQueueSize { get { return _sendQueue.Count; } }
private readonly Guid _connectionId;
private readonly bool _verbose;
private Socket _socket;
private SocketAsyncEventArgs _receiveSocketArgs;
private SocketAsyncEventArgs _sendSocketArgs;
private readonly Common.Concurrent.ConcurrentQueue<ArraySegment<byte>> _sendQueue = new Common.Concurrent.ConcurrentQueue<ArraySegment<byte>>();
private readonly Queue<ReceivedData> _receiveQueue = new Queue<ReceivedData>();
private readonly MemoryStream _memoryStream = new MemoryStream();
private readonly object _receivingLock = new object();
private readonly SpinLock2 _sendingLock = new SpinLock2();
private bool _isSending;
private volatile int _closed;
private Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> _receiveCallback;
private TcpConnection(Guid connectionId, IPEndPoint remoteEndPoint, bool verbose): base(remoteEndPoint)
{
Ensure.NotEmptyGuid(connectionId, "connectionId");
_connectionId = connectionId;
_verbose = verbose;
}
private void InitSocket(Socket socket)
{
InitConnectionBase(socket);
using (_sendingLock.Acquire())
{
_socket = socket;
try
{
socket.NoDelay = true;
}
catch (ObjectDisposedException)
{
CloseInternal(SocketError.Shutdown, "Socket disposed.");
_socket = null;
return;
}
var receiveSocketArgs = SocketArgsPool.Get();
_receiveSocketArgs = receiveSocketArgs;
_receiveSocketArgs.AcceptSocket = socket;
_receiveSocketArgs.Completed += OnReceiveAsyncCompleted;
var sendSocketArgs = SocketArgsPool.Get();
_sendSocketArgs = sendSocketArgs;
_sendSocketArgs.AcceptSocket = socket;
_sendSocketArgs.Completed += OnSendAsyncCompleted;
}
StartReceive();
TrySend();
}
public void EnqueueSend(IEnumerable<ArraySegment<byte>> data)
{
using (_sendingLock.Acquire())
{
int bytes = 0;
foreach (var segment in data)
{
_sendQueue.Enqueue(segment);
bytes += segment.Count;
}
NotifySendScheduled(bytes);
}
TrySend();
}
private void TrySend()
{
using (_sendingLock.Acquire())
{
if (_isSending || _sendQueue.Count == 0 || _socket == null) return;
if (TcpConnectionMonitor.Default.IsSendBlocked()) return;
_isSending = true;
}
_memoryStream.SetLength(0);
ArraySegment<byte> sendPiece;
while (_sendQueue.TryDequeue(out sendPiece))
{
_memoryStream.Write(sendPiece.Array, sendPiece.Offset, sendPiece.Count);
if (_memoryStream.Length >= MaxSendPacketSize)
break;
}
_sendSocketArgs.SetBuffer(_memoryStream.GetBuffer(), 0, (int) _memoryStream.Length);
try
{
NotifySendStarting(_sendSocketArgs.Count);
var firedAsync = _sendSocketArgs.AcceptSocket.SendAsync(_sendSocketArgs);
if (!firedAsync)
ProcessSend(_sendSocketArgs);
}
catch (ObjectDisposedException)
{
ReturnSendingSocketArgs();
}
}
private void OnSendAsyncCompleted(object sender, SocketAsyncEventArgs e)
{
// No other code should go here. All handling is the same for sync/async completion.
ProcessSend(e);
}
private void ProcessSend(SocketAsyncEventArgs socketArgs)
{
if (socketArgs.SocketError != SocketError.Success)
{
NotifySendCompleted(0);
ReturnSendingSocketArgs();
CloseInternal(socketArgs.SocketError, "Socket send error.");
}
else
{
NotifySendCompleted(socketArgs.Count);
if (_closed != 0)
ReturnSendingSocketArgs();
else
{
using (_sendingLock.Acquire())
{
_isSending = false;
}
TrySend();
}
}
}
public void ReceiveAsync(Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> callback)
{
if (callback == null)
throw new ArgumentNullException("callback");
lock (_receivingLock)
{
if (_receiveCallback != null)
{
Log.Fatal("ReceiveAsync called again while previous call wasn't fulfilled");
throw new InvalidOperationException("ReceiveAsync called again while previous call wasn't fulfilled");
}
_receiveCallback = callback;
}
TryDequeueReceivedData();
}
private void StartReceive()
{
var buffer = BufferManager.CheckOut();
if (buffer.Array == null || buffer.Count == 0 || buffer.Array.Length < buffer.Offset + buffer.Count)
throw new Exception("Invalid buffer allocated");
// TODO AN: do we need to lock on _receiveSocketArgs?..
lock (_receiveSocketArgs)
{
_receiveSocketArgs.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
if (_receiveSocketArgs.Buffer == null) throw new Exception("Buffer was not set");
}
try
{
NotifyReceiveStarting();
bool firedAsync;
lock (_receiveSocketArgs)
{
if (_receiveSocketArgs.Buffer == null) throw new Exception("Buffer was lost");
firedAsync = _receiveSocketArgs.AcceptSocket.ReceiveAsync(_receiveSocketArgs);
}
if (!firedAsync)
ProcessReceive(_receiveSocketArgs);
}
catch (ObjectDisposedException)
{
ReturnReceivingSocketArgs();
}
}
private void OnReceiveAsyncCompleted(object sender, SocketAsyncEventArgs e)
{
// No other code should go here. All handling is the same on async and sync completion.
ProcessReceive(e);
}
private void ProcessReceive(SocketAsyncEventArgs socketArgs)
{
// socket closed normally or some error occurred
if (socketArgs.BytesTransferred == 0 || socketArgs.SocketError != SocketError.Success)
{
NotifyReceiveCompleted(0);
ReturnReceivingSocketArgs();
CloseInternal(socketArgs.SocketError, socketArgs.SocketError != SocketError.Success ? "Socket receive error" : "Socket closed");
return;
}
NotifyReceiveCompleted(socketArgs.BytesTransferred);
lock (_receivingLock)
{
var buf = new ArraySegment<byte>(socketArgs.Buffer, socketArgs.Offset, socketArgs.Count);
_receiveQueue.Enqueue(new ReceivedData(buf, socketArgs.BytesTransferred));
}
lock (_receiveSocketArgs)
{
if (socketArgs.Buffer == null)
throw new Exception("Cleaning already null buffer");
socketArgs.SetBuffer(null, 0, 0);
}
StartReceive();
TryDequeueReceivedData();
}
private void TryDequeueReceivedData()
{
Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> callback;
List<ReceivedData> res;
lock (_receivingLock)
{
// no awaiting callback or no data to dequeue
if (_receiveCallback == null || _receiveQueue.Count == 0)
return;
res = new List<ReceivedData>(_receiveQueue.Count);
while (_receiveQueue.Count > 0)
{
res.Add(_receiveQueue.Dequeue());
}
callback = _receiveCallback;
_receiveCallback = null;
}
var data = new ArraySegment<byte>[res.Count];
int bytes = 0;
for (int i = 0; i < data.Length; ++i)
{
var d = res[i];
bytes += d.DataLen;
data[i] = new ArraySegment<byte>(d.Buf.Array, d.Buf.Offset, d.DataLen);
}
callback(this, data);
for (int i = 0, n = res.Count; i < n; ++i)
{
BufferManager.CheckIn(res[i].Buf); // dispose buffers
}
NotifyReceiveDispatched(bytes);
}
public void Close(string reason)
{
CloseInternal(SocketError.Success, reason ?? "Normal socket close."); // normal socket closing
}
private void CloseInternal(SocketError socketError, string reason)
{
#pragma warning disable 420
if (Interlocked.CompareExchange(ref _closed, 1, 0) != 0)
return;
#pragma warning restore 420
NotifyClosed();
if (_verbose)
{
Log.Info("ES {12} closed [{0:HH:mm:ss.fff}: N{1}, L{2}, {3:B}]:\nReceived bytes: {4}, Sent bytes: {5}\n"
+ "Send calls: {6}, callbacks: {7}\nReceive calls: {8}, callbacks: {9}\nClose reason: [{10}] {11}\n",
DateTime.UtcNow, RemoteEndPoint, LocalEndPoint, _connectionId,
TotalBytesReceived, TotalBytesSent,
SendCalls, SendCallbacks,
ReceiveCalls, ReceiveCallbacks,
socketError, reason, GetType().Name);
}
if (_socket != null)
{
Helper.EatException(() => _socket.Shutdown(SocketShutdown.Both));
Helper.EatException(() => _socket.Close(TcpConfiguration.SocketCloseTimeoutMs));
_socket = null;
}
using (_sendingLock.Acquire())
{
if (!_isSending)
ReturnSendingSocketArgs();
}
var handler = ConnectionClosed;
if (handler != null)
handler(this, socketError);
}
private void ReturnSendingSocketArgs()
{
var socketArgs = Interlocked.Exchange(ref _sendSocketArgs, null);
if (socketArgs != null)
{
socketArgs.Completed -= OnSendAsyncCompleted;
socketArgs.AcceptSocket = null;
if (socketArgs.Buffer != null)
socketArgs.SetBuffer(null, 0, 0);
SocketArgsPool.Return(socketArgs);
}
}
private void ReturnReceivingSocketArgs()
{
var socketArgs = Interlocked.Exchange(ref _receiveSocketArgs, null);
if (socketArgs != null)
{
socketArgs.Completed -= OnReceiveAsyncCompleted;
socketArgs.AcceptSocket = null;
if (socketArgs.Buffer != null)
{
BufferManager.CheckIn(new ArraySegment<byte>(socketArgs.Buffer, socketArgs.Offset, socketArgs.Count));
socketArgs.SetBuffer(null, 0, 0);
}
SocketArgsPool.Return(socketArgs);
}
}
public override string ToString()
{
return RemoteEndPoint.ToString();
}
private struct ReceivedData
{
public readonly ArraySegment<byte> Buf;
public readonly int DataLen;
public ReceivedData(ArraySegment<byte> buf, int dataLen)
{
Buf = buf;
DataLen = dataLen;
}
}
}
}
| |
// 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.Dialogflow.Cx.V3.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 GeneratedEntityTypesClientSnippets
{
/// <summary>Snippet for ListEntityTypes</summary>
public void ListEntityTypesRequestObject()
{
// Snippet: ListEntityTypes(ListEntityTypesRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
ListEntityTypesRequest request = new ListEntityTypesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
LanguageCode = "",
};
// Make the request
PagedEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypes(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (EntityType 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 (ListEntityTypesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType 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<EntityType> 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 (EntityType 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 ListEntityTypesAsync</summary>
public async Task ListEntityTypesRequestObjectAsync()
{
// Snippet: ListEntityTypesAsync(ListEntityTypesRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
ListEntityTypesRequest request = new ListEntityTypesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
LanguageCode = "",
};
// Make the request
PagedAsyncEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((EntityType 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((ListEntityTypesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType 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<EntityType> 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 (EntityType 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 ListEntityTypes</summary>
public void ListEntityTypes()
{
// Snippet: ListEntityTypes(string, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
// Make the request
PagedEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypes(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (EntityType 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 (ListEntityTypesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType 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<EntityType> 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 (EntityType 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 ListEntityTypesAsync</summary>
public async Task ListEntityTypesAsync()
{
// Snippet: ListEntityTypesAsync(string, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
// Make the request
PagedAsyncEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((EntityType 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((ListEntityTypesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType 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<EntityType> 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 (EntityType 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 ListEntityTypes</summary>
public void ListEntityTypesResourceNames()
{
// Snippet: ListEntityTypes(AgentName, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypes(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (EntityType 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 (ListEntityTypesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType 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<EntityType> 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 (EntityType 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 ListEntityTypesAsync</summary>
public async Task ListEntityTypesResourceNamesAsync()
{
// Snippet: ListEntityTypesAsync(AgentName, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedAsyncEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((EntityType 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((ListEntityTypesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType 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<EntityType> 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 (EntityType 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 GetEntityType</summary>
public void GetEntityTypeRequestObject()
{
// Snippet: GetEntityType(GetEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
LanguageCode = "",
};
// Make the request
EntityType response = entityTypesClient.GetEntityType(request);
// End snippet
}
/// <summary>Snippet for GetEntityTypeAsync</summary>
public async Task GetEntityTypeRequestObjectAsync()
{
// Snippet: GetEntityTypeAsync(GetEntityTypeRequest, CallSettings)
// Additional: GetEntityTypeAsync(GetEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
LanguageCode = "",
};
// Make the request
EntityType response = await entityTypesClient.GetEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for GetEntityType</summary>
public void GetEntityType()
{
// Snippet: GetEntityType(string, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
EntityType response = entityTypesClient.GetEntityType(name);
// End snippet
}
/// <summary>Snippet for GetEntityTypeAsync</summary>
public async Task GetEntityTypeAsync()
{
// Snippet: GetEntityTypeAsync(string, CallSettings)
// Additional: GetEntityTypeAsync(string, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
EntityType response = await entityTypesClient.GetEntityTypeAsync(name);
// End snippet
}
/// <summary>Snippet for GetEntityType</summary>
public void GetEntityTypeResourceNames()
{
// Snippet: GetEntityType(EntityTypeName, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
EntityType response = entityTypesClient.GetEntityType(name);
// End snippet
}
/// <summary>Snippet for GetEntityTypeAsync</summary>
public async Task GetEntityTypeResourceNamesAsync()
{
// Snippet: GetEntityTypeAsync(EntityTypeName, CallSettings)
// Additional: GetEntityTypeAsync(EntityTypeName, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
EntityType response = await entityTypesClient.GetEntityTypeAsync(name);
// End snippet
}
/// <summary>Snippet for CreateEntityType</summary>
public void CreateEntityTypeRequestObject()
{
// Snippet: CreateEntityType(CreateEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
CreateEntityTypeRequest request = new CreateEntityTypeRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
EntityType = new EntityType(),
LanguageCode = "",
};
// Make the request
EntityType response = entityTypesClient.CreateEntityType(request);
// End snippet
}
/// <summary>Snippet for CreateEntityTypeAsync</summary>
public async Task CreateEntityTypeRequestObjectAsync()
{
// Snippet: CreateEntityTypeAsync(CreateEntityTypeRequest, CallSettings)
// Additional: CreateEntityTypeAsync(CreateEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
CreateEntityTypeRequest request = new CreateEntityTypeRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
EntityType = new EntityType(),
LanguageCode = "",
};
// Make the request
EntityType response = await entityTypesClient.CreateEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for CreateEntityType</summary>
public void CreateEntityType()
{
// Snippet: CreateEntityType(string, EntityType, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
EntityType entityType = new EntityType();
// Make the request
EntityType response = entityTypesClient.CreateEntityType(parent, entityType);
// End snippet
}
/// <summary>Snippet for CreateEntityTypeAsync</summary>
public async Task CreateEntityTypeAsync()
{
// Snippet: CreateEntityTypeAsync(string, EntityType, CallSettings)
// Additional: CreateEntityTypeAsync(string, EntityType, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
EntityType entityType = new EntityType();
// Make the request
EntityType response = await entityTypesClient.CreateEntityTypeAsync(parent, entityType);
// End snippet
}
/// <summary>Snippet for CreateEntityType</summary>
public void CreateEntityTypeResourceNames()
{
// Snippet: CreateEntityType(AgentName, EntityType, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
EntityType entityType = new EntityType();
// Make the request
EntityType response = entityTypesClient.CreateEntityType(parent, entityType);
// End snippet
}
/// <summary>Snippet for CreateEntityTypeAsync</summary>
public async Task CreateEntityTypeResourceNamesAsync()
{
// Snippet: CreateEntityTypeAsync(AgentName, EntityType, CallSettings)
// Additional: CreateEntityTypeAsync(AgentName, EntityType, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
EntityType entityType = new EntityType();
// Make the request
EntityType response = await entityTypesClient.CreateEntityTypeAsync(parent, entityType);
// End snippet
}
/// <summary>Snippet for UpdateEntityType</summary>
public void UpdateEntityTypeRequestObject()
{
// Snippet: UpdateEntityType(UpdateEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
LanguageCode = "",
UpdateMask = new FieldMask(),
};
// Make the request
EntityType response = entityTypesClient.UpdateEntityType(request);
// End snippet
}
/// <summary>Snippet for UpdateEntityTypeAsync</summary>
public async Task UpdateEntityTypeRequestObjectAsync()
{
// Snippet: UpdateEntityTypeAsync(UpdateEntityTypeRequest, CallSettings)
// Additional: UpdateEntityTypeAsync(UpdateEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
LanguageCode = "",
UpdateMask = new FieldMask(),
};
// Make the request
EntityType response = await entityTypesClient.UpdateEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateEntityType</summary>
public void UpdateEntityType()
{
// Snippet: UpdateEntityType(EntityType, FieldMask, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
EntityType entityType = new EntityType();
FieldMask updateMask = new FieldMask();
// Make the request
EntityType response = entityTypesClient.UpdateEntityType(entityType, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateEntityTypeAsync</summary>
public async Task UpdateEntityTypeAsync()
{
// Snippet: UpdateEntityTypeAsync(EntityType, FieldMask, CallSettings)
// Additional: UpdateEntityTypeAsync(EntityType, FieldMask, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
EntityType entityType = new EntityType();
FieldMask updateMask = new FieldMask();
// Make the request
EntityType response = await entityTypesClient.UpdateEntityTypeAsync(entityType, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteEntityType</summary>
public void DeleteEntityTypeRequestObject()
{
// Snippet: DeleteEntityType(DeleteEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
DeleteEntityTypeRequest request = new DeleteEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
Force = false,
};
// Make the request
entityTypesClient.DeleteEntityType(request);
// End snippet
}
/// <summary>Snippet for DeleteEntityTypeAsync</summary>
public async Task DeleteEntityTypeRequestObjectAsync()
{
// Snippet: DeleteEntityTypeAsync(DeleteEntityTypeRequest, CallSettings)
// Additional: DeleteEntityTypeAsync(DeleteEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
DeleteEntityTypeRequest request = new DeleteEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
Force = false,
};
// Make the request
await entityTypesClient.DeleteEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteEntityType</summary>
public void DeleteEntityType()
{
// Snippet: DeleteEntityType(string, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
entityTypesClient.DeleteEntityType(name);
// End snippet
}
/// <summary>Snippet for DeleteEntityTypeAsync</summary>
public async Task DeleteEntityTypeAsync()
{
// Snippet: DeleteEntityTypeAsync(string, CallSettings)
// Additional: DeleteEntityTypeAsync(string, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
await entityTypesClient.DeleteEntityTypeAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteEntityType</summary>
public void DeleteEntityTypeResourceNames()
{
// Snippet: DeleteEntityType(EntityTypeName, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
entityTypesClient.DeleteEntityType(name);
// End snippet
}
/// <summary>Snippet for DeleteEntityTypeAsync</summary>
public async Task DeleteEntityTypeResourceNamesAsync()
{
// Snippet: DeleteEntityTypeAsync(EntityTypeName, CallSettings)
// Additional: DeleteEntityTypeAsync(EntityTypeName, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
await entityTypesClient.DeleteEntityTypeAsync(name);
// End snippet
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2003
//
// File: mediaclock.cs
//
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.ComponentModel;
using MS.Internal;
using MS.Win32;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Media.Composition;
using System.Windows.Markup;
using System.Security.Permissions;
using System.Security;
using MS.Internal.PresentationCore; // SecurityHelper
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.IO;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using UnsafeNativeMethods=MS.Win32.PresentationCore.UnsafeNativeMethods;
namespace System.Windows.Media
{
#region MediaClock
/// <summary>
/// Maintains run-time timing state for media (audio/video) objects.
/// </summary>
public class MediaClock :
Clock
{
#region Constructors and Finalizers
/// <summary>
/// Creates a MediaClock object.
/// </summary>
/// <param name="media">
/// The MediaTimeline to use as a template.
/// </param>
/// <remarks>
/// The returned MediaClock doesn't have any children.
/// </remarks>
protected internal MediaClock(MediaTimeline media)
: base(media)
{}
#endregion
#region Properties
/// <summary>
/// Gets the MediaTimeline object that holds the description controlling the
/// behavior of this clock.
/// </summary>
/// <value>
/// The MediaTimeline object that holds the description controlling the
/// behavior of this clock.
/// </value>
public new MediaTimeline Timeline
{
get
{
return (MediaTimeline)base.Timeline;
}
}
#endregion
#region Clock Overrides
/// <summary>
/// Returns True because Media has the potential to slip.
/// </summary>
/// <returns>True</returns>
protected override bool GetCanSlip()
{
return true;
}
/// <summary>
/// Get the actual media time for slip synchronization
/// </summary>
protected override TimeSpan GetCurrentTimeCore()
{
if (_mediaPlayer != null)
{
return _mediaPlayer.Position;
}
else // Otherwise use base implementation
{
return base.GetCurrentTimeCore();
}
}
/// <summary>
/// Called when we are stopped. This is the same as pausing and seeking
/// to the beginning.
/// </summary>
protected override void Stopped()
{
// Only perform the operation if we're controlling a player
if (_mediaPlayer != null)
{
_mediaPlayer.SetSpeedRatio(0);
_mediaPlayer.SetPosition(TimeSpan.FromTicks(0));
}
}
/// <summary>
/// Called when our speed changes. A discontinuous time movement may or
/// may not have occurred.
/// </summary>
protected override void SpeedChanged()
{
Sync();
}
/// <summary>
/// Called when we have a discontinuous time movement, but no change in
/// speed
/// </summary>
protected override void DiscontinuousTimeMovement()
{
Sync();
}
private void Sync()
{
// Only perform the operation if we're controlling a player
if (_mediaPlayer != null)
{
double? currentSpeedProperty = this.CurrentGlobalSpeed;
double currentSpeedValue = currentSpeedProperty.HasValue ? currentSpeedProperty.Value : 0;
TimeSpan? currentTimeProperty = this.CurrentTime;
TimeSpan currentTimeValue = currentTimeProperty.HasValue ? currentTimeProperty.Value : TimeSpan.Zero;
// If speed was potentially changed to 0, make sure we set media's speed to 0 (e.g. pause) before
// setting the position to the target frame. Otherwise, the media's scrubbing mechanism would
// not work correctly, because scrubbing requires media to be paused by the time it is seeked.
if (currentSpeedValue == 0)
{
_mediaPlayer.SetSpeedRatio(currentSpeedValue);
_mediaPlayer.SetPosition(currentTimeValue);
}
else
{
// In the case where speed != 0, we first want to set the position and then the speed.
// This is because if we were previously paused, we want to be at the right position
// before we begin to play.
_mediaPlayer.SetPosition(currentTimeValue);
_mediaPlayer.SetSpeedRatio(currentSpeedValue);
}
}
}
/// <summary>
/// Returns true if this timeline needs continuous frames.
/// This is a hint that we should keep updating our time during the active period.
/// </summary>
/// <returns></returns>
internal override bool NeedsTicksWhenActive
{
get
{
return true;
}
}
/// <summary>
/// The instance of media that this clock is driving
/// </summary>
internal MediaPlayer Player
{
get
{
return _mediaPlayer;
}
set
{
MediaPlayer oldPlayer = _mediaPlayer;
MediaPlayer newPlayer = value;
// avoid inifite loops
if (newPlayer != oldPlayer)
{
_mediaPlayer = newPlayer;
// Disassociate the old player
if (oldPlayer != null)
{
oldPlayer.Clock = null;
}
// Associate the new player
if (newPlayer != null)
{
newPlayer.Clock = this;
Uri baseUri = ((IUriContext)Timeline).BaseUri;
Uri toPlay = null;
// ignore pack URIs for now (see work items 45396 and 41636)
if (baseUri != null
&& baseUri.Scheme != System.IO.Packaging.PackUriHelper.UriSchemePack
&& !Timeline.Source.IsAbsoluteUri)
{
toPlay = new Uri(baseUri, Timeline.Source);
}
else
{
//
// defaults to app domain base if Timeline.Source is
// relative
//
toPlay = Timeline.Source;
}
// we need to [....] to the current state of the clock
newPlayer.SetSource(toPlay);
SpeedChanged();
}
}
}
}
#endregion
#region Private Data members
/// <summary>
/// MediaPlayer -- holds all the precious resource references
/// </summary>
private MediaPlayer _mediaPlayer;
#endregion
}
#endregion
};
| |
// 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.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Utils;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Taiko;
using osu.Game.Screens.Play;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[TestFixture]
public class TestScenePlaySongSelect : ScreenTestScene
{
private BeatmapManager manager;
private RulesetStore rulesets;
private MusicController music;
private WorkingBeatmap defaultBeatmap;
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(Screens.Select.SongSelect),
typeof(BeatmapCarousel),
typeof(CarouselItem),
typeof(CarouselGroup),
typeof(CarouselGroupEagerSelect),
typeof(CarouselBeatmap),
typeof(CarouselBeatmapSet),
typeof(DrawableCarouselItem),
typeof(CarouselItemState),
typeof(DrawableCarouselBeatmap),
typeof(DrawableCarouselBeatmapSet),
};
private TestSongSelect songSelect;
[BackgroundDependencyLoader]
private void load(GameHost host, AudioManager audio)
{
Dependencies.Cache(rulesets = new RulesetStore(ContextFactory));
Dependencies.Cache(manager = new BeatmapManager(LocalStorage, ContextFactory, rulesets, null, audio, host, defaultBeatmap = Beatmap.Default));
Dependencies.Cache(music = new MusicController());
// required to get bindables attached
Add(music);
Dependencies.Cache(config = new OsuConfigManager(LocalStorage));
}
private OsuConfigManager config;
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("delete all beatmaps", () =>
{
Ruleset.Value = new OsuRuleset().RulesetInfo;
manager?.Delete(manager.GetAllUsableBeatmapSets());
Beatmap.SetDefault();
});
}
[Test]
public void TestSingleFilterOnEnter()
{
addRulesetImportStep(0);
addRulesetImportStep(0);
createSongSelect();
AddAssert("filter count is 1", () => songSelect.FilterCount == 1);
}
[Test]
public void TestChangeBeatmapBeforeEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for initial selection", () => !Beatmap.IsDefault);
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.PressKey(Key.Down);
InputManager.ReleaseKey(Key.Down);
InputManager.PressKey(Key.Enter);
InputManager.ReleaseKey(Key.Enter);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection changed", () => selected != Beatmap.Value);
}
[Test]
public void TestChangeBeatmapAfterEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for initial selection", () => !Beatmap.IsDefault);
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.PressKey(Key.Enter);
InputManager.ReleaseKey(Key.Enter);
InputManager.PressKey(Key.Down);
InputManager.ReleaseKey(Key.Down);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection didn't change", () => selected == Beatmap.Value);
}
[Test]
public void TestChangeBeatmapViaMouseBeforeEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for initial selection", () => !Beatmap.IsDefault);
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.MoveMouseTo(songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmap>()
.First(b => ((CarouselBeatmap)b.Item).Beatmap != songSelect.Carousel.SelectedBeatmap));
InputManager.PressButton(MouseButton.Left);
InputManager.ReleaseButton(MouseButton.Left);
InputManager.PressKey(Key.Enter);
InputManager.ReleaseKey(Key.Enter);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection changed", () => selected != Beatmap.Value);
}
[Test]
public void TestChangeBeatmapViaMouseAfterEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for initial selection", () => !Beatmap.IsDefault);
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.MoveMouseTo(songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmap>()
.First(b => ((CarouselBeatmap)b.Item).Beatmap != songSelect.Carousel.SelectedBeatmap));
InputManager.PressButton(MouseButton.Left);
InputManager.PressKey(Key.Enter);
InputManager.ReleaseKey(Key.Enter);
InputManager.ReleaseButton(MouseButton.Left);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection didn't change", () => selected == Beatmap.Value);
}
[Test]
public void TestNoFilterOnSimpleResume()
{
addRulesetImportStep(0);
addRulesetImportStep(0);
createSongSelect();
AddStep("push child screen", () => Stack.Push(new TestSceneOsuScreenStack.TestScreen("test child")));
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddStep("return", () => songSelect.MakeCurrent());
AddUntilStep("wait for current", () => songSelect.IsCurrentScreen());
AddAssert("filter count is 1", () => songSelect.FilterCount == 1);
}
[Test]
public void TestFilterOnResumeAfterChange()
{
addRulesetImportStep(0);
addRulesetImportStep(0);
AddStep("change convert setting", () => config.Set(OsuSetting.ShowConvertedBeatmaps, false));
createSongSelect();
AddStep("push child screen", () => Stack.Push(new TestSceneOsuScreenStack.TestScreen("test child")));
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddStep("change convert setting", () => config.Set(OsuSetting.ShowConvertedBeatmaps, true));
AddStep("return", () => songSelect.MakeCurrent());
AddUntilStep("wait for current", () => songSelect.IsCurrentScreen());
AddAssert("filter count is 2", () => songSelect.FilterCount == 2);
}
[Test]
public void TestAudioResuming()
{
createSongSelect();
addRulesetImportStep(0);
addRulesetImportStep(0);
checkMusicPlaying(true);
AddStep("select first", () => songSelect.Carousel.SelectBeatmap(songSelect.Carousel.BeatmapSets.First().Beatmaps.First()));
checkMusicPlaying(true);
AddStep("manual pause", () => music.TogglePause());
checkMusicPlaying(false);
AddStep("select next difficulty", () => songSelect.Carousel.SelectNext(skipDifficulties: false));
checkMusicPlaying(false);
AddStep("select next set", () => songSelect.Carousel.SelectNext());
checkMusicPlaying(true);
}
[TestCase(false)]
[TestCase(true)]
public void TestAudioRemainsCorrectOnRulesetChange(bool rulesetsInSameBeatmap)
{
createSongSelect();
// start with non-osu! to avoid convert confusion
changeRuleset(1);
if (rulesetsInSameBeatmap)
{
AddStep("import multi-ruleset map", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.ID != 2).ToArray();
manager.Import(createTestBeatmapSet(0, usableRulesets)).Wait();
});
}
else
{
addRulesetImportStep(1);
addRulesetImportStep(0);
}
checkMusicPlaying(true);
AddStep("manual pause", () => music.TogglePause());
checkMusicPlaying(false);
changeRuleset(0);
checkMusicPlaying(!rulesetsInSameBeatmap);
}
[Test]
public void TestDummy()
{
createSongSelect();
AddAssert("dummy selected", () => songSelect.CurrentBeatmap == defaultBeatmap);
AddUntilStep("dummy shown on wedge", () => songSelect.CurrentBeatmapDetailsBeatmap == defaultBeatmap);
addManyTestMaps();
AddWaitStep("wait for select", 3);
AddAssert("random map selected", () => songSelect.CurrentBeatmap != defaultBeatmap);
}
[Test]
public void TestSorting()
{
createSongSelect();
addManyTestMaps();
AddWaitStep("wait for add", 3);
AddAssert("random map selected", () => songSelect.CurrentBeatmap != defaultBeatmap);
var sortMode = config.GetBindable<SortMode>(OsuSetting.SongSelectSortingMode);
AddStep(@"Sort by Artist", delegate { sortMode.Value = SortMode.Artist; });
AddStep(@"Sort by Title", delegate { sortMode.Value = SortMode.Title; });
AddStep(@"Sort by Author", delegate { sortMode.Value = SortMode.Author; });
AddStep(@"Sort by DateAdded", delegate { sortMode.Value = SortMode.DateAdded; });
AddStep(@"Sort by BPM", delegate { sortMode.Value = SortMode.BPM; });
AddStep(@"Sort by Length", delegate { sortMode.Value = SortMode.Length; });
AddStep(@"Sort by Difficulty", delegate { sortMode.Value = SortMode.Difficulty; });
}
[Test]
public void TestImportUnderDifferentRuleset()
{
createSongSelect();
addRulesetImportStep(2);
AddUntilStep("no selection", () => songSelect.Carousel.SelectedBeatmap == null);
}
[Test]
public void TestImportUnderCurrentRuleset()
{
createSongSelect();
changeRuleset(2);
addRulesetImportStep(2);
addRulesetImportStep(1);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap.RulesetID == 2);
changeRuleset(1);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap.RulesetID == 1);
changeRuleset(0);
AddUntilStep("no selection", () => songSelect.Carousel.SelectedBeatmap == null);
}
[Test]
public void TestRulesetChangeResetsMods()
{
createSongSelect();
changeRuleset(0);
changeMods(new OsuModHardRock());
int actionIndex = 0;
int modChangeIndex = 0;
int rulesetChangeIndex = 0;
AddStep("change ruleset", () =>
{
SelectedMods.ValueChanged += onModChange;
songSelect.Ruleset.ValueChanged += onRulesetChange;
Ruleset.Value = new TaikoRuleset().RulesetInfo;
SelectedMods.ValueChanged -= onModChange;
songSelect.Ruleset.ValueChanged -= onRulesetChange;
});
AddAssert("mods changed before ruleset", () => modChangeIndex < rulesetChangeIndex);
AddAssert("empty mods", () => !SelectedMods.Value.Any());
void onModChange(ValueChangedEvent<IReadOnlyList<Mod>> e) => modChangeIndex = actionIndex++;
void onRulesetChange(ValueChangedEvent<RulesetInfo> e) => rulesetChangeIndex = actionIndex++;
}
[Test]
public void TestModsRetainedBetweenSongSelect()
{
AddAssert("empty mods", () => !SelectedMods.Value.Any());
createSongSelect();
addRulesetImportStep(0);
changeMods(new OsuModHardRock());
createSongSelect();
AddAssert("mods retained", () => SelectedMods.Value.Any());
}
[Test]
public void TestStartAfterUnMatchingFilterDoesNotStart()
{
createSongSelect();
addManyTestMaps();
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap != null);
bool startRequested = false;
AddStep("set filter and finalize", () =>
{
songSelect.StartRequested = () => startRequested = true;
songSelect.Carousel.Filter(new FilterCriteria { SearchText = "somestringthatshouldn'tbematchable" });
songSelect.FinaliseSelection();
songSelect.StartRequested = null;
});
AddAssert("start not requested", () => !startRequested);
}
[TestCase(false)]
[TestCase(true)]
public void TestExternalBeatmapChangeWhileFiltered(bool differentRuleset)
{
createSongSelect();
addManyTestMaps();
changeRuleset(0);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap != null);
AddStep("set filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = "nonono");
AddUntilStep("dummy selected", () => Beatmap.Value is DummyWorkingBeatmap);
AddUntilStep("has no selection", () => songSelect.Carousel.SelectedBeatmap == null);
BeatmapInfo target = null;
AddStep("select beatmap externally", () =>
{
target = manager.GetAllUsableBeatmapSets().Where(b => b.Beatmaps.Any(bi => bi.RulesetID == (differentRuleset ? 1 : 0)))
.ElementAt(5).Beatmaps.First();
Beatmap.Value = manager.GetWorkingBeatmap(target);
});
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap != null);
AddUntilStep("carousel has correct", () => songSelect.Carousel.SelectedBeatmap?.OnlineBeatmapID == target.OnlineBeatmapID);
AddUntilStep("game has correct", () => Beatmap.Value.BeatmapInfo.OnlineBeatmapID == target.OnlineBeatmapID);
AddStep("reset filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = string.Empty);
AddAssert("game still correct", () => Beatmap.Value?.BeatmapInfo.OnlineBeatmapID == target.OnlineBeatmapID);
AddAssert("carousel still correct", () => songSelect.Carousel.SelectedBeatmap.OnlineBeatmapID == target.OnlineBeatmapID);
}
[Test]
public void TestExternalBeatmapChangeWhileFilteredThenRefilter()
{
createSongSelect();
addManyTestMaps();
changeRuleset(0);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap != null);
AddStep("set filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = "nonono");
AddUntilStep("dummy selected", () => Beatmap.Value is DummyWorkingBeatmap);
AddUntilStep("has no selection", () => songSelect.Carousel.SelectedBeatmap == null);
BeatmapInfo target = null;
AddStep("select beatmap externally", () =>
{
target = manager.GetAllUsableBeatmapSets().Where(b => b.Beatmaps.Any(bi => bi.RulesetID == 1))
.ElementAt(5).Beatmaps.First();
Beatmap.Value = manager.GetWorkingBeatmap(target);
});
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmap != null);
AddUntilStep("carousel has correct", () => songSelect.Carousel.SelectedBeatmap?.OnlineBeatmapID == target.OnlineBeatmapID);
AddUntilStep("game has correct", () => Beatmap.Value.BeatmapInfo.OnlineBeatmapID == target.OnlineBeatmapID);
AddStep("set filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = "nononoo");
AddUntilStep("game lost selection", () => Beatmap.Value is DummyWorkingBeatmap);
AddAssert("carousel lost selection", () => songSelect.Carousel.SelectedBeatmap == null);
}
[Test]
public void TestAutoplayViaCtrlEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddStep("press ctrl+enter", () =>
{
InputManager.PressKey(Key.ControlLeft);
InputManager.PressKey(Key.Enter);
InputManager.ReleaseKey(Key.ControlLeft);
InputManager.ReleaseKey(Key.Enter);
});
AddUntilStep("wait for player", () => Stack.CurrentScreen is PlayerLoader);
AddAssert("autoplay enabled", () => songSelect.Mods.Value.FirstOrDefault() is ModAutoplay);
AddUntilStep("wait for return to ss", () => songSelect.IsCurrentScreen());
AddAssert("mod disabled", () => songSelect.Mods.Value.Count == 0);
}
[Test]
public void TestHideSetSelectsCorrectBeatmap()
{
int? previousID = null;
createSongSelect();
addRulesetImportStep(0);
AddStep("Move to last difficulty", () => songSelect.Carousel.SelectBeatmap(songSelect.Carousel.BeatmapSets.First().Beatmaps.Last()));
AddStep("Store current ID", () => previousID = songSelect.Carousel.SelectedBeatmap.ID);
AddStep("Hide first beatmap", () => manager.Hide(songSelect.Carousel.SelectedBeatmapSet.Beatmaps.First()));
AddAssert("Selected beatmap has not changed", () => songSelect.Carousel.SelectedBeatmap.ID == previousID);
}
[Test]
public void TestDifficultyIconSelecting()
{
addRulesetImportStep(0);
createSongSelect();
DrawableCarouselBeatmapSet set = null;
AddStep("Find the DrawableCarouselBeatmapSet", () =>
{
set = songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmapSet>().First();
});
DrawableCarouselBeatmapSet.FilterableDifficultyIcon difficultyIcon = null;
AddStep("Find an icon", () =>
{
difficultyIcon = set.ChildrenOfType<DrawableCarouselBeatmapSet.FilterableDifficultyIcon>()
.First(icon => getDifficultyIconIndex(set, icon) != getCurrentBeatmapIndex());
});
AddStep("Click on a difficulty", () =>
{
InputManager.MoveMouseTo(difficultyIcon);
InputManager.PressButton(MouseButton.Left);
InputManager.ReleaseButton(MouseButton.Left);
});
AddAssert("Selected beatmap correct", () => getCurrentBeatmapIndex() == getDifficultyIconIndex(set, difficultyIcon));
double? maxBPM = null;
AddStep("Filter some difficulties", () => songSelect.Carousel.Filter(new FilterCriteria
{
BPM = new FilterCriteria.OptionalRange<double>
{
Min = maxBPM = songSelect.Carousel.SelectedBeatmapSet.MaxBPM,
IsLowerInclusive = true
}
}));
DrawableCarouselBeatmapSet.FilterableDifficultyIcon filteredIcon = null;
AddStep("Get filtered icon", () =>
{
var filteredBeatmap = songSelect.Carousel.SelectedBeatmapSet.Beatmaps.Find(b => b.BPM < maxBPM);
int filteredBeatmapIndex = getBeatmapIndex(filteredBeatmap.BeatmapSet, filteredBeatmap);
filteredIcon = set.ChildrenOfType<DrawableCarouselBeatmapSet.FilterableDifficultyIcon>().ElementAt(filteredBeatmapIndex);
});
int? previousID = null;
AddStep("Store current ID", () => previousID = songSelect.Carousel.SelectedBeatmap.ID);
AddStep("Click on a filtered difficulty", () =>
{
InputManager.MoveMouseTo(filteredIcon);
InputManager.PressButton(MouseButton.Left);
InputManager.ReleaseButton(MouseButton.Left);
});
AddAssert("Selected beatmap has not changed", () => songSelect.Carousel.SelectedBeatmap.ID == previousID);
}
private int getBeatmapIndex(BeatmapSetInfo set, BeatmapInfo info) => set.Beatmaps.FindIndex(b => b == info);
private int getCurrentBeatmapIndex() => getBeatmapIndex(songSelect.Carousel.SelectedBeatmapSet, songSelect.Carousel.SelectedBeatmap);
private int getDifficultyIconIndex(DrawableCarouselBeatmapSet set, DrawableCarouselBeatmapSet.FilterableDifficultyIcon icon)
{
return set.ChildrenOfType<DrawableCarouselBeatmapSet.FilterableDifficultyIcon>().ToList().FindIndex(i => i == icon);
}
private void addRulesetImportStep(int id) => AddStep($"import test map for ruleset {id}", () => importForRuleset(id));
private void importForRuleset(int id) => manager.Import(createTestBeatmapSet(getImportId(), rulesets.AvailableRulesets.Where(r => r.ID == id).ToArray())).Wait();
private static int importId;
private int getImportId() => ++importId;
private void checkMusicPlaying(bool playing) =>
AddUntilStep($"music {(playing ? "" : "not ")}playing", () => music.IsPlaying == playing);
private void changeMods(params Mod[] mods) => AddStep($"change mods to {string.Join(", ", mods.Select(m => m.Acronym))}", () => SelectedMods.Value = mods);
private void changeRuleset(int id) => AddStep($"change ruleset to {id}", () => Ruleset.Value = rulesets.AvailableRulesets.First(r => r.ID == id));
private void createSongSelect()
{
AddStep("create song select", () => LoadScreen(songSelect = new TestSongSelect()));
AddUntilStep("wait for present", () => songSelect.IsCurrentScreen());
}
private void addManyTestMaps()
{
AddStep("import test maps", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.ID != 2).ToArray();
for (int i = 0; i < 100; i += 10)
manager.Import(createTestBeatmapSet(i, usableRulesets)).Wait();
});
}
private BeatmapSetInfo createTestBeatmapSet(int setId, RulesetInfo[] rulesets)
{
int j = 0;
RulesetInfo getRuleset() => rulesets[j++ % rulesets.Length];
var beatmaps = new List<BeatmapInfo>();
for (int i = 0; i < 6; i++)
{
int beatmapId = setId * 10 + i;
int length = RNG.Next(30000, 200000);
double bpm = RNG.NextSingle(80, 200);
beatmaps.Add(new BeatmapInfo
{
Ruleset = getRuleset(),
OnlineBeatmapID = beatmapId,
Path = "normal.osu",
Version = $"{beatmapId} (length {TimeSpan.FromMilliseconds(length):m\\:ss}, bpm {bpm:0.#})",
Length = length,
BPM = bpm,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 3.5f,
},
});
}
return new BeatmapSetInfo
{
OnlineBeatmapSetID = setId,
Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(),
Metadata = new BeatmapMetadata
{
// Create random metadata, then we can check if sorting works based on these
Artist = "Some Artist " + RNG.Next(0, 9),
Title = $"Some Song (set id {setId}, max bpm {beatmaps.Max(b => b.BPM):0.#})",
AuthorString = "Some Guy " + RNG.Next(0, 9),
},
Beatmaps = beatmaps,
DateAdded = DateTimeOffset.UtcNow,
};
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
rulesets?.Dispose();
}
private class TestSongSelect : PlaySongSelect
{
public Action StartRequested;
public new Bindable<RulesetInfo> Ruleset => base.Ruleset;
public new FilterControl FilterControl => base.FilterControl;
public WorkingBeatmap CurrentBeatmap => Beatmap.Value;
public WorkingBeatmap CurrentBeatmapDetailsBeatmap => BeatmapDetails.Beatmap;
public new BeatmapCarousel Carousel => base.Carousel;
protected override bool OnStart()
{
StartRequested?.Invoke();
return base.OnStart();
}
public int FilterCount;
protected override void ApplyFilterToCarousel(FilterCriteria criteria)
{
FilterCount++;
base.ApplyFilterToCarousel(criteria);
}
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// This service is for HG1.5 only, to make up for the fact that clients don't
/// keep any private information in themselves, and that their 'home service'
/// needs to do it for them.
/// Once we have better clients, this shouldn't be needed.
/// </summary>
public class UserAgentService : IUserAgentService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// This will need to go into a DB table
static Dictionary<UUID, TravelingAgentInfo> m_TravelingAgents = new Dictionary<UUID, TravelingAgentInfo>();
static bool m_Initialized = false;
protected static IGridUserService m_GridUserService;
protected static IGridService m_GridService;
protected static GatekeeperServiceConnector m_GatekeeperConnector;
protected static IGatekeeperService m_GatekeeperService;
protected static string m_GridName;
protected static bool m_BypassClientVerification;
public UserAgentService(IConfigSource config)
{
if (!m_Initialized)
{
m_Initialized = true;
m_log.DebugFormat("[HOME USERS SECURITY]: Starting...");
IConfig serverConfig = config.Configs["UserAgentService"];
if (serverConfig == null)
throw new Exception(String.Format("No section UserAgentService in config file"));
string gridService = serverConfig.GetString("GridService", String.Empty);
string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
string gatekeeperService = serverConfig.GetString("GatekeeperService", String.Empty);
m_BypassClientVerification = serverConfig.GetBoolean("BypassClientVerification", false);
if (gridService == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function."));
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
m_GatekeeperConnector = new GatekeeperServiceConnector();
m_GatekeeperService = ServerUtils.LoadPlugin<IGatekeeperService>(gatekeeperService, args);
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
if (m_GridName == string.Empty)
{
serverConfig = config.Configs["GatekeeperService"];
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
}
if (!m_GridName.EndsWith("/"))
m_GridName = m_GridName + "/";
}
}
public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
{
position = new Vector3(128, 128, 0); lookAt = Vector3.UnitY;
m_log.DebugFormat("[USER AGENT SERVICE]: Request to get home region of user {0}", userID);
GridRegion home = null;
GridUserInfo uinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (uinfo != null)
{
if (uinfo.HomeRegionID != UUID.Zero)
{
home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
position = uinfo.HomePosition;
lookAt = uinfo.HomeLookAt;
}
if (home == null)
{
List<GridRegion> defs = m_GridService.GetDefaultRegions(UUID.Zero);
if (defs != null && defs.Count > 0)
home = defs[0];
}
}
return home;
}
public bool LoginAgentToGrid(AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, IPEndPoint clientIP, out string reason)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} {1} (@{2}) to grid {3}",
agentCircuit.firstname, agentCircuit.lastname, ((clientIP == null) ? "stored IP" : clientIP.Address.ToString()), gatekeeper.ServerURI);
// Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
GridRegion region = new GridRegion(gatekeeper);
region.ServerURI = gatekeeper.ServerURI;
region.ExternalHostName = finalDestination.ExternalHostName;
region.InternalEndPoint = finalDestination.InternalEndPoint;
region.RegionName = finalDestination.RegionName;
region.RegionID = finalDestination.RegionID;
region.RegionLocX = finalDestination.RegionLocX;
region.RegionLocY = finalDestination.RegionLocY;
// Generate a new service session
agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
TravelingAgentInfo old = UpdateTravelInfo(agentCircuit, region);
bool success = false;
string myExternalIP = string.Empty;
string gridName = gatekeeper.ServerURI;
m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}", m_GridName, gridName);
if (m_GridName == gridName)
success = m_GatekeeperService.LoginAgent(agentCircuit, finalDestination, out reason);
else
success = m_GatekeeperConnector.CreateAgent(region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, out myExternalIP, out reason);
if (!success)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);
// restore the old travel info
lock (m_TravelingAgents)
m_TravelingAgents[agentCircuit.SessionID] = old;
return false;
}
m_log.DebugFormat("[USER AGENT SERVICE]: Gatekeeper sees me as {0}", myExternalIP);
// else set the IP addresses associated with this client
if (clientIP != null)
m_TravelingAgents[agentCircuit.SessionID].ClientIPAddress = clientIP.Address.ToString();
m_TravelingAgents[agentCircuit.SessionID].MyIpAddress = myExternalIP;
return true;
}
public bool LoginAgentToGrid(AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
{
reason = string.Empty;
return LoginAgentToGrid(agentCircuit, gatekeeper, finalDestination, null, out reason);
}
private void SetClientIP(UUID sessionID, string ip)
{
if (m_TravelingAgents.ContainsKey(sessionID))
{
m_log.DebugFormat("[USER AGENT SERVICE]: Setting IP {0} for session {1}", ip, sessionID);
m_TravelingAgents[sessionID].ClientIPAddress = ip;
}
}
TravelingAgentInfo UpdateTravelInfo(AgentCircuitData agentCircuit, GridRegion region)
{
TravelingAgentInfo travel = new TravelingAgentInfo();
TravelingAgentInfo old = null;
lock (m_TravelingAgents)
{
if (m_TravelingAgents.ContainsKey(agentCircuit.SessionID))
{
// Very important! Override whatever this agent comes with.
// UserAgentService always sets the IP for every new agent
// with the original IP address.
agentCircuit.IPAddress = m_TravelingAgents[agentCircuit.SessionID].ClientIPAddress;
old = m_TravelingAgents[agentCircuit.SessionID];
}
m_TravelingAgents[agentCircuit.SessionID] = travel;
}
travel.UserID = agentCircuit.AgentID;
travel.GridExternalName = region.ServerURI;
travel.ServiceToken = agentCircuit.ServiceSessionID;
if (old != null)
travel.ClientIPAddress = old.ClientIPAddress;
return old;
}
public void LogoutAgent(UUID userID, UUID sessionID)
{
m_log.DebugFormat("[USER AGENT SERVICE]: User {0} logged out", userID);
lock (m_TravelingAgents)
{
List<UUID> travels = new List<UUID>();
foreach (KeyValuePair<UUID, TravelingAgentInfo> kvp in m_TravelingAgents)
if (kvp.Value == null) // do some clean up
travels.Add(kvp.Key);
else if (kvp.Value.UserID == userID)
travels.Add(kvp.Key);
foreach (UUID session in travels)
m_TravelingAgents.Remove(session);
}
GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (guinfo != null)
m_GridUserService.LoggedOut(userID.ToString(), sessionID, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
}
// We need to prevent foreign users with the same UUID as a local user
public bool AgentIsComingHome(UUID sessionID, string thisGridExternalName)
{
if (!m_TravelingAgents.ContainsKey(sessionID))
return false;
TravelingAgentInfo travel = m_TravelingAgents[sessionID];
return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower();
}
public bool VerifyClient(UUID sessionID, string reportedIP)
{
if (m_BypassClientVerification)
return true;
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with reported IP {1}.",
sessionID, reportedIP);
if (m_TravelingAgents.ContainsKey(sessionID))
{
bool result = m_TravelingAgents[sessionID].ClientIPAddress == reportedIP ||
m_TravelingAgents[sessionID].MyIpAddress == reportedIP; // NATed
m_log.DebugFormat("[USER AGENT SERVICE]: Comparing {0} with login IP {1} and MyIP {1}; result is {3}",
reportedIP, m_TravelingAgents[sessionID].ClientIPAddress, m_TravelingAgents[sessionID].MyIpAddress, result);
return result;
}
return false;
}
public bool VerifyAgent(UUID sessionID, string token)
{
if (m_TravelingAgents.ContainsKey(sessionID))
{
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying agent token {0} against {1}", token, m_TravelingAgents[sessionID].ServiceToken);
return m_TravelingAgents[sessionID].ServiceToken == token;
}
m_log.DebugFormat("[USER AGENT SERVICE]: Token verification for session {0}: no such session", sessionID);
return false;
}
}
class TravelingAgentInfo
{
public UUID UserID;
public string GridExternalName = string.Empty;
public string ServiceToken = string.Empty;
public string ClientIPAddress = string.Empty; // as seen from this user agent service
public string MyIpAddress = string.Empty; // the user agent service's external IP, as seen from the next gatekeeper
}
}
| |
//Matt Schoen
//5-29-2013
//
// This software is the copyrighted material of its author, Matt Schoen, and his company Defective Studios.
// It is available for sale on the Unity Asset store and is subject to their restrictions and limitations, as well as
// the following: You shall not reproduce or re-distribute this software without the express written (e-mail is fine)
// permission of the author. If permission is granted, the code (this file and related files) must bear this license
// in its entirety. Anyone who purchases the script is welcome to modify and re-use the code at their personal risk
// and under the condition that it not be included in any distribution builds. The software is provided as-is without
// warranty and the author bears no responsibility for damages or losses caused by the software.
// This Agreement becomes effective from the day you have installed, copied, accessed, downloaded and/or otherwise used
// the software.
#define DEV //Comment this out to not auto-populate scene merge
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
public class SceneMerge : EditorWindow {
const string messagePath = "Assets/merges.txt";
public static Object mine, theirs;
private static bool merged;
//If these names end up conflicting with names within your scene, change them here
public const string mineContainerName = "mine", theirsContainerName = "theirs";
public static GameObject mineContainer, theirsContainer;
public static float colWidth;
static SceneData mySceneData, theirSceneData;
Vector2 scroll;
[MenuItem("Window/UniMerge/Scene Merge %&m")]
static void Init() {
GetWindow(typeof(SceneMerge));
}
#if DEV
//If these names end up conflicting with names within your project, change them here
public const string mineSceneName = "Mine", theirsSceneName = "Theirs";
void OnEnable() {
//Get path
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
//Unity 3 path stuff?
#else
string scriptPath = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this));
UniMergeConfig.DEFAULT_PATH = scriptPath.Substring(0, scriptPath.IndexOf("Editor") - 1);
#endif
if(Directory.Exists(UniMergeConfig.DEFAULT_PATH + "/Demo/Scene Merge")){
string[] assets = Directory.GetFiles(UniMergeConfig.DEFAULT_PATH + "/Demo/Scene Merge");
foreach(var asset in assets) {
if(asset.EndsWith(".unity")) {
if(asset.Contains(mineSceneName)) {
mine = AssetDatabase.LoadAssetAtPath(asset.Replace('\\', '/'), typeof(Object));
}
if(asset.Contains(theirsSceneName)) {
theirs = AssetDatabase.LoadAssetAtPath(asset.Replace('\\', '/'), typeof(Object));
}
}
}
}
}
#endif
void OnGUI(){
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
//Layout fix for older versions?
#else
EditorGUIUtility.labelWidth = 100;
#endif
//Ctrl + w to close
if(Event.current.Equals(Event.KeyboardEvent("^w"))) {
Close();
GUIUtility.ExitGUI();
}
/*
* SETUP
*/
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
EditorGUIUtility.LookLikeControls();
#endif
ObjectMerge.alt = false;
//Adjust colWidth as the window resizes
colWidth = (position.width - UniMergeConfig.midWidth*2 - UniMergeConfig.margin)/2;
if(mine == null || theirs == null
|| mine.GetType() != typeof(Object) || mine.GetType() != typeof(Object)
) //|| !AssetDatabase.GetAssetPath(mine).Contains(".unity") || !AssetDatabase.GetAssetPath(theirs).Contains(".unity"))
merged = GUI.enabled = false;
if(GUILayout.Button("Merge")) {
Merge(mine, theirs);
GUIUtility.ExitGUI();
}
GUI.enabled = merged;
GUILayout.BeginHorizontal();
{
GUI.enabled = mineContainer;
if (!GUI.enabled)
merged = false;
if(GUILayout.Button("Unpack Mine")) {
DestroyImmediate(theirsContainer);
List<Transform> tmp = new List<Transform>();
foreach(Transform t in mineContainer.transform)
tmp.Add(t);
foreach(Transform t in tmp)
t.parent = null;
DestroyImmediate(mineContainer);
mySceneData.ApplySettings();
}
GUI.enabled = theirsContainer;
if (!GUI.enabled)
merged = false;
if(GUILayout.Button("Unpack Theirs")) {
DestroyImmediate(mineContainer);
List<Transform> tmp = new List<Transform>();
foreach(Transform t in theirsContainer.transform)
tmp.Add(t);
foreach(Transform t in tmp)
t.parent = null;
DestroyImmediate(theirsContainer);
theirSceneData.ApplySettings();
}
}
GUILayout.EndHorizontal();
GUI.enabled = true;
ObjectMerge.DrawRowHeight();
GUILayout.BeginHorizontal();
{
GUILayout.BeginVertical(GUILayout.Width(colWidth));
{
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
mine = EditorGUILayout.ObjectField("Mine", mine, typeof(Object));
#else
mine = EditorGUILayout.ObjectField("Mine", mine, typeof(Object), true);
#endif
}
GUILayout.EndVertical();
GUILayout.Space(UniMergeConfig.midWidth*2);
GUILayout.BeginVertical(GUILayout.Width(colWidth));
{
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
theirs = EditorGUILayout.ObjectField("Theirs", theirs, typeof(Object));
#else
theirs = EditorGUILayout.ObjectField("Theirs", theirs, typeof(Object), true);
#endif
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
if(mine == null || theirs == null)
merged = false;
if(merged) {
scroll = GUILayout.BeginScrollView(scroll);
//Fog
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.fog == theirSceneData.fog;
return same;
},
left = delegate {
if(mine)
mySceneData.fog = EditorGUILayout.Toggle("Fog", mySceneData.fog);
},
leftButton = delegate {
mySceneData.fog = theirSceneData.fog;
},
rightButton = delegate {
theirSceneData.fog = mySceneData.fog;
},
right = delegate {
if(theirs)
theirSceneData.fog = EditorGUILayout.Toggle("Fog", theirSceneData.fog);
},
drawButtons = mine && theirs
});
//Fog Color
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.fogColor == theirSceneData.fogColor;
return same;
},
left = delegate {
if(mine)
mySceneData.fogColor = EditorGUILayout.ColorField("Fog Color", mySceneData.fogColor);
},
leftButton = delegate {
mySceneData.fogColor = theirSceneData.fogColor;
},
rightButton = delegate {
theirSceneData.fogColor = mySceneData.fogColor;
},
right = delegate {
if(theirs)
theirSceneData.fogColor = EditorGUILayout.ColorField("Fog Color", theirSceneData.fogColor);
},
drawButtons = mine && theirs
});
//Fog Mode
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.fogMode == theirSceneData.fogMode;
return same;
},
left = delegate {
if(mine)
mySceneData.fogMode = (FogMode)EditorGUILayout.EnumPopup("Fog Mode", mySceneData.fogMode);
},
leftButton = delegate {
mySceneData.fogMode = theirSceneData.fogMode;
},
rightButton = delegate {
theirSceneData.fogMode = mySceneData.fogMode;
},
right = delegate {
if(theirs)
theirSceneData.fogMode = (FogMode)EditorGUILayout.EnumPopup("Fog Mode", theirSceneData.fogMode);
},
drawButtons = mine && theirs
});
//Fog Density
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.fogDensity == theirSceneData.fogDensity;
return same;
},
left = delegate {
if(mine)
mySceneData.fogDensity = EditorGUILayout.FloatField("Linear Density", mySceneData.fogDensity);
},
leftButton = delegate {
mySceneData.fogDensity = theirSceneData.fogDensity;
},
rightButton = delegate {
theirSceneData.fogDensity = mySceneData.fogDensity;
},
right = delegate {
if(theirs)
theirSceneData.fogDensity = EditorGUILayout.FloatField("Linear Density", theirSceneData.fogDensity);
},
drawButtons = mine && theirs
});
//Linear Fog Start
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.fogStartDistance == theirSceneData.fogStartDistance;
return same;
},
left = delegate {
if(mine)
mySceneData.fogStartDistance = EditorGUILayout.FloatField("Linear Fog Start", mySceneData.fogStartDistance);
},
leftButton = delegate {
mySceneData.fogStartDistance = theirSceneData.fogStartDistance;
},
rightButton = delegate {
theirSceneData.fogStartDistance = mySceneData.fogStartDistance;
},
right = delegate {
if(theirs)
theirSceneData.fogStartDistance = EditorGUILayout.FloatField("Linear Fog Start", theirSceneData.fogStartDistance);
},
drawButtons = mine && theirs
});
//Linear Fog End
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.fogEndDistance == theirSceneData.fogEndDistance;
return same;
},
left = delegate {
if(mine)
mySceneData.fogEndDistance = EditorGUILayout.FloatField("Linear Fog End", mySceneData.fogEndDistance);
},
leftButton = delegate {
mySceneData.fogEndDistance = theirSceneData.fogEndDistance;
},
rightButton = delegate {
theirSceneData.fogEndDistance = mySceneData.fogEndDistance;
},
right = delegate {
if(theirs)
theirSceneData.fogEndDistance = EditorGUILayout.FloatField("Linear Fog End", theirSceneData.fogEndDistance);
},
drawButtons = mine && theirs
});
//Ambient Light
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.ambientLight == theirSceneData.ambientLight;
return same;
},
left = delegate {
if(mine)
mySceneData.ambientLight = EditorGUILayout.ColorField("Ambient Light", mySceneData.ambientLight);
},
leftButton = delegate {
mySceneData.ambientLight = theirSceneData.ambientLight;
},
rightButton = delegate {
theirSceneData.ambientLight = mySceneData.ambientLight;
},
right = delegate {
if(theirs)
theirSceneData.ambientLight = EditorGUILayout.ColorField("Ambient Light", theirSceneData.ambientLight);
},
drawButtons = mine && theirs
});
//Skybox
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.skybox == theirSceneData.skybox;
return same;
},
left = delegate {
if(mine)
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
mySceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", mySceneData.skybox, typeof(Material));
#else
mySceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", mySceneData.skybox, typeof(Material), false);
#endif
},
leftButton = delegate {
mySceneData.skybox = theirSceneData.skybox;
},
rightButton = delegate {
theirSceneData.skybox = mySceneData.skybox;
},
right = delegate {
if(theirs)
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
theirSceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", theirSceneData.skybox, typeof(Material));
#else
theirSceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", theirSceneData.skybox, typeof(Material), false);
#endif
},
drawButtons = mine && theirs
});
//Halo Strength
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.haloStrength == theirSceneData.haloStrength;
return same;
},
left = delegate {
if(mine)
mySceneData.haloStrength = EditorGUILayout.FloatField("Halo Strength", mySceneData.haloStrength);
},
leftButton = delegate {
mySceneData.haloStrength = theirSceneData.haloStrength;
},
rightButton = delegate {
theirSceneData.haloStrength = mySceneData.haloStrength;
},
right = delegate {
if(theirs)
theirSceneData.haloStrength = EditorGUILayout.FloatField("Halo Strength", theirSceneData.haloStrength);
},
drawButtons = mine && theirs
});
//Flare Strength
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.flareStrength == theirSceneData.flareStrength;
return same;
},
left = delegate {
if(mine)
mySceneData.flareStrength = EditorGUILayout.FloatField("Flare Strength", mySceneData.flareStrength);
},
leftButton = delegate {
mySceneData.flareStrength = theirSceneData.flareStrength;
},
rightButton = delegate {
theirSceneData.flareStrength = mySceneData.flareStrength;
},
right = delegate {
if(theirs)
theirSceneData.flareStrength = EditorGUILayout.FloatField("Flare Strength", theirSceneData.flareStrength);
},
drawButtons = mine && theirs
});
//Flare Fade Speed
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = 0,
colWidth = colWidth,
compare = delegate {
bool same = GenericCompare();
if(same)
same = mySceneData.flareFadeSpeed == theirSceneData.flareFadeSpeed;
return same;
},
left = delegate {
if(mine)
mySceneData.flareFadeSpeed = EditorGUILayout.FloatField("Flare Fade Speed", mySceneData.flareFadeSpeed);
},
leftButton = delegate {
mySceneData.flareFadeSpeed = theirSceneData.flareFadeSpeed;
},
rightButton = delegate {
theirSceneData.flareFadeSpeed = mySceneData.flareFadeSpeed;
},
right = delegate {
if(theirs)
theirSceneData.flareFadeSpeed = EditorGUILayout.FloatField("Flare Fade Speed", theirSceneData.flareFadeSpeed);
},
drawButtons = mine && theirs
});
GUILayout.EndScrollView();
}
}
static bool GenericCompare() {
bool same = mine;
if(same)
same = theirs;
return same;
}
public static void CLIIn() {
string[] args = System.Environment.GetCommandLineArgs();
foreach(string arg in args)
Debug.Log(arg);
Merge(args[args.Length - 2], args[args.Length - 1]);
}
void Update() {
TextAsset mergeFile = (TextAsset)AssetDatabase.LoadAssetAtPath(messagePath, typeof(TextAsset));
if(mergeFile) {
string[] files = mergeFile.text.Split('\n');
AssetDatabase.DeleteAsset(messagePath);
foreach(string file in files)
Debug.Log(file);
//TODO: Add prefab case
DoMerge(files);
}
}
public static void DoMerge(string[] paths) {
if(paths.Length > 2) {
Merge(paths[0], paths[1]);
} else Debug.LogError("need at least 2 paths, " + paths.Length + " given");
}
public static void Merge(Object myScene, Object theirScene) {
if(myScene == null || theirScene == null)
return;
Merge(AssetDatabase.GetAssetPath(myScene), AssetDatabase.GetAssetPath(theirScene));
}
public static void Merge(string myPath, string theirPath) {
if(string.IsNullOrEmpty(myPath) || string.IsNullOrEmpty(theirPath))
return;
if(AssetDatabase.LoadAssetAtPath(myPath, typeof(Object)) && AssetDatabase.LoadAssetAtPath(theirPath, typeof(Object))) {
if(EditorApplication.SaveCurrentSceneIfUserWantsTo()) {
//Load "theirs" to get RenderSettings, etc.
EditorApplication.OpenScene(theirPath);
theirSceneData.ambientLight = RenderSettings.ambientLight;
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#else
theirSceneData.flareFadeSpeed = RenderSettings.flareFadeSpeed;
#endif
theirSceneData.flareStrength = RenderSettings.flareStrength;
theirSceneData.fog = RenderSettings.fog;
theirSceneData.fogColor = RenderSettings.fogColor;
theirSceneData.fogDensity = RenderSettings.fogDensity;
theirSceneData.fogEndDistance = RenderSettings.fogEndDistance;
theirSceneData.fogMode = RenderSettings.fogMode;
theirSceneData.fogStartDistance = RenderSettings.fogStartDistance;
theirSceneData.haloStrength = RenderSettings.haloStrength;
theirSceneData.skybox = RenderSettings.skybox;
//Load "mine" to start the merge
EditorApplication.OpenScene(myPath);
mySceneData.ambientLight = RenderSettings.ambientLight;
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#else
mySceneData.flareFadeSpeed = RenderSettings.flareFadeSpeed;
#endif
mySceneData.flareStrength = RenderSettings.flareStrength;
mySceneData.fog = RenderSettings.fog;
mySceneData.fogColor = RenderSettings.fogColor;
mySceneData.fogDensity = RenderSettings.fogDensity;
mySceneData.fogEndDistance = RenderSettings.fogEndDistance;
mySceneData.fogMode = RenderSettings.fogMode;
mySceneData.fogStartDistance = RenderSettings.fogStartDistance;
mySceneData.haloStrength = RenderSettings.haloStrength;
mySceneData.skybox = RenderSettings.skybox;
mineContainer = new GameObject {name = mineContainerName};
GameObject[] allObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject));
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null
&& EditorUtility.GetPrefabType(obj) != PrefabType.Prefab
&& EditorUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = mineContainer.transform;
}
#else
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null
&& PrefabUtility.GetPrefabType(obj) != PrefabType.Prefab
&& PrefabUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = mineContainer.transform;
}
#endif
EditorApplication.OpenSceneAdditive(theirPath);
theirsContainer = new GameObject {name = theirsContainerName};
allObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject));
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null && obj.name != mineContainerName
&& EditorUtility.GetPrefabType(obj) != PrefabType.Prefab
&& EditorUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = theirsContainer.transform;
}
#else
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null && obj.name != mineContainerName
&& PrefabUtility.GetPrefabType(obj) != PrefabType.Prefab
&& PrefabUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = theirsContainer.transform;
}
#endif
GetWindow(typeof(ObjectMerge));
ObjectMerge.mine = mineContainer;
ObjectMerge.theirs = theirsContainer;
merged = true;
}
}
}
}
public struct SceneData {
public Color ambientLight,
fogColor;
public float flareFadeSpeed,
flareStrength,
fogDensity,
fogEndDistance,
fogStartDistance,
haloStrength;
public bool fog;
public FogMode fogMode;
public Material skybox;
//Hmm... can't get at haloTexture or spotCookie
//public Texture haloTexture, spotCookie;
public void ApplySettings() {
RenderSettings.ambientLight = ambientLight;
RenderSettings.fogColor = fogColor;
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#else
RenderSettings.flareFadeSpeed = flareFadeSpeed;
#endif
RenderSettings.flareStrength = flareStrength;
RenderSettings.fogDensity = fogDensity;
RenderSettings.fogEndDistance = fogEndDistance;
RenderSettings.fogStartDistance = fogStartDistance;
RenderSettings.haloStrength = haloStrength;
RenderSettings.fog = fog;
RenderSettings.fogMode = fogMode;
RenderSettings.skybox = skybox;
}
}
| |
//
// SchedulerTests.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 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.
//
#if ENABLE_TESTS
using System;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Hyena;
namespace Hyena.Jobs
{
[TestFixture]
public class SchedulerTests
{
private Scheduler scheduler;
[SetUp]
public void Setup ()
{
//Log.Debugging = true;
TestJob.job_count = 0;
Log.Debug ("New job scheduler test");
}
[TearDown]
public void TearDown ()
{
if (scheduler != null) {
// Ensure the scheduler's jobs are all finished, otherwise
// their job threads will be killed, throwing an exception
while (scheduler.JobCount > 0);
}
//Log.Debugging = false;
}
[Test]
public void TestSimultaneousSpeedJobs ()
{
scheduler = new Scheduler ();
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));
scheduler.Add (new TestJob (200, PriorityHints.None, Resource.Cpu, Resource.Disk));
// Test that two SpeedSensitive jobs with the same Resources will run simultaneously
AssertJobsRunning (2);
// but that the third that isn't SpeedSensitive won't run until they are both done
while (scheduler.JobCount > 1);
Assert.AreEqual (PriorityHints.None, scheduler.Jobs.First ().PriorityHints);
}
[Test]
public void TestOneNonSpeedJobPerResource ()
{
// Test that two SpeedSensitive jobs with the same Resources will run simultaneously
scheduler = new Scheduler ();
scheduler.Add (new TestJob (200, PriorityHints.None, Resource.Cpu, Resource.Disk));
scheduler.Add (new TestJob (200, PriorityHints.None, Resource.Cpu, Resource.Disk));
AssertJobsRunning (1);
}
[Test]
public void TestSpeedJobPreemptsNonSpeedJobs ()
{
scheduler = new Scheduler ();
TestJob a = new TestJob (200, PriorityHints.None, Resource.Cpu);
TestJob b = new TestJob (200, PriorityHints.None, Resource.Disk);
TestJob c = new TestJob (200, PriorityHints.LongRunning, Resource.Database);
scheduler.Add (a);
scheduler.Add (b);
scheduler.Add (c);
// Test that three jobs got started
AssertJobsRunning (3);
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));
// Make sure the SpeedSensitive jobs has caused the Cpu and Disk jobs to be paused
AssertJobsRunning (2);
Assert.AreEqual (true, a.IsScheduled);
Assert.AreEqual (true, b.IsScheduled);
Assert.AreEqual (true, c.IsRunning);
}
/*[Test]
public void TestManyJobs ()
{
var timer = System.Diagnostics.Stopwatch.StartNew ();
scheduler = new Scheduler ("TestManyJobs");
// First add some long running jobs
for (int i = 0; i < 100; i++) {
scheduler.Add (new TestJob (20, PriorityHints.LongRunning, Resource.Cpu));
}
// Then add some normal jobs that will prempt them
for (int i = 0; i < 100; i++) {
scheduler.Add (new TestJob (10, PriorityHints.None, Resource.Cpu));
}
// Then add some SpeedSensitive jobs that will prempt all of them
for (int i = 0; i < 100; i++) {
scheduler.Add (new TestJob (5, PriorityHints.SpeedSensitive, Resource.Cpu));
}
while (scheduler.Jobs.Count > 0);
Log.DebugFormat ("Took {0} to schedule and process all jobs", timer.Elapsed);
//scheduler.StopAll ();
}*/
/*[Test]
public void TestCannotDisposeWhileDatalossJobsScheduled ()
{
scheduler = new Scheduler ();
TestJob loss_job;
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu));
scheduler.Add (loss_job = new TestJob (200, PriorityHints.DataLossIfStopped, Resource.Cpu));
AssertJobsRunning (1);
Assert.AreEqual (false, scheduler.JobInfo[loss_job].IsRunning);
try {
//scheduler.StopAll ();
Assert.Fail ("Cannot stop with dataloss job scheduled");
} catch {
}
}
public void TestCannotDisposeWhileDatalossJobsRunning ()
{
scheduler = new Scheduler ();
scheduler.Add (new TestJob (200, PriorityHints.DataLossIfStopped, Resource.Cpu));
AssertJobsRunning (1);
try {
//scheduler.StopAll ();
Assert.Fail ("Cannot stop with dataloss job running");
} catch {
}
}*/
private void AssertJobsRunning (int count)
{
Assert.AreEqual (count, scheduler.Jobs.Count (j => j.IsRunning));
}
private class TestJob : SimpleAsyncJob
{
internal static int job_count;
int iteration;
int sleep_time;
public TestJob (int sleep_time, PriorityHints hints, params Resource [] resources)
: base (String.Format ("{0} ( {1}, {2})", job_count++, hints, resources.Aggregate ("", (a, b) => a += b.Id + " ")),
hints,
resources)
{
this.sleep_time = sleep_time;
}
protected override void Run ()
{
for (int i = 0; !IsCancelRequested && i < 2; i++) {
YieldToScheduler ();
Hyena.Log.DebugFormat ("{0} iteration {1}", Title, iteration++);
System.Threading.Thread.Sleep (sleep_time);
}
OnFinished ();
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityHistory.Extensions;
using Abp.Events.Bus.Entities;
using Abp.Extensions;
using Abp.Json;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Abp.EntityHistory
{
public class EntityHistoryHelper : EntityHistoryHelperBase, IEntityHistoryHelper, ITransientDependency
{
public EntityHistoryHelper(
IEntityHistoryConfiguration configuration,
IUnitOfWorkManager unitOfWorkManager)
: base(configuration, unitOfWorkManager)
{
}
public virtual EntityChangeSet CreateEntityChangeSet(ICollection<EntityEntry> entityEntries)
{
var changeSet = new EntityChangeSet
{
Reason = EntityChangeSetReasonProvider.Reason.TruncateWithPostfix(EntityChangeSet.MaxReasonLength),
// Fill "who did this change"
BrowserInfo = ClientInfoProvider.BrowserInfo.TruncateWithPostfix(EntityChangeSet.MaxBrowserInfoLength),
ClientIpAddress = ClientInfoProvider.ClientIpAddress.TruncateWithPostfix(EntityChangeSet.MaxClientIpAddressLength),
ClientName = ClientInfoProvider.ComputerName.TruncateWithPostfix(EntityChangeSet.MaxClientNameLength),
ImpersonatorTenantId = AbpSession.ImpersonatorTenantId,
ImpersonatorUserId = AbpSession.ImpersonatorUserId,
TenantId = AbpSession.TenantId,
UserId = AbpSession.UserId
};
if (!IsEntityHistoryEnabled)
{
return changeSet;
}
foreach (var entityEntry in entityEntries)
{
var typeOfEntity = entityEntry.Entity.GetType();
var shouldTrackEntity = IsTypeOfTrackedEntity(typeOfEntity);
if (shouldTrackEntity.HasValue && !shouldTrackEntity.Value)
{
continue;
}
if (!IsTypeOfEntity(typeOfEntity) && !entityEntry.Metadata.IsOwned())
{
continue;
}
var shouldAuditEntity = IsTypeOfAuditedEntity(typeOfEntity);
if (shouldAuditEntity.HasValue && !shouldAuditEntity.Value)
{
continue;
}
bool? shouldAuditOwnerEntity = null;
bool? shouldAuditOwnerProperty = null;
if (!shouldAuditEntity.HasValue && entityEntry.Metadata.IsOwned())
{
// Check if owner entity has auditing attribute
var foreignKey = entityEntry.Metadata.GetForeignKeys().First();
var ownerEntity = foreignKey.PrincipalEntityType.ClrType;
shouldAuditOwnerEntity = IsTypeOfAuditedEntity(ownerEntity);
if (shouldAuditOwnerEntity.HasValue && !shouldAuditOwnerEntity.Value)
{
continue;
}
var ownerPropertyInfo = foreignKey.PrincipalToDependent.PropertyInfo;
shouldAuditOwnerProperty = IsAuditedPropertyInfo(ownerPropertyInfo);
if (shouldAuditOwnerProperty.HasValue && !shouldAuditOwnerProperty.Value)
{
continue;
}
}
var entityChange = CreateEntityChange(entityEntry);
if (entityChange == null)
{
continue;
}
var isAuditableEntity = (shouldAuditEntity.HasValue && shouldAuditEntity.Value) ||
(shouldAuditOwnerEntity.HasValue && shouldAuditOwnerEntity.Value) ||
(shouldAuditOwnerProperty.HasValue && shouldAuditOwnerProperty.Value);
var isTrackableEntity = shouldTrackEntity.HasValue && shouldTrackEntity.Value;
var shouldSaveAuditedPropertiesOnly = !isAuditableEntity && !isTrackableEntity;
var propertyChanges = GetPropertyChanges(entityEntry, shouldSaveAuditedPropertiesOnly);
if (propertyChanges.Count == 0)
{
continue;
}
entityChange.PropertyChanges = propertyChanges;
changeSet.EntityChanges.Add(entityChange);
}
return changeSet;
}
public virtual async Task SaveAsync(EntityChangeSet changeSet)
{
if (!IsEntityHistoryEnabled)
{
return;
}
UpdateChangeSet(changeSet);
if (changeSet.EntityChanges.Count == 0)
{
return;
}
using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress))
{
await EntityHistoryStore.SaveAsync(changeSet);
await uow.CompleteAsync();
}
}
public virtual void Save(EntityChangeSet changeSet)
{
if (!IsEntityHistoryEnabled)
{
return;
}
UpdateChangeSet(changeSet);
if (changeSet.EntityChanges.Count == 0)
{
return;
}
using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress))
{
EntityHistoryStore.Save(changeSet);
uow.Complete();
}
}
protected virtual string GetEntityId(EntityEntry entry)
{
var primaryKeys = entry.Properties.Where(p => p.Metadata.IsPrimaryKey());
return primaryKeys.First().CurrentValue?.ToJsonString();
}
[CanBeNull]
private EntityChange CreateEntityChange(EntityEntry entityEntry)
{
var entityId = GetEntityId(entityEntry);
var entityTypeFullName = entityEntry.Entity.GetType().FullName;
EntityChangeType changeType;
switch (entityEntry.State)
{
case EntityState.Added:
changeType = EntityChangeType.Created;
break;
case EntityState.Deleted:
changeType = EntityChangeType.Deleted;
break;
case EntityState.Modified:
changeType = entityEntry.IsDeleted() ? EntityChangeType.Deleted : EntityChangeType.Updated;
break;
case EntityState.Detached:
case EntityState.Unchanged:
return null;
default:
Logger.ErrorFormat("Unexpected {0} - {1}", nameof(entityEntry.State), entityEntry.State);
return null;
}
if (entityId == null && changeType != EntityChangeType.Created)
{
Logger.ErrorFormat("EntityChangeType {0} must have non-empty entity id", changeType);
return null;
}
return new EntityChange
{
ChangeType = changeType,
EntityEntry = entityEntry, // [NotMapped]
EntityId = entityId,
EntityTypeFullName = entityTypeFullName,
TenantId = AbpSession.TenantId
};
}
/// <summary>
/// Gets the property changes for this entry.
/// </summary>
private ICollection<EntityPropertyChange> GetPropertyChanges(EntityEntry entityEntry, bool auditedPropertiesOnly)
{
var propertyChanges = new List<EntityPropertyChange>();
var properties = entityEntry.Metadata.GetProperties();
foreach (var property in properties)
{
if (property.IsPrimaryKey())
{
continue;
}
var shouldSaveProperty = property.IsShadowProperty() ||
(IsAuditedPropertyInfo(property.PropertyInfo) ?? !auditedPropertiesOnly);
if (shouldSaveProperty)
{
var propertyEntry = entityEntry.Property(property.Name);
propertyChanges.Add(
CreateEntityPropertyChange(
propertyEntry.GetOriginalValue(),
propertyEntry.GetNewValue(),
property
)
);
}
}
return propertyChanges;
}
/// <summary>
/// Updates change time, entity id, Adds foreign keys, Removes/Updates property changes after SaveChanges is called.
/// </summary>
private void UpdateChangeSet(EntityChangeSet changeSet)
{
var entityChangesToRemove = new List<EntityChange>();
foreach (var entityChange in changeSet.EntityChanges)
{
var entityEntry = entityChange.EntityEntry.As<EntityEntry>();
var isAuditedEntity = IsTypeOfAuditedEntity(entityEntry.Entity.GetType()) == true;
/* Update change time */
entityChange.ChangeTime = GetChangeTime(entityChange.ChangeType, entityEntry.Entity);
/* Update entity id */
entityChange.EntityId = GetEntityId(entityEntry);
/* Update property changes */
var trackedPropertyNames = entityChange.PropertyChanges.Select(pc => pc.PropertyName);
var trackedNavigationProperties = entityEntry.Navigations
.Where(np => trackedPropertyNames.Contains(np.Metadata.Name))
.ToList();
var additionalForeignKeys = trackedNavigationProperties
.Where(np => !trackedPropertyNames.Contains(np.Metadata.Name))
.Select(np => np.Metadata.ForeignKey)
.Distinct()
.ToList();
/* Add additional foreign keys from navigation properties */
foreach (var foreignKey in additionalForeignKeys)
{
foreach (var property in foreignKey.Properties)
{
var shouldSaveProperty = property.IsShadowProperty() ?
null :
IsAuditedPropertyInfo(property.PropertyInfo);
if (shouldSaveProperty.HasValue && !shouldSaveProperty.Value)
{
continue;
}
var propertyEntry = entityEntry.Property(property.Name);
// TODO: fix new value comparison before truncation
var newValue = propertyEntry.GetNewValue()?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength);
var oldValue = propertyEntry.GetOriginalValue()?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength);
// Add foreign key
entityChange.PropertyChanges.Add(CreateEntityPropertyChange(oldValue, newValue, property));
}
}
/* Update/Remove property changes */
var propertyChangesToRemove = new List<EntityPropertyChange>();
foreach (var propertyChange in entityChange.PropertyChanges)
{
var propertyEntry = entityEntry.Property(propertyChange.PropertyName);
var isAuditedProperty = !propertyEntry.Metadata.IsShadowProperty() &&
IsAuditedPropertyInfo(propertyEntry.Metadata.PropertyInfo) == true;
// TODO: fix new value comparison before truncation
propertyChange.NewValue = propertyEntry.GetNewValue()?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength);
if (!isAuditedProperty && propertyChange.OriginalValue == propertyChange.NewValue)
{
// No change
propertyChangesToRemove.Add(propertyChange);
}
}
foreach (var propertyChange in propertyChangesToRemove)
{
entityChange.PropertyChanges.Remove(propertyChange);
}
if (!isAuditedEntity && entityChange.PropertyChanges.Count == 0)
{
entityChangesToRemove.Add(entityChange);
}
}
foreach (var entityChange in entityChangesToRemove)
{
changeSet.EntityChanges.Remove(entityChange);
}
}
private EntityPropertyChange CreateEntityPropertyChange(object oldValue, object newValue, IProperty property)
{
return new EntityPropertyChange()
{
OriginalValue = oldValue?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength),
NewValue = newValue?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength),
PropertyName = property.Name.TruncateWithPostfix(EntityPropertyChange.MaxPropertyNameLength),
PropertyTypeFullName = property.ClrType.FullName.TruncateWithPostfix(EntityPropertyChange.MaxPropertyTypeFullNameLength),
TenantId = AbpSession.TenantId
};
}
}
}
| |
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 16:50
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Lexer class that parses MIB files into symbol list.
/// </summary>
public sealed class Lexer
{
private readonly SymbolList _symbols = new SymbolList();
public Lexer(string file)
: this(file, new StreamReader(file))
{
}
public Lexer(string file, TextReader stream)
{
this.Parse(file, stream);
}
public ISymbolEnumerator GetEnumerator()
{
return _symbols.GetSymbolEnumerator();
}
#region Parsing of MIB File
private class ParseParams
{
public string File;
public StringBuilder Temp = new StringBuilder();
public bool StringSection = false;
public bool AssignSection = false;
public bool AssignAhead = false;
public bool DotSection = false;
}
/// <summary>
/// Parses MIB file to symbol list.
/// </summary>
/// <param name="file">File</param>
/// <param name="stream">File stream</param>
private void Parse(string file, TextReader stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
ParseParams pp = new ParseParams();
pp.File = file;
string line;
int row = 0;
while ((line = stream.ReadLine()) != null)
{
if (!pp.StringSection && line.TrimStart().StartsWith("--", StringComparison.Ordinal))
{
row++;
continue; // commented line
}
ParseLine(pp, line, row);
row++;
}
}
private void ParseLine(ParseParams pp, string line, int row)
{
line = line + "\n";
int count = line.Length;
for (int i = 0; i < count; i++)
{
char current = line[i];
bool moveNext = Parse(pp, current, row, i);
if (moveNext)
{
break;
}
}
}
private bool Parse(ParseParams pp, char current, int row, int column)
{
switch (current)
{
case '\n':
case '{':
case '}':
case '(':
case ')':
case '[':
case ']':
case ';':
case ',':
case '|':
if (!pp.StringSection)
{
bool moveNext = ParseLastSymbol(pp, row, column);
if (moveNext)
{
_symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
return true;
}
_symbols.Add(CreateSpecialSymbol(pp.File, current, row, column));
return false;
}
break;
case '"':
pp.StringSection = !pp.StringSection;
break;
case '\r':
return false;
default:
if ((int)current == 0x1A)
{
// IMPORTANT: ignore invisible characters such as SUB.
return false;
}
if (Char.IsWhiteSpace(current) && !pp.AssignSection && !pp.StringSection)
{
bool moveNext = ParseLastSymbol(pp, row, column);
if (moveNext)
{
_symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
return true;
}
return false;
}
if (pp.AssignAhead)
{
pp.AssignAhead = false;
ParseLastSymbol(pp, row, column);
break;
}
if (pp.DotSection && current != '.')
{
ParseLastSymbol(pp, row, column);
pp.DotSection = false;
}
if (current == '.' && !pp.StringSection)
{
if (!pp.DotSection)
{
ParseLastSymbol(pp, row, column);
pp.DotSection = true;
}
}
if (current == ':' && !pp.StringSection)
{
if (!pp.AssignSection)
{
ParseLastSymbol(pp, row, column);
}
pp.AssignSection = true;
}
if (current == '=' && !pp.StringSection)
{
pp.AssignSection = false;
pp.AssignAhead = true;
}
break;
}
pp.Temp.Append(current);
return false;
}
private bool ParseLastSymbol(ParseParams pp, int row, int column)
{
if (pp.Temp.Length > 0)
{
Symbol s = new Symbol(pp.File, pp.Temp.ToString(), row, column);
pp.Temp.Length = 0;
if (s.ToString().StartsWith(Symbol.Comment.ToString()))
{
// ignore the rest symbols on this line because they are in comment.
return true;
}
_symbols.Add(s);
}
return false;
}
private static Symbol CreateSpecialSymbol(string file, char value, int row, int column)
{
string str;
switch (value)
{
case '\n':
str = Environment.NewLine;
break;
case '{':
str = "{";
break;
case '}':
str = "}";
break;
case '(':
str = "(";
break;
case ')':
str = ")";
break;
case '[':
str = "[";
break;
case ']':
str = "]";
break;
case ';':
str = ";";
break;
case ',':
str = ",";
break;
case '|':
str = "|";
break;
default:
throw new ArgumentException("value is not a special character");
}
return new Symbol(file, str, row, column);
}
#endregion
#region Static Parse Helper
public static ITypeAssignment ParseBasicTypeDef(IModule module, string name, ISymbolEnumerator symbols, bool isMacroSyntax = false)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Bits)
{
return new BitsType(module, name, symbols);
}
if (IntegerType.IsIntegerType(current))
{
return new IntegerType(module, name, current, symbols);
}
if (UnsignedType.IsUnsignedType(current))
{
return new UnsignedType(module, name, current, symbols);
}
if (current == Symbol.Opaque)
{
return new OpaqueType(module, name, symbols);
}
if (current == Symbol.IpAddress)
{
return new IpAddressType(module, name, symbols);
}
if (current == Symbol.TextualConvention)
{
return new TextualConvention(module, name, symbols);
}
if (current == Symbol.Octet)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.String)
{
return new OctetStringType(module, name, symbols);
}
symbols.PutBack(next);
}
if (current == Symbol.Object)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.Identifier)
{
return new ObjectIdentifierType(module, name, symbols);
}
symbols.PutBack(next);
}
if (current == Symbol.Sequence)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.Of)
{
return new SequenceOf(module, name, symbols);
}
else
{
symbols.PutBack(next);
return new Sequence(module, name, symbols);
}
}
if (current == Symbol.Choice)
{
return new Choice(module, name, symbols);
}
return new TypeAssignment(module, name, current, symbols, isMacroSyntax);
}
public static void ParseOidValue(ISymbolEnumerator symbols, out string parent, out uint value)
{
parent = null;
value = 0;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
Symbol previous = null;
StringBuilder longParent = new StringBuilder();
current = symbols.NextNonEOLSymbol();
longParent.Append(current);
while ((current = symbols.NextNonEOLSymbol()) != null)
{
bool succeeded;
if (current == Symbol.OpenParentheses)
{
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
longParent.Append(current);
continue;
}
if (current == Symbol.CloseBracket)
{
parent = longParent.ToString();
return;
}
succeeded = UInt32.TryParse(current.ToString(), out value);
if (succeeded)
{
// numerical way
while ((current = symbols.NextNonEOLSymbol()) != Symbol.CloseBracket)
{
longParent.Append(".").Append(value);
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
}
current.Expect(Symbol.CloseBracket);
parent = longParent.ToString();
return;
}
longParent.Append(".");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenParentheses);
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
longParent.Append(current);
previous = current;
}
throw MibException.Create("end of file reached", previous);
}
public static ValueRanges DecodeRanges(ISymbolEnumerator symbols)
{
ValueRanges result = new ValueRanges();
Symbol startSymbol = symbols.NextNonEOLSymbol();
Symbol current = startSymbol;
current.Expect(Symbol.OpenParentheses);
while (current != Symbol.CloseParentheses)
{
Symbol value1Symbol = symbols.NextNonEOLSymbol();
if ((value1Symbol == Symbol.Size) && !result.IsSizeDeclaration)
{
result.IsSizeDeclaration = true;
symbols.NextNonEOLSymbol().Expect(Symbol.OpenParentheses);
continue;
}
// check for valid number
Int64? value1 = DecodeNumber(value1Symbol);
if (!value1.HasValue)
{
value1Symbol.Assert(false, "Invalid range declaration!");
}
// process next symbol
ValueRange range;
current = symbols.NextNonEOLSymbol();
if (current == Symbol.DoubleDot)
{
// its a continous range
Symbol value2Symbol = symbols.NextNonEOLSymbol();
Int64? value2 = DecodeNumber(value2Symbol);
value2Symbol.Assert(value2.HasValue && (value2.Value >= value1.Value), "Invalid range declaration!");
if (value2.Value == value1.Value)
{
range = new ValueRange(value1.Value, null);
}
else
{
range = new ValueRange(value1.Value, value2.Value);
}
current = symbols.NextNonEOLSymbol();
}
else
{
// its a single number
range = new ValueRange(value1.Value, null);
}
// validate range
if (result.IsSizeDeclaration)
{
value1Symbol.Assert(range.Start >= 0, "Invalid range declaration! Size must be greater than 0");
}
result.Add(range);
// check next symbol
current.Expect(Symbol.Pipe, Symbol.CloseParentheses);
}
if (result.IsSizeDeclaration)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
}
// validate ranges in between
for (int i=0; i<result.Count; i++)
{
for (int k=i+1; k<result.Count; k++)
{
startSymbol.Assert(!result[i].IntersectsWith(result[k]), "Invalid range declaration! Overlapping of ranges!");
}
}
return result;
}
public static Int64? DecodeNumber(Symbol number)
{
Int64 result;
string numString = (number != null) ? number.ToString() : null;
if (!String.IsNullOrEmpty(numString))
{
if (numString.StartsWith("'") && (numString.Length > 3))
{
// search second apostrophe
int end = numString.IndexOf('\'', 1);
if (end == (numString.Length - 2))
{
try
{
switch (numString[numString.Length - 1])
{
case 'b':
case 'B':
result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 2);
return result;
case 'h':
case 'H':
result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 16);
return result;
}
}
catch
{
}
}
}
else if (Int64.TryParse(numString, out result))
{
return result;
}
}
return null;
}
public static ValueMap DecodeEnumerations(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
ValueMap map = new ValueMap();
do
{
current = symbols.NextNonEOLSymbol();
string identifier = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenParentheses);
current = symbols.NextNonEOLSymbol();
Int64 enumValue;
if (Int64.TryParse(current.ToString(), out enumValue))
{
try
{
// Have to include the number as it seems repeated identifiers are allowed ??
map.Add(enumValue, String.Format("{0}({1})", identifier, enumValue));
}
catch (ArgumentException ex)
{
current.Assert(false, ex.Message);
}
}
else
{
// Need to get "DefinedValue".
}
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
current = symbols.NextNonEOLSymbol();
} while (current == Symbol.Comma);
current.Expect(Symbol.CloseBracket);
return map;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Need to use "extern alias", because both the writer and reader define types with same names.
extern alias writer;
using System;
using System.IO;
using System.Linq;
using Xunit;
using Reader = Internal.Metadata.NativeFormat;
using Writer = writer.Internal.Metadata.NativeFormat.Writer;
using TypeAttributes = System.Reflection.TypeAttributes;
using MethodAttributes = System.Reflection.MethodAttributes;
using CallingConventions = System.Reflection.CallingConventions;
namespace System.Private.Reflection.Metadata.Tests
{
/// <summary>
/// Tests for metadata roundtripping. We emit a metadata blob, and read it back
/// to check if it has expected values.
/// </summary>
public class RoundTripTests
{
/// <summary>
/// Builds a graph of simple metadata test data.
/// </summary>
private static Writer.ScopeDefinition BuildSimpleTestData()
{
// Scope for System.Runtime, 4.0.0.0
var systemRuntimeScope = new Writer.ScopeDefinition
{
Name = (Writer.ConstantStringValue)"System.Runtime",
MajorVersion = 4,
};
// Root namespace (".")
var rootNamespaceDefinition = new Writer.NamespaceDefinition
{
ParentScopeOrNamespace = systemRuntimeScope,
};
systemRuntimeScope.RootNamespaceDefinition = rootNamespaceDefinition;
// The <Module> type
var moduleTypeDefinition = new Writer.TypeDefinition
{
Flags = TypeAttributes.Abstract | TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"<Module>",
NamespaceDefinition = rootNamespaceDefinition,
};
rootNamespaceDefinition.TypeDefinitions.Add(moduleTypeDefinition);
// System namespace
var systemNamespaceDefinition = new Writer.NamespaceDefinition
{
Name = (Writer.ConstantStringValue)"System",
ParentScopeOrNamespace = rootNamespaceDefinition,
};
rootNamespaceDefinition.NamespaceDefinitions.Add(systemNamespaceDefinition);
// System.Object type
var objectType = new Writer.TypeDefinition
{
Flags = TypeAttributes.Public | TypeAttributes.SequentialLayout,
Name = (Writer.ConstantStringValue)"Object",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(objectType);
// System.ValueType type
var valueTypeType = new Writer.TypeDefinition
{
BaseType = objectType,
Flags = TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"ValueType",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(valueTypeType);
// System.Void type
var voidType = new Writer.TypeDefinition
{
BaseType = valueTypeType,
Flags = TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"Void",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(voidType);
// System.String type
var stringType = new Writer.TypeDefinition
{
BaseType = objectType,
Flags = TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"String",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(stringType);
// System.Object..ctor() method
var objectCtorMethod = new Writer.Method
{
Flags = MethodAttributes.Public
| MethodAttributes.RTSpecialName
| MethodAttributes.SpecialName,
Name = (Writer.ConstantStringValue)".ctor",
Signature = new Writer.MethodSignature
{
CallingConvention = CallingConventions.HasThis,
ReturnType = voidType,
},
};
objectType.Methods.Add(objectCtorMethod);
// System.String..ctor() method
var stringCtorMethod = new Writer.Method
{
Flags = MethodAttributes.Public
| MethodAttributes.RTSpecialName
| MethodAttributes.SpecialName,
Name = (Writer.ConstantStringValue)".ctor",
Signature = new Writer.MethodSignature
{
CallingConvention = CallingConventions.HasThis,
ReturnType = voidType,
},
};
stringType.Methods.Add(stringCtorMethod);
return systemRuntimeScope;
}
[Fact]
public static unsafe void TestSimpleRoundTripping()
{
var wr = new Writer.MetadataWriter();
wr.ScopeDefinitions.Add(BuildSimpleTestData());
var ms = new MemoryStream();
wr.Write(ms);
fixed (byte* pBuffer = ms.ToArray())
{
var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);
// Validate the System.Runtime scope
Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
Assert.Equal(4, systemRuntimeScope.MajorVersion);
Assert.Equal("System.Runtime", systemRuntimeScope.Name.GetConstantStringValue(rd).Value);
// Validate the root namespace and <Module> type
Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
Assert.Equal(1, rootNamespace.TypeDefinitions.Count);
Reader.TypeDefinition moduleType = rootNamespace.TypeDefinitions.Single().GetTypeDefinition(rd);
Assert.Equal("<Module>", moduleType.Name.GetConstantStringValue(rd).Value);
Assert.Equal(1, rootNamespace.NamespaceDefinitions.Count);
// Validate the System namespace
Reader.NamespaceDefinition systemNamespace = rootNamespace.NamespaceDefinitions.Single().GetNamespaceDefinition(rd);
Assert.Equal(4, systemNamespace.TypeDefinitions.Count);
foreach (var typeHandle in systemNamespace.TypeDefinitions)
{
Reader.TypeDefinition type = typeHandle.GetTypeDefinition(rd);
string typeName = type.Name.GetConstantStringValue(rd).Value;
string baseTypeName = null;
if (!type.BaseType.IsNull(rd))
{
baseTypeName = type.BaseType.ToTypeDefinitionHandle(rd).GetTypeDefinition(rd).Name.GetConstantStringValue(rd).Value;
}
switch (typeName)
{
case "Object":
Assert.Null(baseTypeName);
Assert.Equal(1, type.Methods.Count);
break;
case "Void":
Assert.Equal("ValueType", baseTypeName);
Assert.Equal(0, type.Methods.Count);
break;
case "String":
Assert.Equal("Object", baseTypeName);
Assert.Equal(1, type.Methods.Count);
break;
case "ValueType":
Assert.Equal("Object", baseTypeName);
Assert.Equal(0, type.Methods.Count);
break;
default:
throw new NotImplementedException();
}
}
}
}
[Fact]
public static unsafe void TestCommonTailOptimization()
{
var wr = new Writer.MetadataWriter();
wr.ScopeDefinitions.Add(BuildSimpleTestData());
var ms = new MemoryStream();
wr.Write(ms);
fixed (byte* pBuffer = ms.ToArray())
{
var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);
Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
Reader.NamespaceDefinition systemNamespace =
rootNamespace.NamespaceDefinitions.AsEnumerable().Single(
ns => ns.GetNamespaceDefinition(rd).Name.StringEquals("System", rd)
).GetNamespaceDefinition(rd);
// This validates the common tail optimization.
// Since both System.Object and System.String define a default constructor and the
// records are structurally equivalent, there should only be one metadata record
// representing a default .ctor in the blob.
Reader.TypeDefinition objectType = systemNamespace.TypeDefinitions.AsEnumerable().Single(
t => t.GetTypeDefinition(rd).Name.StringEquals("Object", rd)
).GetTypeDefinition(rd);
Reader.TypeDefinition stringType = systemNamespace.TypeDefinitions.AsEnumerable().Single(
t => t.GetTypeDefinition(rd).Name.StringEquals("String", rd)
).GetTypeDefinition(rd);
Reader.MethodHandle objectCtor = objectType.Methods.Single();
Reader.MethodHandle stringCtor = stringType.Methods.Single();
Assert.True(objectCtor.Equals(stringCtor));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Orchard.ResourceManagement
{
public class ResourceDefinition
{
private static readonly Dictionary<string, string> _resourceTypeTagNames = new Dictionary<string, string> {
{ "script", "script" },
{ "stylesheet", "link" }
};
private static readonly Dictionary<string, string> _filePathAttributes = new Dictionary<string, string> {
{ "script", "src" },
{ "link", "href" }
};
private static readonly Dictionary<string, Dictionary<string, string>> _resourceAttributes = new Dictionary<string, Dictionary<string, string>> {
{ "script", new Dictionary<string, string> { {"type", "text/javascript"} } },
{ "stylesheet", new Dictionary<string, string> { {"type", "text/css"}, {"rel", "stylesheet"} } }
};
private static readonly Dictionary<string, TagRenderMode> _fileTagRenderModes = new Dictionary<string, TagRenderMode> {
{ "script", TagRenderMode.Normal },
{ "link", TagRenderMode.SelfClosing }
};
private static readonly Dictionary<string, string> _resourceTypeDirectories = new Dictionary<string, string> {
{"script", "scripts/"},
{"stylesheet", "styles/"}
};
private string _basePath;
private readonly Dictionary<RequireSettings, string> _urlResolveCache = new Dictionary<RequireSettings, string>();
public ResourceDefinition(ResourceManifest manifest, string type, string name)
{
Manifest = manifest;
Type = type;
Name = name;
TagName = _resourceTypeTagNames.ContainsKey(Type) ? _resourceTypeTagNames[Type] : "meta";
FilePathAttributeName = _filePathAttributes.ContainsKey(TagName) ? _filePathAttributes[TagName] : null;
TagRenderMode = _fileTagRenderModes.ContainsKey(TagName) ? _fileTagRenderModes[TagName] : TagRenderMode.Normal;
}
internal static string GetBasePathFromViewPath(string resourceType, string viewPath)
{
if (String.IsNullOrEmpty(viewPath))
{
return null;
}
string basePath = null;
var viewsPartIndex = viewPath.IndexOf("/Views", StringComparison.OrdinalIgnoreCase);
if (viewsPartIndex >= 0)
{
basePath = viewPath.Substring(0, viewsPartIndex + 1) + GetResourcePath(resourceType);
}
return basePath;
}
internal static string GetResourcePath(string resourceType)
{
string path;
_resourceTypeDirectories.TryGetValue(resourceType, out path);
return path ?? "";
}
private static string Coalesce(params string[] strings)
{
foreach (var str in strings)
{
if (!String.IsNullOrEmpty(str))
{
return str;
}
}
return null;
}
public ResourceManifest Manifest { get; private set; }
public string TagName { get; private set; }
public TagRenderMode TagRenderMode { get; private set; }
public string Name { get; private set; }
public string Type { get; private set; }
public string Version { get; private set; }
public string BasePath
{
get
{
if (!String.IsNullOrEmpty(_basePath))
{
return _basePath;
}
var basePath = Manifest.BasePath;
if (!String.IsNullOrEmpty(basePath))
{
basePath += GetResourcePath(Type);
}
return basePath ?? "";
}
}
public string Url { get; private set; }
public string UrlDebug { get; private set; }
public string UrlCdn { get; private set; }
public string UrlCdnDebug { get; private set; }
public string CdnDebugIntegrity { get; private set; }
public string CdnIntegrity { get; private set; }
public string[] Cultures { get; private set; }
public bool CdnSupportsSsl { get; private set; }
public IEnumerable<string> Dependencies { get; private set; }
public string FilePathAttributeName { get; private set; }
public AttributeDictionary Attributes { get; private set; }
public ResourceDefinition SetAttribute(string name, string value)
{
if (Attributes == null)
{
Attributes = new AttributeDictionary();
}
Attributes[name] = value;
return this;
}
public ResourceDefinition SetBasePath(string virtualPath)
{
_basePath = virtualPath;
return this;
}
public ResourceDefinition SetUrl(string url)
{
return SetUrl(url, null);
}
public ResourceDefinition SetUrl(string url, string urlDebug)
{
if (String.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
Url = url;
if (urlDebug != null)
{
UrlDebug = urlDebug;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl)
{
return SetCdn(cdnUrl, null, null);
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug)
{
return SetCdn(cdnUrl, cdnUrlDebug, null);
}
public ResourceDefinition SetCdnIntegrity(string cdnIntegrity)
{
return SetCdnIntegrity(cdnIntegrity, null);
}
public ResourceDefinition SetCdnIntegrity(string cdnIntegrity, string cdnDebugIntegrity)
{
if (String.IsNullOrEmpty(cdnIntegrity))
{
throw new ArgumentNullException("cdnUrl");
}
CdnIntegrity = cdnIntegrity;
if (cdnDebugIntegrity != null)
{
CdnDebugIntegrity = cdnDebugIntegrity;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug, bool? cdnSupportsSsl)
{
if (String.IsNullOrEmpty(cdnUrl))
{
throw new ArgumentNullException("cdnUrl");
}
UrlCdn = cdnUrl;
if (cdnUrlDebug != null)
{
UrlCdnDebug = cdnUrlDebug;
}
if (cdnSupportsSsl.HasValue)
{
CdnSupportsSsl = cdnSupportsSsl.Value;
}
return this;
}
/// <summary>
/// Sets the version of the resource.
/// </summary>
/// <param name="version">The version to set, in the form of <code>major.minor[.build[.revision]]</code></param>
public ResourceDefinition SetVersion(string version)
{
Version = version;
return this;
}
public ResourceDefinition SetCultures(params string[] cultures)
{
Cultures = cultures;
return this;
}
public ResourceDefinition SetDependencies(params string[] dependencies)
{
Dependencies = dependencies;
return this;
}
public TagBuilder GetTagBuilder(RequireSettings settings, string applicationPath)
{
string url;
if (!_urlResolveCache.TryGetValue(settings, out url))
{
// Url priority:
if (settings.DebugMode)
{
url = settings.CdnMode
? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url)
: Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn);
}
else
{
url = settings.CdnMode
? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug)
: Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug);
}
if (String.IsNullOrEmpty(url))
{
url = null;
}
if (!String.IsNullOrEmpty(settings.Culture))
{
string nearestCulture = FindNearestCulture(settings.Culture);
if (!String.IsNullOrEmpty(nearestCulture))
{
url = Path.ChangeExtension(url, nearestCulture + Path.GetExtension(url));
}
}
if (url.StartsWith("~/", StringComparison.Ordinal))
{
// For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
url = url.Substring(1);
}
_urlResolveCache[settings] = url;
}
var tagBuilder = new TagBuilder(TagName);
if (!String.IsNullOrEmpty(CdnIntegrity) && url != null && url == UrlCdn)
{
tagBuilder.Attributes["integrity"] = CdnIntegrity;
tagBuilder.Attributes["crossorigin"] = "anonymous";
}
else if (!String.IsNullOrEmpty(CdnDebugIntegrity) && url != null && url == UrlCdnDebug)
{
tagBuilder.Attributes["integrity"] = CdnDebugIntegrity;
tagBuilder.Attributes["crossorigin"] = "anonymous";
}
if (_resourceAttributes.ContainsKey(Type))
{
tagBuilder.MergeAttributes(_resourceAttributes[Type]);
}
if (Attributes != null)
{
tagBuilder.MergeAttributes(Attributes);
}
if (settings.Attributes != null)
{
tagBuilder.MergeAttributes(settings.Attributes);
}
if (!String.IsNullOrEmpty(FilePathAttributeName))
{
if (!String.IsNullOrEmpty(url))
{
tagBuilder.MergeAttribute(FilePathAttributeName, url, true);
}
}
return tagBuilder;
}
public string FindNearestCulture(string culture)
{
// go for an exact match
if (Cultures == null)
{
return null;
}
int selectedIndex = Array.IndexOf(Cultures, culture);
if (selectedIndex != -1)
{
return Cultures[selectedIndex];
}
// try parent culture if any
var cultureInfo = new CultureInfo(culture);
if (cultureInfo.Parent.Name != culture)
{
var selectedCulture = FindNearestCulture(cultureInfo.Parent.Name);
if (selectedCulture != null)
{
return selectedCulture;
}
}
return null;
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
{
return false;
}
var that = (ResourceDefinition)obj;
return string.Equals(that.Name, Name, StringComparison.Ordinal) &&
string.Equals(that.Type, Type, StringComparison.Ordinal) &&
string.Equals(that.Version, Version, StringComparison.Ordinal);
}
public override int GetHashCode()
{
return (Name ?? "").GetHashCode() ^ (Type ?? "").GetHashCode();
}
}
}
| |
using System;
namespace NUnit.Framework
{
#region StringAsserter
/// <summary>
/// Abstract class used as a base for asserters that compare
/// expected and an actual string values in some way or another.
/// </summary>
public abstract class StringAsserter : AbstractAsserter
{
/// <summary>
/// The expected value, used as the basis for comparison.
/// </summary>
protected string expected;
/// <summary>
/// The actual value to be compared.
/// </summary>
protected string actual;
/// <summary>
/// Constructs a StringAsserter for two strings
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="message">The message to issue on failure</param>
/// <param name="args">Arguments to apply in formatting the message</param>
public StringAsserter( string expected, string actual, string message, params object[] args )
: base( message, args )
{
this.expected = expected;
this.actual = actual;
}
/// <summary>
/// Message related to a failure. If no failure has
/// occured, the result is unspecified.
/// </summary>
public override string Message
{
get
{
FailureMessage.AddExpectedLine( Expectation );
FailureMessage.DisplayActualValue( actual );
return FailureMessage.ToString();
}
}
/// <summary>
/// String value that represents what the asserter expected
/// to find. Defaults to the expected value itself.
/// </summary>
protected virtual string Expectation
{
get { return string.Format( "<\"{0}\">", expected ); }
}
}
#endregion
#region ContainsAsserter
/// <summary>
/// Summary description for ContainsAsserter.
/// </summary>
public class ContainsAsserter : StringAsserter
{
/// <summary>
/// Constructs a ContainsAsserter for two strings
/// </summary>
/// <param name="expected">The expected substring</param>
/// <param name="actual">The actual string to be examined</param>
/// <param name="message">The message to issue on failure</param>
/// <param name="args">Arguments to apply in formatting the message</param>
public ContainsAsserter( string expected, string actual, string message, params object[] args )
: base( expected, actual, message, args ) { }
/// <summary>
/// Test the assertion.
/// </summary>
/// <returns>True if the test succeeds</returns>
public override bool Test()
{
return actual.IndexOf( expected ) >= 0;
}
/// <summary>
/// String value that represents what the asserter expected
/// </summary>
protected override string Expectation
{
get { return string.Format( "String containing \"{0}\"", expected ); }
}
}
#endregion
#region StartsWithAsserter
/// <summary>
/// Summary description for StartsWithAsserter.
/// </summary>
public class StartsWithAsserter : StringAsserter
{
/// <summary>
/// Constructs a StartsWithAsserter for two strings
/// </summary>
/// <param name="expected">The expected substring</param>
/// <param name="actual">The actual string to be examined</param>
/// <param name="message">The message to issue on failure</param>
/// <param name="args">Arguments to apply in formatting the message</param>
public StartsWithAsserter( string expected, string actual, string message, params object[] args )
: base( expected, actual, message, args ) { }
/// <summary>
/// Test the assertion.
/// </summary>
/// <returns>True if the test succeeds</returns>
public override bool Test()
{
return actual.StartsWith( expected );
}
/// <summary>
/// String value that represents what the asserter expected
/// </summary>
protected override string Expectation
{
get { return string.Format( "String starting with \"{0}\"", expected ); }
}
}
#endregion
#region EndsWithAsserter
/// <summary>
/// Summary description for EndsWithAsserter.
/// </summary>
public class EndsWithAsserter : StringAsserter
{
/// <summary>
/// Constructs a EndsWithAsserter for two strings
/// </summary>
/// <param name="expected">The expected substring</param>
/// <param name="actual">The actual string to be examined</param>
/// <param name="message">The message to issue on failure</param>
/// <param name="args">Arguments to apply in formatting the message</param>
public EndsWithAsserter( string expected, string actual, string message, params object[] args )
: base( expected, actual, message, args ) { }
/// <summary>
/// Test the assertion.
/// </summary>
/// <returns>True if the test succeeds</returns>
public override bool Test()
{
return actual.EndsWith( expected );
}
/// <summary>
/// String value that represents what the asserter expected
/// </summary>
protected override string Expectation
{
get { return string.Format( "String ending with \"{0}\"", expected ); }
}
}
#endregion
#region EqualIgnoringCaseAsserter
/// <summary>
/// Asserter that implements AreEqualIgnoringCase
/// </summary>
public class EqualIgnoringCaseAsserter : StringAsserter
{
/// <summary>
/// Constructs an EqualIgnoringCaseAsserter for two strings
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
/// <param name="message">The message to issue on failure</param>
/// <param name="args">Arguments to apply in formatting the message</param>
public EqualIgnoringCaseAsserter( string expected, string actual, string message, params object[] args )
: base( expected, actual, message, args ) { }
/// <summary>
/// Test the assertion.
/// </summary>
/// <returns>True if the test succeeds</returns>
public override bool Test()
{
return string.Compare( expected, actual, true ) == 0;
}
/// <summary>
/// String value that represents what the asserter expected
/// </summary>
public override string Message
{
get
{
FailureMessage.DisplayDifferences( expected, actual, true );
return FailureMessage.ToString();
}
}
}
#endregion
}
| |
// 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.Bot.Connector
{
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;
/// <summary>
/// Attachments operations.
/// </summary>
public partial class Attachments : IServiceOperations<ConnectorClient>, IAttachments
{
/// <summary>
/// Initializes a new instance of the Attachments class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Attachments(ConnectorClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ConnectorClient
/// </summary>
public ConnectorClient Client { get; private set; }
/// <summary>
/// GetAttachmentInfo
/// </summary>
/// Get AttachmentInfo structure describing the attachment views
/// <param name='attachmentId'>
/// attachment id
/// </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<HttpOperationResponse<object>> GetAttachmentInfoWithHttpMessagesAsync(string attachmentId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (attachmentId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("attachmentId", attachmentId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetAttachmentInfo", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/attachments/{attachmentId}").ToString();
_url = _url.Replace("{attachmentId}", Uri.EscapeDataString(attachmentId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new 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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 429 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(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 (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<AttachmentInfo>(_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 == 400)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 401)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 403)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 404)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 429)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 500)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 503)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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>
/// GetAttachment
/// </summary>
/// Get the named view as binary content
/// <param name='attachmentId'>
/// attachment id
/// </param>
/// <param name='viewId'>
/// View id from attachmentInfo
/// </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<HttpOperationResponse<object>> GetAttachmentWithHttpMessagesAsync(string attachmentId, string viewId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (attachmentId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId");
}
if (viewId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "viewId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("attachmentId", attachmentId);
tracingParameters.Add("viewId", viewId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetAttachment", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/attachments/{attachmentId}/views/{viewId}").ToString();
_url = _url.Replace("{attachmentId}", Uri.EscapeDataString(attachmentId));
_url = _url.Replace("{viewId}", Uri.EscapeDataString(viewId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new 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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 301 && (int)_statusCode != 302 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 429 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(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 (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_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 == 400)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 401)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 403)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 404)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 429)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 500)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 == 503)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ErrorResponse>(_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;
}
}
}
| |
// <copyright file="Libraries.Interfaces.Generated.cs" company="MIT License">
// Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
/// <summary>
/// This file is auto-generated by a build task. It shouldn't be edited by hand.
/// </summary>
namespace SmallBasic.Compiler.Runtime
{
using System;
using System.Threading.Tasks;
public interface IArrayLibrary
{
bool ContainsIndex(ArrayValue array, string index);
bool ContainsValue(ArrayValue array, string value);
ArrayValue GetAllIndices(ArrayValue array);
decimal GetItemCount(ArrayValue array);
BaseValue GetValue(string arrayName, string index);
bool IsArray(BaseValue array);
void RemoveValue(string arrayName, string index);
void SetValue(string arrayName, string index, BaseValue value);
}
public interface IClockLibrary
{
string Get_Date();
decimal Get_Day();
decimal Get_ElapsedMilliseconds();
decimal Get_Hour();
decimal Get_Millisecond();
decimal Get_Minute();
decimal Get_Month();
decimal Get_Second();
string Get_Time();
string Get_WeekDay();
decimal Get_Year();
}
public interface IControlsLibrary
{
event Action ButtonClicked;
event Action TextTyped;
string Get_LastClickedButton();
string Get_LastTypedTextBox();
string AddButton(string caption, decimal left, decimal top);
string AddMultiLineTextBox(decimal left, decimal top);
string AddTextBox(decimal left, decimal top);
string GetButtonCaption(string buttonName);
string GetTextBoxText(string textBoxName);
void HideControl(string controlName);
void Move(string control, decimal x, decimal y);
void Remove(string controlName);
void SetButtonCaption(string buttonName, string caption);
void SetSize(string control, decimal width, decimal height);
void SetTextBoxText(string textBoxName, string text);
void ShowControl(string controlName);
}
public interface IDesktopLibrary
{
}
public interface IDictionaryLibrary
{
}
public interface IFileLibrary
{
string Get_LastError();
void Set_LastError(string value);
Task<string> AppendContents(string filePath, string contents);
Task<string> CopyFile(string sourceFilePath, string destinationFilePath);
Task<string> CreateDirectory(string directoryPath);
Task<string> DeleteDirectory(string directoryPath);
Task<string> DeleteFile(string filePath);
Task<BaseValue> GetDirectories(string directoryPath);
Task<BaseValue> GetFiles(string directoryPath);
Task<BaseValue> GetTemporaryFilePath();
Task<string> InsertLine(string filePath, decimal lineNumber, string contents);
Task<BaseValue> ReadContents(string filePath);
Task<BaseValue> ReadLine(string filePath, decimal lineNumber);
Task<string> WriteContents(string filePath, string contents);
Task<string> WriteLine(string filePath, decimal lineNumber, string contents);
}
public interface IFlickrLibrary
{
}
public interface IGraphicsWindowLibrary
{
event Action KeyDown;
event Action KeyUp;
event Action MouseDown;
event Action MouseMove;
event Action MouseUp;
event Action TextInput;
string Get_BackgroundColor();
void Set_BackgroundColor(string value);
string Get_BrushColor();
void Set_BrushColor(string value);
bool Get_FontBold();
void Set_FontBold(bool value);
bool Get_FontItalic();
void Set_FontItalic(bool value);
string Get_FontName();
void Set_FontName(string value);
decimal Get_FontSize();
void Set_FontSize(decimal value);
Task<decimal> Get_Height();
Task Set_Height(decimal value);
string Get_LastKey();
string Get_LastText();
decimal Get_MouseX();
decimal Get_MouseY();
string Get_PenColor();
void Set_PenColor(string value);
decimal Get_PenWidth();
void Set_PenWidth(decimal value);
string Get_Title();
void Set_Title(string value);
Task<decimal> Get_Width();
Task Set_Width(decimal value);
void Clear();
void DrawBoundText(decimal x, decimal y, decimal width, string text);
void DrawEllipse(decimal x, decimal y, decimal width, decimal height);
void DrawImage(string imageName, decimal x, decimal y);
void DrawLine(decimal x1, decimal y1, decimal x2, decimal y2);
void DrawRectangle(decimal x, decimal y, decimal width, decimal height);
void DrawResizedImage(string imageName, decimal x, decimal y, decimal width, decimal height);
void DrawText(decimal x, decimal y, string text);
void DrawTriangle(decimal x1, decimal y1, decimal x2, decimal y2, decimal x3, decimal y3);
void FillEllipse(decimal x, decimal y, decimal width, decimal height);
void FillRectangle(decimal x, decimal y, decimal width, decimal height);
void FillTriangle(decimal x1, decimal y1, decimal x2, decimal y2, decimal x3, decimal y3);
string GetColorFromRGB(decimal red, decimal green, decimal blue);
string GetRandomColor();
void Hide();
void SetPixel(decimal x, decimal y, string color);
void Show();
Task ShowMessage(string text, string title);
}
public interface IImageListLibrary
{
decimal GetHeightOfImage(string imageName);
decimal GetWidthOfImage(string imageName);
Task<string> LoadImage(string fileNameOrUrl);
}
public interface IMathLibrary
{
decimal Get_Pi();
decimal Abs(decimal number);
decimal ArcCos(decimal cosValue);
decimal ArcSin(decimal sinValue);
decimal ArcTan(decimal tanValue);
decimal Ceiling(decimal number);
decimal Cos(decimal angle);
decimal Floor(decimal number);
decimal GetDegrees(decimal angle);
decimal GetRadians(decimal angle);
decimal GetRandomNumber(decimal maxNumber);
decimal Log(decimal number);
decimal Max(decimal number1, decimal number2);
decimal Min(decimal number1, decimal number2);
decimal NaturalLog(decimal number);
decimal Power(decimal baseNumber, decimal exponent);
decimal Remainder(decimal dividend, decimal divisor);
decimal Round(decimal number);
decimal Sin(decimal angle);
decimal SquareRoot(decimal number);
decimal Tan(decimal angle);
}
public interface IMouseLibrary
{
bool Get_IsLeftButtonDown();
bool Get_IsRightButtonDown();
decimal Get_MouseX();
decimal Get_MouseY();
void HideCursor();
void ShowCursor();
}
public interface INetworkLibrary
{
Task<string> DownloadFile(string url);
Task<string> GetWebPageContents(string url);
}
public interface IProgramLibrary
{
Task Delay(decimal milliSeconds);
void End();
void Pause();
}
public interface IShapesLibrary
{
string AddEllipse(decimal width, decimal height);
string AddImage(string imageName);
string AddLine(decimal x1, decimal y1, decimal x2, decimal y2);
string AddRectangle(decimal width, decimal height);
string AddText(string text);
string AddTriangle(decimal x1, decimal y1, decimal x2, decimal y2, decimal x3, decimal y3);
Task Animate(string shapeName, decimal x, decimal y, decimal duration);
decimal GetLeft(string shapeName);
decimal GetOpacity(string shapeName);
decimal GetTop(string shapeName);
void HideShape(string shapeName);
void Move(string shapeName, decimal x, decimal y);
void Remove(string shapeName);
void Rotate(string shapeName, decimal angle);
void SetOpacity(string shapeName, decimal level);
void SetText(string shapeName, string text);
void ShowShape(string shapeName);
void Zoom(string shapeName, decimal scaleX, decimal scaleY);
}
public interface ISoundLibrary
{
}
public interface IStackLibrary
{
decimal GetCount(string stackName);
string PopValue(string stackName);
void PushValue(string stackName, string value);
}
public interface ITextLibrary
{
string Append(string text1, string text2);
string ConvertToLowerCase(string text);
string ConvertToUpperCase(string text);
bool EndsWith(string text, string subText);
string GetCharacter(decimal characterCode);
decimal GetCharacterCode(string character);
decimal GetIndexOf(string text, string subText);
decimal GetLength(string text);
string GetSubText(string text, decimal start, decimal length);
string GetSubTextToEnd(string text, decimal start);
bool IsSubText(string text, string subText);
bool StartsWith(string text, string subText);
}
public interface ITextWindowLibrary
{
string Get_BackgroundColor();
void Set_BackgroundColor(string value);
string Get_ForegroundColor();
void Set_ForegroundColor(string value);
string Get_Title();
void Set_Title(string value);
void Clear();
string Read();
decimal ReadNumber();
Task Write(string data);
Task WriteLine(string data);
}
public interface ITimerLibrary
{
event Action Tick;
decimal Get_Interval();
void Set_Interval(decimal value);
void Pause();
void Resume();
}
public interface ITurtleLibrary
{
decimal Get_Angle();
void Set_Angle(decimal value);
decimal Get_Speed();
void Set_Speed(decimal value);
decimal Get_X();
void Set_X(decimal value);
decimal Get_Y();
void Set_Y(decimal value);
void Hide();
Task Move(decimal distance);
Task MoveTo(decimal x, decimal y);
void PenDown();
void PenUp();
void Show();
Task Turn(decimal angle);
Task TurnLeft();
Task TurnRight();
}
public interface IEngineLibraries
{
IArrayLibrary Array { get; }
IClockLibrary Clock { get; }
IControlsLibrary Controls { get; }
IDesktopLibrary Desktop { get; }
IDictionaryLibrary Dictionary { get; }
IFileLibrary File { get; }
IFlickrLibrary Flickr { get; }
IGraphicsWindowLibrary GraphicsWindow { get; }
IImageListLibrary ImageList { get; }
IMathLibrary Math { get; }
IMouseLibrary Mouse { get; }
INetworkLibrary Network { get; }
IProgramLibrary Program { get; }
IShapesLibrary Shapes { get; }
ISoundLibrary Sound { get; }
IStackLibrary Stack { get; }
ITextLibrary Text { get; }
ITextWindowLibrary TextWindow { get; }
ITimerLibrary Timer { get; }
ITurtleLibrary Turtle { get; }
}
internal static class IEngineLibrariesExtensions
{
public static void SetEventCallbacks(this IEngineLibraries libraries, SmallBasicEngine engine)
{
libraries.Controls.ButtonClicked += () => engine.RaiseEvent("Controls", "ButtonClicked");
libraries.Controls.TextTyped += () => engine.RaiseEvent("Controls", "TextTyped");
libraries.GraphicsWindow.KeyDown += () => engine.RaiseEvent("GraphicsWindow", "KeyDown");
libraries.GraphicsWindow.KeyUp += () => engine.RaiseEvent("GraphicsWindow", "KeyUp");
libraries.GraphicsWindow.MouseDown += () => engine.RaiseEvent("GraphicsWindow", "MouseDown");
libraries.GraphicsWindow.MouseMove += () => engine.RaiseEvent("GraphicsWindow", "MouseMove");
libraries.GraphicsWindow.MouseUp += () => engine.RaiseEvent("GraphicsWindow", "MouseUp");
libraries.GraphicsWindow.TextInput += () => engine.RaiseEvent("GraphicsWindow", "TextInput");
libraries.Timer.Tick += () => engine.RaiseEvent("Timer", "Tick");
}
}
}
| |
namespace Mahan.Tralus.Infrastructure.Migration.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Pending : DbMigration
{
public override void Up()
{
DropForeignKey("Infrastructure.Countries", "ContinentId", "Infrastructure.Continents");
DropForeignKey("Infrastructure.Countries", "CurrencyId", "Infrastructure.Currencies");
DropForeignKey("Infrastructure.Countries", "IataRegionCodeId", "Infrastructure.IataRegionCodes");
DropForeignKey("Infrastructure.Cities", "CountryId", "Infrastructure.Countries");
DropForeignKey("Infrastructure.Airports", "CityId", "Infrastructure.Cities");
DropForeignKey("Infrastructure.Airports", "LocalityTypeId", "Infrastructure.LocalityTypes");
DropForeignKey("Infrastructure.Aircrafts", "AircraftTypeId", "Infrastructure.AircraftTypes");
DropForeignKey("Infrastructure.AircraftRegisters", "AircraftId", "Infrastructure.Aircrafts");
DropForeignKey("Infrastructure.AircraftRegisters", "LirRegisterGroupId", "Infrastructure.LirRegisterGroups");
DropForeignKey("Infrastructure.AircraftRegisterNonAvailableSeats", "AircraftRegisterId", "Infrastructure.AircraftRegisters");
DropForeignKey("Infrastructure.AircraftRegisterSeatInfos", "AircraftRegisterId", "Infrastructure.AircraftRegisters");
DropForeignKey("Infrastructure.Airlines", "CountryId", "Infrastructure.Countries");
DropForeignKey("Infrastructure.CityOffsetDsts", "CityId", "Infrastructure.Cities");
DropForeignKey("Infrastructure.CityOffsetUtcs", "CityId", "Infrastructure.Cities");
DropForeignKey("Infrastructure.IataCountryCodes", "CountryId", "Infrastructure.Countries");
DropForeignKey("Infrastructure.RouteLegAirports", "ArrivalAirportId", "Infrastructure.Airports");
DropForeignKey("Infrastructure.RouteLegAirports", "DepartureAirportId", "Infrastructure.Airports");
DropIndex("Infrastructure.Airports", new[] { "CityId" });
DropIndex("Infrastructure.Airports", new[] { "LocalityTypeId" });
DropIndex("Infrastructure.Cities", new[] { "CountryId" });
DropIndex("Infrastructure.Countries", new[] { "IataRegionCodeId" });
DropIndex("Infrastructure.Countries", new[] { "CurrencyId" });
DropIndex("Infrastructure.Countries", new[] { "ContinentId" });
DropIndex("Infrastructure.Aircrafts", new[] { "AircraftTypeId" });
DropIndex("Infrastructure.AircraftRegisters", new[] { "AircraftId" });
DropIndex("Infrastructure.AircraftRegisters", new[] { "LirRegisterGroupId" });
DropIndex("Infrastructure.AircraftRegisterNonAvailableSeats", new[] { "AircraftRegisterId" });
DropIndex("Infrastructure.AircraftRegisterSeatInfos", new[] { "AircraftRegisterId" });
DropIndex("Infrastructure.Airlines", new[] { "CountryId" });
DropIndex("Infrastructure.CityOffsetDsts", new[] { "CityId" });
DropIndex("Infrastructure.CityOffsetUtcs", new[] { "CityId" });
DropIndex("Infrastructure.IataCountryCodes", new[] { "CountryId" });
DropIndex("Infrastructure.RouteLegAirports", new[] { "ArrivalAirportId" });
DropIndex("Infrastructure.RouteLegAirports", new[] { "DepartureAirportId" });
DropTable("Infrastructure.Airports");
DropTable("Infrastructure.Cities");
DropTable("Infrastructure.Countries");
DropTable("Infrastructure.Continents");
DropTable("Infrastructure.Currencies");
DropTable("Infrastructure.IataRegionCodes");
DropTable("Infrastructure.LocalityTypes");
DropTable("Infrastructure.Aircrafts");
DropTable("Infrastructure.AircraftTypes");
DropTable("Infrastructure.AircraftRegisters");
DropTable("Infrastructure.LirRegisterGroups");
DropTable("Infrastructure.AircraftRegisterNonAvailableSeats");
DropTable("Infrastructure.AircraftRegisterSeatInfos");
DropTable("Infrastructure.Airlines");
DropTable("Infrastructure.CityOffsetDsts");
DropTable("Infrastructure.CityOffsetUtcs");
DropTable("Infrastructure.Companies");
DropTable("Infrastructure.IataCountryCodes");
DropTable("Infrastructure.People");
DropTable("Infrastructure.RouteLegAirports");
DropTable("Infrastructure.Units");
}
public override void Down()
{
CreateTable(
"Infrastructure.Units",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.RouteLegAirports",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
ArrivalAirportId = c.String(maxLength: 128),
DepartureAirportId = c.String(maxLength: 128),
Name = c.String(maxLength: 200),
Status = c.String(maxLength: 20),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.People",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
FirstName = c.String(maxLength: 200),
LastName = c.String(maxLength: 200),
NationalCode = c.Double(),
IdentificationNumber = c.Double(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.IataCountryCodes",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
IataCode = c.String(maxLength: 2),
CountryId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Companies",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
CommercialCode = c.Double(),
Title = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.CityOffsetUtcs",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
CityId = c.String(maxLength: 128),
OffsetUtc = c.Long(),
FromDate = c.DateTime(),
ToDate = c.DateTime(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.CityOffsetDsts",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
CityId = c.String(maxLength: 128),
FromDate = c.DateTime(),
ToDate = c.DateTime(),
OffsetDst = c.Long(),
ToDateUtc = c.DateTime(),
FromDateUtc = c.DateTime(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Airlines",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
CountryId = c.String(maxLength: 128),
IataCode = c.String(maxLength: 200),
IcaoCode = c.String(maxLength: 200),
Abv = c.String(maxLength: 200),
FullName = c.String(maxLength: 200),
ShortName = c.String(maxLength: 200),
Status = c.String(maxLength: 20),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.AircraftRegisterSeatInfos",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
StartDate = c.DateTime(),
EndDate = c.DateTime(),
SeatCountBusiness = c.Long(),
SeatCountEconomy = c.Long(),
AircraftRegisterId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.AircraftRegisterNonAvailableSeats",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
StartDate = c.DateTime(),
EndDate = c.DateTime(),
AircraftRegisterId = c.String(maxLength: 128),
SeatCountBusiness = c.Long(),
SeatCountBusinessPlus = c.Long(),
SeatCountEconomy = c.Long(),
SeatNumberBusiness = c.String(maxLength: 200),
SeatNumberBusinessPlus = c.String(maxLength: 200),
SeatNumberEconomy = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.LirRegisterGroups",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Title = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.AircraftRegisters",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Code = c.String(maxLength: 200),
AircraftId = c.String(maxLength: 128),
ShortRegisterCode = c.String(maxLength: 3),
HasFirstClassSeat = c.Boolean(),
Status = c.String(maxLength: 20),
LirRegisterGroupId = c.String(maxLength: 128),
Timestamp = c.DateTime(),
IsActive = c.Boolean(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.AircraftTypes",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
Manufacturer = c.String(maxLength: 200),
TypeVariation = c.String(maxLength: 200),
FullTypeName = c.String(maxLength: 200),
IataCode = c.String(maxLength: 3),
IcaoCode = c.String(maxLength: 4),
FwName = c.String(maxLength: 3),
Status = c.String(maxLength: 20),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Aircrafts",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
SerialNo = c.String(maxLength: 200),
AircraftTypeId = c.String(maxLength: 128),
Register = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.LocalityTypes",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
Code = c.Long(),
NameEn = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.IataRegionCodes",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
RegionCode = c.String(maxLength: 200),
RegionName = c.String(maxLength: 200),
RegionNameEn = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Currencies",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 50),
Symbol = c.String(maxLength: 20),
NameEn = c.String(maxLength: 50),
Code = c.String(maxLength: 5),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Continents",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Code = c.String(maxLength: 200),
NameEn = c.String(maxLength: 200),
Name = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Countries",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
IsoAlpha3 = c.String(maxLength: 3),
IsoAlpha2 = c.String(maxLength: 2),
NameEn = c.String(maxLength: 200),
UnNumeric3 = c.String(maxLength: 3),
Fips104 = c.String(maxLength: 2),
IataRegionCodeId = c.String(maxLength: 128),
CurrencyId = c.String(maxLength: 128),
ContinentId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Cities",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
CountryId = c.String(maxLength: 128),
NameEn = c.String(maxLength: 200),
TimeZone = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Infrastructure.Airports",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(maxLength: 200),
IataAirportCode = c.String(maxLength: 3),
NameEn = c.String(maxLength: 200),
CityId = c.String(maxLength: 128),
Status = c.String(maxLength: 20),
LocalityTypeId = c.String(maxLength: 128),
NickName = c.String(maxLength: 200),
})
.PrimaryKey(t => t.Id);
CreateIndex("Infrastructure.RouteLegAirports", "DepartureAirportId");
CreateIndex("Infrastructure.RouteLegAirports", "ArrivalAirportId");
CreateIndex("Infrastructure.IataCountryCodes", "CountryId");
CreateIndex("Infrastructure.CityOffsetUtcs", "CityId");
CreateIndex("Infrastructure.CityOffsetDsts", "CityId");
CreateIndex("Infrastructure.Airlines", "CountryId");
CreateIndex("Infrastructure.AircraftRegisterSeatInfos", "AircraftRegisterId");
CreateIndex("Infrastructure.AircraftRegisterNonAvailableSeats", "AircraftRegisterId");
CreateIndex("Infrastructure.AircraftRegisters", "LirRegisterGroupId");
CreateIndex("Infrastructure.AircraftRegisters", "AircraftId");
CreateIndex("Infrastructure.Aircrafts", "AircraftTypeId");
CreateIndex("Infrastructure.Countries", "ContinentId");
CreateIndex("Infrastructure.Countries", "CurrencyId");
CreateIndex("Infrastructure.Countries", "IataRegionCodeId");
CreateIndex("Infrastructure.Cities", "CountryId");
CreateIndex("Infrastructure.Airports", "LocalityTypeId");
CreateIndex("Infrastructure.Airports", "CityId");
AddForeignKey("Infrastructure.RouteLegAirports", "DepartureAirportId", "Infrastructure.Airports", "Id");
AddForeignKey("Infrastructure.RouteLegAirports", "ArrivalAirportId", "Infrastructure.Airports", "Id");
AddForeignKey("Infrastructure.IataCountryCodes", "CountryId", "Infrastructure.Countries", "Id");
AddForeignKey("Infrastructure.CityOffsetUtcs", "CityId", "Infrastructure.Cities", "Id");
AddForeignKey("Infrastructure.CityOffsetDsts", "CityId", "Infrastructure.Cities", "Id");
AddForeignKey("Infrastructure.Airlines", "CountryId", "Infrastructure.Countries", "Id");
AddForeignKey("Infrastructure.AircraftRegisterSeatInfos", "AircraftRegisterId", "Infrastructure.AircraftRegisters", "Id");
AddForeignKey("Infrastructure.AircraftRegisterNonAvailableSeats", "AircraftRegisterId", "Infrastructure.AircraftRegisters", "Id");
AddForeignKey("Infrastructure.AircraftRegisters", "LirRegisterGroupId", "Infrastructure.LirRegisterGroups", "Id");
AddForeignKey("Infrastructure.AircraftRegisters", "AircraftId", "Infrastructure.Aircrafts", "Id");
AddForeignKey("Infrastructure.Aircrafts", "AircraftTypeId", "Infrastructure.AircraftTypes", "Id");
AddForeignKey("Infrastructure.Airports", "LocalityTypeId", "Infrastructure.LocalityTypes", "Id");
AddForeignKey("Infrastructure.Airports", "CityId", "Infrastructure.Cities", "Id");
AddForeignKey("Infrastructure.Cities", "CountryId", "Infrastructure.Countries", "Id");
AddForeignKey("Infrastructure.Countries", "IataRegionCodeId", "Infrastructure.IataRegionCodes", "Id");
AddForeignKey("Infrastructure.Countries", "CurrencyId", "Infrastructure.Currencies", "Id");
AddForeignKey("Infrastructure.Countries", "ContinentId", "Infrastructure.Continents", "Id");
}
}
}
| |
// 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.Diagnostics;
using osu.Framework.Caching;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Utils;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Graphics.Containers
{
public abstract class ScrollContainer<T> : Container<T>, DelayedLoadWrapper.IOnScreenOptimisingContainer, IKeyBindingHandler<PlatformAction>
where T : Drawable
{
/// <summary>
/// Determines whether the scroll dragger appears on the left side. If not, then it always appears on the right side.
/// </summary>
public Anchor ScrollbarAnchor
{
get => Scrollbar.Anchor;
set
{
Scrollbar.Anchor = value;
Scrollbar.Origin = value;
updatePadding();
}
}
private bool scrollbarVisible = true;
/// <summary>
/// Whether the scrollbar is visible.
/// </summary>
public bool ScrollbarVisible
{
get => scrollbarVisible;
set
{
scrollbarVisible = value;
scrollbarCache.Invalidate();
}
}
protected readonly ScrollbarContainer Scrollbar;
private bool scrollbarOverlapsContent = true;
/// <summary>
/// Whether the scrollbar overlaps the content or resides in its own padded space.
/// </summary>
public bool ScrollbarOverlapsContent
{
get => scrollbarOverlapsContent;
set
{
scrollbarOverlapsContent = value;
updatePadding();
}
}
/// <summary>
/// Size of available content (i.e. everything that can be scrolled to) in the scroll direction.
/// </summary>
public float AvailableContent => ScrollContent.DrawSize[ScrollDim];
/// <summary>
/// Size of the viewport in the scroll direction.
/// </summary>
public float DisplayableContent => ChildSize[ScrollDim];
/// <summary>
/// Controls the distance scrolled per unit of mouse scroll.
/// </summary>
public float ScrollDistance = 80;
/// <summary>
/// This limits how far out of clamping bounds we allow the target position to be at most.
/// Effectively, larger values result in bouncier behavior as the scroll boundaries are approached
/// with high velocity.
/// </summary>
public float ClampExtension = 500;
/// <summary>
/// This corresponds to the clamping force. A larger value means more aggressive clamping. Default is 0.012.
/// </summary>
private const double distance_decay_clamping = 0.012;
/// <summary>
/// Controls the rate with which the target position is approached after ending a drag. Default is 0.0035.
/// </summary>
public double DistanceDecayDrag = 0.0035;
/// <summary>
/// Controls the rate with which the target position is approached after scrolling. Default is 0.01
/// </summary>
public double DistanceDecayScroll = 0.01;
/// <summary>
/// Controls the rate with which the target position is approached after jumping to a specific location. Default is 0.01.
/// </summary>
public double DistanceDecayJump = 0.01;
/// <summary>
/// Controls the rate with which the target position is approached. It is automatically set after
/// dragging or scrolling.
/// </summary>
private double distanceDecay;
/// <summary>
/// The current scroll position.
/// </summary>
public float Current { get; private set; }
/// <summary>
/// The target scroll position which is exponentially approached by current via a rate of distanceDecay.
/// </summary>
protected float Target { get; private set; }
/// <summary>
/// The maximum distance that can be scrolled in the scroll direction.
/// </summary>
public float ScrollableExtent => Math.Max(AvailableContent - DisplayableContent, 0);
/// <summary>
/// The maximum distance that the scrollbar can move in the scroll direction.
/// </summary>
public float ScrollbarMovementExtent => Math.Max(DrawSize[ScrollDim] - Scrollbar.DrawSize[ScrollDim], 0);
/// <summary>
/// Clamp a value to the available scroll range.
/// </summary>
/// <param name="position">The value to clamp.</param>
/// <param name="extension">An extension value beyond the normal extent.</param>
protected float Clamp(float position, float extension = 0) => Math.Max(Math.Min(position, ScrollableExtent + extension), -extension);
protected override Container<T> Content => ScrollContent;
/// <summary>
/// Whether we are currently scrolled as far as possible into the scroll direction.
/// </summary>
/// <param name="lenience">How close to the extent we need to be.</param>
public bool IsScrolledToEnd(float lenience = Precision.FLOAT_EPSILON) => Precision.AlmostBigger(Target, ScrollableExtent, lenience);
/// <summary>
/// The container holding all children which are getting scrolled around.
/// </summary>
public Container<T> ScrollContent { get; }
protected virtual bool IsDragging { get; private set; }
public bool IsHandlingKeyboardScrolling
{
get
{
if (IsHovered)
return true;
InputManager inputManager = GetContainingInputManager();
return inputManager != null && ReceivePositionalInputAt(inputManager.CurrentState.Mouse.Position);
}
}
/// <summary>
/// The direction in which scrolling is supported.
/// </summary>
protected readonly Direction ScrollDirection;
/// <summary>
/// The direction in which scrolling is supported, converted to an int for array index lookups.
/// </summary>
protected int ScrollDim => ScrollDirection == Direction.Horizontal ? 0 : 1;
/// <summary>
/// Creates a scroll container.
/// </summary>
/// <param name="scrollDirection">The direction in which should be scrolled. Can be vertical or horizontal. Default is vertical.</param>
protected ScrollContainer(Direction scrollDirection = Direction.Vertical)
{
ScrollDirection = scrollDirection;
Masking = true;
Axes scrollAxis = scrollDirection == Direction.Horizontal ? Axes.X : Axes.Y;
AddRangeInternal(new Drawable[]
{
ScrollContent = new Container<T>
{
RelativeSizeAxes = Axes.Both & ~scrollAxis,
AutoSizeAxes = scrollAxis,
},
Scrollbar = CreateScrollbar(scrollDirection)
});
Scrollbar.Hide();
Scrollbar.Dragged = onScrollbarMovement;
ScrollbarAnchor = scrollDirection == Direction.Vertical ? Anchor.TopRight : Anchor.BottomLeft;
}
private float lastUpdateDisplayableContent = -1;
private float lastAvailableContent = -1;
private void updateSize()
{
// ensure we only update scrollbar when something has changed, to avoid transform helpers resetting their transform every frame.
// also avoids creating many needless Transforms every update frame.
if (lastAvailableContent != AvailableContent || lastUpdateDisplayableContent != DisplayableContent)
{
lastAvailableContent = AvailableContent;
lastUpdateDisplayableContent = DisplayableContent;
scrollbarCache.Invalidate();
}
}
private readonly Cached scrollbarCache = new Cached();
private void updatePadding()
{
if (scrollbarOverlapsContent || AvailableContent <= DisplayableContent)
ScrollContent.Padding = new MarginPadding();
else
{
if (ScrollDirection == Direction.Vertical)
{
ScrollContent.Padding = ScrollbarAnchor == Anchor.TopLeft
? new MarginPadding { Left = Scrollbar.Width + Scrollbar.Margin.Left }
: new MarginPadding { Right = Scrollbar.Width + Scrollbar.Margin.Right };
}
else
{
ScrollContent.Padding = ScrollbarAnchor == Anchor.TopLeft
? new MarginPadding { Top = Scrollbar.Height + Scrollbar.Margin.Top }
: new MarginPadding { Bottom = Scrollbar.Height + Scrollbar.Margin.Bottom };
}
}
}
protected override bool OnDragStart(DragStartEvent e)
{
if (IsDragging || e.Button != MouseButton.Left || Content.AliveInternalChildren.Count == 0)
return false;
lastDragTime = Time.Current;
averageDragDelta = averageDragTime = 0;
IsDragging = true;
dragButtonManager = GetContainingInputManager().GetButtonEventManagerFor(e.Button);
return true;
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (IsHandlingKeyboardScrolling && !IsDragging)
{
switch (e.Key)
{
case Key.PageUp:
OnUserScroll(Target - DisplayableContent);
return true;
case Key.PageDown:
OnUserScroll(Target + DisplayableContent);
return true;
}
}
return base.OnKeyDown(e);
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (IsDragging || e.Button != MouseButton.Left) return false;
// Continue from where we currently are scrolled to.
Target = Current;
return true;
}
// We keep track of this because input events may happen at different intervals than update frames
// and we are interested in the time difference between drag _input_ events.
private double lastDragTime;
// These keep track of a sliding average (w.r.t. time) of the time between drag events
// and the delta of drag events. Both of these moving averages are decayed at the same
// rate and thus the velocity remains constant across time. The overall magnitude
// of averageDragTime and averageDragDelta simple decreases such that more recent movements
// have a larger weight.
private double averageDragTime;
private double averageDragDelta;
private MouseButtonEventManager dragButtonManager;
private bool dragBlocksClick;
public override bool DragBlocksClick => dragBlocksClick;
protected override void OnDrag(DragEvent e)
{
Trace.Assert(IsDragging, "We should never receive OnDrag if we are not dragging.");
double currentTime = Time.Current;
double timeDelta = currentTime - lastDragTime;
double decay = Math.Pow(0.95, timeDelta);
averageDragTime = averageDragTime * decay + timeDelta;
averageDragDelta = averageDragDelta * decay - e.Delta[ScrollDim];
lastDragTime = currentTime;
Vector2 childDelta = ToLocalSpace(e.ScreenSpaceMousePosition) - ToLocalSpace(e.ScreenSpaceLastMousePosition);
float scrollOffset = -childDelta[ScrollDim];
float clampedScrollOffset = Clamp(Target + scrollOffset) - Clamp(Target);
Debug.Assert(Precision.AlmostBigger(Math.Abs(scrollOffset), clampedScrollOffset * Math.Sign(scrollOffset)));
// If we are dragging past the extent of the scrollable area, half the offset
// such that the user can feel it.
scrollOffset = clampedScrollOffset + (scrollOffset - clampedScrollOffset) / 2;
// similar calculation to what is already done in MouseButtonEventManager.HandlePositionChange
// handles the case where a drag was triggered on an axis we are not interested in.
// can be removed if/when drag events are split out per axis or contain direction information.
dragBlocksClick |= Math.Abs(e.MouseDownPosition[ScrollDim] - e.MousePosition[ScrollDim]) > dragButtonManager.ClickDragDistance;
scrollByOffset(scrollOffset, false);
}
protected override void OnDragEnd(DragEndEvent e)
{
Trace.Assert(IsDragging, "We should never receive OnDragEnd if we are not dragging.");
dragBlocksClick = false;
dragButtonManager = null;
IsDragging = false;
if (averageDragTime <= 0.0)
return;
double velocity = averageDragDelta / averageDragTime;
// Detect whether we halted at the end of the drag and in fact should _not_
// perform a flick event.
const double velocity_cutoff = 0.1;
if (Math.Abs(Math.Pow(0.95, Time.Current - lastDragTime) * velocity) < velocity_cutoff)
velocity = 0;
// Differentiate f(t) = distance * (1 - exp(-t)) w.r.t. "t" to obtain
// velocity w.r.t. time. Then rearrange to solve for distance given velocity.
double distance = velocity / (1 - Math.Exp(-DistanceDecayDrag));
scrollByOffset((float)distance, true, DistanceDecayDrag);
}
protected override bool OnScroll(ScrollEvent e)
{
if (Content.AliveInternalChildren.Count == 0)
return false;
bool isPrecise = e.IsPrecise;
Vector2 scrollDelta = e.ScrollDelta;
float scrollDeltaFloat = scrollDelta.Y;
if (ScrollDirection == Direction.Horizontal && scrollDelta.X != 0)
scrollDeltaFloat = scrollDelta.X;
scrollByOffset((isPrecise ? 10 : ScrollDistance) * -scrollDeltaFloat, true, isPrecise ? 0.05 : DistanceDecayScroll);
return true;
}
private void onScrollbarMovement(float value) => scrollTo(Clamp(fromScrollbarPosition(value)), false);
/// <summary>
/// Immediately offsets the current and target scroll position.
/// </summary>
/// <param name="offset">The scroll offset.</param>
public void OffsetScrollPosition(float offset)
{
Target += offset;
Current += offset;
}
private void scrollByOffset(float value, bool animated, double distanceDecay = float.PositiveInfinity) =>
OnUserScroll(Target + value, animated, distanceDecay);
/// <summary>
/// Scroll to the start of available content.
/// </summary>
/// <param name="animated">Whether to animate the movement.</param>
/// <param name="allowDuringDrag">Whether we should interrupt a user's active drag.</param>
public void ScrollToStart(bool animated = true, bool allowDuringDrag = false)
{
if (!IsDragging || allowDuringDrag)
scrollTo(0, animated, DistanceDecayJump);
}
/// <summary>
/// Scroll to the end of available content.
/// </summary>
/// <param name="animated">Whether to animate the movement.</param>
/// <param name="allowDuringDrag">Whether we should interrupt a user's active drag.</param>
public void ScrollToEnd(bool animated = true, bool allowDuringDrag = false)
{
if (!IsDragging || allowDuringDrag)
scrollTo(ScrollableExtent, animated, DistanceDecayJump);
}
/// <summary>
/// Scrolls to a new position relative to the current scroll offset.
/// </summary>
/// <param name="offset">The amount by which we should scroll.</param>
/// <param name="animated">Whether to animate the movement.</param>
public void ScrollBy(float offset, bool animated = true) => scrollTo(Target + offset, animated);
/// <summary>
/// Handle a scroll to an absolute position from a user input.
/// </summary>
/// <param name="value">The position to scroll to.</param>
/// <param name="animated">Whether to animate the movement.</param>
/// <param name="distanceDecay">Controls the rate with which the target position is approached after jumping to a specific location. Default is <see cref="DistanceDecayJump"/>.</param>
protected virtual void OnUserScroll(float value, bool animated = true, double? distanceDecay = null) =>
ScrollTo(value, animated, distanceDecay);
/// <summary>
/// Scrolls to an absolute position.
/// </summary>
/// <param name="value">The position to scroll to.</param>
/// <param name="animated">Whether to animate the movement.</param>
/// <param name="distanceDecay">Controls the rate with which the target position is approached after jumping to a specific location. Default is <see cref="DistanceDecayJump"/>.</param>
public void ScrollTo(float value, bool animated = true, double? distanceDecay = null) => scrollTo(value, animated, distanceDecay ?? DistanceDecayJump);
private void scrollTo(float value, bool animated, double distanceDecay = float.PositiveInfinity)
{
Target = Clamp(value, ClampExtension);
if (animated)
this.distanceDecay = distanceDecay;
else
Current = Target;
}
/// <summary>
/// Scrolls a <see cref="Drawable"/> to the top.
/// </summary>
/// <param name="d">The <see cref="Drawable"/> to scroll to.</param>
/// <param name="animated">Whether to animate the movement.</param>
public void ScrollTo(Drawable d, bool animated = true) => ScrollTo(GetChildPosInContent(d), animated);
/// <summary>
/// Scrolls a <see cref="Drawable"/> into view.
/// </summary>
/// <param name="d">The <see cref="Drawable"/> to scroll into view.</param>
/// <param name="animated">Whether to animate the movement.</param>
public void ScrollIntoView(Drawable d, bool animated = true)
{
float childPos0 = GetChildPosInContent(d);
float childPos1 = GetChildPosInContent(d, d.DrawSize);
float minPos = Math.Min(childPos0, childPos1);
float maxPos = Math.Max(childPos0, childPos1);
if (minPos < Current || (minPos > Current && d.DrawSize[ScrollDim] > DisplayableContent))
ScrollTo(minPos, animated);
else if (maxPos > Current + DisplayableContent)
ScrollTo(maxPos - DisplayableContent, animated);
}
/// <summary>
/// Determines the position of a child in the content.
/// </summary>
/// <param name="d">The child to get the position from.</param>
/// <param name="offset">Positional offset in the child's space.</param>
/// <returns>The position of the child.</returns>
public float GetChildPosInContent(Drawable d, Vector2 offset) => d.ToSpaceOfOtherDrawable(offset, ScrollContent)[ScrollDim];
/// <summary>
/// Determines the position of a child in the content.
/// </summary>
/// <param name="d">The child to get the position from.</param>
/// <returns>The position of the child.</returns>
public float GetChildPosInContent(Drawable d) => GetChildPosInContent(d, Vector2.Zero);
private void updatePosition()
{
double localDistanceDecay = distanceDecay;
// If we are not currently dragging the content, and we have scrolled out of bounds,
// then we should handle the clamping force. Note, that if the target is _within_
// acceptable bounds, then we do not need special handling of the clamping force, as
// we will naturally scroll back into acceptable bounds.
if (!IsDragging && Current != Clamp(Current) && Target != Clamp(Target, -0.01f))
{
// Firstly, we want to limit how far out the target may go to limit overly bouncy
// behaviour with extreme scroll velocities.
Target = Clamp(Target, ClampExtension);
// Secondly, we would like to quickly approach the target while we are out of bounds.
// This is simulating a "strong" clamping force towards the target.
if (Current < Target && Target < 0 || Current > Target && Target > ScrollableExtent)
localDistanceDecay = distance_decay_clamping * 2;
// Lastly, we gradually nudge the target towards valid bounds.
Target = (float)Interpolation.Lerp(Clamp(Target), Target, Math.Exp(-distance_decay_clamping * Time.Elapsed));
float clampedTarget = Clamp(Target);
if (Precision.AlmostEquals(clampedTarget, Target))
Target = clampedTarget;
}
// Exponential interpolation between the target and our current scroll position.
Current = (float)Interpolation.Lerp(Target, Current, Math.Exp(-localDistanceDecay * Time.Elapsed));
// This prevents us from entering the de-normalized range of floating point numbers when approaching target closely.
if (Precision.AlmostEquals(Current, Target))
Current = Target;
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
updateSize();
updatePosition();
if (!scrollbarCache.IsValid)
{
var size = ScrollDirection == Direction.Horizontal ? DrawWidth : DrawHeight;
if (size > 0)
Scrollbar.ResizeTo(Math.Clamp(AvailableContent > 0 ? DisplayableContent / AvailableContent : 0, Math.Min(Scrollbar.MinimumDimSize / size, 1), 1), 200, Easing.OutQuint);
Scrollbar.FadeTo(ScrollbarVisible && AvailableContent - 1 > DisplayableContent ? 1 : 0, 200);
updatePadding();
scrollbarCache.Validate();
}
if (ScrollDirection == Direction.Horizontal)
{
Scrollbar.X = toScrollbarPosition(Current);
ScrollContent.X = -Current + ScrollableExtent * ScrollContent.RelativeAnchorPosition.X;
}
else
{
Scrollbar.Y = toScrollbarPosition(Current);
ScrollContent.Y = -Current + ScrollableExtent * ScrollContent.RelativeAnchorPosition.Y;
}
}
/// <summary>
/// Converts a scroll position to a scrollbar position.
/// </summary>
/// <param name="scrollPosition">The absolute scroll position (e.g. <see cref="Current"/>).</param>
/// <returns>The scrollbar position.</returns>
private float toScrollbarPosition(float scrollPosition)
{
if (Precision.AlmostEquals(0, ScrollableExtent))
return 0;
return ScrollbarMovementExtent * (scrollPosition / ScrollableExtent);
}
/// <summary>
/// Converts a scrollbar position to a scroll position.
/// </summary>
/// <param name="scrollbarPosition">The scrollbar position.</param>
/// <returns>The absolute scroll position.</returns>
private float fromScrollbarPosition(float scrollbarPosition)
{
if (Precision.AlmostEquals(0, ScrollbarMovementExtent))
return 0;
return ScrollableExtent * (scrollbarPosition / ScrollbarMovementExtent);
}
/// <summary>
/// Creates the scrollbar for this <see cref="ScrollContainer{T}"/>.
/// </summary>
/// <param name="direction">The scrolling direction.</param>
protected abstract ScrollbarContainer CreateScrollbar(Direction direction);
protected internal abstract class ScrollbarContainer : Container
{
private float dragOffset;
internal Action<float> Dragged;
protected readonly Direction ScrollDirection;
/// <summary>
/// The minimum size of this <see cref="ScrollbarContainer"/>. Defaults to the size in the non-scrolling direction.
/// </summary>
protected internal virtual float MinimumDimSize => Size[ScrollDirection == Direction.Vertical ? 0 : 1];
protected ScrollbarContainer(Direction direction)
{
ScrollDirection = direction;
RelativeSizeAxes = direction == Direction.Horizontal ? Axes.X : Axes.Y;
}
public abstract void ResizeTo(float val, int duration = 0, Easing easing = Easing.None);
protected override bool OnClick(ClickEvent e) => true;
protected override bool OnDragStart(DragStartEvent e)
{
if (e.Button != MouseButton.Left) return false;
dragOffset = e.MousePosition[(int)ScrollDirection] - Position[(int)ScrollDirection];
return true;
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (e.Button != MouseButton.Left) return false;
dragOffset = Position[(int)ScrollDirection];
Dragged?.Invoke(dragOffset);
return true;
}
protected override void OnDrag(DragEvent e)
{
Dragged?.Invoke(e.MousePosition[(int)ScrollDirection] - dragOffset);
}
}
public bool OnPressed(PlatformAction action)
{
if (!IsHandlingKeyboardScrolling)
return false;
switch (action.ActionType)
{
case PlatformActionType.LineStart:
ScrollToStart();
return true;
case PlatformActionType.LineEnd:
ScrollToEnd();
return true;
default:
return false;
}
}
public void OnReleased(PlatformAction action)
{
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Repl {
[Export(typeof(InteractiveWindowProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
class InteractiveWindowProvider {
private readonly Dictionary<int, IVsInteractiveWindow> _windows = new Dictionary<int, IVsInteractiveWindow>();
private int _nextId = 1;
/// <summary>
/// A reverse-ordered list of recently used windows. Last item is most recently used.
/// </summary>
private readonly List<IVsInteractiveWindow> _lruWindows = new List<IVsInteractiveWindow>();
private readonly Dictionary<string, int> _temporaryWindows = new Dictionary<string, int>();
private readonly IServiceProvider _serviceProvider;
private readonly IInteractiveEvaluatorProvider[] _evaluators;
private readonly IVsInteractiveWindowFactory _windowFactory;
private readonly IContentType _pythonContentType;
private static readonly object VsInteractiveWindowKey = new object();
private const string SavedWindowsCategoryBase = "InteractiveWindows\\";
[ImportingConstructor]
public InteractiveWindowProvider(
[Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider,
[Import] IVsInteractiveWindowFactory factory,
[ImportMany] IInteractiveEvaluatorProvider[] evaluators,
[Import] IContentTypeRegistryService contentTypeService
) {
_serviceProvider = serviceProvider;
_evaluators = evaluators;
_windowFactory = factory;
_pythonContentType = contentTypeService.GetContentType(PythonCoreConstants.ContentType);
}
public IEnumerable<IVsInteractiveWindow> AllOpenWindows {
get {
lock (_windows) {
return _windows.Values.ToArray();
}
}
}
private int GetNextId() {
lock (_windows) {
do {
var curId = _nextId++;
if (!_windows.ContainsKey(curId)) {
return curId;
}
} while (_nextId < int.MaxValue);
}
throw new InvalidOperationException(Strings.ReplWindowOutOfIds);
}
private bool EnsureInterpretersAvailable() {
var registry = _serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();
if (registry.Configurations.Where(PythonInterpreterFactoryExtensions.IsRunnable).Any()) {
return true;
}
PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider);
return false;
}
public void OnWindowUsed(IVsInteractiveWindow window) {
if (window == null) {
throw new ArgumentNullException(nameof(window));
}
lock (_windows) {
_lruWindows.Remove(window);
_lruWindows.Add(window);
}
}
public IVsInteractiveWindow Open(string replId) => Open(replId, null);
public IVsInteractiveWindow Open(string replId, Func<IInteractiveEvaluator, bool> predicate) {
EnsureInterpretersAvailable();
lock (_windows) {
foreach(var window in _lruWindows.AsEnumerable().Reverse().Concat(_windows.Values)) {
var eval = window.InteractiveWindow?.Evaluator as SelectableReplEvaluator;
if (eval?.CurrentEvaluator == replId && predicate?.Invoke(eval) != false) {
OnWindowUsed(window);
window.Show(true);
return window;
}
}
}
return null;
}
public IVsInteractiveWindow OpenOrCreate(string replId) => OpenOrCreate(replId, null);
public IVsInteractiveWindow OpenOrCreate(string replId, Func<IInteractiveEvaluator, bool> predicate) {
EnsureInterpretersAvailable();
IVsInteractiveWindow wnd;
lock (_windows) {
foreach(var window in _lruWindows.AsEnumerable().Reverse().Concat(_windows.Values)) {
var eval = window.InteractiveWindow?.Evaluator as SelectableReplEvaluator;
if (eval?.CurrentEvaluator == replId && predicate?.Invoke(eval) != false) {
OnWindowUsed(window);
window.Show(true);
return window;
}
}
}
wnd = Create(replId);
wnd.Show(true);
return wnd;
}
public IVsInteractiveWindow Create(string replId, int curId = -1) {
EnsureInterpretersAvailable();
if (curId < 0) {
curId = GetNextId();
}
var window = CreateInteractiveWindowInternal(
new SelectableReplEvaluator(_serviceProvider, _evaluators, replId, curId.ToString()),
_pythonContentType,
true,
curId,
Strings.ReplCaptionNoEvaluator,
typeof(Navigation.PythonLanguageInfo).GUID,
"PythonInteractive"
);
lock (_windows) {
_windows[curId] = window;
_lruWindows.Add(window);
}
window.InteractiveWindow.TextView.Closed += (s, e) => {
lock (_windows) {
Debug.Assert(ReferenceEquals(_windows[curId], window));
_windows.Remove(curId);
_lruWindows.Remove(window);
}
};
return window;
}
public IVsInteractiveWindow OpenOrCreateTemporary(string replId, string title) {
bool dummy;
return OpenOrCreateTemporary(replId, title, out dummy);
}
public IVsInteractiveWindow OpenOrCreateTemporary(string replId, string title, out bool wasCreated) {
EnsureInterpretersAvailable();
IVsInteractiveWindow wnd;
lock (_windows) {
int curId;
if (_temporaryWindows.TryGetValue(replId, out curId)) {
if (_windows.TryGetValue(curId, out wnd)) {
wnd.Show(true);
wasCreated = false;
return wnd;
}
}
_temporaryWindows.Remove(replId);
}
wnd = CreateTemporary(replId, title);
wnd.Show(true);
wasCreated = true;
return wnd;
}
public IVsInteractiveWindow CreateTemporary(string replId, string title) {
EnsureInterpretersAvailable();
int curId = GetNextId();
var window = CreateInteractiveWindowInternal(
_evaluators.Select(p => p.GetEvaluator(replId)).FirstOrDefault(e => e != null),
_pythonContentType,
false,
curId,
title,
typeof(Navigation.PythonLanguageInfo).GUID,
replId
);
lock (_windows) {
_windows[curId] = window;
_temporaryWindows[replId] = curId;
_lruWindows.Add(window);
}
window.InteractiveWindow.TextView.Closed += (s, e) => {
lock (_windows) {
Debug.Assert(ReferenceEquals(_windows[curId], window));
_windows.Remove(curId);
_temporaryWindows.Remove(replId);
_lruWindows.Remove(window);
}
};
return window;
}
private IVsInteractiveWindow CreateInteractiveWindowInternal(
IInteractiveEvaluator evaluator,
IContentType contentType,
bool alwaysCreate,
int id,
string title,
Guid languageServiceGuid,
string replId
) {
var creationFlags =
__VSCREATETOOLWIN.CTW_fMultiInstance |
__VSCREATETOOLWIN.CTW_fActivateWithProject;
if (alwaysCreate) {
creationFlags |= __VSCREATETOOLWIN.CTW_fForceCreate;
}
#if DEV15_OR_LATER
var windowFactory2 = _windowFactory as IVsInteractiveWindowFactory2;
var replWindow = windowFactory2.Create(
GuidList.guidPythonInteractiveWindowGuid,
id,
title,
evaluator,
creationFlags,
GuidList.guidPythonToolsCmdSet,
PythonConstants.ReplWindowToolbar,
null
);
#else
var replWindow = _windowFactory.Create(
GuidList.guidPythonInteractiveWindowGuid,
id,
title,
evaluator,
creationFlags
);
#endif
replWindow.InteractiveWindow.Properties[VsInteractiveWindowKey] = replWindow;
var toolWindow = replWindow as ToolWindowPane;
if (toolWindow != null) {
toolWindow.BitmapImageMoniker = KnownMonikers.PYInteractiveWindow;
}
replWindow.SetLanguage(GuidList.guidPythonLanguageServiceGuid, contentType);
var selectEval = evaluator as SelectableReplEvaluator;
if (selectEval != null) {
selectEval.ProvideInteractiveWindowEvents(InteractiveWindowEvents.GetOrCreate(replWindow));
}
_serviceProvider.GetUIThread().InvokeTaskSync(() => replWindow.InteractiveWindow.InitializeAsync(), CancellationToken.None);
return replWindow;
}
internal static IVsInteractiveWindow GetVsInteractiveWindow(IInteractiveWindow window) {
IVsInteractiveWindow wnd = null;
return (window?.Properties.TryGetProperty(VsInteractiveWindowKey, out wnd) ?? false) ? wnd : null;
}
internal static void Close(object obj) {
var frame = ((obj as ToolWindowPane)?.Frame as IVsWindowFrame);
frame?.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
internal static void CloseIfEvaluatorMatches(object obj, string evalId) {
var eval = (obj as IVsInteractiveWindow)?.InteractiveWindow.Evaluator as SelectableReplEvaluator;
if (eval?.CurrentEvaluator == evalId) {
Close(obj);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using BooleanClause = Lucene.Net.Search.BooleanClause;
using BooleanQuery = Lucene.Net.Search.BooleanQuery;
using DisjunctionMaxQuery = Lucene.Net.Search.DisjunctionMaxQuery;
using FilteredQuery = Lucene.Net.Search.FilteredQuery;
using MultiPhraseQuery = Lucene.Net.Search.MultiPhraseQuery;
using PhraseQuery = Lucene.Net.Search.PhraseQuery;
using Query = Lucene.Net.Search.Query;
using TermQuery = Lucene.Net.Search.TermQuery;
using SpanNearQuery = Lucene.Net.Search.Spans.SpanNearQuery;
using SpanOrQuery = Lucene.Net.Search.Spans.SpanOrQuery;
using SpanQuery = Lucene.Net.Search.Spans.SpanQuery;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
namespace Lucene.Net.Search.Payloads
{
/// <summary> Experimental class to get set of payloads for most standard Lucene queries.
/// Operates like Highlighter - IndexReader should only contain doc of interest,
/// best to use MemoryIndex.
///
/// <p/>
/// <font color="#FF0000">
/// WARNING: The status of the <b>Payloads</b> feature is experimental.
/// The APIs introduced here might change in the future and will not be
/// supported anymore in such a case.</font>
///
/// </summary>
public class PayloadSpanUtil
{
private IndexReader reader;
/// <param name="reader">that contains doc with payloads to extract
/// </param>
public PayloadSpanUtil(IndexReader reader)
{
this.reader = reader;
}
/// <summary> Query should be rewritten for wild/fuzzy support.
///
/// </summary>
/// <param name="query">
/// </param>
/// <returns> payloads Collection
/// </returns>
/// <throws> IOException </throws>
public virtual ICollection<byte[]> GetPayloadsForQuery(Query query)
{
ICollection<byte[]> payloads = new List<byte[]>();
QueryToSpanQuery(query, payloads);
return payloads;
}
private void QueryToSpanQuery(Query query, ICollection<byte[]> payloads)
{
if (query is BooleanQuery)
{
BooleanClause[] queryClauses = ((BooleanQuery) query).GetClauses();
for (int i = 0; i < queryClauses.Length; i++)
{
if (!queryClauses[i].IsProhibited())
{
QueryToSpanQuery(queryClauses[i].GetQuery(), payloads);
}
}
}
else if (query is PhraseQuery)
{
Term[] phraseQueryTerms = ((PhraseQuery) query).GetTerms();
SpanQuery[] clauses = new SpanQuery[phraseQueryTerms.Length];
for (int i = 0; i < phraseQueryTerms.Length; i++)
{
clauses[i] = new SpanTermQuery(phraseQueryTerms[i]);
}
int slop = ((PhraseQuery) query).GetSlop();
bool inorder = false;
if (slop == 0)
{
inorder = true;
}
SpanNearQuery sp = new SpanNearQuery(clauses, slop, inorder);
sp.SetBoost(query.GetBoost());
GetPayloads(payloads, sp);
}
else if (query is TermQuery)
{
SpanTermQuery stq = new SpanTermQuery(((TermQuery) query).GetTerm());
stq.SetBoost(query.GetBoost());
GetPayloads(payloads, stq);
}
else if (query is SpanQuery)
{
GetPayloads(payloads, (SpanQuery) query);
}
else if (query is FilteredQuery)
{
QueryToSpanQuery(((FilteredQuery) query).GetQuery(), payloads);
}
else if (query is DisjunctionMaxQuery)
{
for (System.Collections.IEnumerator iterator = ((DisjunctionMaxQuery) query).Iterator(); iterator.MoveNext(); )
{
QueryToSpanQuery((Query) iterator.Current, payloads);
}
}
else if (query is MultiPhraseQuery)
{
MultiPhraseQuery mpq = (MultiPhraseQuery) query;
System.Collections.IList termArrays = mpq.GetTermArrays();
int[] positions = mpq.GetPositions();
if (positions.Length > 0)
{
int maxPosition = positions[positions.Length - 1];
for (int i = 0; i < positions.Length - 1; ++i)
{
if (positions[i] > maxPosition)
{
maxPosition = positions[i];
}
}
System.Collections.ArrayList[] disjunctLists = new System.Collections.ArrayList[maxPosition + 1];
int distinctPositions = 0;
for (int i = 0; i < termArrays.Count; ++i)
{
Term[] termArray = (Term[]) termArrays[i];
System.Collections.IList disjuncts = disjunctLists[positions[i]];
if (disjuncts == null)
{
disjuncts = (disjunctLists[positions[i]] = new System.Collections.ArrayList(termArray.Length));
++distinctPositions;
}
for (int j = 0; j < termArray.Length; ++j)
{
disjuncts.Add(new SpanTermQuery(termArray[j]));
}
}
int positionGaps = 0;
int position = 0;
SpanQuery[] clauses = new SpanQuery[distinctPositions];
for (int i = 0; i < disjunctLists.Length; ++i)
{
System.Collections.ArrayList disjuncts = disjunctLists[i];
if (disjuncts != null)
{
clauses[position++] = new SpanOrQuery((SpanQuery[]) (disjuncts.ToArray(typeof(SpanQuery[]))));
}
else
{
++positionGaps;
}
}
int slop = mpq.GetSlop();
bool inorder = (slop == 0);
SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, inorder);
sp.SetBoost(query.GetBoost());
GetPayloads(payloads, sp);
}
}
}
private void GetPayloads(ICollection<byte[]> payloads, SpanQuery query)
{
Lucene.Net.Search.Spans.Spans spans = query.GetSpans(reader);
while (spans.Next() == true)
{
if (spans.IsPayloadAvailable())
{
//ICollection<byte[]> payload = spans.GetPayload();
System.Collections.Generic.ICollection<byte[]> payload = spans.GetPayload();
//IEnumerator<byte[]> it = payload.GetEnumerator();
foreach (byte[] bytes in payload)
{
payloads.Add(bytes);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
protected SocketAsyncEventArgs _userArgs;
protected SocketAsyncEventArgs _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
protected abstract Socket UserSocket { get; }
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = DnsAPMExtensions.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = DnsAPMExtensions.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
_internalArgs.SetBuffer(_userArgs.Buffer, _userArgs.Offset, _userArgs.Count);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is ObjectDisposedException)
{
NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
}
private static Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
if (!attemptSocket.ConnectAsync(args))
{
return new SocketException((int)args.SocketError);
}
}
catch (ObjectDisposedException)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
throw e;
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.FinishOperationAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket;
private bool _userSocket;
protected override Socket UserSocket => _socket;
public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket4;
private Socket _socket6;
protected override Socket UserSocket => null;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
if (_socket4 != null)
{
_socket4.Dispose();
}
if (_socket6 != null)
{
_socket6.Dispose();
}
}
}
internal sealed class MultipleSocketMultipleConnectAsync : MultipleConnectAsync
{
private readonly SocketType _socketType;
private readonly ProtocolType _protocolType;
private readonly bool _supportsIPv4;
private readonly bool _supportsIPv6;
protected override Socket UserSocket => null;
public MultipleSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
_socketType = socketType;
_protocolType = protocolType;
_supportsIPv4 = Socket.OSSupportsIPv4;
_supportsIPv6 = Socket.OSSupportsIPv6;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
if (_supportsIPv4 || _supportsIPv6)
{
while (_nextAddress < _addressList.Length)
{
IPAddress rval = _addressList[_nextAddress];
++_nextAddress;
if (_supportsIPv6 && rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = new Socket(AddressFamily.InterNetworkV6, _socketType, _protocolType);
return rval;
}
else if (_supportsIPv4 && rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = new Socket(AddressFamily.InterNetwork, _socketType, _protocolType);
return rval;
}
}
}
attemptSocket = null;
return null;
}
// nothing to do on failure
protected override void OnFail(bool abortive) { }
// nothing to do on success
protected override void OnSucceed() { }
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.ds
{
public class EnumValueMap<K, V> : global::haxe.ds.BalancedTree<K, V>, global::haxe.ds.EnumValueMap, global::IMap<K, V>
{
public EnumValueMap(global::haxe.lang.EmptyObject empty) : base(global::haxe.lang.EmptyObject.EMPTY)
{
unchecked
{
}
#line default
}
public EnumValueMap() : base(global::haxe.lang.EmptyObject.EMPTY)
{
unchecked
{
#line 41 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/BalancedTree.hx"
global::haxe.ds.EnumValueMap<object, object>.__hx_ctor_haxe_ds_EnumValueMap<K, V>(this);
}
#line default
}
public static void __hx_ctor_haxe_ds_EnumValueMap<K_c, V_c>(global::haxe.ds.EnumValueMap<K_c, V_c> __temp_me32)
{
unchecked
{
#line 41 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/BalancedTree.hx"
global::haxe.ds.BalancedTree<object, object>.__hx_ctor_haxe_ds_BalancedTree<K_c, V_c>(__temp_me32);
}
#line default
}
public static new object __hx_cast<K_c_c, V_c_c>(global::haxe.ds.EnumValueMap me)
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return ( (( me != default(global::haxe.ds.EnumValueMap) )) ? (me.haxe_ds_EnumValueMap_cast<K_c_c, V_c_c>()) : (default(global::haxe.ds.EnumValueMap)) );
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return new global::haxe.ds.EnumValueMap<object, object>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return new global::haxe.ds.EnumValueMap<object, object>();
}
#line default
}
public virtual object haxe_ds_EnumValueMap_cast<K_c, V_c>()
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
if (( global::haxe.lang.Runtime.eq(typeof(K), typeof(K_c)) && global::haxe.lang.Runtime.eq(typeof(V), typeof(V_c)) ))
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return this;
}
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
global::haxe.ds.EnumValueMap<K_c, V_c> new_me = new global::haxe.ds.EnumValueMap<K_c, V_c>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
object __temp_iterator149 = global::Reflect.fields(this).iterator();
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator149, "hasNext", 407283053, default(global::Array))) ))
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
string field = global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.callField(__temp_iterator149, "next", 1224901875, default(global::Array)));
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
switch (field)
{
default:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
global::Reflect.setField(new_me, field, ((object) (global::Reflect.field(this, field)) ));
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
break;
}
}
}
}
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return new_me;
}
#line default
}
public virtual object IMap_cast<K_c, V_c>()
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return this.haxe_ds_EnumValueMap_cast<K_c, V_c>();
}
#line default
}
public virtual object haxe_ds_BalancedTree_cast<K_c, V_c>()
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return this.haxe_ds_EnumValueMap_cast<K_c, V_c>();
}
#line default
}
public override int compare(K __temp_k133, K __temp_k234)
{
unchecked
{
#line 33 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
object k2 = ((object) (__temp_k234) );
#line 33 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
object k1 = ((object) (__temp_k133) );
int d = ( global::Type.enumIndex(k1) - global::Type.enumIndex(k2) );
if (( d != 0 ))
{
#line 35 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return d;
}
global::Array p1 = global::Type.enumParameters(k1);
global::Array p2 = global::Type.enumParameters(k2);
if (( ( ((int) (global::haxe.lang.Runtime.getField_f(p1, "length", 520590566, true)) ) == 0 ) && ( ((int) (global::haxe.lang.Runtime.getField_f(p2, "length", 520590566, true)) ) == 0 ) ))
{
#line 38 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return 0;
}
return this.compareArgs(p1, p2);
}
#line default
}
public virtual int compareArgs(global::Array a1, global::Array a2)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
int ld = ( ((int) (global::haxe.lang.Runtime.getField_f(a1, "length", 520590566, true)) ) - ((int) (global::haxe.lang.Runtime.getField_f(a2, "length", 520590566, true)) ) );
if (( ld != 0 ))
{
#line 44 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return ld;
}
{
#line 45 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
int _g1 = 0;
#line 45 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
int _g = ((int) (global::haxe.lang.Runtime.getField_f(a1, "length", 520590566, true)) );
#line 45 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
while (( _g1 < _g ))
{
#line 45 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
int i = _g1++;
int d = this.compareArg(a1[i], a2[i]);
if (( d != 0 ))
{
#line 47 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return d;
}
}
}
#line 49 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return 0;
}
#line default
}
public virtual int compareArg(object v1, object v2)
{
unchecked
{
#line 53 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
if (( global::Reflect.isEnumValue(v1) && global::Reflect.isEnumValue(v2) ))
{
return this.compare(global::haxe.lang.Runtime.genericCast<K>(v1), global::haxe.lang.Runtime.genericCast<K>(v2));
}
else
{
if (( ( v1 is global::Array ) && ( v2 is global::Array ) ))
{
return this.compareArgs(((global::Array) (v1) ), ((global::Array) (v2) ));
}
else
{
#line 58 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return global::Reflect.compare<object>(v1, v2);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
switch (hash)
{
case 244830897:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("compareArg"), ((int) (244830897) ))) );
}
case 910198946:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("compareArgs"), ((int) (910198946) ))) );
}
case 57219237:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("compare"), ((int) (57219237) ))) );
}
default:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
switch (hash)
{
case 57219237:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return global::haxe.lang.Runtime.slowCallField(this, field, dynargs);
}
case 244830897:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return this.compareArg(dynargs[0], dynargs[1]);
}
case 910198946:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return this.compareArgs(((global::Array) (dynargs[0]) ), ((global::Array) (dynargs[1]) ));
}
default:
{
#line 31 "C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.ds
{
public interface EnumValueMap : global::haxe.lang.IHxObject, global::haxe.ds.BalancedTree, global::haxe.lang.IGenericObject
{
object haxe_ds_EnumValueMap_cast<K_c, V_c>();
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Development;
using osu.Framework.Input.Bindings;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Input.Bindings;
using osu.Game.Models;
using osu.Game.Rulesets;
using osu.Game.Scoring;
using osu.Game.Skinning;
using osu.Game.Stores;
using Realms;
using Realms.Exceptions;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// A factory which provides safe access to the realm storage backend.
/// </summary>
public class RealmAccess : IDisposable
{
private readonly Storage storage;
/// <summary>
/// The filename of this realm.
/// </summary>
public readonly string Filename;
private readonly IDatabaseContextFactory? efContextFactory;
/// <summary>
/// Version history:
/// 6 ~2021-10-18 First tracked version.
/// 7 2021-10-18 Changed OnlineID fields to non-nullable to add indexing support.
/// 8 2021-10-29 Rebind scroll adjust keys to not have control modifier.
/// 9 2021-11-04 Converted BeatmapMetadata.Author from string to RealmUser.
/// 10 2021-11-22 Use ShortName instead of RulesetID for ruleset settings.
/// 11 2021-11-22 Use ShortName instead of RulesetID for ruleset key bindings.
/// 12 2021-11-24 Add Status to RealmBeatmapSet.
/// 13 2022-01-13 Final migration of beatmaps and scores to realm (multiple new storage fields).
/// 14 2022-03-01 Added BeatmapUserSettings to BeatmapInfo.
/// </summary>
private const int schema_version = 14;
/// <summary>
/// Lock object which is held during <see cref="BlockAllOperations"/> sections, blocking realm retrieval during blocking periods.
/// </summary>
private readonly SemaphoreSlim realmRetrievalLock = new SemaphoreSlim(1);
private readonly ThreadLocal<bool> currentThreadCanCreateRealmInstances = new ThreadLocal<bool>();
/// <summary>
/// Holds a map of functions registered via <see cref="RegisterCustomSubscription"/> and <see cref="RegisterForNotifications{T}"/> and a coinciding action which when triggered,
/// will unregister the subscription from realm.
///
/// Put another way, the key is an action which registers the subscription with realm. The returned <see cref="IDisposable"/> from the action is stored as the value and only
/// used internally.
///
/// Entries in this dictionary are only removed when a consumer signals that the subscription should be permanently ceased (via their own <see cref="IDisposable"/>).
/// </summary>
private readonly Dictionary<Func<Realm, IDisposable?>, IDisposable?> customSubscriptionsResetMap = new Dictionary<Func<Realm, IDisposable?>, IDisposable?>();
/// <summary>
/// Holds a map of functions registered via <see cref="RegisterForNotifications{T}"/> and a coinciding action which when triggered,
/// fires a change set event with an empty collection. This is used to inform subscribers when the main realm instance gets recycled, and ensure they don't use invalidated
/// managed realm objects from a previous firing.
/// </summary>
private readonly Dictionary<Func<Realm, IDisposable?>, Action> notificationsResetMap = new Dictionary<Func<Realm, IDisposable?>, Action>();
private static readonly GlobalStatistic<int> realm_instances_created = GlobalStatistics.Get<int>(@"Realm", @"Instances (Created)");
private static readonly GlobalStatistic<int> total_subscriptions = GlobalStatistics.Get<int>(@"Realm", @"Subscriptions");
private static readonly GlobalStatistic<int> total_reads_update = GlobalStatistics.Get<int>(@"Realm", @"Reads (Update)");
private static readonly GlobalStatistic<int> total_reads_async = GlobalStatistics.Get<int>(@"Realm", @"Reads (Async)");
private static readonly GlobalStatistic<int> total_writes_update = GlobalStatistics.Get<int>(@"Realm", @"Writes (Update)");
private static readonly GlobalStatistic<int> total_writes_async = GlobalStatistics.Get<int>(@"Realm", @"Writes (Async)");
private readonly object realmLock = new object();
private Realm? updateRealm;
private bool isSendingNotificationResetEvents;
public Realm Realm => ensureUpdateRealm();
private const string realm_extension = @".realm";
private Realm ensureUpdateRealm()
{
if (isSendingNotificationResetEvents)
throw new InvalidOperationException("Cannot retrieve a realm context from a notification callback during a blocking operation.");
if (!ThreadSafety.IsUpdateThread)
throw new InvalidOperationException(@$"Use {nameof(getRealmInstance)} when performing realm operations from a non-update thread");
lock (realmLock)
{
if (updateRealm == null)
{
updateRealm = getRealmInstance();
Logger.Log(@$"Opened realm ""{updateRealm.Config.DatabasePath}"" at version {updateRealm.Config.SchemaVersion}");
// Resubscribe any subscriptions
foreach (var action in customSubscriptionsResetMap.Keys)
registerSubscription(action);
}
Debug.Assert(updateRealm != null);
return updateRealm;
}
}
internal static bool CurrentThreadSubscriptionsAllowed => current_thread_subscriptions_allowed.Value;
private static readonly ThreadLocal<bool> current_thread_subscriptions_allowed = new ThreadLocal<bool>();
/// <summary>
/// Construct a new instance.
/// </summary>
/// <param name="storage">The game storage which will be used to create the realm backing file.</param>
/// <param name="filename">The filename to use for the realm backing file. A ".realm" extension will be added automatically if not specified.</param>
/// <param name="efContextFactory">An EF factory used only for migration purposes.</param>
public RealmAccess(Storage storage, string filename, IDatabaseContextFactory? efContextFactory = null)
{
this.storage = storage;
this.efContextFactory = efContextFactory;
Filename = filename;
if (!Filename.EndsWith(realm_extension, StringComparison.Ordinal))
Filename += realm_extension;
string newerVersionFilename = $"{Filename.Replace(realm_extension, string.Empty)}_newer_version{realm_extension}";
// Attempt to recover a newer database version if available.
if (storage.Exists(newerVersionFilename))
{
Logger.Log(@"A newer realm database has been found, attempting recovery...", LoggingTarget.Database);
attemptRecoverFromFile(newerVersionFilename);
}
try
{
// This method triggers the first `getRealmInstance` call, which will implicitly run realm migrations and bring the schema up-to-date.
cleanupPendingDeletions();
}
catch (Exception e)
{
// See https://github.com/realm/realm-core/blob/master/src%2Frealm%2Fobject-store%2Fobject_store.cpp#L1016-L1022
// This is the best way we can detect a schema version downgrade.
if (e.Message.StartsWith(@"Provided schema version", StringComparison.Ordinal))
{
Logger.Error(e, "Your local database is too new to work with this version of osu!. Please close osu! and install the latest release to recover your data.");
// If a newer version database already exists, don't backup again. We can presume that the first backup is the one we care about.
if (!storage.Exists(newerVersionFilename))
CreateBackup(newerVersionFilename);
storage.Delete(Filename);
}
else
{
Logger.Error(e, "Realm startup failed with unrecoverable error; starting with a fresh database. A backup of your database has been made.");
CreateBackup($"{Filename.Replace(realm_extension, string.Empty)}_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_corrupt{realm_extension}");
storage.Delete(Filename);
}
cleanupPendingDeletions();
}
}
private void attemptRecoverFromFile(string recoveryFilename)
{
Logger.Log($@"Performing recovery from {recoveryFilename}", LoggingTarget.Database);
// First check the user hasn't started to use the database that is in place..
try
{
using (var realm = Realm.GetInstance(getConfiguration()))
{
if (realm.All<ScoreInfo>().Any())
{
Logger.Log(@"Recovery aborted as the existing database has scores set already.", LoggingTarget.Database);
Logger.Log(@"To perform recovery, delete client.realm while osu! is not running.", LoggingTarget.Database);
return;
}
}
}
catch
{
// Even if reading the in place database fails, still attempt to recover.
}
// Then check that the database we are about to attempt recovery can actually be recovered on this version..
try
{
using (Realm.GetInstance(getConfiguration(recoveryFilename)))
{
// Don't need to do anything, just check that opening the realm works correctly.
}
}
catch
{
Logger.Log(@"Recovery aborted as the newer version could not be loaded by this osu! version.", LoggingTarget.Database);
return;
}
// For extra safety, also store the temporarily-used database which we are about to replace.
CreateBackup($"{Filename.Replace(realm_extension, string.Empty)}_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_newer_version_before_recovery{realm_extension}");
storage.Delete(Filename);
using (var inputStream = storage.GetStream(recoveryFilename))
using (var outputStream = storage.GetStream(Filename, FileAccess.Write, FileMode.Create))
inputStream.CopyTo(outputStream);
storage.Delete(recoveryFilename);
Logger.Log(@"Recovery complete!", LoggingTarget.Database);
}
private void cleanupPendingDeletions()
{
using (var realm = getRealmInstance())
using (var transaction = realm.BeginWrite())
{
var pendingDeleteScores = realm.All<ScoreInfo>().Where(s => s.DeletePending);
foreach (var score in pendingDeleteScores)
realm.Remove(score);
var pendingDeleteSets = realm.All<BeatmapSetInfo>().Where(s => s.DeletePending);
foreach (var beatmapSet in pendingDeleteSets)
{
foreach (var beatmap in beatmapSet.Beatmaps)
{
// Cascade delete related scores, else they will have a null beatmap against the model's spec.
foreach (var score in beatmap.Scores)
realm.Remove(score);
realm.Remove(beatmap.Metadata);
realm.Remove(beatmap);
}
realm.Remove(beatmapSet);
}
var pendingDeleteSkins = realm.All<SkinInfo>().Where(s => s.DeletePending);
foreach (var s in pendingDeleteSkins)
realm.Remove(s);
transaction.Commit();
}
// clean up files after dropping any pending deletions.
// in the future we may want to only do this when the game is idle, rather than on every startup.
new RealmFileStore(this, storage).Cleanup();
}
/// <summary>
/// Compact this realm.
/// </summary>
/// <returns></returns>
public bool Compact() => Realm.Compact(getConfiguration());
/// <summary>
/// Run work on realm with a return value.
/// </summary>
/// <param name="action">The work to run.</param>
/// <typeparam name="T">The return type.</typeparam>
public T Run<T>(Func<Realm, T> action)
{
if (ThreadSafety.IsUpdateThread)
{
total_reads_update.Value++;
return action(Realm);
}
total_reads_async.Value++;
using (var realm = getRealmInstance())
return action(realm);
}
/// <summary>
/// Run work on realm.
/// </summary>
/// <param name="action">The work to run.</param>
public void Run(Action<Realm> action)
{
if (ThreadSafety.IsUpdateThread)
{
total_reads_update.Value++;
action(Realm);
}
else
{
total_reads_async.Value++;
using (var realm = getRealmInstance())
action(realm);
}
}
/// <summary>
/// Write changes to realm.
/// </summary>
/// <param name="action">The work to run.</param>
public void Write(Action<Realm> action)
{
if (ThreadSafety.IsUpdateThread)
{
total_writes_update.Value++;
Realm.Write(action);
}
else
{
total_writes_async.Value++;
using (var realm = getRealmInstance())
realm.Write(action);
}
}
/// <summary>
/// Write changes to realm asynchronously, guaranteeing order of execution.
/// </summary>
/// <param name="action">The work to run.</param>
public async Task WriteAsync(Action<Realm> action)
{
total_writes_async.Value++;
using (var realm = getRealmInstance())
await realm.WriteAsync(action);
}
/// <summary>
/// Subscribe to a realm collection and begin watching for asynchronous changes.
/// </summary>
/// <remarks>
/// This adds osu! specific thread and managed state safety checks on top of <see cref="IRealmCollection{T}.SubscribeForNotifications"/>.
///
/// In addition to the documented realm behaviour, we have the additional requirement of handling subscriptions over potential realm instance recycle.
/// When this happens, callback events will be automatically fired:
/// - On recycle start, a callback with an empty collection and <c>null</c> <see cref="ChangeSet"/> will be invoked.
/// - On recycle end, a standard initial realm callback will arrive, with <c>null</c> <see cref="ChangeSet"/> and an up-to-date collection.
/// </remarks>
/// <param name="query">The <see cref="IQueryable{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the list.</typeparam>
/// <param name="callback">The callback to be invoked with the updated <see cref="IRealmCollection{T}"/>.</param>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
public IDisposable RegisterForNotifications<T>(Func<Realm, IQueryable<T>> query, NotificationCallbackDelegate<T> callback)
where T : RealmObjectBase
{
if (!ThreadSafety.IsUpdateThread)
throw new InvalidOperationException(@$"{nameof(RegisterForNotifications)} must be called from the update thread.");
lock (realmLock)
{
Func<Realm, IDisposable?> action = realm => query(realm).QueryAsyncWithNotifications(callback);
// Store an action which is used when blocking to ensure consumers don't use results of a stale changeset firing.
notificationsResetMap.Add(action, () => callback(new EmptyRealmSet<T>(), null, null));
return RegisterCustomSubscription(action);
}
}
/// <summary>
/// Subscribe to the property of a realm object to watch for changes.
/// </summary>
/// <remarks>
/// On subscribing, unless the <paramref name="modelAccessor"/> does not match an object, an initial invocation of <paramref name="onChanged"/> will occur immediately.
/// Further invocations will occur when the value changes, but may also fire on a realm recycle with no actual value change.
/// </remarks>
/// <param name="modelAccessor">A function to retrieve the relevant model from realm.</param>
/// <param name="propertyLookup">A function to traverse to the relevant property from the model.</param>
/// <param name="onChanged">A function to be invoked when a change of value occurs.</param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property to be watched.</typeparam>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
public IDisposable SubscribeToPropertyChanged<TModel, TProperty>(Func<Realm, TModel?> modelAccessor, Expression<Func<TModel, TProperty>> propertyLookup, Action<TProperty> onChanged)
where TModel : RealmObjectBase
{
return RegisterCustomSubscription(r =>
{
string propertyName = getMemberName(propertyLookup);
var model = Run(modelAccessor);
var propLookupCompiled = propertyLookup.Compile();
if (model == null)
return null;
model.PropertyChanged += onPropertyChanged;
// Update initial value immediately.
onChanged(propLookupCompiled(model));
return new InvokeOnDisposal(() => model.PropertyChanged -= onPropertyChanged);
void onPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == propertyName)
onChanged(propLookupCompiled(model));
}
});
static string getMemberName(Expression<Func<TModel, TProperty>> expression)
{
if (!(expression is LambdaExpression lambda))
throw new ArgumentException("Outermost expression must be a lambda expression", nameof(expression));
if (!(lambda.Body is MemberExpression memberExpression))
throw new ArgumentException("Lambda body must be a member access expression", nameof(expression));
// TODO: nested access can be supported, with more iteration here
// (need to iteratively soft-cast `memberExpression.Expression` into `MemberExpression`s until `lambda.Parameters[0]` is hit)
if (memberExpression.Expression != lambda.Parameters[0])
throw new ArgumentException("Nested access expressions are not supported", nameof(expression));
return memberExpression.Member.Name;
}
}
/// <summary>
/// Run work on realm that will be run every time the update thread realm instance gets recycled.
/// </summary>
/// <param name="action">The work to run. Return value should be an <see cref="IDisposable"/> from QueryAsyncWithNotifications, or an <see cref="InvokeOnDisposal"/> to clean up any bindings.</param>
/// <returns>An <see cref="IDisposable"/> which should be disposed to unsubscribe any inner subscription.</returns>
public IDisposable RegisterCustomSubscription(Func<Realm, IDisposable?> action)
{
if (!ThreadSafety.IsUpdateThread)
throw new InvalidOperationException(@$"{nameof(RegisterForNotifications)} must be called from the update thread.");
var syncContext = SynchronizationContext.Current;
total_subscriptions.Value++;
registerSubscription(action);
// This token is returned to the consumer.
// When disposed, it will cause the registration to be permanently ceased (unsubscribed with realm and unregistered by this class).
return new InvokeOnDisposal(() =>
{
if (ThreadSafety.IsUpdateThread)
syncContext.Send(_ => unsubscribe(), null);
else
syncContext.Post(_ => unsubscribe(), null);
void unsubscribe()
{
lock (realmLock)
{
if (customSubscriptionsResetMap.TryGetValue(action, out var unsubscriptionAction))
{
unsubscriptionAction?.Dispose();
customSubscriptionsResetMap.Remove(action);
notificationsResetMap.Remove(action);
total_subscriptions.Value--;
}
}
}
});
}
private void registerSubscription(Func<Realm, IDisposable?> action)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
lock (realmLock)
{
// Retrieve realm instance outside of flag update to ensure that the instance is retrieved,
// as attempting to access it inside the subscription if it's not constructed would lead to
// cyclic invocations of the subscription callback.
var realm = Realm;
Debug.Assert(!customSubscriptionsResetMap.TryGetValue(action, out var found) || found == null);
current_thread_subscriptions_allowed.Value = true;
customSubscriptionsResetMap[action] = action(realm);
current_thread_subscriptions_allowed.Value = false;
}
}
private Realm getRealmInstance()
{
if (isDisposed)
throw new ObjectDisposedException(nameof(RealmAccess));
bool tookSemaphoreLock = false;
try
{
if (!currentThreadCanCreateRealmInstances.Value)
{
realmRetrievalLock.Wait();
currentThreadCanCreateRealmInstances.Value = true;
tookSemaphoreLock = true;
}
else
{
// the semaphore is used to handle blocking of all realm retrieval during certain periods.
// once the semaphore has been taken by this code section, it is safe to retrieve further realm instances on the same thread.
// this can happen if a realm subscription is active and triggers a callback which has user code that calls `Run`.
}
realm_instances_created.Value++;
return Realm.GetInstance(getConfiguration());
}
finally
{
if (tookSemaphoreLock)
{
realmRetrievalLock.Release();
currentThreadCanCreateRealmInstances.Value = false;
}
}
}
private RealmConfiguration getConfiguration(string? filename = null)
{
// This is currently the only usage of temporary files at the osu! side.
// If we use the temporary folder in more situations in the future, this should be moved to a higher level (helper method or OsuGameBase).
string tempPathLocation = Path.Combine(Path.GetTempPath(), @"lazer");
if (!Directory.Exists(tempPathLocation))
Directory.CreateDirectory(tempPathLocation);
return new RealmConfiguration(storage.GetFullPath(filename ?? Filename, true))
{
SchemaVersion = schema_version,
MigrationCallback = onMigration,
FallbackPipePath = tempPathLocation,
};
}
private void onMigration(Migration migration, ulong lastSchemaVersion)
{
for (ulong i = lastSchemaVersion + 1; i <= schema_version; i++)
applyMigrationsForVersion(migration, i);
}
private void applyMigrationsForVersion(Migration migration, ulong targetVersion)
{
switch (targetVersion)
{
case 7:
convertOnlineIDs<BeatmapInfo>();
convertOnlineIDs<BeatmapSetInfo>();
convertOnlineIDs<RulesetInfo>();
void convertOnlineIDs<T>() where T : RealmObject
{
string className = getMappedOrOriginalName(typeof(T));
// version was not bumped when the beatmap/ruleset models were added
// therefore we must manually check for their presence to avoid throwing on the `DynamicApi` calls.
if (!migration.OldRealm.Schema.TryFindObjectSchema(className, out _))
return;
var oldItems = migration.OldRealm.DynamicApi.All(className);
var newItems = migration.NewRealm.DynamicApi.All(className);
int itemCount = newItems.Count();
for (int i = 0; i < itemCount; i++)
{
dynamic? oldItem = oldItems.ElementAt(i);
dynamic? newItem = newItems.ElementAt(i);
long? nullableOnlineID = oldItem?.OnlineID;
newItem.OnlineID = (int)(nullableOnlineID ?? -1);
}
}
break;
case 8:
// Ctrl -/+ now adjusts UI scale so let's clear any bindings which overlap these combinations.
// New defaults will be populated by the key store afterwards.
var keyBindings = migration.NewRealm.All<RealmKeyBinding>();
var increaseSpeedBinding = keyBindings.FirstOrDefault(k => k.ActionInt == (int)GlobalAction.IncreaseScrollSpeed);
if (increaseSpeedBinding != null && increaseSpeedBinding.KeyCombination.Keys.SequenceEqual(new[] { InputKey.Control, InputKey.Plus }))
migration.NewRealm.Remove(increaseSpeedBinding);
var decreaseSpeedBinding = keyBindings.FirstOrDefault(k => k.ActionInt == (int)GlobalAction.DecreaseScrollSpeed);
if (decreaseSpeedBinding != null && decreaseSpeedBinding.KeyCombination.Keys.SequenceEqual(new[] { InputKey.Control, InputKey.Minus }))
migration.NewRealm.Remove(decreaseSpeedBinding);
break;
case 9:
// Pretty pointless to do this as beatmaps aren't really loaded via realm yet, but oh well.
string metadataClassName = getMappedOrOriginalName(typeof(BeatmapMetadata));
// May be coming from a version before `RealmBeatmapMetadata` existed.
if (!migration.OldRealm.Schema.TryFindObjectSchema(metadataClassName, out _))
return;
var oldMetadata = migration.OldRealm.DynamicApi.All(metadataClassName);
var newMetadata = migration.NewRealm.All<BeatmapMetadata>();
int metadataCount = newMetadata.Count();
for (int i = 0; i < metadataCount; i++)
{
dynamic? oldItem = oldMetadata.ElementAt(i);
var newItem = newMetadata.ElementAt(i);
string username = oldItem.Author;
newItem.Author = new RealmUser
{
Username = username
};
}
break;
case 10:
string rulesetSettingClassName = getMappedOrOriginalName(typeof(RealmRulesetSetting));
if (!migration.OldRealm.Schema.TryFindObjectSchema(rulesetSettingClassName, out _))
return;
var oldSettings = migration.OldRealm.DynamicApi.All(rulesetSettingClassName);
var newSettings = migration.NewRealm.All<RealmRulesetSetting>().ToList();
for (int i = 0; i < newSettings.Count; i++)
{
dynamic? oldItem = oldSettings.ElementAt(i);
var newItem = newSettings.ElementAt(i);
long rulesetId = oldItem.RulesetID;
string? rulesetName = getRulesetShortNameFromLegacyID(rulesetId);
if (string.IsNullOrEmpty(rulesetName))
migration.NewRealm.Remove(newItem);
else
newItem.RulesetName = rulesetName;
}
break;
case 11:
string keyBindingClassName = getMappedOrOriginalName(typeof(RealmKeyBinding));
if (!migration.OldRealm.Schema.TryFindObjectSchema(keyBindingClassName, out _))
return;
var oldKeyBindings = migration.OldRealm.DynamicApi.All(keyBindingClassName);
var newKeyBindings = migration.NewRealm.All<RealmKeyBinding>().ToList();
for (int i = 0; i < newKeyBindings.Count; i++)
{
dynamic? oldItem = oldKeyBindings.ElementAt(i);
var newItem = newKeyBindings.ElementAt(i);
if (oldItem.RulesetID == null)
continue;
long rulesetId = oldItem.RulesetID;
string? rulesetName = getRulesetShortNameFromLegacyID(rulesetId);
if (string.IsNullOrEmpty(rulesetName))
migration.NewRealm.Remove(newItem);
else
newItem.RulesetName = rulesetName;
}
break;
case 14:
foreach (var beatmap in migration.NewRealm.All<BeatmapInfo>())
beatmap.UserSettings = new BeatmapUserSettings();
break;
}
}
private string? getRulesetShortNameFromLegacyID(long rulesetId) =>
efContextFactory?.Get().RulesetInfo.FirstOrDefault(r => r.ID == rulesetId)?.ShortName;
public void CreateBackup(string backupFilename)
{
using (BlockAllOperations())
{
Logger.Log($"Creating full realm database backup at {backupFilename}", LoggingTarget.Database);
int attempts = 10;
while (attempts-- > 0)
{
try
{
using (var source = storage.GetStream(Filename))
using (var destination = storage.GetStream(backupFilename, FileAccess.Write, FileMode.CreateNew))
source.CopyTo(destination);
return;
}
catch (IOException)
{
// file may be locked during use.
Thread.Sleep(500);
}
}
}
}
/// <summary>
/// Flush any active realm instances and block any further writes.
/// </summary>
/// <remarks>
/// This should be used in places we need to ensure no ongoing reads/writes are occurring with realm.
/// ie. to move the realm backing file to a new location.
/// </remarks>
/// <returns>An <see cref="IDisposable"/> which should be disposed to end the blocking section.</returns>
public IDisposable BlockAllOperations()
{
if (isDisposed)
throw new ObjectDisposedException(nameof(RealmAccess));
SynchronizationContext? syncContext = null;
try
{
realmRetrievalLock.Wait();
lock (realmLock)
{
if (updateRealm == null)
{
// null realm means the update thread has not yet retrieved its instance.
// we don't need to worry about reviving the update instance in this case, so don't bother with the SynchronizationContext.
Debug.Assert(!ThreadSafety.IsUpdateThread);
}
else
{
if (!ThreadSafety.IsUpdateThread)
throw new InvalidOperationException(@$"{nameof(BlockAllOperations)} must be called from the update thread.");
syncContext = SynchronizationContext.Current;
// Before disposing the update context, clean up all subscriptions.
// Note that in the case of realm notification subscriptions, this is not really required (they will be cleaned up by disposal).
// In the case of custom subscriptions, we want them to fire before the update realm is disposed in case they do any follow-up work.
foreach (var action in customSubscriptionsResetMap)
{
action.Value?.Dispose();
customSubscriptionsResetMap[action.Key] = null;
}
}
Logger.Log(@"Blocking realm operations.", LoggingTarget.Database);
updateRealm?.Dispose();
updateRealm = null;
}
const int sleep_length = 200;
int timeout = 5000;
try
{
// see https://github.com/realm/realm-dotnet/discussions/2657
while (!Compact())
{
Thread.Sleep(sleep_length);
timeout -= sleep_length;
if (timeout < 0)
throw new TimeoutException(@"Took too long to acquire lock");
}
}
catch (RealmException e)
{
// Compact may fail if the realm is in a bad state.
// We still want to continue with the blocking operation, though.
Logger.Log($"Realm compact failed with error {e}", LoggingTarget.Database);
}
// In order to ensure events arrive in the correct order, these *must* be fired post disposal of the update realm,
// and must be posted to the synchronization context.
// This is because realm may fire event callbacks between the `unregisterAllSubscriptions` and `updateRealm.Dispose`
// calls above.
syncContext?.Send(_ =>
{
// Flag ensures that we don't get in a deadlocked scenario due to a callback attempting to access `RealmAccess.Realm` or `RealmAccess.Run`
// and hitting `realmRetrievalLock` a second time. Generally such usages should not exist, and as such we throw when an attempt is made
// to use in this fashion.
isSendingNotificationResetEvents = true;
try
{
foreach (var action in notificationsResetMap.Values)
action();
}
finally
{
isSendingNotificationResetEvents = false;
}
}, null);
}
catch
{
restoreOperation();
throw;
}
return new InvokeOnDisposal(restoreOperation);
void restoreOperation()
{
Logger.Log(@"Restoring realm operations.", LoggingTarget.Database);
realmRetrievalLock.Release();
// Post back to the update thread to revive any subscriptions.
// In the case we are on the update thread, let's also require this to run synchronously.
// This requirement is mostly due to test coverage, but shouldn't cause any harm.
if (ThreadSafety.IsUpdateThread)
syncContext?.Send(_ => ensureUpdateRealm(), null);
else
syncContext?.Post(_ => ensureUpdateRealm(), null);
}
}
// https://github.com/realm/realm-dotnet/blob/32f4ebcc88b3e80a3b254412665340cd9f3bd6b5/Realm/Realm/Extensions/ReflectionExtensions.cs#L46
private static string getMappedOrOriginalName(MemberInfo member) => member.GetCustomAttribute<MapToAttribute>()?.Mapping ?? member.Name;
private bool isDisposed;
public void Dispose()
{
lock (realmLock)
{
updateRealm?.Dispose();
}
if (!isDisposed)
{
// intentionally block realm retrieval indefinitely. this ensures that nothing can start consuming a new instance after disposal.
realmRetrievalLock.Wait();
realmRetrievalLock.Dispose();
isDisposed = true;
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TextEntry.xaml.cs" company="MADE Apps">
// Copyright (c) MADE Apps.
// </copyright>
// <summary>
// Defines a UI element representing a text entry with a header component.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MADE.App.Views
{
using System;
using MADE.App.Views.Extensions;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XPlat.UI.Controls;
/// <summary>
/// Defines a UI element representing a text entry with a header component.
/// </summary>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TextEntry : ContentView
{
/// <summary>
/// Defines the bindable property for the <see cref="Header"/> value.
/// </summary>
public static readonly BindableProperty HeaderProperty = BindableProperty.Create(
nameof(Header),
typeof(string),
typeof(TextEntry),
null,
propertyChanged: (bindable, valueChangedEventArgs, newValue) =>
{
var control = (TextEntry)bindable;
control.TextEntryHeader.Text = (string)newValue;
control.UpdateHeaderVisibility(!string.IsNullOrWhiteSpace(control.Header));
});
/// <summary>
/// Defines the bindable property for the <see cref="HeaderStyle"/> value.
/// </summary>
public static readonly BindableProperty HeaderStyleProperty = BindableProperty.Create(
nameof(HeaderStyle),
typeof(Style),
typeof(TextEntry),
default(Style),
propertyChanged: (bindable, value, newValue) =>
{
var control = (TextEntry)bindable;
control.TextEntryHeader.Style = (Style)newValue;
});
/// <summary>
/// Defines the bindable property for the <see cref="Text"/> value.
/// </summary>
public static readonly BindableProperty TextProperty = BindableProperty.Create(
nameof(Text),
typeof(string),
typeof(TextEntry),
null,
propertyChanged: (bindable, value, newValue) =>
{
var control = (TextEntry)bindable;
var text = (string)newValue;
if (control.TextEntryContent.Text != text)
{
control.TextEntryContent.Text = text;
}
});
/// <summary>
/// Defines the bindable property for the <see cref="TextStyle"/> value.
/// </summary>
public static readonly BindableProperty TextStyleProperty = BindableProperty.Create(
nameof(TextStyle),
typeof(Style),
typeof(TextEntry),
default(Style),
propertyChanged: (bindable, value, newValue) =>
{
var control = (TextEntry)bindable;
control.TextEntryContent.Style = (Style)newValue;
});
/// <summary>
/// Defines the bindable property for the <see cref="Orientation"/> value.
/// </summary>
public static readonly BindableProperty OrientationProperty = BindableProperty.Create(
nameof(Orientation),
typeof(Orientation),
typeof(TextEntry),
Orientation.Vertical,
propertyChanged: (bindable, value, newValue) =>
{
var control = (TextEntry)bindable;
control.UpdateOrientation();
});
/// <summary>
/// Defines the bindable property for the <see cref="IsHeaderVisible"/> value.
/// </summary>
public static readonly BindableProperty HeaderVisibleProperty = BindableProperty.Create(
nameof(IsHeaderVisible),
typeof(bool),
typeof(TextEntry),
true,
propertyChanged: (bindable, value, newValue) =>
{
var control = (TextEntry)bindable;
control.UpdateHeaderVisibility((bool)newValue);
});
/// <summary>
/// Defines the bindable property for the <see cref="TextBoxHeight"/> value.
/// </summary>
public static readonly BindableProperty TextBoxHeightProperty = BindableProperty.Create(
nameof(TextBoxHeight),
typeof(double),
typeof(TextEntry),
propertyChanged: (bindable, value, newValue) =>
{
var control = (TextEntry)bindable;
control.TextEntryContent.HeightRequest = (double)newValue;
});
/// <summary>
/// Initializes a new instance of the <see cref="TextEntry"/> class.
/// </summary>
public TextEntry()
{
this.InitializeComponent();
this.TextEntryContent.TextChanged += this.OnTextChanged;
}
public event EventHandler<TextChangedEventArgs> TextChanged;
/// <summary>
/// Gets or sets the string associated with the header.
/// </summary>
public string Header
{
get => (string)this.GetValue(HeaderProperty);
set => this.SetValue(HeaderProperty, value);
}
/// <summary>
/// Gets or sets the style associated with the header content.
/// </summary>
public Style HeaderStyle
{
get => (Style)this.GetValue(HeaderStyleProperty);
set => this.SetValue(HeaderStyleProperty, value);
}
/// <summary>
/// Gets or sets the string associated with the text.
/// </summary>
public string Text
{
get => (string)this.GetValue(TextProperty);
set => this.SetValue(TextProperty, value);
}
/// <summary>
/// Gets or sets the style associated with the text content.
/// </summary>
public Style TextStyle
{
get => (Style)this.GetValue(TextStyleProperty);
set => this.SetValue(TextStyleProperty, value);
}
/// <summary>
/// Gets or sets the orientation the header and text should layout as.
/// </summary>
public Orientation Orientation
{
get => (Orientation)this.GetValue(OrientationProperty);
set => this.SetValue(OrientationProperty, value);
}
/// <summary>
/// Gets or sets whether the header is visible.
/// </summary>
public bool IsHeaderVisible
{
get => (bool)this.GetValue(HeaderVisibleProperty);
set => this.SetValue(HeaderVisibleProperty, value);
}
/// <summary>
/// Gets or sets the height of the text box within the <see cref="TextEntry"/>
/// </summary>
public double TextBoxHeight
{
get => (double)this.GetValue(TextBoxHeightProperty);
set => this.SetValue(TextBoxHeightProperty, value);
}
/// <summary>
/// Updates the header for the control based on the value passed in.
/// </summary>
/// <param name="isVisible">
/// The value indicating whther the header should be visible.
/// </param>
public void UpdateHeaderVisibility(bool isVisible)
{
this.TextEntryHeader.SetVisible(isVisible);
}
/// <summary>
/// Updates the layout for the control based on the current <see cref="XPlat.UI.Controls.Orientation"/> value.
/// </summary>
public void UpdateOrientation()
{
this.TextEntryContainer.SetOrientation(this.Orientation);
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
this.Text = e.NewTextValue;
this.TextChanged?.Invoke(this, e);
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Static methods to serialize and deserialize scene objects to and from XML
/// </summary>
public class SceneXmlLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region old xml format
public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
if (fileName.StartsWith("http:") || File.Exists(fileName))
{
XmlTextReader reader = new XmlTextReader(fileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml);
if (newIDS)
{
obj.ResetIDs();
}
//if we want this to be a import method then we need new uuids for the object to avoid any clashes
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
}
}
else
{
throw new Exception("Could not open file " + fileName + " for reading");
}
}
public static void SavePrimsToXml(Scene scene, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
StreamWriter stream = new StreamWriter(file);
int primCount = 0;
stream.WriteLine("<scene>\n");
EntityBase[] entityList = scene.GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Close();
file.Close();
}
#endregion
#region XML2 serialization
// Called by archives (save oar)
public static string SaveGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
//return SceneObjectSerializer.ToXml2Format(grp);
using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, System.Text.Encoding.UTF8))
{
SceneObjectSerializer.SOGToXml2(writer, grp, options);
writer.Flush();
using (StreamReader reader = new StreamReader(mem))
{
mem.Seek(0, SeekOrigin.Begin);
return reader.ReadToEnd();
}
}
}
}
// Called by scene serializer (save xml2)
public static void SavePrimsToXml2(Scene scene, string fileName)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, fileName);
}
// Called by scene serializer (save xml2)
public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
m_log.InfoFormat(
"[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}",
primName, scene.RegionInfo.RegionName, fileName);
EntityBase[] entityList = scene.GetEntities();
List<EntityBase> primList = new List<EntityBase>();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (ent.Name == primName)
{
primList.Add(ent);
}
}
}
SavePrimListToXml2(primList.ToArray(), fileName);
}
// Called by REST Application plugin
public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, stream, min, max);
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
try
{
StreamWriter stream = new StreamWriter(file);
try
{
SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero);
}
finally
{
stream.Close();
}
}
finally
{
file.Close();
}
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
XmlTextWriter writer = new XmlTextWriter(stream);
int primCount = 0;
stream.WriteLine("<scene>\n");
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup g = (SceneObjectGroup)ent;
if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero))
{
Vector3 pos = g.RootPart.GetWorldPosition();
if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z)
continue;
if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z)
continue;
}
//stream.WriteLine(SceneObjectSerializer.ToXml2Format(g));
SceneObjectSerializer.SOGToXml2(writer, (SceneObjectGroup)ent, new Dictionary<string,object>());
stream.WriteLine();
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Flush();
}
#endregion
#region XML2 deserialization
public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
XmlTextReader reader = new XmlTextReader(new StringReader(xmlString));
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
// This is to deal with neighbouring regions that are still surrounding the group xml with the <scene>
// tag. It should be possible to remove the first part of this if statement once we go past 0.5.9 (or
// when some other changes forces all regions to upgrade).
// This might seem rather pointless since prim crossing from this revision to an earlier revision remains
// broken. But it isn't much work to accomodate the old format here.
if (rootNode.LocalName.Equals("scene"))
{
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
// There is only ever one prim. This oddity should be removeable post 0.5.9
//return SceneObjectSerializer.FromXml2Format(aPrimNode.OuterXml);
using (reader = new XmlTextReader(new StringReader(aPrimNode.OuterXml)))
{
SceneObjectGroup obj = new SceneObjectGroup();
if (SceneObjectSerializer.Xml2ToSOG(reader, obj))
return obj;
return null;
}
}
return null;
}
else
{
//return SceneObjectSerializer.FromXml2Format(rootNode.OuterXml);
using (reader = new XmlTextReader(new StringReader(rootNode.OuterXml)))
{
SceneObjectGroup obj = new SceneObjectGroup();
if (SceneObjectSerializer.Xml2ToSOG(reader, obj))
return obj;
return null;
}
}
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="fileName"></param>
public static void LoadPrimsFromXml2(Scene scene, string fileName)
{
LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts);
}
/// <summary>
/// Load prims from the xml2 format. This method will close the reader
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts)
{
XmlDocument doc = new XmlDocument();
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
XmlNode rootNode = doc.FirstChild;
ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = CreatePrimFromXml2(scene, aPrimNode.OuterXml);
if (obj != null && startScripts)
sceneObjects.Add(obj);
}
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
/// <summary>
/// Create a prim from the xml2 representation.
/// </summary>
/// <param name="scene"></param>
/// <param name="xmlData"></param>
/// <returns>The scene object created. null if the scene object already existed</returns>
protected static SceneObjectGroup CreatePrimFromXml2(Scene scene, string xmlData)
{
//SceneObjectGroup obj = SceneObjectSerializer.FromXml2Format(xmlData);
using (XmlTextReader reader = new XmlTextReader(new StringReader(xmlData)))
{
SceneObjectGroup obj = new SceneObjectGroup();
SceneObjectSerializer.Xml2ToSOG(reader, obj);
if (scene.AddRestoredSceneObject(obj, true, false))
return obj;
else
return null;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Network.Fluent
{
using Microsoft.Azure.Management.Network.Fluent.PCFilter.Definition;
using Microsoft.Azure.Management.Network.Fluent.PacketCapture.Definition;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent.HasProtocol.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using System.Collections.Generic;
internal partial class PCFilterImpl
{
/// <summary>
/// Gets local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPCFilter.LocalIPAddress
{
get
{
return this.LocalIPAddress();
}
}
/// <summary>
/// Gets remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPCFilter.RemotePort
{
get
{
return this.RemotePort();
}
}
/// <summary>
/// Gets protocol to be filtered on.
/// </summary>
Models.PcProtocol Microsoft.Azure.Management.Network.Fluent.IPCFilter.Protocol
{
get
{
return this.Protocol();
}
}
/// <summary>
/// Gets remote IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPCFilter.RemoteIPAddress
{
get
{
return this.RemoteIPAddress();
}
}
/// <summary>
/// Gets local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPCFilter.LocalPort
{
get
{
return this.LocalPort();
}
}
/// <summary>
/// Specifies the transport protocol.
/// </summary>
/// <param name="protocol">A transport protocol.</param>
/// <return>The next stage of the definition.</return>
PCFilter.Definition.IWithAttach<PacketCapture.Definition.IWithCreate> HasProtocol.Definition.IWithProtocol<PCFilter.Definition.IWithAttach<PacketCapture.Definition.IWithCreate>, Models.PcProtocol>.WithProtocol(PcProtocol protocol)
{
return this.WithProtocol(protocol);
}
/// <summary>
/// Gets the parent of this child object.
/// </summary>
Microsoft.Azure.Management.Network.Fluent.IPacketCapture Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasParent<Microsoft.Azure.Management.Network.Fluent.IPacketCapture>.Parent
{
get
{
return this.Parent();
}
}
/// <summary>
/// Set the list of remote ports to be filtered on.
/// </summary>
/// <param name="ports">List of remote ports.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithRemotePort<PacketCapture.Definition.IWithCreate>.WithRemotePorts(IList<int> ports)
{
return this.WithRemotePorts(ports);
}
/// <summary>
/// Set the remote port to be filtered on.
/// </summary>
/// <param name="port">Port number.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithRemotePort<PacketCapture.Definition.IWithCreate>.WithRemotePort(int port)
{
return this.WithRemotePort(port);
}
/// <summary>
/// Set the remote port range to be filtered on.
/// </summary>
/// <param name="startPort">Range start port number.</param>
/// <param name="endPort">Range end port number.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithRemotePort<PacketCapture.Definition.IWithCreate>.WithRemotePortRange(int startPort, int endPort)
{
return this.WithRemotePortRange(startPort, endPort);
}
/// <summary>
/// Set remote IP addresses range to be filtered on.
/// </summary>
/// <param name="startIPAddress">Range start IP address.</param>
/// <param name="endIPAddress">Range end IP address.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithRemoteIPAddress<PacketCapture.Definition.IWithCreate>.WithRemoteIPAddressesRange(string startIPAddress, string endIPAddress)
{
return this.WithRemoteIPAddressesRange(startIPAddress, endIPAddress);
}
/// <summary>
/// Set list of remote IP addresses to be filtered on.
/// </summary>
/// <param name="ipAddresses">List of IP addresses.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithRemoteIPAddress<PacketCapture.Definition.IWithCreate>.WithRemoteIPAddresses(IList<string> ipAddresses)
{
return this.WithRemoteIPAddresses(ipAddresses);
}
/// <summary>
/// Set remote IP address to be filtered on.
/// </summary>
/// <param name="ipAddress">Remote IP address.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithRemoteIPAddress<PacketCapture.Definition.IWithCreate>.WithRemoteIPAddress(string ipAddress)
{
return this.WithRemoteIPAddress(ipAddress);
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
PacketCapture.Definition.IWithCreate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<PacketCapture.Definition.IWithCreate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Set the local port range to be filtered on.
/// </summary>
/// <param name="startPort">Range start port number.</param>
/// <param name="endPort">Range end port number.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithLocalPort<PacketCapture.Definition.IWithCreate>.WithLocalPortRange(int startPort, int endPort)
{
return this.WithLocalPortRange(startPort, endPort);
}
/// <summary>
/// Set the list of local ports to be filtered on.
/// </summary>
/// <param name="ports">List of local ports.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithLocalPort<PacketCapture.Definition.IWithCreate>.WithLocalPorts(IList<int> ports)
{
return this.WithLocalPorts(ports);
}
/// <summary>
/// Set the local port to be filtered on.
/// </summary>
/// <param name="port">Port number.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithLocalPort<PacketCapture.Definition.IWithCreate>.WithLocalPort(int port)
{
return this.WithLocalPort(port);
}
/// <summary>
/// Set local IP addresses range to be filtered on.
/// </summary>
/// <param name="startIPAddress">Range start IP address.</param>
/// <param name="endIPAddress">Range end IP address.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithLocalIP<PacketCapture.Definition.IWithCreate>.WithLocalIPAddressesRange(string startIPAddress, string endIPAddress)
{
return this.WithLocalIPAddressesRange(startIPAddress, endIPAddress);
}
/// <summary>
/// Set list of local IP addresses to be filtered on.
/// </summary>
/// <param name="ipAddresses">List of IP address.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithLocalIP<PacketCapture.Definition.IWithCreate>.WithLocalIPAddresses(IList<string> ipAddresses)
{
return this.WithLocalIPAddresses(ipAddresses);
}
/// <summary>
/// Set local IP address to be filtered on.
/// </summary>
/// <param name="ipAddress">Local IP address.</param>
/// <return>The next stage.</return>
PCFilter.Definition.IDefinition<PacketCapture.Definition.IWithCreate> PCFilter.Definition.IWithLocalIP<PacketCapture.Definition.IWithCreate>.WithLocalIPAddress(string ipAddress)
{
return this.WithLocalIPAddress(ipAddress);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace Aurora.Framework
{
public interface IHandle
{
}
[Serializable, ComVisible(false)]
public class MinHeap<T> : ICollection<T>, ICollection
{
public const int DEFAULT_CAPACITY = 4;
private readonly Comparison<T> comparison;
private HeapItem[] items;
private int size;
private object sync_root;
private int version;
public MinHeap() : this(DEFAULT_CAPACITY, Comparer<T>.Default)
{
}
public MinHeap(int capacity) : this(capacity, Comparer<T>.Default)
{
}
public MinHeap(IComparer<T> comparer) : this(DEFAULT_CAPACITY, comparer)
{
}
public MinHeap(int capacity, IComparer<T> comparer) :
this(capacity, comparer.Compare)
{
}
public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison)
{
}
public MinHeap(int capacity, Comparison<T> comparison)
{
this.items = new HeapItem[capacity];
this.comparison = comparison;
this.size = this.version = 0;
}
public T this[IHandle key]
{
get
{
Handle handle = ValidateThisHandle(key);
return this.items[handle.index].value;
}
set
{
Handle handle = ValidateThisHandle(key);
this.items[handle.index].value = value;
if (!BubbleUp(handle.index))
BubbleDown(handle.index);
}
}
#region ICollection Members
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get
{
if (this.sync_root == null)
Interlocked.CompareExchange<object>(ref this.sync_root, new object(), null);
return this.sync_root;
}
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException("Multidimensional array not supported");
if (array.GetLowerBound(0) != 0)
throw new ArgumentException("Non-zero lower bound array not supported");
int length = array.Length;
if ((index < 0) || (index > length))
throw new ArgumentOutOfRangeException("index");
if ((length - index) < this.size)
throw new ArgumentException("Not enough space available in array starting at index");
try
{
for (int i = 0; i < this.size; ++i)
array.SetValue(this.items[i].value, index + i);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException("Invalid array type");
}
}
#endregion
#region ICollection<T> Members
public int Count
{
get { return this.size; }
}
public bool IsReadOnly
{
get { return false; }
}
public void Add(T value)
{
Add(value, null);
}
public void Clear()
{
for (int index = 0; index < this.size; ++index)
this.items[index].Clear();
this.size = 0;
++this.version;
}
public bool Contains(T value)
{
return GetIndex(value) != -1;
}
public bool Remove(T value)
{
int index = GetIndex(value);
if (index != -1)
{
RemoveAt(index);
return true;
}
return false;
}
public void CopyTo(T[] array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException("Multidimensional array not supported");
if (array.GetLowerBound(0) != 0)
throw new ArgumentException("Non-zero lower bound array not supported");
int length = array.Length;
if ((index < 0) || (index > length))
throw new ArgumentOutOfRangeException("index");
if ((length - index) < this.size)
throw new ArgumentException("Not enough space available in array starting at index");
for (int i = 0; i < this.size; ++i)
array[index + i] = this.items[i].value;
}
public IEnumerator<T> GetEnumerator()
{
int version2 = this.version;
for (int index = 0; index < this.size; ++index)
{
if (version2 != this.version)
throw new InvalidOperationException("Heap was modified while enumerating");
yield return this.items[index].value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
private Handle ValidateHandle(IHandle ihandle)
{
if (ihandle == null)
throw new ArgumentNullException("handle");
Handle handle = ihandle as Handle;
if (handle == null)
throw new InvalidOperationException("handle is not valid");
return handle;
}
private Handle ValidateThisHandle(IHandle ihandle)
{
Handle handle = ValidateHandle(ihandle);
if (!ReferenceEquals(handle.heap, this))
throw new InvalidOperationException("handle is not valid for this heap");
if (handle.index < 0)
throw new InvalidOperationException("handle is not associated to a value");
return handle;
}
private void Set(HeapItem item, int index)
{
this.items[index] = item;
if (item.handle != null)
item.handle.index = index;
}
private bool BubbleUp(int index)
{
HeapItem item = this.items[index];
int current, parent;
for (current = index, parent = (current - 1)/2;
(current > 0) && (this.comparison(this.items[parent].value, item.value)) > 0;
current = parent, parent = (current - 1)/2)
{
Set(this.items[parent], current);
}
if (current != index)
{
Set(item, current);
++this.version;
return true;
}
return false;
}
private void BubbleDown(int index)
{
HeapItem item = this.items[index];
int current, child;
for (current = index, child = (2*current) + 1;
current < this.size/2;
current = child, child = (2*current) + 1)
{
if ((child < this.size - 1) && this.comparison(this.items[child].value, this.items[child + 1].value) > 0)
++child;
if (this.comparison(this.items[child].value, item.value) >= 0)
break;
Set(this.items[child], current);
}
if (current != index)
{
Set(item, current);
++this.version;
}
}
public bool TryGetValue(IHandle key, out T value)
{
Handle handle = ValidateHandle(key);
if (handle.index > -1)
{
value = this.items[handle.index].value;
return true;
}
value = default(T);
return false;
}
public bool ContainsHandle(IHandle ihandle)
{
Handle handle = ValidateHandle(ihandle);
return ReferenceEquals(handle.heap, this) && handle.index > -1;
}
public void Add(T value, ref IHandle handle)
{
if (handle == null)
handle = new Handle();
Add(value, handle);
}
public void Add(T value, IHandle ihandle)
{
if (this.size == this.items.Length)
{
int capacity = (int) ((this.items.Length*200L)/100L);
if (capacity < (this.items.Length + DEFAULT_CAPACITY))
capacity = this.items.Length + DEFAULT_CAPACITY;
Array.Resize(ref this.items, capacity);
}
Handle handle = null;
if (ihandle != null)
{
handle = ValidateHandle(ihandle);
handle.heap = this;
}
HeapItem item = new HeapItem(value, handle);
Set(item, this.size);
BubbleUp(this.size++);
}
public T Min()
{
if (this.size == 0)
throw new InvalidOperationException("Heap is empty");
return this.items[0].value;
}
public void TrimExcess()
{
int length = (int) (this.items.Length*0.9);
if (this.size < length)
Array.Resize(ref this.items, Math.Min(this.size, DEFAULT_CAPACITY));
}
private void RemoveAt(int index)
{
if (this.size == 0)
throw new InvalidOperationException("Heap is empty");
if (index >= this.size)
throw new ArgumentOutOfRangeException("index");
this.items[index].Clear();
if (--this.size > 0 && index != this.size)
{
Set(this.items[this.size], index);
if (!BubbleUp(index))
BubbleDown(index);
}
}
public T RemoveMin()
{
if (this.size == 0)
throw new InvalidOperationException("Heap is empty");
HeapItem item = this.items[0];
RemoveAt(0);
return item.value;
}
public T Remove(IHandle ihandle)
{
Handle handle = ValidateThisHandle(ihandle);
HeapItem item = this.items[handle.index];
RemoveAt(handle.index);
return item.value;
}
private int GetIndex(T value)
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
int index;
for (index = 0; index < this.size; ++index)
{
if (comparer.Equals(this.items[index].value, value))
return index;
}
return -1;
}
#region Nested type: Handle
private class Handle : IHandle
{
internal MinHeap<T> heap;
internal int index = -1;
internal void Clear()
{
this.index = -1;
this.heap = null;
}
}
#endregion
#region Nested type: HeapItem
private struct HeapItem
{
internal Handle handle;
internal T value;
internal HeapItem(T value, Handle handle)
{
this.value = value;
this.handle = handle;
}
internal void Clear()
{
this.value = default(T);
if (this.handle != null)
{
this.handle.Clear();
this.handle = null;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Nest
{
[ContractJsonConverter(typeof(IndexSettingsConverter))]
public interface IDynamicIndexSettings : IIsADictionary<string, object>
{
/// <summary>
///The number of replicas each primary shard has. Defaults to 1.
/// </summary>
int? NumberOfReplicas { get; set; }
/// <summary>
///Auto-expand the number of replicas based on the number of available nodes.
/// Set to a dash delimited lower and upper bound (e.g. 0-5) or use all for the upper bound (e.g. 0-all). Defaults to false (i.e. disabled).
/// </summary>
AutoExpandReplicas AutoExpandReplicas { get; set; }
/// <summary>
/// How often to perform a refresh operation, which makes recent changes to the index visible to search.
/// Defaults to 1s. Can be set to -1 to disable refresh.
/// </summary>
Time RefreshInterval { get; set; }
/// <summary>
/// Set to true to make the index and index metadata read only, false to allow writes and metadata changes.
/// </summary>
bool? BlocksReadOnly { get; set; }
/// <summary>
/// Set to true to disable read operations against the index.
/// </summary>
bool? BlocksRead { get; set; }
/// <summary>
/// Set to true to disable write operations against the index.
/// </summary>
bool? BlocksWrite { get; set; }
/// <summary>
/// Set to true to disable index metadata reads and writes.
/// </summary>
bool? BlocksMetadata { get; set; }
/// <summary>
/// Unallocated shards are recovered in order of priority when set
/// </summary>
int? Priority { get; set; }
/// <summary>
/// A primary shard is only recovered only if there are
/// enough nodes available to allocate sufficient replicas to form a quorum.
/// </summary>
Union<int, RecoveryInitialShards> RecoveryInitialShards { get; set; }
/// <summary>
/// Enables the shard-level request cache. Not enabled by default.
/// </summary>
bool? RequestsCacheEnabled { get; set; }
/// <summary>
/// The allocation of replica shards which become unassigned because a node has left can be
/// delayed with this dynamic setting, which defaults to 1m.
/// </summary>
Time UnassignedNodeLeftDelayedTimeout { get; set; }
/// <summary>
/// The maximum number of shards (replicas and primaries) that will be allocated to a single node. Defaults to unbounded.
/// </summary>
int? RoutingAllocationTotalShardsPerNode { get; set; }
/// <summary>
/// All of the settings exposed in the merge module are expert only and may be obsoleted in the future at any time!
/// </summary>
IMergeSettings Merge { get; set; }
/// <summary>
/// Configure logging thresholds and levels in elasticsearch for search/fetch and indexing
/// </summary>
ISlowLog SlowLog { get; set; }
/// <summary>
/// Configure translog settings. This should only be used by experts who know what they're doing
/// </summary>
ITranslogSettings Translog { get; set; }
/// <summary>
/// Configure analysis
/// </summary>
IAnalysis Analysis { get; set; }
}
public class DynamicIndexSettings : IsADictionaryBase<string, object>, IDynamicIndexSettings
{
public DynamicIndexSettings() { }
public DynamicIndexSettings(IDictionary<string, object> container) : base(container) { }
/// <inheritdoc/>
public int? NumberOfReplicas { get; set; }
/// <inheritdoc/>
public AutoExpandReplicas AutoExpandReplicas { get; set; }
/// <inheritdoc/>
public bool? BlocksMetadata { get; set; }
/// <inheritdoc/>
public bool? BlocksRead { get; set; }
/// <inheritdoc/>
public bool? BlocksReadOnly { get; set; }
/// <inheritdoc/>
public bool? BlocksWrite { get; set; }
/// <inheritdoc/>
public int? Priority { get; set; }
/// <inheritdoc/>
public bool? RequestsCacheEnabled { get; set; }
/// <inheritdoc/>
public IMergeSettings Merge { get; set; }
/// <inheritdoc/>
public Union<int, RecoveryInitialShards> RecoveryInitialShards { get; set; }
/// <inheritdoc/>
public Time RefreshInterval { get; set; }
/// <inheritdoc/>
public int? RoutingAllocationTotalShardsPerNode { get; set; }
/// <inheritdoc/>
public ISlowLog SlowLog { get; set; }
/// <inheritdoc/>
public ITranslogSettings Translog { get; set; }
/// <inheritdoc/>
public Time UnassignedNodeLeftDelayedTimeout { get; set; }
/// <inheritdoc/>
public IAnalysis Analysis { get; set; }
/// <summary>
/// Add any setting to the index
/// </summary>
public void Add(string setting, object value) => this.BackingDictionary.Add(setting, value);
}
public class DynamicIndexSettingsDescriptor :
DynamicIndexSettingsDescriptorBase<DynamicIndexSettingsDescriptor, DynamicIndexSettings>
{
public DynamicIndexSettingsDescriptor() : base(new DynamicIndexSettings()) { }
}
public abstract class DynamicIndexSettingsDescriptorBase<TDescriptor, TIndexSettings> : IsADictionaryDescriptorBase<TDescriptor, TIndexSettings, string, object>
where TDescriptor : DynamicIndexSettingsDescriptorBase<TDescriptor, TIndexSettings>
where TIndexSettings : class, IDynamicIndexSettings
{
protected DynamicIndexSettingsDescriptorBase(TIndexSettings instance) : base(instance) { }
/// <summary>
/// Add any setting to the index
/// </summary>
public TDescriptor Setting(string setting, object value)
{
this.PromisedValue.Add(setting, value);
return (TDescriptor)this;
}
/// <inheritdoc/>
public TDescriptor NumberOfReplicas(int? numberOfReplicas) => Assign(a => a.NumberOfReplicas = numberOfReplicas);
/// <inheritdoc/>
public TDescriptor AutoExpandReplicas(AutoExpandReplicas autoExpandReplicas) => Assign(a => a.AutoExpandReplicas = autoExpandReplicas);
/// <inheritdoc/>
public TDescriptor BlocksMetadata(bool? blocksMetadata = true) => Assign(a => a.BlocksMetadata = blocksMetadata);
/// <inheritdoc/>
public TDescriptor BlocksRead(bool? blocksRead = true) => Assign(a => a.BlocksRead = blocksRead);
/// <inheritdoc/>
public TDescriptor BlocksReadOnly(bool? blocksReadOnly = true) => Assign(a => a.BlocksReadOnly = blocksReadOnly);
/// <inheritdoc/>
public TDescriptor BlocksWrite(bool? blocksWrite = true) => Assign(a => a.BlocksWrite = blocksWrite);
/// <inheritdoc/>
public TDescriptor Priority(int? priority) => Assign(a => a.Priority = priority);
/// <inheritdoc/>
public TDescriptor Merge(Func<MergeSettingsDescriptor, IMergeSettings> merge) =>
Assign(a => a.Merge = merge?.Invoke(new MergeSettingsDescriptor()));
/// <inheritdoc/>
public TDescriptor RecoveryInitialShards(Union<int, RecoveryInitialShards> initialShards) =>
Assign(a => a.RecoveryInitialShards = initialShards);
/// <inheritdoc/>
public TDescriptor RequestsCacheEnabled(bool? enable = true) =>
Assign(a => a.RequestsCacheEnabled = enable);
/// <inheritdoc/>
public TDescriptor RefreshInterval(Time time) => Assign(a => a.RefreshInterval = time);
/// <inheritdoc/>
public TDescriptor TotalShardsPerNode(int? totalShardsPerNode) =>
Assign(a => a.RoutingAllocationTotalShardsPerNode = totalShardsPerNode);
/// <inheritdoc/>
public TDescriptor SlowLog(Func<SlowLogDescriptor, ISlowLog> slowLogSelector) =>
Assign(a => a.SlowLog = slowLogSelector?.Invoke(new SlowLogDescriptor()));
/// <inheritdoc/>
public TDescriptor Translog(Func<TranslogSettingsDescriptor, ITranslogSettings> translogSelector) =>
Assign(a => a.Translog = translogSelector?.Invoke(new TranslogSettingsDescriptor()));
/// <inheritdoc/>
public TDescriptor UnassignedNodeLeftDelayedTimeout(Time time) =>
Assign(a => a.UnassignedNodeLeftDelayedTimeout = time);
public TDescriptor Analysis(Func<AnalysisDescriptor, IAnalysis> selector) =>
Assign(a => a.Analysis = selector?.Invoke(new AnalysisDescriptor()));
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Cryptography;
using Azure.Storage.Cryptography.Models;
namespace Azure.Storage.Cryptography
{
internal class ClientSideDecryptor
{
/// <summary>
/// A cache for encryption key if high level API spans across multiple service calls.
/// </summary>
private static readonly AsyncLocal<ContentEncryptionKeyCache> s_contentEncryptionKeyCache = new();
/// <summary>
/// Clients that can upload data have a key encryption key stored on them. Checking if
/// a cached key exists and matches a given <see cref="EncryptionData"/> saves a call
/// to the external key resolver implementation when available.
/// </summary>
private readonly IKeyEncryptionKey _potentialCachedIKeyEncryptionKey;
/// <summary>
/// Resolver to fetch the key encryption key.
/// </summary>
private readonly IKeyEncryptionKeyResolver _keyResolver;
public ClientSideDecryptor(ClientSideEncryptionOptions options)
{
_potentialCachedIKeyEncryptionKey = options.KeyEncryptionKey;
_keyResolver = options.KeyResolver;
}
/// <summary>
/// Decrypts the given stream if decryption information is provided.
/// Does not shave off unwanted start/end bytes, but will shave off padding.
/// </summary>
/// <param name="ciphertext">Stream to decrypt.</param>
/// <param name="encryptionData">
/// Encryption metadata and wrapped content encryption key.
/// </param>
/// <param name="ivInStream">
/// Whether to use the first block of the stream for the IV instead of the value in
/// <paramref name="encryptionData"/>. Generally for partial blob downloads where the
/// previous block of the ciphertext is the IV for the next.
/// </param>
/// <param name="noPadding">
/// Whether to ignore padding. Generally for partial blob downloads where the end of
/// the blob (where the padding occurs) was not downloaded.
/// </param>
/// <param name="async">Whether to perform this function asynchronously.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Decrypted plaintext.
/// </returns>
/// <exception cref="Exception">
/// Exceptions thrown based on implementations of <see cref="IKeyEncryptionKey"/> and
/// <see cref="IKeyEncryptionKeyResolver"/>.
/// </exception>
public async Task<Stream> DecryptInternal(
Stream ciphertext,
EncryptionData encryptionData,
bool ivInStream,
bool noPadding,
bool async,
CancellationToken cancellationToken)
{
switch (encryptionData.EncryptionAgent.EncryptionVersion)
{
case ClientSideEncryptionVersion.V1_0:
return await DecryptInternalV1_0(
ciphertext,
encryptionData,
ivInStream,
noPadding,
async,
cancellationToken).ConfigureAwait(false);
default:
throw Errors.ClientSideEncryption.BadEncryptionAgent(encryptionData.EncryptionAgent.EncryptionVersion.ToString());
}
}
/// <summary>
/// Decrypts the given stream if decryption information is provided.
/// Does not shave off unwanted start/end bytes, but will shave off padding.
/// </summary>
/// <param name="ciphertext">Stream to decrypt.</param>
/// <param name="encryptionData">
/// Encryption metadata and wrapped content encryption key.
/// </param>
/// <param name="ivInStream">
/// Whether to use the first block of the stream for the IV instead of the value in
/// <paramref name="encryptionData"/>. Generally for partial blob downloads where the
/// previous block of the ciphertext is the IV for the next.
/// </param>
/// <param name="noPadding">
/// Whether to ignore padding. Generally for partial blob downloads where the end of
/// the blob (where the padding occurs) was not downloaded.
/// </param>
/// <param name="async">Whether to perform this function asynchronously.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Decrypted plaintext.
/// </returns>
/// <exception cref="Exception">
/// Exceptions thrown based on implementations of <see cref="IKeyEncryptionKey"/> and
/// <see cref="IKeyEncryptionKeyResolver"/>.
/// </exception>
private async Task<Stream> DecryptInternalV1_0(
Stream ciphertext,
EncryptionData encryptionData,
bool ivInStream,
bool noPadding,
bool async,
CancellationToken cancellationToken)
{
var contentEncryptionKey = await GetContentEncryptionKeyAsync(
encryptionData,
async,
cancellationToken).ConfigureAwait(false);
Stream plaintext;
//int read = 0;
if (encryptionData != default)
{
byte[] IV;
if (!ivInStream)
{
IV = encryptionData.ContentEncryptionIV;
}
else
{
IV = new byte[Constants.ClientSideEncryption.EncryptionBlockSize];
if (async)
{
await ciphertext.ReadAsync(IV, 0, IV.Length, cancellationToken).ConfigureAwait(false);
}
else
{
ciphertext.Read(IV, 0, IV.Length);
}
//read = IV.Length;
}
plaintext = WrapStream(
ciphertext,
contentEncryptionKey.ToArray(),
encryptionData,
IV,
noPadding);
}
else
{
plaintext = ciphertext;
}
return plaintext;
}
#pragma warning disable CS1587 // XML comment is not placed on a valid language element
/// <summary>
/// Returns the content encryption key for blob. First tries to get the key encryption key from KeyResolver,
/// then falls back to IKey stored on this EncryptionPolicy. Unwraps the content encryption key with the
/// correct key wrapper.
/// </summary>
/// <param name="encryptionData">The encryption data.</param>
/// <param name="async">Whether to perform asynchronously.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Encryption key as a byte array.
/// </returns>
/// <exception cref="Exception">
/// Exceptions thrown based on implementations of <see cref="IKeyEncryptionKey"/> and
/// <see cref="IKeyEncryptionKeyResolver"/>.
/// </exception>
private async Task<Memory<byte>> GetContentEncryptionKeyAsync(
#pragma warning restore CS1587 // XML comment is not placed on a valid language element
EncryptionData encryptionData,
bool async,
CancellationToken cancellationToken)
{
if (s_contentEncryptionKeyCache.Value?.Key.HasValue ?? false)
{
return s_contentEncryptionKeyCache.Value.Key.Value;
}
IKeyEncryptionKey key = default;
// If we already have a local key and it is the correct one, use that.
if (encryptionData.WrappedContentKey.KeyId == _potentialCachedIKeyEncryptionKey?.KeyId)
{
key = _potentialCachedIKeyEncryptionKey;
}
// Otherwise, use the resolver.
else if (_keyResolver != null)
{
key = async
? await _keyResolver.ResolveAsync(encryptionData.WrappedContentKey.KeyId, cancellationToken).ConfigureAwait(false)
: _keyResolver.Resolve(encryptionData.WrappedContentKey.KeyId, cancellationToken);
}
// We throw for every other reason that decryption couldn't happen. Throw a reasonable
// exception here instead of nullref.
if (key == default)
{
throw Errors.ClientSideEncryption.KeyNotFound(encryptionData.WrappedContentKey.KeyId);
}
var contentEncryptionKey = async
? await key.UnwrapKeyAsync(
encryptionData.WrappedContentKey.Algorithm,
encryptionData.WrappedContentKey.EncryptedKey,
cancellationToken).ConfigureAwait(false)
: key.UnwrapKey(
encryptionData.WrappedContentKey.Algorithm,
encryptionData.WrappedContentKey.EncryptedKey,
cancellationToken);
if (s_contentEncryptionKeyCache.Value != default)
{
s_contentEncryptionKeyCache.Value.Key = contentEncryptionKey;
}
return contentEncryptionKey;
}
/// <summary>
/// Wraps a stream of ciphertext to stream plaintext.
/// </summary>
/// <param name="contentStream"></param>
/// <param name="contentEncryptionKey"></param>
/// <param name="encryptionData"></param>
/// <param name="iv"></param>
/// <param name="noPadding"></param>
/// <returns></returns>
private static Stream WrapStream(
Stream contentStream,
byte[] contentEncryptionKey,
EncryptionData encryptionData,
byte[] iv,
bool noPadding)
{
if (encryptionData.EncryptionAgent.EncryptionAlgorithm == ClientSideEncryptionAlgorithm.AesCbc256)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.IV = iv ?? encryptionData.ContentEncryptionIV;
aesProvider.Key = contentEncryptionKey;
if (noPadding)
{
aesProvider.Padding = PaddingMode.None;
}
// Buffer network stream. CryptoStream issues tiny (~16 byte) reads which can lead to resources churn.
// By default buffer is 4KB.
var bufferedContentStream = new BufferedStream(contentStream);
return new CryptoStream(bufferedContentStream, aesProvider.CreateDecryptor(), CryptoStreamMode.Read);
}
}
throw Errors.ClientSideEncryption.BadEncryptionAlgorithm(encryptionData.EncryptionAgent.EncryptionAlgorithm.ToString());
}
internal static void BeginContentEncryptionKeyCaching(ContentEncryptionKeyCache cache = default)
{
s_contentEncryptionKeyCache.Value = cache ?? new ContentEncryptionKeyCache();
}
internal class ContentEncryptionKeyCache
{
public Memory<byte>? Key { get; set; }
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="UpdateExpressionVisitor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Mapping.Update.Internal
{
using System.Data.Common.CommandTrees;
/// <summary>
/// Abstract implementation of node visitor that allows the specification of visit methods
/// for different node types (VisitPre virtual methods) and evaluation of nodes with respect
/// to the typed (TReturn) return values of their children.
/// </summary>
/// <remarks>
/// This is not a general purpose class. It is tailored to the needs of the update pipeline.
///
/// All virtual methods throw NotSupportedException (must be explicitly overridden by each visitor).
/// </remarks>
/// <typeparam name="TReturn">Return type for the visitor</typeparam>
internal abstract class UpdateExpressionVisitor<TReturn> : DbExpressionVisitor<TReturn>
{
/// <summary>
/// Gets the name of this visitor for debugging and tracing purposes.
/// </summary>
protected abstract string VisitorName
{
get;
}
/// <summary>
/// Utility method to generate an exception when unsupported node types are encountered.
/// </summary>
/// <param name="node">Unsupported node</param>
/// <returns>Not supported exception</returns>
protected NotSupportedException ConstructNotSupportedException(DbExpression node)
{
string nodeKind = null == node ? null :
node.ExpressionKind.ToString();
return EntityUtil.NotSupported(
System.Data.Entity.Strings.Update_UnsupportedExpressionKind(nodeKind, VisitorName));
}
#region IExpressionVisitor<TReturn> Members
public override TReturn Visit(DbExpression expression)
{
if (null != expression)
{
return expression.Accept(this);
}
else
{
throw ConstructNotSupportedException(expression);
}
}
public override TReturn Visit(DbAndExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbApplyExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbArithmeticExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbCaseExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbCastExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbComparisonExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbConstantExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbCrossJoinExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbDerefExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbDistinctExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbElementExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbExceptExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbFilterExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbFunctionExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbLambdaExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbEntityRefExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbRefKeyExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbGroupByExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbIntersectExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbIsEmptyExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbIsNullExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbIsOfExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbJoinExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbLikeExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbLimitExpression expression)
{
throw ConstructNotSupportedException(expression);
}
#if METHOD_EXPRESSION
public override TReturn Visit(MethodExpression expression)
{
throw ConstructNotSupportedException(expression);
}
#endif
public override TReturn Visit(DbNewInstanceExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbNotExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbNullExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbOfTypeExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbOrExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbParameterReferenceExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbProjectExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbPropertyExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbQuantifierExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbRefExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbRelationshipNavigationExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbSkipExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbSortExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbTreatExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbUnionAllExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbVariableReferenceExpression expression)
{
throw ConstructNotSupportedException(expression);
}
public override TReturn Visit(DbScanExpression expression)
{
throw ConstructNotSupportedException(expression);
}
#endregion
}
}
| |
using System;
using Android.Views;
using Android.Graphics;
using Android.Util;
using Android.Content;
namespace AndroidHUD
{
public class ProgressWheel : View
{
public ProgressWheel(Context context)
: this(context, null, 0)
{
}
public ProgressWheel(Context context, IAttributeSet attrs)
: this(context, attrs, 0)
{
}
public ProgressWheel (Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
CircleRadius = 80;
BarLength = 60;
BarWidth = 20;
RimWidth = 20;
TextSize = 20;
//Padding (with defaults)
WheelPaddingTop = 5;
WheelPaddingBottom = 5;
WheelPaddingLeft = 5;
WheelPaddingRight = 5;
//Colors (with defaults)
BarColor = Color.White;
CircleColor = Color.Transparent;
RimColor = Color.Gray;
TextColor = Color.White;
//Animation
//The amount of pixels to move the bar by on each draw
SpinSpeed = 2;
//The number of milliseconds to wait inbetween each draw
DelayMillis = 0;
spinHandler = new SpinHandler(msg => {
Invalidate ();
if (isSpinning)
{
progress += SpinSpeed;
if (progress > 360)
progress = 0;
spinHandler.SendEmptyMessageDelayed (0, DelayMillis);
}
});
//ParseAttributes(context.ObtainStyledAttributes(attrs, null)); //TODO: swap null for R.styleable.ProgressWheel
}
// public string Text
// {
// get { return text; }
// set { text = value; splitText = text.Split('\n'); }
// }
//public string[] SplitText { get { return splitText; } }
public int CircleRadius { get;set; }
public int BarLength { get;set; }
public int BarWidth { get;set; }
public int TextSize { get;set; }
public int WheelPaddingTop { get;set; }
public int WheelPaddingBottom { get; set; }
public int WheelPaddingLeft { get;set; }
public int WheelPaddingRight { get;set; }
public Color BarColor { get;set; }
public Color CircleColor { get;set; }
public Color RimColor { get;set; }
public Shader RimShader { get { return rimPaint.Shader; } set { rimPaint.SetShader(value); } }
public Color TextColor { get;set; }
public int SpinSpeed { get;set; }
public int RimWidth { get;set; }
public int DelayMillis { get;set; }
public bool IsSpinning { get { return isSpinning; } }
//Sizes (with defaults)
int fullRadius = 100;
//Paints
Paint barPaint = new Paint();
Paint circlePaint = new Paint();
Paint rimPaint = new Paint();
Paint textPaint = new Paint();
//Rectangles
//RectF rectBounds = new RectF();
RectF circleBounds = new RectF();
int progress = 0;
bool isSpinning = false;
SpinHandler spinHandler;
Android.OS.BuildVersionCodes version = Android.OS.Build.VERSION.SdkInt;
//Other
//string text = "";
//string[] splitText = new string[]{};
protected override void OnAttachedToWindow ()
{
base.OnAttachedToWindow ();
SetupBounds ();
SetupPaints ();
Invalidate ();
}
void SetupPaints()
{
barPaint.Color = BarColor;
barPaint.AntiAlias = true;
barPaint.SetStyle (Paint.Style.Stroke);
barPaint.StrokeWidth = BarWidth;
rimPaint.Color = RimColor;
rimPaint.AntiAlias = true;
rimPaint.SetStyle (Paint.Style.Stroke);
rimPaint.StrokeWidth = RimWidth;
circlePaint.Color = CircleColor;
circlePaint.AntiAlias = true;
circlePaint.SetStyle(Paint.Style.Fill);
textPaint.Color = TextColor;
textPaint.SetStyle(Paint.Style.Fill);
textPaint.AntiAlias = true;
textPaint.TextSize = TextSize;
}
void SetupBounds()
{
WheelPaddingTop = this.WheelPaddingTop;
WheelPaddingBottom = this.WheelPaddingBottom;
WheelPaddingLeft = this.WheelPaddingLeft;
WheelPaddingRight = this.WheelPaddingRight;
// rectBounds = new RectF(WheelPaddingLeft,
// WheelPaddingTop,
// this.LayoutParameters.Width - WheelPaddingRight,
// this.LayoutParameters.Height - WheelPaddingBottom);
//
circleBounds = new RectF(WheelPaddingLeft + BarWidth,
WheelPaddingTop + BarWidth,
this.LayoutParameters.Width - WheelPaddingRight - BarWidth,
this.LayoutParameters.Height - WheelPaddingBottom - BarWidth);
fullRadius = (this.LayoutParameters.Width - WheelPaddingRight - BarWidth)/2;
CircleRadius = (fullRadius - BarWidth) + 1;
}
// void ParseAttributes(Android.Content.Res.TypedArray a)
// {
// BarWidth = (int) a.GetDimension(R.styleable.ProgressWheel_barWidth, barWidth);
// RimWidth = (int) a.GetDimension(R.styleable.ProgressWheel_rimWidth, rimWidth);
// SpinSpeed = (int) a.GetDimension(R.styleable.ProgressWheel_spinSpeed, spinSpeed);
// DelayMillis = (int) a.GetInteger(R.styleable.ProgressWheel_delayMillis, delayMillis);
//
// if(DelayMillis < 0)
// DelayMillis = 0;
//
// BarColor = a.GetColor(R.styleable.ProgressWheel_barColor, barColor);
// BarLength = (int) a.GetDimension(R.styleable.ProgressWheel_barLength, barLength);
// TextSize = (int) a.GetDimension(R.styleable.ProgressWheel_textSize, textSize);
// TextColor = (int) a.GetColor(R.styleable.ProgressWheel_textColor, textColor);
//
// Text = a.GetString(R.styleable.ProgressWheel_text);
//
// RimColor = (int) a.GetColor(R.styleable.ProgressWheel_rimColor, rimColor);
// CircleColor = (int) a.GetColor(R.styleable.ProgressWheel_circleColor, circleColor);
// }
//----------------------------------
//Animation stuff
//----------------------------------
protected override void OnDraw (Canvas canvas)
{
base.OnDraw (canvas);
//Draw the rim
canvas.DrawArc(circleBounds, 360, 360, false, rimPaint);
//Draw the bar
if(isSpinning)
canvas.DrawArc(circleBounds, progress - 90, BarLength, false, barPaint);
else
canvas.DrawArc(circleBounds, -90, progress, false, barPaint);
//Draw the inner circle
canvas.DrawCircle((circleBounds.Width() / 2) + RimWidth + WheelPaddingLeft,
(circleBounds.Height() / 2) + RimWidth + WheelPaddingTop,
CircleRadius,
circlePaint);
//Draw the text (attempts to center it horizontally and vertically)
// int offsetNum = 2;
//
// foreach (var s in splitText)
// {
// float offset = textPaint.MeasureText(s) / 2;
//
// canvas.DrawText(s, this.Width / 2 - offset,
// this.Height / 2 + (TextSize * (offsetNum))
// - ((splitText.Length - 1) * (TextSize / 2)), textPaint);
// offsetNum++;
// }
}
public void ResetCount()
{
progress = 0;
//Text = "0%";
Invalidate();
}
public void StopSpinning()
{
isSpinning = false;
progress = 0;
spinHandler.RemoveMessages(0);
}
public void Spin()
{
isSpinning = true;
spinHandler.SendEmptyMessage(0);
}
public void IncrementProgress()
{
isSpinning = false;
progress++;
//Text = Math.Round(((float)progress/(float)360)*(float)100) + "%";
spinHandler.SendEmptyMessage(0);
}
public void SetProgress(int i) {
isSpinning = false;
var newProgress = (int)((float)i / (float)100 * (float)360);
if (version >= Android.OS.BuildVersionCodes.Honeycomb)
{
Android.Animation.ValueAnimator va =
(Android.Animation.ValueAnimator)Android.Animation.ValueAnimator.OfInt (progress, newProgress).SetDuration (250);
va.Update += (sender, e) => {
var interimValue = (int)e.Animation.AnimatedValue;
progress = interimValue;
//Text = Math.Round(((float)interimValue/(float)360)*(float)100) + "%";
Invalidate ();
};
va.Start ();
} else {
progress = newProgress;
Invalidate ();
}
spinHandler.SendEmptyMessage(0);
}
class SpinHandler : Android.OS.Handler
{
public SpinHandler(Action<Android.OS.Message> msgAction) : base()
{
MessageAction = msgAction;
}
public Action<Android.OS.Message> MessageAction { get; private set; }
public override void HandleMessage (Android.OS.Message msg)
{
MessageAction (msg);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Globalization;
using System.Security;
using System.Reflection;
using System.Runtime.Versioning;
namespace System.Xml
{
internal sealed class DocumentSchemaValidator : IXmlNamespaceResolver
{
private XmlSchemaValidator _validator;
private XmlSchemaSet _schemas;
private XmlNamespaceManager _nsManager;
private XmlNameTable _nameTable;
//Attributes
private ArrayList _defaultAttributes;
private XmlValueGetter _nodeValueGetter;
private XmlSchemaInfo _attributeSchemaInfo;
//Element PSVI
private XmlSchemaInfo _schemaInfo;
//Event Handler
private ValidationEventHandler _eventHandler;
private ValidationEventHandler _internalEventHandler;
//Store nodes
private XmlNode _startNode;
private XmlNode _currentNode;
private XmlDocument _document;
//List of nodes for partial validation tree walk
private XmlNode[] _nodeSequenceToValidate;
private bool _isPartialTreeValid;
private bool _psviAugmentation;
private bool _isValid;
//To avoid SchemaNames creation
private string _nsXmlNs;
private string _nsXsi;
private string _xsiType;
private string _xsiNil;
public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler eventHandler)
{
_schemas = schemas;
_eventHandler = eventHandler;
_document = ownerDocument;
_internalEventHandler = new ValidationEventHandler(InternalValidationCallBack);
_nameTable = _document.NameTable;
_nsManager = new XmlNamespaceManager(_nameTable);
Debug.Assert(schemas != null && schemas.Count > 0);
_nodeValueGetter = new XmlValueGetter(GetNodeValue);
_psviAugmentation = true;
//Add common strings to be compared to NameTable
_nsXmlNs = _nameTable.Add(XmlReservedNs.NsXmlNs);
_nsXsi = _nameTable.Add(XmlReservedNs.NsXsi);
_xsiType = _nameTable.Add("type");
_xsiNil = _nameTable.Add("nil");
}
public bool PsviAugmentation
{
get { return _psviAugmentation; }
set { _psviAugmentation = value; }
}
public bool Validate(XmlNode nodeToValidate)
{
XmlSchemaObject partialValidationType = null;
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
Debug.Assert(nodeToValidate.SchemaInfo != null);
_startNode = nodeToValidate;
switch (nodeToValidate.NodeType)
{
case XmlNodeType.Document:
validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
break;
case XmlNodeType.DocumentFragment:
break;
case XmlNodeType.Element: //Validate children of this element
IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo;
XmlSchemaElement schemaElement = schemaInfo.SchemaElement;
if (schemaElement != null)
{
if (!schemaElement.RefName.IsEmpty)
{ //If it is element ref,
partialValidationType = _schemas.GlobalElements[schemaElement.QualifiedName]; //Get Global element with correct Nillable, Default etc
}
else
{ //local element
partialValidationType = schemaElement;
}
//Verify that if there was xsi:type, the schemaElement returned has the correct type set
Debug.Assert(schemaElement.ElementSchemaType == schemaInfo.SchemaType);
}
else
{ //Can be an element that matched xs:any and had xsi:type
partialValidationType = schemaInfo.SchemaType;
if (partialValidationType == null)
{ //Validated against xs:any with pc= lax or skip or undeclared / not validated element
if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document)
{
//If this is the documentElement and it has not been validated at all
nodeToValidate = nodeToValidate.ParentNode;
}
else
{
partialValidationType = FindSchemaInfo(nodeToValidate as XmlElement);
if (partialValidationType == null)
{
throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
}
}
break;
case XmlNodeType.Attribute:
if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) goto default;
partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute;
if (partialValidationType == null)
{ //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute
partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute);
if (partialValidationType == null)
{
throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
break;
default:
throw new InvalidOperationException(SR.Format(SR.XmlDocument_ValidateInvalidNodeType, null));
}
_isValid = true;
CreateValidator(partialValidationType, validationFlags);
if (_psviAugmentation)
{
if (_schemaInfo == null)
{ //Might have created it during FindSchemaInfo
_schemaInfo = new XmlSchemaInfo();
}
_attributeSchemaInfo = new XmlSchemaInfo();
}
ValidateNode(nodeToValidate);
_validator.EndValidation();
return _isValid;
}
public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
IDictionary<string, string> dictionary = _nsManager.GetNamespacesInScope(scope);
if (scope != XmlNamespaceScope.Local)
{
XmlNode node = _startNode;
while (node != null)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attr = attrs[i];
if (Ref.Equal(attr.NamespaceURI, _document.strReservedXmlns))
{
if (attr.Prefix.Length == 0)
{
// xmlns='' declaration
if (!dictionary.ContainsKey(string.Empty))
{
dictionary.Add(string.Empty, attr.Value);
}
}
else
{
// xmlns:prefix='' declaration
if (!dictionary.ContainsKey(attr.LocalName))
{
dictionary.Add(attr.LocalName, attr.Value);
}
}
}
}
}
node = node.ParentNode;
break;
case XmlNodeType.Attribute:
node = ((XmlAttribute)node).OwnerElement;
break;
default:
node = node.ParentNode;
break;
}
}
}
return dictionary;
}
public string LookupNamespace(string prefix)
{
string namespaceName = _nsManager.LookupNamespace(prefix);
if (namespaceName == null)
{
namespaceName = _startNode.GetNamespaceOfPrefixStrict(prefix);
}
return namespaceName;
}
public string LookupPrefix(string namespaceName)
{
string prefix = _nsManager.LookupPrefix(namespaceName);
if (prefix == null)
{
prefix = _startNode.GetPrefixOfNamespaceStrict(namespaceName);
}
return prefix;
}
private IXmlNamespaceResolver NamespaceResolver
{
get
{
if ((object)_startNode == (object)_document)
{
return _nsManager;
}
return this;
}
}
private void CreateValidator(XmlSchemaObject partialValidationType, XmlSchemaValidationFlags validationFlags)
{
_validator = new XmlSchemaValidator(_nameTable, _schemas, NamespaceResolver, validationFlags);
_validator.SourceUri = XmlConvert.ToUri(_document.BaseURI);
_validator.XmlResolver = null;
_validator.ValidationEventHandler += _internalEventHandler;
_validator.ValidationEventSender = this;
if (partialValidationType != null)
{
_validator.Initialize(partialValidationType);
}
else
{
_validator.Initialize();
}
}
private void ValidateNode(XmlNode node)
{
_currentNode = node;
switch (_currentNode.NodeType)
{
case XmlNodeType.Document:
XmlElement docElem = ((XmlDocument)node).DocumentElement;
if (docElem == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle));
}
ValidateNode(docElem);
break;
case XmlNodeType.DocumentFragment:
case XmlNodeType.EntityReference:
for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling)
{
ValidateNode(child);
}
break;
case XmlNodeType.Element:
ValidateElement();
break;
case XmlNodeType.Attribute: //Top-level attribute
XmlAttribute attr = _currentNode as XmlAttribute;
_validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo);
if (_psviAugmentation)
{
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
}
break;
case XmlNodeType.Text:
_validator.ValidateText(_nodeValueGetter);
break;
case XmlNodeType.CDATA:
_validator.ValidateText(_nodeValueGetter);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(_nodeValueGetter);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, _currentNode.NodeType));
}
}
private void ValidateElement()
{
_nsManager.PushScope();
XmlElement elementNode = _currentNode as XmlElement;
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(_nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiType))
{
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs, _nsXmlNs))
{
_nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
_validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo, xsiType, xsiNil, null, null);
ValidateAttributes(elementNode);
_validator.ValidateEndOfAttributes(_schemaInfo);
//If element has children, drill down
for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling)
{
ValidateNode(child);
}
//Validate end of element
_currentNode = elementNode; //Reset current Node for validation call back
_validator.ValidateEndElement(_schemaInfo);
//Get XmlName, as memberType / validity might be set now
if (_psviAugmentation)
{
elementNode.XmlName = _document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo);
if (_schemaInfo.IsDefault)
{ //the element has a default value
XmlText textNode = _document.CreateTextNode(_schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw);
elementNode.AppendChild(textNode);
}
}
_nsManager.PopScope(); //Pop current namespace scope
}
private void ValidateAttributes(XmlElement elementNode)
{
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
_currentNode = attr; //For nodeValueGetter to pick up the right attribute value
if (Ref.Equal(attr.NamespaceURI, _nsXmlNs))
{ //Do not validate namespace decls
continue;
}
_validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo);
if (_psviAugmentation)
{
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
}
}
if (_psviAugmentation)
{
//Add default attributes to the attributes collection
if (_defaultAttributes == null)
{
_defaultAttributes = new ArrayList();
}
else
{
_defaultAttributes.Clear();
}
_validator.GetUnspecifiedDefaultAttributes(_defaultAttributes);
XmlSchemaAttribute schemaAttribute = null;
XmlQualifiedName attrQName;
attr = null;
for (int i = 0; i < _defaultAttributes.Count; i++)
{
schemaAttribute = _defaultAttributes[i] as XmlSchemaAttribute;
attrQName = schemaAttribute.QualifiedName;
Debug.Assert(schemaAttribute != null);
attr = _document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace);
SetDefaultAttributeSchemaInfo(schemaAttribute);
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef.DefaultValueRaw));
attributes.Append(attr);
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
if (defAttr != null)
{
defAttr.SetSpecified(false);
}
}
}
}
private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute)
{
Debug.Assert(_attributeSchemaInfo != null);
_attributeSchemaInfo.Clear();
_attributeSchemaInfo.IsDefault = true;
_attributeSchemaInfo.IsNil = false;
_attributeSchemaInfo.SchemaType = schemaAttribute.AttributeSchemaType;
_attributeSchemaInfo.SchemaAttribute = schemaAttribute;
//Get memberType for default attribute
SchemaAttDef attributeDef = schemaAttribute.AttDef;
if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union)
{
XsdSimpleValue simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue;
Debug.Assert(simpleValue != null);
_attributeSchemaInfo.MemberType = simpleValue.XmlType;
}
_attributeSchemaInfo.Validity = XmlSchemaValidity.Valid;
}
private string GetDefaultPrefix(string attributeNS)
{
IDictionary<string, string> namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All);
string defaultPrefix = null;
string defaultNS;
attributeNS = _nameTable.Add(attributeNS); //atomize ns
foreach (KeyValuePair<string, string> pair in namespaceDecls)
{
defaultNS = _nameTable.Add(pair.Value);
if (object.ReferenceEquals(defaultNS, attributeNS))
{
defaultPrefix = pair.Key;
if (defaultPrefix.Length != 0)
{ //Locate first non-empty prefix
return defaultPrefix;
}
}
}
return defaultPrefix;
}
private object GetNodeValue()
{
return _currentNode.Value;
}
//Code for finding type during partial validation
private XmlSchemaObject FindSchemaInfo(XmlElement elementToValidate)
{
_isPartialTreeValid = true;
Debug.Assert(elementToValidate.ParentNode.NodeType != XmlNodeType.Document); //Handle if it is the documentElement separately
//Create nodelist to navigate down again
XmlNode currentNode = elementToValidate;
IXmlSchemaInfo parentSchemaInfo = null;
int nodeIndex = 0;
//Check common case of parent node first
XmlNode parentNode = currentNode.ParentNode;
do
{
parentSchemaInfo = parentNode.SchemaInfo;
if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null)
{
break; //Found ancestor with schemaInfo
}
CheckNodeSequenceCapacity(nodeIndex);
_nodeSequenceToValidate[nodeIndex++] = parentNode;
parentNode = parentNode.ParentNode;
} while (parentNode != null);
if (parentNode == null)
{ //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment
nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null
_nodeSequenceToValidate[nodeIndex] = null;
return GetTypeFromAncestors(elementToValidate, null, nodeIndex);
}
else
{
//Start validating down from the parent or ancestor that has schema info and shallow validate all previous siblings
//to correctly ascertain particle for current node
CheckNodeSequenceCapacity(nodeIndex);
_nodeSequenceToValidate[nodeIndex++] = parentNode;
XmlSchemaObject ancestorSchemaObject = parentSchemaInfo.SchemaElement;
if (ancestorSchemaObject == null)
{
ancestorSchemaObject = parentSchemaInfo.SchemaType;
}
return GetTypeFromAncestors(elementToValidate, ancestorSchemaObject, nodeIndex);
}
}
/*private XmlSchemaElement GetTypeFromParent(XmlElement elementToValidate, XmlSchemaComplexType parentSchemaType) {
XmlQualifiedName elementName = new XmlQualifiedName(elementToValidate.LocalName, elementToValidate.NamespaceURI);
XmlSchemaElement elem = parentSchemaType.LocalElements[elementName] as XmlSchemaElement;
if (elem == null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member
SchemaInfo compiledSchemaInfo = schemas.CompiledInfo;
XmlSchemaElement memberElem = compiledSchemaInfo.GetElement(elementName);
if (memberElem != null) {
}
}
}*/
private void CheckNodeSequenceCapacity(int currentIndex)
{
if (_nodeSequenceToValidate == null)
{ //Normally users would call Validate one level down, this allows for 4
_nodeSequenceToValidate = new XmlNode[4];
}
else if (currentIndex >= _nodeSequenceToValidate.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
XmlNode[] newNodeSequence = new XmlNode[_nodeSequenceToValidate.Length * 2];
Array.Copy(_nodeSequenceToValidate, 0, newNodeSequence, 0, _nodeSequenceToValidate.Length);
_nodeSequenceToValidate = newNodeSequence;
}
}
private XmlSchemaAttribute FindSchemaInfo(XmlAttribute attributeToValidate)
{
XmlElement parentElement = attributeToValidate.OwnerElement;
XmlSchemaObject schemaObject = FindSchemaInfo(parentElement);
XmlSchemaComplexType elementSchemaType = GetComplexType(schemaObject);
if (elementSchemaType == null)
{
return null;
}
XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI);
XmlSchemaAttribute schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute;
if (schemaAttribute == null)
{
XmlSchemaAnyAttribute anyAttribute = elementSchemaType.AttributeWildcard;
if (anyAttribute != null)
{
if (anyAttribute.NamespaceList.Allows(attName))
{ //Match wildcard against global attribute
schemaAttribute = _schemas.GlobalAttributes[attName] as XmlSchemaAttribute;
}
}
}
return schemaAttribute;
}
private XmlSchemaObject GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject ancestorType, int ancestorsCount)
{
//schemaInfo is currentNode's schemaInfo
_validator = CreateTypeFinderValidator(ancestorType);
_schemaInfo = new XmlSchemaInfo();
//start at the ancestor to start validating
int startIndex = ancestorsCount - 1;
bool ancestorHasWildCard = AncestorTypeHasWildcard(ancestorType);
for (int i = startIndex; i >= 0; i--)
{
XmlNode node = _nodeSequenceToValidate[i];
XmlElement currentElement = node as XmlElement;
ValidateSingleElement(currentElement, false, _schemaInfo);
if (!ancestorHasWildCard)
{ //store type if ancestor does not have wildcard in its content model
currentElement.XmlName = _document.AddXmlName(currentElement.Prefix, currentElement.LocalName, currentElement.NamespaceURI, _schemaInfo);
//update wildcard flag
ancestorHasWildCard = AncestorTypeHasWildcard(_schemaInfo.SchemaElement);
}
_validator.ValidateEndOfAttributes(null);
if (i > 0)
{
ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]);
}
else
{ //i == 0
ValidateChildrenTillNextAncestor(node, elementToValidate);
}
}
Debug.Assert(_nodeSequenceToValidate[0] == elementToValidate.ParentNode);
//validate element whose type is needed,
ValidateSingleElement(elementToValidate, false, _schemaInfo);
XmlSchemaObject schemaInfoFound = null;
if (_schemaInfo.SchemaElement != null)
{
schemaInfoFound = _schemaInfo.SchemaElement;
}
else
{
schemaInfoFound = _schemaInfo.SchemaType;
}
if (schemaInfoFound == null)
{ //Detect if the node was validated lax or skip
if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Skip)
{
if (_isPartialTreeValid)
{ //Then node assessed as skip; if there was error we turn processContents to skip as well. But this is not the same as validating as skip.
return XmlSchemaComplexType.AnyTypeSkip;
}
}
else if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Lax)
{
return XmlSchemaComplexType.AnyType;
}
}
return schemaInfoFound;
}
private bool AncestorTypeHasWildcard(XmlSchemaObject ancestorType)
{
XmlSchemaComplexType ancestorSchemaType = GetComplexType(ancestorType);
if (ancestorType != null)
{
return ancestorSchemaType.HasWildCard;
}
return false;
}
private XmlSchemaComplexType GetComplexType(XmlSchemaObject schemaObject)
{
if (schemaObject == null)
{
return null;
}
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
XmlSchemaComplexType complexType = null;
if (schemaElement != null)
{
complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType;
}
else
{
complexType = schemaObject as XmlSchemaComplexType;
}
return complexType;
}
private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo newSchemaInfo)
{
_nsManager.PushScope();
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(_nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiType))
{
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs, _nsXmlNs))
{
_nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
_validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null);
//Validate end of element
if (skipToEnd)
{
_validator.ValidateEndOfAttributes(newSchemaInfo);
_validator.SkipToEndElement(newSchemaInfo);
_nsManager.PopScope(); //Pop current namespace scope
}
}
private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childToStopAt)
{
XmlNode child;
for (child = parentNode.FirstChild; child != null; child = child.NextSibling)
{
if (child == childToStopAt)
{
break;
}
switch (child.NodeType)
{
case XmlNodeType.EntityReference:
ValidateChildrenTillNextAncestor(child, childToStopAt);
break;
case XmlNodeType.Element: //Flat validation, do not drill down into children
ValidateSingleElement(child as XmlElement, true, null);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_validator.ValidateText(child.Value);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(child.Value);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, _currentNode.NodeType));
}
}
Debug.Assert(child == childToStopAt);
}
private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject partialValidationType)
{
XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(_document.NameTable, _document.Schemas, _nsManager, XmlSchemaValidationFlags.None);
findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack);
if (partialValidationType != null)
{
findTypeValidator.Initialize(partialValidationType);
}
else
{ //If we walked up to the root and no schemaInfo was there, start validating from root
findTypeValidator.Initialize();
}
return findTypeValidator;
}
private void TypeFinderCallBack(object sender, ValidationEventArgs arg)
{
if (arg.Severity == XmlSeverityType.Error)
{
_isPartialTreeValid = false;
}
}
private void InternalValidationCallBack(object sender, ValidationEventArgs arg)
{
if (arg.Severity == XmlSeverityType.Error)
{
_isValid = false;
}
XmlSchemaValidationException ex = arg.Exception as XmlSchemaValidationException;
Debug.Assert(ex != null);
ex.SetSourceObject(_currentNode);
if (_eventHandler != null)
{ //Invoke user's event handler
_eventHandler(sender, arg);
}
else if (arg.Severity == XmlSeverityType.Error)
{
throw ex;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
//using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
public abstract class Comparer<T> : IComparer, IComparer<T>
{
static readonly Comparer<T> defaultComparer = CreateComparer();
public static Comparer<T> Default {
get {
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
return defaultComparer;
}
}
public static Comparer<T> Create(Comparison<T> comparison)
{
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
if (comparison == null)
throw new ArgumentNullException(nameof(comparison));
return new ComparisonComparer<T>(comparison);
}
//
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
private static Comparer<T> CreateComparer()
{
object result = null;
RuntimeType t = (RuntimeType)typeof(T);
// If T implements IComparable<T> return a GenericComparer<T>
if (typeof(IComparable<T>).IsAssignableFrom(t))
{
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t);
}
else if (default(T) == null)
{
// If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U>
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
if (typeof(IComparable<>).MakeGenericType(u).IsAssignableFrom(u)) {
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), u);
}
}
}
else if (t.IsEnum)
{
// Explicitly call Enum.GetUnderlyingType here. Although GetTypeCode
// ends up doing this anyway, we end up avoiding an unnecessary P/Invoke
// and virtual method call.
TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t));
// Depending on the enum type, we need to special case the comparers so that we avoid boxing
// Specialize differently for signed/unsigned types so we avoid problems with large numbers
switch (underlyingTypeCode)
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int32EnumComparer<int>), t);
break;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt32EnumComparer<uint>), t);
break;
// 64-bit enums: use UnsafeEnumCastLong
case TypeCode.Int64:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int64EnumComparer<long>), t);
break;
case TypeCode.UInt64:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt64EnumComparer<ulong>), t);
break;
}
}
return result != null ?
(Comparer<T>)result :
new ObjectComparer<T>(); // Fallback to ObjectComparer, which uses boxing
}
public abstract int Compare(T x, T y);
int IComparer.Compare(object x, object y) {
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
if (x is T && y is T) return Compare((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
}
// Note: although there is a lot of shared code in the following
// comparers, we do not incorporate it into a base class for perf
// reasons. Adding another base class (even one with no fields)
// means another generic instantiation, which can be costly esp.
// for value types.
[Serializable]
internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
public override int Compare(T x, T y) {
if (x != null) {
if (y != null) return x.CompareTo(y);
return 1;
}
if (y != null) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T>
{
public override int Compare(T? x, T? y) {
if (x.HasValue) {
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
}
if (y.HasValue) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
internal sealed class ObjectComparer<T> : Comparer<T>
{
public override int Compare(T x, T y) {
return System.Collections.Comparer.Default.Compare(x, y);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
internal sealed class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison) {
_comparison = comparison;
}
public override int Compare(T x, T y) {
return _comparison(x, y);
}
}
// Enum comparers (specialized to avoid boxing)
// NOTE: Each of these needs to implement ISerializable
// and have a SerializationInfo/StreamingContext ctor,
// since we want to serialize as ObjectComparer for
// back-compat reasons (see below).
[Serializable]
internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public Int32EnumComparer()
{
Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
private Int32EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
int ix = JitHelpers.UnsafeEnumCast(x);
int iy = JitHelpers.UnsafeEnumCast(y);
return ix.CompareTo(iy);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Previously Comparer<T> was not specialized for enums,
// and instead fell back to ObjectComparer which uses boxing.
// Set the type as ObjectComparer here so code that serializes
// Comparer for enums will not break.
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
internal sealed class UInt32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public UInt32EnumComparer()
{
Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
private UInt32EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
uint ix = (uint)JitHelpers.UnsafeEnumCast(x);
uint iy = (uint)JitHelpers.UnsafeEnumCast(y);
return ix.CompareTo(iy);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
internal sealed class Int64EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public Int64EnumComparer()
{
Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
private Int64EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
long lx = JitHelpers.UnsafeEnumCastLong(x);
long ly = JitHelpers.UnsafeEnumCastLong(y);
return lx.CompareTo(ly);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
internal sealed class UInt64EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public UInt64EnumComparer()
{
Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
private UInt64EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
ulong lx = (ulong)JitHelpers.UnsafeEnumCastLong(x);
ulong ly = (ulong)JitHelpers.UnsafeEnumCastLong(y);
return lx.CompareTo(ly);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Threading;
namespace SteamTrade
{
/// <summary>
/// This class represents the TF2 Item schema as deserialized from its
/// JSON representation.
/// </summary>
public class Dota2Schema
{
public static Dota2Schema Schema;
private const string SchemaMutexName = "steam_bot_cache_file_mutex";
private const string SchemaApiUrlBase = "http://api.steampowered.com/IEconItems_570/GetSchema/v0001/?key=";
private const string cachefile = "schema_dota2.cache";
/// <summary>
/// Fetches the Dota 2 Item schema.
/// </summary>
/// <param name="apiKey">The API key.</param>
/// <returns>A deserialized instance of the Item Schema.</returns>
/// <remarks>
/// The schema will be cached for future use if it is updated.
/// </remarks>
public static Dota2Schema FetchSchema (string apiKey)
{
var url = SchemaApiUrlBase + apiKey;
// just let one thread/proc do the initial check/possible update.
bool wasCreated;
var mre = new EventWaitHandle(false,
EventResetMode.ManualReset, SchemaMutexName, out wasCreated);
// the thread that create the wait handle will be the one to
// write the cache file. The others will wait patiently.
if (!wasCreated)
{
bool signaled = mre.WaitOne(10000);
if (!signaled)
{
return null;
}
}
HttpWebResponse response = SteamWeb.Request(url, "GET");
DateTime schemaLastModified = response.LastModified;
string result = GetSchemaString(response, schemaLastModified);
response.Close();
mre.Set();
SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult> (result);
return schemaResult.result ?? null;
}
// Gets the schema from the web or from the cached file.
private static string GetSchemaString(HttpWebResponse response, DateTime schemaLastModified)
{
string result;
bool mustUpdateCache = !File.Exists(cachefile) || schemaLastModified > File.GetCreationTime(cachefile);
if (mustUpdateCache)
{
var reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
File.WriteAllText(cachefile, result);
File.SetCreationTime(cachefile, schemaLastModified);
}
else
{
// read previously cached file.
TextReader reader = new StreamReader(cachefile);
result = reader.ReadToEnd();
reader.Close();
}
return result;
}
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("items_game_url")]
public string ItemsGameUrl { get; set; }
[JsonProperty("items")]
public Item[] Items { get; set; }
[JsonProperty("originNames")]
public ItemOrigin[] OriginNames { get; set; }
/// <summary>
/// Find an SchemaItem by it's defindex.
/// </summary>
public Item GetItem (int defindex)
{
foreach (Item item in Items)
{
if (item.Defindex == defindex)
return item;
}
return null;
}
public List<Item> GetItems()
{
return Items.ToList();
}
public class ItemOrigin
{
[JsonProperty("origin")]
public int Origin { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class Item
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("defindex")]
public ushort Defindex { get; set; }
[JsonProperty("item_class")]
public string ItemClass { get; set; }
[JsonProperty("item_type_name")]
public string ItemTypeName { get; set; }
[JsonProperty("item_name")]
public string ItemName { get; set; }
[JsonProperty("item_description")]
public string ItemDescription { get; set; }
[JsonProperty("proper_name")]
public bool IsProperName { get; set; }
[JsonProperty("item_quality")]
public int ItemQuality { get; set; }
[JsonProperty("item_set")]
private string itemSet { get; set; }
public string ItemSet
{
get
{
return string.IsNullOrEmpty(itemSet) ? "" : itemSet;
}
}
[JsonProperty("capabilities")]
public Capabilities Capabilities { get; set; }
}
public class Capabilities
{
[JsonProperty("nameable")]
private bool isNameable { get; set; }
public bool IsNameable
{
get
{
try
{
return isNameable;
}
catch
{
return false;
}
}
}
[JsonProperty("can_craft_mark")]
public bool IsCraftable { get; set; }
[JsonProperty("can_be_restored")]
public bool IsRestorable { get; set; }
[JsonProperty("strange_parts")]
public bool HasStrangeParts { get; set; }
[JsonProperty("paintable_unusual")]
public bool IsPaintableUnusual { get; set; }
[JsonProperty("autograph")]
public bool IsAutographable { get; set; }
[JsonProperty("can_consume")]
public bool IsConsumable { get; set; }
[JsonProperty("can_have_sockets")]
private bool isSocketable { get; set; }
public bool IsSocketable
{
get
{
try
{
return isSocketable;
}
catch
{
return false;
}
}
}
}
protected class SchemaResult
{
public Dota2Schema result { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.IntegrationTesting.Common;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.IntegrationTesting
{
/// <summary>
/// Deployer for Kestrel on Nginx.
/// </summary>
public class NginxDeployer : SelfHostDeployer
{
private string _configFile;
private readonly int _waitTime = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
private Socket _portSelector;
public NginxDeployer(DeploymentParameters deploymentParameters, ILoggerFactory loggerFactory)
: base(deploymentParameters, loggerFactory)
{
}
public override async Task<DeploymentResult> DeployAsync()
{
using (Logger.BeginScope("Deploy"))
{
_configFile = Path.GetTempFileName();
var uri = string.IsNullOrEmpty(DeploymentParameters.ApplicationBaseUriHint) ?
new Uri("http://localhost:0") :
new Uri(DeploymentParameters.ApplicationBaseUriHint);
if (uri.Port == 0)
{
var builder = new UriBuilder(uri);
if (OperatingSystem.IsLinux())
{
// This works with nginx 1.9.1 and later using the reuseport flag, available on Ubuntu 16.04.
// Keep it open so nobody else claims the port
_portSelector = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_portSelector.Bind(new IPEndPoint(IPAddress.Loopback, 0));
builder.Port = ((IPEndPoint)_portSelector.LocalEndPoint).Port;
}
else
{
builder.Port = TestPortHelper.GetNextPort();
}
uri = builder.Uri;
}
var redirectUri = TestUriHelper.BuildTestUri(ServerType.Nginx);
if (DeploymentParameters.RuntimeFlavor == RuntimeFlavor.CoreClr
&& DeploymentParameters.ApplicationType == ApplicationType.Standalone)
{
// Publish is required to get the correct files in the output directory
DeploymentParameters.PublishApplicationBeforeDeployment = true;
}
if (DeploymentParameters.PublishApplicationBeforeDeployment)
{
DotnetPublish();
}
var (appUri, exitToken) = await StartSelfHostAsync(redirectUri);
SetupNginx(appUri.ToString(), uri);
Logger.LogInformation("Application ready at URL: {appUrl}", uri);
// Wait for App to be loaded since Nginx returns 502 instead of 503 when App isn't loaded
// Target actual address to avoid going through Nginx proxy
using (var httpClient = new HttpClient())
{
var response = await RetryHelper.RetryRequest(() =>
{
return httpClient.GetAsync(redirectUri);
}, Logger, exitToken);
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException("Deploy failed");
}
}
return new DeploymentResult(
LoggerFactory,
DeploymentParameters,
applicationBaseUri: uri.ToString(),
contentRoot: DeploymentParameters.ApplicationPath,
hostShutdownToken: exitToken);
}
}
private string GetUserName()
{
var retVal = Environment.GetEnvironmentVariable("LOGNAME")
?? Environment.GetEnvironmentVariable("USER")
?? Environment.GetEnvironmentVariable("USERNAME");
if (!string.IsNullOrEmpty(retVal))
{
return retVal;
}
if (!OperatingSystem.IsWindows())
{
using (var process = new Process
{
StartInfo =
{
FileName = "whoami",
RedirectStandardOutput = true,
}
})
{
process.Start();
process.WaitForExit(10_000);
return process.StandardOutput.ReadToEnd();
}
}
return null;
}
private void SetupNginx(string redirectUri, Uri originalUri)
{
using (Logger.BeginScope("SetupNginx"))
{
var userName = GetUserName() ?? throw new InvalidOperationException("Could not identify the current username");
// copy nginx.conf template and replace pertinent information
var pidFile = Path.Combine(DeploymentParameters.ApplicationPath, $"{Guid.NewGuid()}.nginx.pid");
var errorLog = Path.Combine(DeploymentParameters.ApplicationPath, "nginx.error.log");
var accessLog = Path.Combine(DeploymentParameters.ApplicationPath, "nginx.access.log");
DeploymentParameters.ServerConfigTemplateContent = DeploymentParameters.ServerConfigTemplateContent
.Replace("[user]", userName)
.Replace("[errorlog]", errorLog)
.Replace("[accesslog]", accessLog)
.Replace("[listenPort]", originalUri.Port.ToString(CultureInfo.InvariantCulture) + (_portSelector != null ? " reuseport" : ""))
.Replace("[redirectUri]", redirectUri)
.Replace("[pidFile]", pidFile);
Logger.LogDebug("Using PID file: {pidFile}", pidFile);
Logger.LogDebug("Using Error Log file: {errorLog}", pidFile);
Logger.LogDebug("Using Access Log file: {accessLog}", pidFile);
if (Logger.IsEnabled(LogLevel.Trace))
{
Logger.LogTrace($"Config File Content:{Environment.NewLine}===START CONFIG==={Environment.NewLine}{{configContent}}{Environment.NewLine}===END CONFIG===", DeploymentParameters.ServerConfigTemplateContent);
}
File.WriteAllText(_configFile, DeploymentParameters.ServerConfigTemplateContent);
var startInfo = new ProcessStartInfo
{
FileName = "nginx",
Arguments = $"-c {_configFile}",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
// Trying a work around for https://github.com/aspnet/Hosting/issues/140.
RedirectStandardInput = true
};
using (var runNginx = new Process() { StartInfo = startInfo })
{
runNginx.StartAndCaptureOutAndErrToLogger("nginx start", Logger);
runNginx.WaitForExit(_waitTime);
if (runNginx.ExitCode != 0)
{
throw new InvalidOperationException("Failed to start nginx");
}
// Read the PID file
if (!File.Exists(pidFile))
{
Logger.LogWarning("Unable to find nginx PID file: {pidFile}", pidFile);
}
else
{
var pid = File.ReadAllText(pidFile);
Logger.LogInformation("nginx process ID {pid} started", pid);
}
}
}
}
public override void Dispose()
{
using (Logger.BeginScope("Dispose"))
{
if (File.Exists(_configFile))
{
var startInfo = new ProcessStartInfo
{
FileName = "nginx",
Arguments = $"-s stop -c {_configFile}",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
// Trying a work around for https://github.com/aspnet/Hosting/issues/140.
RedirectStandardInput = true
};
using (var runNginx = new Process() { StartInfo = startInfo })
{
runNginx.StartAndCaptureOutAndErrToLogger("nginx stop", Logger);
runNginx.WaitForExit(_waitTime);
Logger.LogInformation("nginx stop command issued");
}
Logger.LogDebug("Deleting config file: {configFile}", _configFile);
File.Delete(_configFile);
}
_portSelector?.Dispose();
base.Dispose();
}
}
}
}
| |
namespace SPD.GUI {
/// <summary>
///
/// </summary>
partial class Plan_OP {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.label1 = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxAge = new System.Windows.Forms.TextBox();
this.textBoxSex = new System.Windows.Forms.TextBox();
this.textBoxWeight = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.buttonCopyToClipboard = new System.Windows.Forms.Button();
this.buttonClose = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.textBoxIndication = new System.Windows.Forms.TextBox();
this.buttonRestore = new System.Windows.Forms.Button();
this.labelID = new System.Windows.Forms.Label();
this.textBoxID = new System.Windows.Forms.TextBox();
this.textBoxTherapy = new System.Windows.Forms.TextBox();
this.labelTherapy = new System.Windows.Forms.Label();
this.buttonCopyToClipboardAndClose = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(24, 41);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(38, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Name:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(68, 38);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(543, 20);
this.textBoxName.TabIndex = 1;
this.textBoxName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// textBoxAge
//
this.textBoxAge.Location = new System.Drawing.Point(68, 64);
this.textBoxAge.Name = "textBoxAge";
this.textBoxAge.Size = new System.Drawing.Size(543, 20);
this.textBoxAge.TabIndex = 2;
this.textBoxAge.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// textBoxSex
//
this.textBoxSex.Location = new System.Drawing.Point(68, 90);
this.textBoxSex.Name = "textBoxSex";
this.textBoxSex.Size = new System.Drawing.Size(543, 20);
this.textBoxSex.TabIndex = 3;
this.textBoxSex.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// textBoxWeight
//
this.textBoxWeight.Location = new System.Drawing.Point(68, 116);
this.textBoxWeight.Name = "textBoxWeight";
this.textBoxWeight.Size = new System.Drawing.Size(543, 20);
this.textBoxWeight.TabIndex = 4;
this.textBoxWeight.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(33, 67);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(29, 13);
this.label2.TabIndex = 7;
this.label2.Text = "Age:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(34, 93);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(28, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Sex:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(18, 119);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(44, 13);
this.label4.TabIndex = 9;
this.label4.Text = "Weight:";
//
// buttonCopyToClipboard
//
this.buttonCopyToClipboard.Location = new System.Drawing.Point(227, 194);
this.buttonCopyToClipboard.Name = "buttonCopyToClipboard";
this.buttonCopyToClipboard.Size = new System.Drawing.Size(124, 23);
this.buttonCopyToClipboard.TabIndex = 8;
this.buttonCopyToClipboard.Text = "C&opy to Clipboard";
this.buttonCopyToClipboard.UseVisualStyleBackColor = true;
this.buttonCopyToClipboard.Click += new System.EventHandler(this.buttonCopyToClipboard_Click);
this.buttonCopyToClipboard.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// buttonClose
//
this.buttonClose.Location = new System.Drawing.Point(357, 194);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(124, 23);
this.buttonClose.TabIndex = 9;
this.buttonClose.Text = "C&lose";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
this.buttonClose.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 145);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(56, 13);
this.label5.TabIndex = 14;
this.label5.Text = "Indication:";
//
// textBoxIndication
//
this.textBoxIndication.Location = new System.Drawing.Point(68, 142);
this.textBoxIndication.Name = "textBoxIndication";
this.textBoxIndication.Size = new System.Drawing.Size(543, 20);
this.textBoxIndication.TabIndex = 5;
this.textBoxIndication.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// buttonRestore
//
this.buttonRestore.Location = new System.Drawing.Point(487, 194);
this.buttonRestore.Name = "buttonRestore";
this.buttonRestore.Size = new System.Drawing.Size(124, 23);
this.buttonRestore.TabIndex = 10;
this.buttonRestore.Text = "Restore";
this.buttonRestore.UseVisualStyleBackColor = true;
this.buttonRestore.Click += new System.EventHandler(this.buttonRestore_Click);
this.buttonRestore.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// labelID
//
this.labelID.AutoSize = true;
this.labelID.Location = new System.Drawing.Point(41, 15);
this.labelID.Name = "labelID";
this.labelID.Size = new System.Drawing.Size(21, 13);
this.labelID.TabIndex = 0;
this.labelID.Text = "ID:";
//
// textBoxID
//
this.textBoxID.Location = new System.Drawing.Point(68, 12);
this.textBoxID.Name = "textBoxID";
this.textBoxID.Size = new System.Drawing.Size(543, 20);
this.textBoxID.TabIndex = 0;
this.textBoxID.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// textBoxTherapy
//
this.textBoxTherapy.Location = new System.Drawing.Point(68, 168);
this.textBoxTherapy.Name = "textBoxTherapy";
this.textBoxTherapy.Size = new System.Drawing.Size(543, 20);
this.textBoxTherapy.TabIndex = 6;
this.textBoxTherapy.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
//
// labelTherapy
//
this.labelTherapy.AutoSize = true;
this.labelTherapy.Location = new System.Drawing.Point(12, 171);
this.labelTherapy.Name = "labelTherapy";
this.labelTherapy.Size = new System.Drawing.Size(49, 13);
this.labelTherapy.TabIndex = 14;
this.labelTherapy.Text = "Therapy:";
//
// buttonCopyToClipboardAndClose
//
this.buttonCopyToClipboardAndClose.Location = new System.Drawing.Point(68, 194);
this.buttonCopyToClipboardAndClose.Name = "buttonCopyToClipboardAndClose";
this.buttonCopyToClipboardAndClose.Size = new System.Drawing.Size(153, 23);
this.buttonCopyToClipboardAndClose.TabIndex = 7;
this.buttonCopyToClipboardAndClose.Text = "&Copy to Clipboard and Close";
this.buttonCopyToClipboardAndClose.UseVisualStyleBackColor = true;
this.buttonCopyToClipboardAndClose.Click += new System.EventHandler(this.buttonCopyToClipboardAndClose_Click);
//
// Plan_OP
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(625, 232);
this.ControlBox = false;
this.Controls.Add(this.buttonCopyToClipboardAndClose);
this.Controls.Add(this.buttonRestore);
this.Controls.Add(this.labelTherapy);
this.Controls.Add(this.label5);
this.Controls.Add(this.textBoxTherapy);
this.Controls.Add(this.textBoxIndication);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.buttonCopyToClipboard);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBoxWeight);
this.Controls.Add(this.textBoxSex);
this.Controls.Add(this.textBoxAge);
this.Controls.Add(this.textBoxID);
this.Controls.Add(this.labelID);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.label1);
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(633, 259);
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(633, 259);
this.Name = "Plan_OP";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "Plan OP";
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Plan_OP_KeyPress);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxName;
private System.Windows.Forms.TextBox textBoxAge;
private System.Windows.Forms.TextBox textBoxSex;
private System.Windows.Forms.TextBox textBoxWeight;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button buttonCopyToClipboard;
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBoxIndication;
private System.Windows.Forms.Button buttonRestore;
private System.Windows.Forms.Label labelID;
private System.Windows.Forms.TextBox textBoxID;
private System.Windows.Forms.TextBox textBoxTherapy;
private System.Windows.Forms.Label labelTherapy;
private System.Windows.Forms.Button buttonCopyToClipboardAndClose;
}
}
| |
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 VentudaVibexDemo.Areas.HelpPage.ModelDescriptions;
using VentudaVibexDemo.Areas.HelpPage.Models;
namespace VentudaVibexDemo.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Development;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Replays.Legacy;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Online.Spectator
{
public abstract class SpectatorClient : Component, ISpectatorClient
{
/// <summary>
/// The maximum milliseconds between frame bundle sends.
/// </summary>
public const double TIME_BETWEEN_SENDS = 200;
/// <summary>
/// Whether the <see cref="SpectatorClient"/> is currently connected.
/// This is NOT thread safe and usage should be scheduled.
/// </summary>
public abstract IBindable<bool> IsConnected { get; }
private readonly List<int> watchingUsers = new List<int>();
public IBindableList<int> PlayingUsers => playingUsers;
private readonly BindableList<int> playingUsers = new BindableList<int>();
public IBindableDictionary<int, SpectatorState> PlayingUserStates => playingUserStates;
private readonly BindableDictionary<int, SpectatorState> playingUserStates = new BindableDictionary<int, SpectatorState>();
private IBeatmap? currentBeatmap;
private Score? currentScore;
[Resolved]
private IBindable<RulesetInfo> currentRuleset { get; set; } = null!;
[Resolved]
private IBindable<IReadOnlyList<Mod>> currentMods { get; set; } = null!;
private readonly SpectatorState currentState = new SpectatorState();
/// <summary>
/// Whether the local user is playing.
/// </summary>
protected bool IsPlaying { get; private set; }
/// <summary>
/// Called whenever new frames arrive from the server.
/// </summary>
public event Action<int, FrameDataBundle>? OnNewFrames;
/// <summary>
/// Called whenever a user starts a play session, or immediately if the user is being watched and currently in a play session.
/// </summary>
public event Action<int, SpectatorState>? OnUserBeganPlaying;
/// <summary>
/// Called whenever a user finishes a play session.
/// </summary>
public event Action<int, SpectatorState>? OnUserFinishedPlaying;
[BackgroundDependencyLoader]
private void load()
{
IsConnected.BindValueChanged(connected => Schedule(() =>
{
if (connected.NewValue)
{
// get all the users that were previously being watched
int[] users = watchingUsers.ToArray();
watchingUsers.Clear();
// resubscribe to watched users.
foreach (var userId in users)
WatchUser(userId);
// re-send state in case it wasn't received
if (IsPlaying)
BeginPlayingInternal(currentState);
}
else
{
playingUsers.Clear();
playingUserStates.Clear();
}
}), true);
}
Task ISpectatorClient.UserBeganPlaying(int userId, SpectatorState state)
{
Schedule(() =>
{
if (!playingUsers.Contains(userId))
playingUsers.Add(userId);
// UserBeganPlaying() is called by the server regardless of whether the local user is watching the remote user, and is called a further time when the remote user is watched.
// This may be a temporary thing (see: https://github.com/ppy/osu-server-spectator/blob/2273778e02cfdb4a9c6a934f2a46a8459cb5d29c/osu.Server.Spectator/Hubs/SpectatorHub.cs#L28-L29).
// We don't want the user states to update unless the player is being watched, otherwise calling BindUserBeganPlaying() can lead to double invocations.
if (watchingUsers.Contains(userId))
playingUserStates[userId] = state;
OnUserBeganPlaying?.Invoke(userId, state);
});
return Task.CompletedTask;
}
Task ISpectatorClient.UserFinishedPlaying(int userId, SpectatorState state)
{
Schedule(() =>
{
playingUsers.Remove(userId);
playingUserStates.Remove(userId);
OnUserFinishedPlaying?.Invoke(userId, state);
});
return Task.CompletedTask;
}
Task ISpectatorClient.UserSentFrames(int userId, FrameDataBundle data)
{
Schedule(() => OnNewFrames?.Invoke(userId, data));
return Task.CompletedTask;
}
public void BeginPlaying(GameplayBeatmap beatmap, Score score)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (IsPlaying)
throw new InvalidOperationException($"Cannot invoke {nameof(BeginPlaying)} when already playing");
IsPlaying = true;
// transfer state at point of beginning play
currentState.BeatmapID = beatmap.BeatmapInfo.OnlineBeatmapID;
currentState.RulesetID = currentRuleset.Value.ID;
currentState.Mods = currentMods.Value.Select(m => new APIMod(m));
currentBeatmap = beatmap.PlayableBeatmap;
currentScore = score;
BeginPlayingInternal(currentState);
}
public void SendFrames(FrameDataBundle data) => lastSend = SendFramesInternal(data);
public void EndPlaying()
{
// This method is most commonly called via Dispose(), which is asynchronous.
// Todo: This should not be a thing, but requires framework changes.
Schedule(() =>
{
if (!IsPlaying)
return;
IsPlaying = false;
currentBeatmap = null;
EndPlayingInternal(currentState);
});
}
public void WatchUser(int userId)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (watchingUsers.Contains(userId))
return;
watchingUsers.Add(userId);
WatchUserInternal(userId);
}
public void StopWatchingUser(int userId)
{
// This method is most commonly called via Dispose(), which is asynchronous.
// Todo: This should not be a thing, but requires framework changes.
Schedule(() =>
{
watchingUsers.Remove(userId);
playingUserStates.Remove(userId);
StopWatchingUserInternal(userId);
});
}
protected abstract Task BeginPlayingInternal(SpectatorState state);
protected abstract Task SendFramesInternal(FrameDataBundle data);
protected abstract Task EndPlayingInternal(SpectatorState state);
protected abstract Task WatchUserInternal(int userId);
protected abstract Task StopWatchingUserInternal(int userId);
private readonly Queue<LegacyReplayFrame> pendingFrames = new Queue<LegacyReplayFrame>();
private double lastSendTime;
private Task? lastSend;
private const int max_pending_frames = 30;
protected override void Update()
{
base.Update();
if (pendingFrames.Count > 0 && Time.Current - lastSendTime > TIME_BETWEEN_SENDS)
purgePendingFrames();
}
public void HandleFrame(ReplayFrame frame)
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (!IsPlaying)
return;
if (frame is IConvertibleReplayFrame convertible)
pendingFrames.Enqueue(convertible.ToLegacy(currentBeatmap));
if (pendingFrames.Count > max_pending_frames)
purgePendingFrames();
}
private void purgePendingFrames()
{
if (lastSend?.IsCompleted == false)
return;
var frames = pendingFrames.ToArray();
pendingFrames.Clear();
Debug.Assert(currentScore != null);
SendFrames(new FrameDataBundle(currentScore.ScoreInfo, frames));
lastSendTime = Time.Current;
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A spin lock is a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop ("spins")
// repeatedly checking until the lock becomes available. As the thread remains active performing a non-useful task,
// the use of such a lock is a kind of busy waiting and consumes CPU resources without performing real work.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Threading
{
/// <summary>
/// Provides a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop
/// repeatedly checking until the lock becomes available.
/// </summary>
/// <remarks>
/// <para>
/// Spin locks can be used for leaf-level locks where the object allocation implied by using a <see
/// cref="System.Threading.Monitor"/>, in size or due to garbage collection pressure, is overly
/// expensive. Avoiding blocking is another reason that a spin lock can be useful, however if you expect
/// any significant amount of blocking, you are probably best not using spin locks due to excessive
/// spinning. Spinning can be beneficial when locks are fine grained and large in number (for example, a
/// lock per node in a linked list) as well as when lock hold times are always extremely short. In
/// general, while holding a spin lock, one should avoid blocking, calling anything that itself may
/// block, holding more than one spin lock at once, making dynamically dispatched calls (interface and
/// virtuals), making statically dispatched calls into any code one doesn't own, or allocating memory.
/// </para>
/// <para>
/// <see cref="SpinLock"/> should only be used when it's been determined that doing so will improve an
/// application's performance. It's also important to note that <see cref="SpinLock"/> is a value type,
/// for performance reasons. As such, one must be very careful not to accidentally copy a SpinLock
/// instance, as the two instances (the original and the copy) would then be completely independent of
/// one another, which would likely lead to erroneous behavior of the application. If a SpinLock instance
/// must be passed around, it should be passed by reference rather than by value.
/// </para>
/// <para>
/// Do not store <see cref="SpinLock"/> instances in readonly fields.
/// </para>
/// <para>
/// All members of <see cref="SpinLock"/> are thread-safe and may be used from multiple threads
/// concurrently.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))]
[DebuggerDisplay("IsHeld = {IsHeld}")]
public struct SpinLock
{
// The current ownership state is a single signed int. There are two modes:
//
// 1) Ownership tracking enabled: the high bit is 0, and the remaining bits
// store the managed thread ID of the current owner. When the 31 low bits
// are 0, the lock is available.
// 2) Performance mode: when the high bit is 1, lock availability is indicated by the low bit.
// When the low bit is 1 -- the lock is held; 0 -- the lock is available.
//
// There are several masks and constants below for convenience.
private volatile int _owner;
// After how many yields, call Sleep(1)
private const int SLEEP_ONE_FREQUENCY = 40;
// After how many yields, check the timeout
private const int TIMEOUT_CHECK_FREQUENCY = 10;
// Thr thread tracking disabled mask
private const int LOCK_ID_DISABLE_MASK = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000
// the lock is held by some thread, but we don't know which
private const int LOCK_ANONYMOUS_OWNED = 0x1; // 0000 0000 0000 0000 0000 0000 0000 0001
// Waiters mask if the thread tracking is disabled
private const int WAITERS_MASK = ~(LOCK_ID_DISABLE_MASK | 1); // 0111 1111 1111 1111 1111 1111 1111 1110
// The Thread tacking is disabled and the lock bit is set, used in Enter fast path to make sure the id is disabled and lock is available
private const int ID_DISABLED_AND_ANONYMOUS_OWNED = unchecked((int)0x80000001); // 1000 0000 0000 0000 0000 0000 0000 0001
// If the thread is unowned if:
// m_owner zero and the thread tracking is enabled
// m_owner & LOCK_ANONYMOUS_OWNED = zero and the thread tracking is disabled
private const int LOCK_UNOWNED = 0;
// The maximum number of waiters (only used if the thread tracking is disabled)
// The actual maximum waiters count is this number divided by two because each waiter increments the waiters count by 2
// The waiters count is calculated by m_owner & WAITERS_MASK 01111....110
private const int MAXIMUM_WAITERS = WAITERS_MASK;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CompareExchange(ref int location, int value, int comparand, ref bool success)
{
int result = Interlocked.CompareExchange(ref location, value, comparand);
success = (result == comparand);
return result;
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Threading.SpinLock"/>
/// structure with the option to track thread IDs to improve debugging.
/// </summary>
/// <remarks>
/// The default constructor for <see cref="SpinLock"/> tracks thread ownership.
/// </remarks>
/// <param name="enableThreadOwnerTracking">Whether to capture and use thread IDs for debugging
/// purposes.</param>
public SpinLock(bool enableThreadOwnerTracking)
{
_owner = LOCK_UNOWNED;
if (!enableThreadOwnerTracking)
{
_owner |= LOCK_ID_DISABLE_MASK;
Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Threading.SpinLock"/>
/// structure with the option to track thread IDs to improve debugging.
/// </summary>
/// <remarks>
/// The default constructor for <see cref="SpinLock"/> tracks thread ownership.
/// </remarks>
/// <summary>
/// Acquires the lock in a reliable manner, such that even if an exception occurs within the method
/// call, <paramref name="lockTaken"/> can be examined reliably to determine whether the lock was
/// acquired.
/// </summary>
/// <remarks>
/// <see cref="SpinLock"/> is a non-reentrant lock, meaning that if a thread holds the lock, it is
/// not allowed to enter the lock again. If thread ownership tracking is enabled (whether it's
/// enabled is available through <see cref="IsThreadOwnerTrackingEnabled"/>), an exception will be
/// thrown when a thread tries to re-enter a lock it already holds. However, if thread ownership
/// tracking is disabled, attempting to enter a lock already held will result in deadlock.
/// </remarks>
/// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref
/// name="lockTaken"/> must be initialized to false prior to calling this method.</param>
/// <exception cref="System.Threading.LockRecursionException">
/// Thread ownership tracking is enabled, and the current thread has already acquired this lock.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling Enter.
/// </exception>
public void Enter(ref bool lockTaken)
{
// Try to keep the code and branching in this method as small as possible in order to inline the method
int observedOwner = _owner;
if (lockTaken || // invalid parameter
(observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired
CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed
ContinueTryEnter(Timeout.Infinite, ref lockTaken); // Then try the slow path if any of the above conditions is met
}
/// <summary>
/// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within
/// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the
/// lock was acquired.
/// </summary>
/// <remarks>
/// Unlike <see cref="Enter"/>, TryEnter will not block waiting for the lock to be available. If the
/// lock is not available when TryEnter is called, it will return immediately without any further
/// spinning.
/// </remarks>
/// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref
/// name="lockTaken"/> must be initialized to false prior to calling this method.</param>
/// <exception cref="System.Threading.LockRecursionException">
/// Thread ownership tracking is enabled, and the current thread has already acquired this lock.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter.
/// </exception>
public void TryEnter(ref bool lockTaken)
{
int observedOwner = _owner;
if (((observedOwner & LOCK_ID_DISABLE_MASK) == 0) | lockTaken)
{
// Thread tracking enabled or invalid arg. Take slow path.
ContinueTryEnter(0, ref lockTaken);
}
else if ((observedOwner & LOCK_ANONYMOUS_OWNED) != 0)
{
// Lock already held by someone
lockTaken = false;
}
else
{
// Lock wasn't held; try to acquire it.
CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken);
}
}
/// <summary>
/// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within
/// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the
/// lock was acquired.
/// </summary>
/// <remarks>
/// Unlike <see cref="Enter"/>, TryEnter will not block indefinitely waiting for the lock to be
/// available. It will block until either the lock is available or until the <paramref
/// name="timeout"/>
/// has expired.
/// </remarks>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref
/// name="lockTaken"/> must be initialized to false prior to calling this method.</param>
/// <exception cref="System.Threading.LockRecursionException">
/// Thread ownership tracking is enabled, and the current thread has already acquired this lock.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="int.MaxValue"/> milliseconds.
/// </exception>
public void TryEnter(TimeSpan timeout, ref bool lockTaken)
{
// Validate the timeout
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
nameof(timeout), timeout, SR.SpinLock_TryEnter_ArgumentOutOfRange);
}
// Call reliable enter with the int-based timeout milliseconds
TryEnter((int)timeout.TotalMilliseconds, ref lockTaken);
}
/// <summary>
/// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within
/// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the
/// lock was acquired.
/// </summary>
/// <remarks>
/// Unlike <see cref="Enter"/>, TryEnter will not block indefinitely waiting for the lock to be
/// available. It will block until either the lock is available or until the <paramref
/// name="millisecondsTimeout"/> has expired.
/// </remarks>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
/// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref
/// name="lockTaken"/> must be initialized to false prior to calling this method.</param>
/// <exception cref="System.Threading.LockRecursionException">
/// Thread ownership tracking is enabled, and the current thread has already acquired this lock.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is
/// a negative number other than -1, which represents an infinite time-out.</exception>
public void TryEnter(int millisecondsTimeout, ref bool lockTaken)
{
int observedOwner = _owner;
if (millisecondsTimeout < -1 || // invalid parameter
lockTaken || // invalid parameter
(observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired
CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed
ContinueTryEnter(millisecondsTimeout, ref lockTaken); // The call the slow pth
}
/// <summary>
/// Try acquire the lock with long path, this is usually called after the first path in Enter and
/// TryEnter failed The reason for short path is to make it inline in the run time which improves the
/// performance. This method assumed that the parameter are validated in Enter or TryEnter method.
/// </summary>
/// <param name="millisecondsTimeout">The timeout milliseconds</param>
/// <param name="lockTaken">The lockTaken param</param>
private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken)
{
// The fast path doesn't throw any exception, so we have to validate the parameters here
if (lockTaken)
{
lockTaken = false;
throw new ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException);
}
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinLock_TryEnter_ArgumentOutOfRange);
}
uint startTime = 0;
if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout != 0)
{
startTime = TimeoutHelper.GetTime();
}
if (IsThreadOwnerTrackingEnabled)
{
// Slow path for enabled thread tracking mode
ContinueTryEnterWithThreadTracking(millisecondsTimeout, startTime, ref lockTaken);
return;
}
// then thread tracking is disabled
// In this case there are three ways to acquire the lock
// 1- the first way the thread either tries to get the lock if it's free or updates the waiters, if the turn >= the processors count then go to 3 else go to 2
// 2- In this step the waiter threads spins and tries to acquire the lock, the number of spin iterations and spin count is dependent on the thread turn
// the late the thread arrives the more it spins and less frequent it check the lock availability
// Also the spins count is increases each iteration
// If the spins iterations finished and failed to acquire the lock, go to step 3
// 3- This is the yielding step, there are two ways of yielding Thread.Yield and Sleep(1)
// If the timeout is expired in after step 1, we need to decrement the waiters count before returning
int observedOwner;
int turn = int.MaxValue;
// ***Step 1, take the lock or update the waiters
// try to acquire the lock directly if possible or update the waiters count
observedOwner = _owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
if (CompareExchange(ref _owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner)
{
// Acquired lock
return;
}
if (millisecondsTimeout == 0)
{
// Did not acquire lock in CompareExchange and timeout is 0 so fail fast
return;
}
}
else if (millisecondsTimeout == 0)
{
// Did not acquire lock as owned and timeout is 0 so fail fast
return;
}
else // failed to acquire the lock, then try to update the waiters. If the waiters count reached the maximum, just break the loop to avoid overflow
{
if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS)
{
// This can still overflow, but maybe there will never be that many waiters
turn = (Interlocked.Add(ref _owner, 2) & WAITERS_MASK) >> 1;
}
}
// lock acquired failed and waiters updated
// *** Step 2, Spinning and Yielding
var spinner = new SpinWait();
if (turn > PlatformHelper.ProcessorCount)
{
spinner.Count = SpinWait.YieldThreshold;
}
while (true)
{
spinner.SpinOnce(SLEEP_ONE_FREQUENCY);
observedOwner = _owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
observedOwner | 1 // don't decrement it. just set the lock bit, it is zero because a previous call of Exit(false) which corrupted the waiters
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
Debug.Assert((newOwner & WAITERS_MASK) >= 0);
if (CompareExchange(ref _owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
return;
}
}
if (spinner.Count % TIMEOUT_CHECK_FREQUENCY == 0)
{
// Check the timeout.
if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)
{
DecrementWaiters();
return;
}
}
}
}
/// <summary>
/// decrements the waiters, in case of the timeout is expired
/// </summary>
private void DecrementWaiters()
{
SpinWait spinner = new SpinWait();
while (true)
{
int observedOwner = _owner;
if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false)
if (Interlocked.CompareExchange(ref _owner, observedOwner - 2, observedOwner) == observedOwner)
{
Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
break;
}
spinner.SpinOnce();
}
}
/// <summary>
/// ContinueTryEnter for the thread tracking mode enabled
/// </summary>
private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken)
{
Debug.Assert(IsThreadOwnerTrackingEnabled);
const int LockUnowned = 0;
// We are using thread IDs to mark ownership. Snap the thread ID and check for recursion.
// We also must or the ID enablement bit, to ensure we propagate when we CAS it in.
int newOwner = Environment.CurrentManagedThreadId;
if (_owner == newOwner)
{
// We don't allow lock recursion.
throw new LockRecursionException(SR.SpinLock_TryEnter_LockRecursionException);
}
SpinWait spinner = new SpinWait();
// Loop until the lock has been successfully acquired or, if specified, the timeout expires.
while (true)
{
// We failed to get the lock, either from the fast route or the last iteration
// and the timeout hasn't expired; spin once and try again.
spinner.SpinOnce();
// Test before trying to CAS, to avoid acquiring the line exclusively unnecessarily.
if (_owner == LockUnowned)
{
if (CompareExchange(ref _owner, newOwner, LockUnowned, ref lockTaken) == LockUnowned)
{
return;
}
}
// Check the timeout. We only RDTSC if the next spin will yield, to amortize the cost.
if (millisecondsTimeout == 0 ||
(millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield &&
TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0))
{
return;
}
}
}
/// <summary>
/// Releases the lock.
/// </summary>
/// <remarks>
/// The default overload of <see cref="Exit()"/> provides the same behavior as if calling <see
/// cref="Exit(bool)"/> using true as the argument, but Exit() could be slightly faster than Exit(true).
/// </remarks>
/// <exception cref="SynchronizationLockException">
/// Thread ownership tracking is enabled, and the current thread is not the owner of this lock.
/// </exception>
public void Exit()
{
// This is the fast path for the thread tracking is disabled, otherwise go to the slow path
if ((_owner & LOCK_ID_DISABLE_MASK) == 0)
ExitSlowPath(true);
else
Interlocked.Decrement(ref _owner);
}
/// <summary>
/// Releases the lock.
/// </summary>
/// <param name="useMemoryBarrier">
/// A Boolean value that indicates whether a memory fence should be issued in order to immediately
/// publish the exit operation to other threads.
/// </param>
/// <remarks>
/// Calling <see cref="Exit(bool)"/> with the <paramref name="useMemoryBarrier"/> argument set to
/// true will improve the fairness of the lock at the expense of some performance. The default <see
/// cref="Enter"/>
/// overload behaves as if specifying true for <paramref name="useMemoryBarrier"/>.
/// </remarks>
/// <exception cref="SynchronizationLockException">
/// Thread ownership tracking is enabled, and the current thread is not the owner of this lock.
/// </exception>
public void Exit(bool useMemoryBarrier)
{
// This is the fast path for the thread tracking is disabled and not to use memory barrier, otherwise go to the slow path
// The reason not to add else statement if the usememorybarrier is that it will add more branching in the code and will prevent
// method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true.
int tmpOwner = _owner;
if ((tmpOwner & LOCK_ID_DISABLE_MASK) != 0 & !useMemoryBarrier)
{
_owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED);
}
else
{
ExitSlowPath(useMemoryBarrier);
}
}
/// <summary>
/// The slow path for exit method if the fast path failed
/// </summary>
/// <param name="useMemoryBarrier">
/// A Boolean value that indicates whether a memory fence should be issued in order to immediately
/// publish the exit operation to other threads
/// </param>
private void ExitSlowPath(bool useMemoryBarrier)
{
bool threadTrackingEnabled = (_owner & LOCK_ID_DISABLE_MASK) == 0;
if (threadTrackingEnabled && !IsHeldByCurrentThread)
{
throw new SynchronizationLockException(SR.SpinLock_Exit_SynchronizationLockException);
}
if (useMemoryBarrier)
{
if (threadTrackingEnabled)
{
Interlocked.Exchange(ref _owner, LOCK_UNOWNED);
}
else
{
Interlocked.Decrement(ref _owner);
}
}
else
{
if (threadTrackingEnabled)
{
_owner = LOCK_UNOWNED;
}
else
{
int tmpOwner = _owner;
_owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED);
}
}
}
/// <summary>
/// Gets whether the lock is currently held by any thread.
/// </summary>
public bool IsHeld
{
get
{
if (IsThreadOwnerTrackingEnabled)
return _owner != LOCK_UNOWNED;
return (_owner & LOCK_ANONYMOUS_OWNED) != LOCK_UNOWNED;
}
}
/// <summary>
/// Gets whether the lock is currently held by any thread.
/// </summary>
/// <summary>
/// Gets whether the lock is held by the current thread.
/// </summary>
/// <remarks>
/// If the lock was initialized to track owner threads, this will return whether the lock is acquired
/// by the current thread. It is invalid to use this property when the lock was initialized to not
/// track thread ownership.
/// </remarks>
/// <exception cref="System.InvalidOperationException">
/// Thread ownership tracking is disabled.
/// </exception>
public bool IsHeldByCurrentThread
{
get
{
if (!IsThreadOwnerTrackingEnabled)
{
throw new InvalidOperationException(SR.SpinLock_IsHeldByCurrentThread);
}
return (_owner & (~LOCK_ID_DISABLE_MASK)) == Environment.CurrentManagedThreadId;
}
}
/// <summary>Gets whether thread ownership tracking is enabled for this instance.</summary>
public bool IsThreadOwnerTrackingEnabled => (_owner & LOCK_ID_DISABLE_MASK) == 0;
#region Debugger proxy class
/// <summary>
/// Internal class used by debug type proxy attribute to display the owner thread ID
/// </summary>
internal class SystemThreading_SpinLockDebugView
{
// SpinLock object
private SpinLock _spinLock;
/// <summary>
/// SystemThreading_SpinLockDebugView constructor
/// </summary>
/// <param name="spinLock">The SpinLock to be proxied.</param>
public SystemThreading_SpinLockDebugView(SpinLock spinLock)
{
// Note that this makes a copy of the SpinLock (struct). It doesn't hold a reference to it.
_spinLock = spinLock;
}
/// <summary>
/// Checks if the lock is held by the current thread or not
/// </summary>
public bool? IsHeldByCurrentThread
{
get
{
try
{
return _spinLock.IsHeldByCurrentThread;
}
catch (InvalidOperationException)
{
return null;
}
}
}
/// <summary>
/// Gets the current owner thread, zero if it is released
/// </summary>
public int? OwnerThreadID
{
get
{
if (_spinLock.IsThreadOwnerTrackingEnabled)
{
return _spinLock._owner;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets whether the lock is currently held by any thread or not.
/// </summary>
public bool IsHeld => _spinLock.IsHeld;
}
#endregion
}
}
#pragma warning restore 0420
| |
////////////////////////////////////////////////////////////////////////////////
// StickyWindows
//
// Copyright (c) 2004 Corneliu I. Tusnea, 2017 Thomas Freudenberg
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the author be held liable for any damages arising from
// the use of this software.
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
//
// Notice: Check CodeProject for details about using this class
//
//////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace StickyWindows {
/// <summary>
/// A windows that Sticks to other windows of the same type when moved or resized.
/// You get a nice way of organizing multiple top-level windows.
/// Quite similar with WinAmp 2.x style of sticking the windows
/// </summary>
public class StickyWindow : NativeWindow {
/// <summary>
/// Global List of registered StickyWindows
/// </summary>
private static readonly List<BaseFormAdapter> _globalStickyWindows = new List<BaseFormAdapter>();
[Flags]
private enum ResizeDir {
Top = 2,
Bottom = 4,
Left = 8,
Right = 16
}
// Internal Message Processor
private delegate bool ProcessMessage(ref Message m);
private ProcessMessage _messageProcessor;
// Messages processors based on type
private readonly ProcessMessage _defaultMessageProcessor;
private readonly ProcessMessage _moveMessageProcessor;
private readonly ProcessMessage _resizeMessageProcessor;
// Move stuff
private bool _movingForm;
private Point _formOffsetPoint; // calculated offset rect to be added !! (min distances in all directions!!)
private Point _offsetPoint; // primary offset
// Resize stuff
private bool _resizingForm;
private ResizeDir _resizeDirection;
private Rectangle _formOffsetRect; // calculated rect to fix the size
private Point _mousePoint; // mouse position
// General Stuff
private readonly BaseFormAdapter _originalForm; // the form
private Rectangle _formRect; // form bounds
private Rectangle _formOriginalRect; // bounds before last operation started
// public properties
private static int _stickGap = 20; // distance to stick
/// <summary>
/// Allow the form to stick while resizing
/// Default value = true
/// </summary>
public bool StickOnResize { get; set; }
/// <summary>
/// Allow the form to stick while moving
/// Default value = true
/// </summary>
public bool StickOnMove { get; set; }
/// <summary>
/// Allow sticking to Screen Margins
/// Default value = true
/// </summary>
public bool StickToScreen { get; set; }
/// <summary>
/// Allow sticking to other StickWindows
/// Default value = true
/// </summary>
public bool StickToOther { get; set; }
/// <summary>
/// Register a new form as an external reference form.
/// All Sticky windows will try to stick to the external references
/// Use this to register your MainFrame so the child windows try to stick to it, when your MainFrame is NOT a sticky window
/// </summary>
/// <param name="frmExternal">External window that will be used as reference</param>
public static void RegisterExternalReferenceForm(BaseFormAdapter frmExternal) {
_globalStickyWindows.Add(frmExternal);
}
/// <summary>
/// Register a new form as an external reference form.
/// All Sticky windows will try to stick to the external references
/// Use this to register your MainFrame so the child windows try to stick to it, when your MainFrame is NOT a sticky window
/// </summary>
/// <param name="frmExternal">External window that will be used as reference</param>
public static void RegisterExternalReferenceForm(Form frmExternal) {
RegisterExternalReferenceForm(new WinFormAdapter(frmExternal));
}
/// <summary>
/// Unregister a form from the external references.
/// <see cref="RegisterExternalReferenceForm(BaseFormAdapter)"/>
/// </summary>
/// <param name="frmExternal">External window that will was used as reference</param>
public static void UnregisterExternalReferenceForm(BaseFormAdapter frmExternal) {
_globalStickyWindows.Remove(frmExternal);
}
/// <summary>
/// Make the form Sticky
/// </summary>
/// <param name="form">Form to be made sticky</param>
public StickyWindow(Form form)
: this(new WinFormAdapter(form)) {}
/// <summary>
/// Make the form Sticky
/// </summary>
/// <param name="form">Form to be made sticky</param>
public StickyWindow(BaseFormAdapter form) {
_resizingForm = false;
_movingForm = false;
_originalForm = form;
_formRect = Rectangle.Empty;
_formOffsetRect = Rectangle.Empty;
_formOffsetPoint = Point.Empty;
_offsetPoint = Point.Empty;
_mousePoint = Point.Empty;
StickOnMove = true;
StickOnResize = true;
StickToScreen = true;
StickToOther = true;
_defaultMessageProcessor = DefaultMsgProcessor;
_moveMessageProcessor = MoveMsgProcessor;
_resizeMessageProcessor = ResizeMsgProcessor;
_messageProcessor = _defaultMessageProcessor;
AssignHandle(_originalForm.Handle);
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void OnHandleChange() {
if ((int)Handle != 0) {
_globalStickyWindows.Add(_originalForm);
} else {
_globalStickyWindows.Remove(_originalForm);
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m) {
if (!_messageProcessor(ref m)) {
base.WndProc(ref m);
}
}
/// <summary>
/// Processes messages during normal operations (while the form is not resized or moved)
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private bool DefaultMsgProcessor(ref Message m) {
switch (m.Msg) {
case Win32.WM.WM_NCLBUTTONDOWN: {
_originalForm.Activate();
_mousePoint.X = (short)Win32.Bit.LoWord((int)m.LParam);
_mousePoint.Y = (short)Win32.Bit.HiWord((int)m.LParam);
if (OnNonClientLeftButtonDown((int)m.WParam, _mousePoint)) {
//m.Result = new IntPtr ( (resizingForm || movingForm) ? 1 : 0 );
m.Result = (IntPtr)((_resizingForm || _movingForm) ? 1 : 0);
return true;
}
break;
}
}
return false;
}
/// <summary>
/// Checks where the click was in the NC area and starts move or resize operation
/// </summary>
/// <param name="iHitTest"></param>
/// <param name="point"></param>
/// <returns></returns>
private bool OnNonClientLeftButtonDown(int iHitTest, Point point) {
var rParent = _originalForm.Bounds;
_offsetPoint = point;
switch (iHitTest) {
case Win32.HT.HTCAPTION: {
// request for move
if (StickOnMove) {
_offsetPoint.Offset(-rParent.Left, -rParent.Top);
StartMove();
return true;
}
return false; // leave default processing
}
// requests for resize
case Win32.HT.HTTOPLEFT:
return StartResize(ResizeDir.Top | ResizeDir.Left);
case Win32.HT.HTTOP:
return StartResize(ResizeDir.Top);
case Win32.HT.HTTOPRIGHT:
return StartResize(ResizeDir.Top | ResizeDir.Right);
case Win32.HT.HTRIGHT:
return StartResize(ResizeDir.Right);
case Win32.HT.HTBOTTOMRIGHT:
return StartResize(ResizeDir.Bottom | ResizeDir.Right);
case Win32.HT.HTBOTTOM:
return StartResize(ResizeDir.Bottom);
case Win32.HT.HTBOTTOMLEFT:
return StartResize(ResizeDir.Bottom | ResizeDir.Left);
case Win32.HT.HTLEFT:
return StartResize(ResizeDir.Left);
}
return false;
}
private bool StartResize(ResizeDir resDir) {
if (StickOnResize) {
_resizeDirection = resDir;
_formRect = _originalForm.Bounds;
_formOriginalRect = _originalForm.Bounds; // save the old bounds
if (!_originalForm.Capture) // start capturing messages
{
_originalForm.Capture = true;
}
_messageProcessor = _resizeMessageProcessor;
return true; // catch the message
}
return false; // leave default processing !
}
private bool ResizeMsgProcessor(ref Message m) {
if (!_originalForm.Capture) {
Cancel();
return false;
}
switch (m.Msg) {
case Win32.WM.WM_LBUTTONUP: {
// ok, resize finished !!!
EndResize();
break;
}
case Win32.WM.WM_MOUSEMOVE: {
_mousePoint.X = (short)Win32.Bit.LoWord((int)m.LParam);
_mousePoint.Y = (short)Win32.Bit.HiWord((int)m.LParam);
Resize(_mousePoint);
break;
}
case Win32.WM.WM_KEYDOWN: {
if ((int)m.WParam == Win32.VK.VK_ESCAPE) {
_originalForm.Bounds = _formOriginalRect; // set back old size
Cancel();
}
break;
}
}
return false;
}
private void EndResize() {
Cancel();
}
private void Resize(Point p) {
p = _originalForm.PointToScreen(p);
var activeScr = Screen.FromPoint(p);
_formRect = _originalForm.Bounds;
var iRight = _formRect.Right;
var iBottom = _formRect.Bottom;
// no normalize required
// first strech the window to the new position
if ((_resizeDirection & ResizeDir.Left) == ResizeDir.Left) {
_formRect.Width = _formRect.X - p.X + _formRect.Width;
_formRect.X = iRight - _formRect.Width;
}
if ((_resizeDirection & ResizeDir.Right) == ResizeDir.Right) {
_formRect.Width = p.X - _formRect.Left;
}
if ((_resizeDirection & ResizeDir.Top) == ResizeDir.Top) {
_formRect.Height = _formRect.Height - p.Y + _formRect.Top;
_formRect.Y = iBottom - _formRect.Height;
}
if ((_resizeDirection & ResizeDir.Bottom) == ResizeDir.Bottom) {
_formRect.Height = p.Y - _formRect.Top;
}
// this is the real new position
// now, try to snap it to different objects (first to screen)
// CARE !!! We use "Width" and "Height" as Bottom & Right!! (C++ style)
//formOffsetRect = new Rectangle ( stickGap + 1, stickGap + 1, 0, 0 );
_formOffsetRect.X = _stickGap + 1;
_formOffsetRect.Y = _stickGap + 1;
_formOffsetRect.Height = 0;
_formOffsetRect.Width = 0;
if (StickToScreen) {
Resize_Stick(activeScr.WorkingArea, false);
}
if (StickToOther) {
// now try to stick to other forms
foreach (var sw in _globalStickyWindows) {
if (sw != _originalForm) {
Resize_Stick(sw.Bounds, true);
}
}
}
// Fix (clear) the values that were not updated to stick
if (_formOffsetRect.X == _stickGap + 1) {
_formOffsetRect.X = 0;
}
if (_formOffsetRect.Width == _stickGap + 1) {
_formOffsetRect.Width = 0;
}
if (_formOffsetRect.Y == _stickGap + 1) {
_formOffsetRect.Y = 0;
}
if (_formOffsetRect.Height == _stickGap + 1) {
_formOffsetRect.Height = 0;
}
// compute the new form size
if ((_resizeDirection & ResizeDir.Left) == ResizeDir.Left) {
// left resize requires special handling of X & Width acording to MinSize and MinWindowTrackSize
var iNewWidth = _formRect.Width + _formOffsetRect.Width + _formOffsetRect.X;
if (_originalForm.MaximumSize.Width != 0) {
iNewWidth = Math.Min(iNewWidth, _originalForm.MaximumSize.Width);
}
iNewWidth = Math.Min(iNewWidth, SystemInformation.MaxWindowTrackSize.Width);
iNewWidth = Math.Max(iNewWidth, _originalForm.MinimumSize.Width);
iNewWidth = Math.Max(iNewWidth, SystemInformation.MinWindowTrackSize.Width);
_formRect.X = iRight - iNewWidth;
_formRect.Width = iNewWidth;
} else {
// other resizes
_formRect.Width += _formOffsetRect.Width + _formOffsetRect.X;
}
if ((_resizeDirection & ResizeDir.Top) == ResizeDir.Top) {
var iNewHeight = _formRect.Height + _formOffsetRect.Height + _formOffsetRect.Y;
if (_originalForm.MaximumSize.Height != 0) {
iNewHeight = Math.Min(iNewHeight, _originalForm.MaximumSize.Height);
}
iNewHeight = Math.Min(iNewHeight, SystemInformation.MaxWindowTrackSize.Height);
iNewHeight = Math.Max(iNewHeight, _originalForm.MinimumSize.Height);
iNewHeight = Math.Max(iNewHeight, SystemInformation.MinWindowTrackSize.Height);
_formRect.Y = iBottom - iNewHeight;
_formRect.Height = iNewHeight;
} else {
// all other resizing are fine
_formRect.Height += _formOffsetRect.Height + _formOffsetRect.Y;
}
// Done !!
_originalForm.Bounds = _formRect;
}
private void Resize_Stick(Rectangle toRect, bool bInsideStick) {
if (_formRect.Right >= (toRect.Left - _stickGap) && _formRect.Left <= (toRect.Right + _stickGap)) {
if ((_resizeDirection & ResizeDir.Top) == ResizeDir.Top) {
if (Math.Abs(_formRect.Top - toRect.Bottom) <= Math.Abs(_formOffsetRect.Top) && bInsideStick) {
_formOffsetRect.Y = _formRect.Top - toRect.Bottom; // snap top to bottom
} else if (Math.Abs(_formRect.Top - toRect.Top) <= Math.Abs(_formOffsetRect.Top)) {
_formOffsetRect.Y = _formRect.Top - toRect.Top; // snap top to top
}
}
if ((_resizeDirection & ResizeDir.Bottom) == ResizeDir.Bottom) {
if (Math.Abs(_formRect.Bottom - toRect.Top) <= Math.Abs(_formOffsetRect.Bottom) && bInsideStick) {
_formOffsetRect.Height = toRect.Top - _formRect.Bottom; // snap Bottom to top
} else if (Math.Abs(_formRect.Bottom - toRect.Bottom) <= Math.Abs(_formOffsetRect.Bottom)) {
_formOffsetRect.Height = toRect.Bottom - _formRect.Bottom; // snap bottom to bottom
}
}
}
if (_formRect.Bottom >= (toRect.Top - _stickGap) && _formRect.Top <= (toRect.Bottom + _stickGap)) {
if ((_resizeDirection & ResizeDir.Right) == ResizeDir.Right) {
if (Math.Abs(_formRect.Right - toRect.Left) <= Math.Abs(_formOffsetRect.Right) && bInsideStick) {
_formOffsetRect.Width = toRect.Left - _formRect.Right; // Stick right to left
} else if (Math.Abs(_formRect.Right - toRect.Right) <= Math.Abs(_formOffsetRect.Right)) {
_formOffsetRect.Width = toRect.Right - _formRect.Right; // Stick right to right
}
}
if ((_resizeDirection & ResizeDir.Left) == ResizeDir.Left) {
if (Math.Abs(_formRect.Left - toRect.Right) <= Math.Abs(_formOffsetRect.Left) && bInsideStick) {
_formOffsetRect.X = _formRect.Left - toRect.Right; // Stick left to right
} else if (Math.Abs(_formRect.Left - toRect.Left) <= Math.Abs(_formOffsetRect.Left)) {
_formOffsetRect.X = _formRect.Left - toRect.Left; // Stick left to left
}
}
}
}
private void StartMove() {
_formRect = _originalForm.Bounds;
_formOriginalRect = _originalForm.Bounds; // save original position
if (!_originalForm.Capture) // start capturing messages
{
_originalForm.Capture = true;
}
_messageProcessor = _moveMessageProcessor;
}
private bool MoveMsgProcessor(ref Message m) {
// internal message loop
if (!_originalForm.Capture) {
Cancel();
return false;
}
switch (m.Msg) {
case Win32.WM.WM_LBUTTONUP: {
// ok, move finished !!!
EndMove();
break;
}
case Win32.WM.WM_MOUSEMOVE: {
_mousePoint.X = (short)Win32.Bit.LoWord((int)m.LParam);
_mousePoint.Y = (short)Win32.Bit.HiWord((int)m.LParam);
Move(_mousePoint);
break;
}
case Win32.WM.WM_KEYDOWN: {
if ((int)m.WParam == Win32.VK.VK_ESCAPE) {
_originalForm.Bounds = _formOriginalRect; // set back old size
Cancel();
}
break;
}
}
return false;
}
private void EndMove() {
Cancel();
}
private void Move(Point p) {
p = _originalForm.PointToScreen(p);
var activeScr = Screen.FromPoint(p); // get the screen from the point !!
if (!activeScr.WorkingArea.Contains(p)) {
p.X = NormalizeInside(p.X, activeScr.WorkingArea.Left, activeScr.WorkingArea.Right);
p.Y = NormalizeInside(p.Y, activeScr.WorkingArea.Top, activeScr.WorkingArea.Bottom);
}
p.Offset(-_offsetPoint.X, -_offsetPoint.Y);
// p is the exact location of the frame - so we can play with it
// to detect the new position acording to different bounds
_formRect.Location = p; // this is the new positon of the form
_formOffsetPoint.X = _stickGap + 1; // (more than) maximum gaps
_formOffsetPoint.Y = _stickGap + 1;
if (StickToScreen) {
Move_Stick(activeScr.WorkingArea, false);
}
// Now try to snap to other windows
if (StickToOther) {
foreach (var sw in _globalStickyWindows) {
if (sw != _originalForm) {
Move_Stick(sw.Bounds, true);
}
}
}
if (_formOffsetPoint.X == _stickGap + 1) {
_formOffsetPoint.X = 0;
}
if (_formOffsetPoint.Y == _stickGap + 1) {
_formOffsetPoint.Y = 0;
}
_formRect.Offset(_formOffsetPoint);
_originalForm.Bounds = _formRect;
}
/// <summary>
///
/// </summary>
/// <param name="toRect">Rect to try to snap to</param>
/// <param name="bInsideStick">Allow snapping on the inside (eg: window to screen)</param>
private void Move_Stick(Rectangle toRect, bool bInsideStick) {
// compare distance from toRect to formRect
// and then with the found distances, compare the most closed position
if (_formRect.Bottom >= (toRect.Top - _stickGap) && _formRect.Top <= (toRect.Bottom + _stickGap)) {
if (bInsideStick) {
if ((Math.Abs(_formRect.Left - toRect.Right) <= Math.Abs(_formOffsetPoint.X))) {
// left 2 right
_formOffsetPoint.X = toRect.Right - _formRect.Left;
}
if ((Math.Abs(_formRect.Left + _formRect.Width - toRect.Left) <= Math.Abs(_formOffsetPoint.X))) {
// right 2 left
_formOffsetPoint.X = toRect.Left - _formRect.Width - _formRect.Left;
}
}
if (Math.Abs(_formRect.Left - toRect.Left) <= Math.Abs(_formOffsetPoint.X)) {
// snap left 2 left
_formOffsetPoint.X = toRect.Left - _formRect.Left;
}
if (Math.Abs(_formRect.Left + _formRect.Width - toRect.Left - toRect.Width) <= Math.Abs(_formOffsetPoint.X)) {
// snap right 2 right
_formOffsetPoint.X = toRect.Left + toRect.Width - _formRect.Width - _formRect.Left;
}
}
if (_formRect.Right >= (toRect.Left - _stickGap) && _formRect.Left <= (toRect.Right + _stickGap)) {
if (bInsideStick) {
if (Math.Abs(_formRect.Top - toRect.Bottom) <= Math.Abs(_formOffsetPoint.Y)) {
// Stick Top to Bottom
_formOffsetPoint.Y = toRect.Bottom - _formRect.Top;
}
if (Math.Abs(_formRect.Top + _formRect.Height - toRect.Top) <= Math.Abs(_formOffsetPoint.Y)) {
// snap Bottom to Top
_formOffsetPoint.Y = toRect.Top - _formRect.Height - _formRect.Top;
}
}
// try to snap top 2 top also
if (Math.Abs(_formRect.Top - toRect.Top) <= Math.Abs(_formOffsetPoint.Y)) {
// top 2 top
_formOffsetPoint.Y = toRect.Top - _formRect.Top;
}
if (Math.Abs(_formRect.Top + _formRect.Height - toRect.Top - toRect.Height) <= Math.Abs(_formOffsetPoint.Y)) {
// bottom 2 bottom
_formOffsetPoint.Y = toRect.Top + toRect.Height - _formRect.Height - _formRect.Top;
}
}
}
private static int NormalizeInside(int iP1, int iM1, int iM2) {
if (iP1 <= iM1) {
return iM1;
}
if (iP1 >= iM2) {
return iM2;
}
return iP1;
}
private void Cancel() {
_originalForm.Capture = false;
_movingForm = false;
_resizingForm = false;
_messageProcessor = _defaultMessageProcessor;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Markup;
using Microsoft.Practices.Prism.Properties;
namespace Microsoft.Practices.Prism.Modularity
{
/// <summary>
/// The <see cref="ModuleCatalog"/> holds information about the modules that can be used by the
/// application. Each module is described in a <see cref="ModuleInfo"/> class, that records the
/// name, type and location of the module.
///
/// It also verifies that the <see cref="ModuleCatalog"/> is internally valid. That means that
/// it does not have:
/// <list>
/// <item>Circular dependencies</item>
/// <item>Missing dependencies</item>
/// <item>
/// Invalid dependencies, such as a Module that's loaded at startup that depends on a module
/// that might need to be retrieved.
/// </item>
/// </list>
/// The <see cref="ModuleCatalog"/> also serves as a baseclass for more specialized Catalogs .
/// </summary>
[ContentProperty("Items")]
public class ModuleCatalog : IModuleCatalog
{
private readonly ModuleCatalogItemCollection items;
private bool isLoaded;
/// <summary>
/// Initializes a new instance of the <see cref="ModuleCatalog"/> class.
/// </summary>
public ModuleCatalog()
{
this.items = new ModuleCatalogItemCollection();
this.items.CollectionChanged += this.ItemsCollectionChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="ModuleCatalog"/> class while providing an
/// initial list of <see cref="ModuleInfo"/>s.
/// </summary>
/// <param name="modules">The initial list of modules.</param>
public ModuleCatalog(IEnumerable<ModuleInfo> modules)
: this()
{
if (modules == null) throw new System.ArgumentNullException("modules");
foreach (ModuleInfo moduleInfo in modules)
{
this.Items.Add(moduleInfo);
}
}
/// <summary>
/// Gets the items in the <see cref="ModuleCatalog"/>. This property is mainly used to add <see cref="ModuleInfoGroup"/>s or
/// <see cref="ModuleInfo"/>s through XAML.
/// </summary>
/// <value>The items in the catalog.</value>
public Collection<IModuleCatalogItem> Items
{
get { return this.items; }
}
/// <summary>
/// Gets all the <see cref="ModuleInfo"/> classes that are in the <see cref="ModuleCatalog"/>, regardless
/// if they are within a <see cref="ModuleInfoGroup"/> or not.
/// </summary>
/// <value>The modules.</value>
public virtual IEnumerable<ModuleInfo> Modules
{
get
{
return this.GrouplessModules.Union(this.Groups.SelectMany(g => g));
}
}
/// <summary>
/// Gets the <see cref="ModuleInfoGroup"/>s that have been added to the <see cref="ModuleCatalog"/>.
/// </summary>
/// <value>The groups.</value>
public IEnumerable<ModuleInfoGroup> Groups
{
get
{
return this.Items.OfType<ModuleInfoGroup>();
}
}
/// <summary>
/// Gets or sets a value that remembers whether the <see cref="ModuleCatalog"/> has been validated already.
/// </summary>
protected bool Validated { get; set; }
/// <summary>
/// Returns the list of <see cref="ModuleInfo"/>s that are not contained within any <see cref="ModuleInfoGroup"/>.
/// </summary>
/// <value>The groupless modules.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Groupless")]
protected IEnumerable<ModuleInfo> GrouplessModules
{
get
{
return this.Items.OfType<ModuleInfo>();
}
}
/// <summary>
/// Creates a <see cref="ModuleCatalog"/> from XAML.
/// </summary>
/// <param name="xamlStream"><see cref="Stream"/> that contains the XAML declaration of the catalog.</param>
/// <returns>An instance of <see cref="ModuleCatalog"/> built from the XAML.</returns>
public static ModuleCatalog CreateFromXaml(Stream xamlStream)
{
if (xamlStream == null)
{
throw new ArgumentNullException("xamlStream");
}
return XamlReader.Load(xamlStream) as ModuleCatalog;
}
/// <summary>
/// Creates a <see cref="ModuleCatalog"/> from a XAML included as an Application Resource.
/// </summary>
/// <param name="builderResourceUri">Relative <see cref="Uri"/> that identifies the XAML included as an Application Resource.</param>
/// <returns>An instance of <see cref="ModuleCatalog"/> build from the XAML.</returns>
public static ModuleCatalog CreateFromXaml(Uri builderResourceUri)
{
var streamInfo = System.Windows.Application.GetResourceStream(builderResourceUri);
if ((streamInfo != null) && (streamInfo.Stream != null))
{
return CreateFromXaml(streamInfo.Stream);
}
return null;
}
/// <summary>
/// Loads the catalog if necessary.
/// </summary>
public void Load()
{
this.isLoaded = true;
this.InnerLoad();
}
/// <summary>
/// Return the list of <see cref="ModuleInfo"/>s that <paramref name="moduleInfo"/> depends on.
/// </summary>
/// <remarks>
/// If the <see cref="ModuleCatalog"/> was not yet validated, this method will call <see cref="Validate"/>.
/// </remarks>
/// <param name="moduleInfo">The <see cref="ModuleInfo"/> to get the </param>
/// <returns>An enumeration of <see cref="ModuleInfo"/> that <paramref name="moduleInfo"/> depends on.</returns>
public virtual IEnumerable<ModuleInfo> GetDependentModules(ModuleInfo moduleInfo)
{
this.EnsureCatalogValidated();
return this.GetDependentModulesInner(moduleInfo);
}
/// <summary>
/// Returns a list of <see cref="ModuleInfo"/>s that contain both the <see cref="ModuleInfo"/>s in
/// <paramref name="modules"/>, but also all the modules they depend on.
/// </summary>
/// <param name="modules">The modules to get the dependencies for.</param>
/// <returns>
/// A list of <see cref="ModuleInfo"/> that contains both all <see cref="ModuleInfo"/>s in <paramref name="modules"/>
/// but also all the <see cref="ModuleInfo"/> they depend on.
/// </returns>
public virtual IEnumerable<ModuleInfo> CompleteListWithDependencies(IEnumerable<ModuleInfo> modules)
{
if (modules == null)
{
throw new ArgumentNullException("modules");
}
this.EnsureCatalogValidated();
List<ModuleInfo> completeList = new List<ModuleInfo>();
List<ModuleInfo> pendingList = modules.ToList();
while (pendingList.Count > 0)
{
ModuleInfo moduleInfo = pendingList[0];
foreach (ModuleInfo dependency in this.GetDependentModules(moduleInfo))
{
if (!completeList.Contains(dependency) && !pendingList.Contains(dependency))
{
pendingList.Add(dependency);
}
}
pendingList.RemoveAt(0);
completeList.Add(moduleInfo);
}
IEnumerable<ModuleInfo> sortedList = this.Sort(completeList);
return sortedList;
}
/// <summary>
/// Validates the <see cref="ModuleCatalog"/>.
/// </summary>
/// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails.</exception>
public virtual void Validate()
{
this.ValidateUniqueModules();
this.ValidateDependencyGraph();
this.ValidateCrossGroupDependencies();
this.ValidateDependenciesInitializationMode();
this.Validated = true;
}
/// <summary>
/// Adds a <see cref="ModuleInfo"/> to the <see cref="ModuleCatalog"/>.
/// </summary>
/// <param name="moduleInfo">The <see cref="ModuleInfo"/> to add.</param>
/// <returns>The <see cref="ModuleCatalog"/> for easily adding multiple modules.</returns>
public virtual void AddModule(ModuleInfo moduleInfo)
{
this.Items.Add(moduleInfo);
}
/// <summary>
/// Adds a groupless <see cref="ModuleInfo"/> to the catalog.
/// </summary>
/// <param name="moduleType"><see cref="Type"/> of the module to be added.</param>
/// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param>
/// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns>
public ModuleCatalog AddModule(Type moduleType, params string[] dependsOn)
{
return this.AddModule(moduleType, InitializationMode.WhenAvailable, dependsOn);
}
/// <summary>
/// Adds a groupless <see cref="ModuleInfo"/> to the catalog.
/// </summary>
/// <param name="moduleType"><see cref="Type"/> of the module to be added.</param>
/// <param name="initializationMode">Stage on which the module to be added will be initialized.</param>
/// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param>
/// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns>
public ModuleCatalog AddModule(Type moduleType, InitializationMode initializationMode, params string[] dependsOn)
{
if (moduleType == null) throw new System.ArgumentNullException("moduleType");
return this.AddModule(moduleType.Name, moduleType.AssemblyQualifiedName, initializationMode, dependsOn);
}
/// <summary>
/// Adds a groupless <see cref="ModuleInfo"/> to the catalog.
/// </summary>
/// <param name="moduleName">Name of the module to be added.</param>
/// <param name="moduleType"><see cref="Type"/> of the module to be added.</param>
/// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param>
/// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns>
public ModuleCatalog AddModule(string moduleName, string moduleType, params string[] dependsOn)
{
return this.AddModule(moduleName, moduleType, InitializationMode.WhenAvailable, dependsOn);
}
/// <summary>
/// Adds a groupless <see cref="ModuleInfo"/> to the catalog.
/// </summary>
/// <param name="moduleName">Name of the module to be added.</param>
/// <param name="moduleType"><see cref="Type"/> of the module to be added.</param>
/// <param name="initializationMode">Stage on which the module to be added will be initialized.</param>
/// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param>
/// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns>
public ModuleCatalog AddModule(string moduleName, string moduleType, InitializationMode initializationMode, params string[] dependsOn)
{
return this.AddModule(moduleName, moduleType, null, initializationMode, dependsOn);
}
/// <summary>
/// Adds a groupless <see cref="ModuleInfo"/> to the catalog.
/// </summary>
/// <param name="moduleName">Name of the module to be added.</param>
/// <param name="moduleType"><see cref="Type"/> of the module to be added.</param>
/// <param name="refValue">Reference to the location of the module to be added assembly.</param>
/// <param name="initializationMode">Stage on which the module to be added will be initialized.</param>
/// <param name="dependsOn">Collection of module names (<see cref="ModuleInfo.ModuleName"/>) of the modules on which the module to be added logically depends on.</param>
/// <returns>The same <see cref="ModuleCatalog"/> instance with the added module.</returns>
public ModuleCatalog AddModule(string moduleName, string moduleType, string refValue, InitializationMode initializationMode, params string[] dependsOn)
{
if (moduleName == null)
{
throw new ArgumentNullException("moduleName");
}
if (moduleType == null)
{
throw new ArgumentNullException("moduleType");
}
ModuleInfo moduleInfo = new ModuleInfo(moduleName, moduleType);
moduleInfo.DependsOn.AddRange(dependsOn);
moduleInfo.InitializationMode = initializationMode;
moduleInfo.Ref = refValue;
this.Items.Add(moduleInfo);
return this;
}
/// <summary>
/// Initializes the catalog, which may load and validate the modules.
/// </summary>
/// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalog"/> fails, because this method calls <see cref="Validate"/>.</exception>
public virtual void Initialize()
{
if (!this.isLoaded)
{
this.Load();
}
this.Validate();
}
/// <summary>
/// Creates and adds a <see cref="ModuleInfoGroup"/> to the catalog.
/// </summary>
/// <param name="initializationMode">Stage on which the module group to be added will be initialized.</param>
/// <param name="refValue">Reference to the location of the module group to be added.</param>
/// <param name="moduleInfos">Collection of <see cref="ModuleInfo"/> included in the group.</param>
/// <returns><see cref="ModuleCatalog"/> with the added module group.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
public virtual ModuleCatalog AddGroup(InitializationMode initializationMode, string refValue, params ModuleInfo[] moduleInfos)
{
if (moduleInfos == null) throw new System.ArgumentNullException("moduleInfos");
ModuleInfoGroup newGroup = new ModuleInfoGroup();
newGroup.InitializationMode = initializationMode;
newGroup.Ref = refValue;
foreach (ModuleInfo info in moduleInfos)
{
newGroup.Add(info);
}
this.items.Add(newGroup);
return this;
}
/// <summary>
/// Checks for cyclic dependencies, by calling the dependencysolver.
/// </summary>
/// <param name="modules">the.</param>
/// <returns></returns>
protected static string[] SolveDependencies(IEnumerable<ModuleInfo> modules)
{
if (modules == null) throw new System.ArgumentNullException("modules");
ModuleDependencySolver solver = new ModuleDependencySolver();
foreach (ModuleInfo data in modules)
{
solver.AddModule(data.ModuleName);
if (data.DependsOn != null)
{
foreach (string dependency in data.DependsOn)
{
solver.AddDependency(data.ModuleName, dependency);
}
}
}
if (solver.ModuleCount > 0)
{
return solver.Solve();
}
return new string[0];
}
/// <summary>
/// Ensures that all the dependencies within <paramref name="modules"/> refer to <see cref="ModuleInfo"/>s
/// within that list.
/// </summary>
/// <param name="modules">The modules to validate modules for.</param>
/// <exception cref="ModularityException">
/// Throws if a <see cref="ModuleInfo"/> in <paramref name="modules"/> depends on a module that's
/// not in <paramref name="modules"/>.
/// </exception>
/// <exception cref="System.ArgumentNullException">Throws if <paramref name="modules"/> is <see langword="null"/>.</exception>
protected static void ValidateDependencies(IEnumerable<ModuleInfo> modules)
{
if (modules == null) throw new System.ArgumentNullException("modules");
var moduleNames = modules.Select(m => m.ModuleName).ToList();
foreach (ModuleInfo moduleInfo in modules)
{
if (moduleInfo.DependsOn != null && moduleInfo.DependsOn.Except(moduleNames).Any())
{
throw new ModularityException(
moduleInfo.ModuleName,
String.Format(CultureInfo.CurrentCulture, Resources.ModuleDependenciesNotMetInGroup, moduleInfo.ModuleName));
}
}
}
/// <summary>
/// Does the actual work of loading the catalog. The base implementation does nothing.
/// </summary>
protected virtual void InnerLoad()
{
}
/// <summary>
/// Sorts a list of <see cref="ModuleInfo"/>s. This method is called by <see cref="CompleteListWithDependencies"/>
/// to return a sorted list.
/// </summary>
/// <param name="modules">The <see cref="ModuleInfo"/>s to sort.</param>
/// <returns>Sorted list of <see cref="ModuleInfo"/>s</returns>
protected virtual IEnumerable<ModuleInfo> Sort(IEnumerable<ModuleInfo> modules)
{
foreach (string moduleName in SolveDependencies(modules))
{
yield return modules.First(m => m.ModuleName == moduleName);
}
}
/// <summary>
/// Makes sure all modules have an Unique name.
/// </summary>
/// <exception cref="DuplicateModuleException">
/// Thrown if the names of one or more modules are not unique.
/// </exception>
protected virtual void ValidateUniqueModules()
{
List<string> moduleNames = this.Modules.Select(m => m.ModuleName).ToList();
string duplicateModule = moduleNames.FirstOrDefault(
m => moduleNames.Count(m2 => m2 == m) > 1);
if (duplicateModule != null)
{
throw new DuplicateModuleException(duplicateModule, String.Format(CultureInfo.CurrentCulture, Resources.DuplicatedModule, duplicateModule));
}
}
/// <summary>
/// Ensures that there are no cyclic dependencies.
/// </summary>
protected virtual void ValidateDependencyGraph()
{
SolveDependencies(this.Modules);
}
/// <summary>
/// Ensures that there are no dependencies between modules on different groups.
/// </summary>
/// <remarks>
/// A groupless module can only depend on other groupless modules.
/// A module within a group can depend on other modules within the same group and/or on groupless modules.
/// </remarks>
protected virtual void ValidateCrossGroupDependencies()
{
ValidateDependencies(this.GrouplessModules);
foreach (ModuleInfoGroup group in this.Groups)
{
ValidateDependencies(this.GrouplessModules.Union(group));
}
}
/// <summary>
/// Ensures that there are no modules marked to be loaded <see cref="InitializationMode.WhenAvailable"/>
/// depending on modules loaded <see cref="InitializationMode.OnDemand"/>
/// </summary>
protected virtual void ValidateDependenciesInitializationMode()
{
ModuleInfo moduleInfo = this.Modules.FirstOrDefault(
m =>
m.InitializationMode == InitializationMode.WhenAvailable &&
this.GetDependentModulesInner(m)
.Any(dependency => dependency.InitializationMode == InitializationMode.OnDemand));
if (moduleInfo != null)
{
throw new ModularityException(
moduleInfo.ModuleName,
String.Format(CultureInfo.CurrentCulture, Resources.StartupModuleDependsOnAnOnDemandModule, moduleInfo.ModuleName));
}
}
/// <summary>
/// Returns the <see cref="ModuleInfo"/> on which the received module dependens on.
/// </summary>
/// <param name="moduleInfo">Module whose dependant modules are requested.</param>
/// <returns>Collection of <see cref="ModuleInfo"/> dependants of <paramref name="moduleInfo"/>.</returns>
protected virtual IEnumerable<ModuleInfo> GetDependentModulesInner(ModuleInfo moduleInfo)
{
return this.Modules.Where(dependantModule => moduleInfo.DependsOn.Contains(dependantModule.ModuleName));
}
/// <summary>
/// Ensures that the catalog is validated.
/// </summary>
protected virtual void EnsureCatalogValidated()
{
if (!this.Validated)
{
this.Validate();
}
}
private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (this.Validated)
{
this.EnsureCatalogValidated();
}
}
private class ModuleCatalogItemCollection : Collection<IModuleCatalogItem>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void InsertItem(int index, IModuleCatalogItem item)
{
base.InsertItem(index, item);
this.OnNotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
protected void OnNotifyCollectionChanged(NotifyCollectionChangedEventArgs eventArgs)
{
if (this.CollectionChanged != null)
{
this.CollectionChanged(this, eventArgs);
}
}
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ESRI.ArcLogistics.Data;
using ESRI.ArcLogistics.DomainObjects;
using ESRI.ArcLogistics.Geocoding;
using ESRI.ArcLogistics.Geometry;
using ESRI.ArcLogistics.Routing.Json;
namespace ESRI.ArcLogistics.Routing
{
/// <summary>
/// GenDirectionsParams class.
/// </summary>
internal class GenDirectionsParams
{
/// <summary>
/// Collection of routes.
/// </summary>
public ICollection<Route> Routes { get; internal set; }
}
/// <summary>
/// GenDirectionsOperation class.
/// Class provides generation of directions operation.
/// </summary>
internal sealed class GenDirectionsOperation : ISolveOperation<BatchRouteSolveRequest>
{
#region Constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Constructor with parameters.
/// </summary>
/// <param name="context">Solver context.</param>
/// <param name="inputParams">Input parameters.</param>
public GenDirectionsOperation(SolverContext context, GenDirectionsParams inputParams)
{
Debug.Assert(inputParams != null);
Debug.Assert(inputParams.Routes != null);
if (inputParams.Routes.Count > 0)
_schedule = inputParams.Routes.First().Schedule;
_context = context;
_inputParams = inputParams;
}
#endregion
#region ISolveOperation<TSolveRequest> Members
/// <summary>
/// Schedule.
/// </summary>
public Schedule Schedule
{
get { return _schedule; }
}
/// <summary>
/// Operation type.
/// </summary>
public SolveOperationType OperationType
{
get { return SolveOperationType.GenerateDirections; }
}
/// <summary>
/// Input parameters.
/// </summary>
public Object InputParams
{
get { return _inputParams; }
}
/// <summary>
/// Flag says if can get results without solve operation.
/// </summary>
public bool CanGetResultWithoutSolve
{
get
{
return false;
}
}
/// <summary>
/// Creates result without solve operation.
/// </summary>
/// <returns>Null - not supported.</returns>
public SolveResult CreateResultWithoutSolve()
{
return null;
}
/// <summary>
/// Creates request for solve operation.
/// </summary>
/// <returns>BatchRouteSolveRequest.</returns>
/// <exception cref="RouteException">In case of Invalid routes number,
/// routes belong to different Schedules, not set Schedule or Schedule date.
/// </exception>
public BatchRouteSolveRequest CreateRequest()
{
if (_inputParams.Routes.Count == 0)
throw new RouteException(Properties.Messages.Error_InvalidRoutesNumber);
if (_schedule == null)
throw new RouteException(Properties.Messages.Error_ScheduleNotSet);
if (_schedule.PlannedDate == null)
throw new RouteException(Properties.Messages.Error_ScheduleDateNotSet);
// Check that all routes belong to the same schedule.
foreach (Route route in _inputParams.Routes)
{
if (!route.Schedule.Equals(_schedule))
throw new RouteException(Properties.Messages.Error_RoutesBelongToDifSchedules);
}
// Get barriers for planned date.
ICollection<Barrier> barriers = _context.Project.Barriers.Search(
(DateTime)_schedule.PlannedDate);
// Convert barriers its features collections.
GPFeature[] pointBarrierFeats = null;
GPFeature[] polygonBarrierFeats = null;
GPFeature[] polylineBarrierFeats = null;
if (barriers != null && barriers.Count > 0)
{
// Get barriers with its types.
var gpBarriers = barriers.ToLookup(BarriersConverter.DetermineBarrierType);
// Convert barriers by type.
pointBarrierFeats = _ConvertBarriers(gpBarriers, BarrierGeometryType.Point,
_context.NetworkDescription.NetworkAttributes);
polygonBarrierFeats = _ConvertBarriers(gpBarriers, BarrierGeometryType.Polygon,
_context.NetworkDescription.NetworkAttributes);
polylineBarrierFeats = _ConvertBarriers(gpBarriers, BarrierGeometryType.Polyline,
_context.NetworkDescription.NetworkAttributes);
}
// Create request data.
List<DirRouteData> dirRoutes = _GetDirRoutes(_inputParams.Routes);
// Build request.
RouteRequestBuilder builder = new RouteRequestBuilder(
_context);
List<RouteSolveRequest> requests = new List<RouteSolveRequest>();
foreach (DirRouteData dirRoute in dirRoutes)
{
RouteSolveRequestData reqData = new RouteSolveRequestData();
reqData.Route = dirRoute;
reqData.PointBarriers = pointBarrierFeats;
reqData.PolygonBarriers = polygonBarrierFeats;
reqData.PolylineBarriers = polylineBarrierFeats;
RouteSolveRequest req = builder.BuildRequest(reqData);
// Check if we have at least 2 stops.
if (req.Stops.Features.Length > 1)
requests.Add(req);
}
return new BatchRouteSolveRequest(requests.ToArray());
}
/// <summary>
/// Provides solve operation.
/// </summary>
/// <param name="request">Request to solver.</param>
/// <param name="cancelTracker">Cancel tracker.</param>
/// <returns>Function returning BatchRouteSolveResponse.</returns>
/// <exception cref="ESRI.ArcLogistics.Routing.RouteException">If get
/// directions operation error occurs.</exception>
public Func<SolveOperationResult<BatchRouteSolveRequest>> Solve(
BatchRouteSolveRequest request,
ICancelTracker cancelTracker)
{
Debug.Assert(request != null);
Debug.Assert(request.Requests != null);
try
{
List<RouteSolveResponse> responses = new List<RouteSolveResponse>();
foreach (RouteSolveRequest req in request.Requests)
{
responses.Add(_context.RouteService.Solve(req,
RouteRequestBuilder.JsonTypes));
}
var response = new BatchRouteSolveResponse(responses.ToArray());
return () => new SolveOperationResult<BatchRouteSolveRequest>
{
SolveResult = _ProcessSolveResult(response),
NextStepOperation = null,
};
}
catch (RestException e)
{
throw SolveHelper.ConvertServiceException(
Properties.Messages.Error_GetDirections, e);
}
}
#endregion
#region Private methods
/// <summary>
/// Processing results of solve operation.
/// </summary>
/// <param name="batchResponse">Response from solver.</param>
/// <returns>SolveResult.</returns>
/// <exception cref="RouteException">In case of invalid GPFeature mapping.
/// </exception>
private SolveResult _ProcessSolveResult(BatchRouteSolveResponse batchResponse)
{
Debug.Assert(batchResponse != null);
Debug.Assert(batchResponse.Responses != null);
List<RouteMessage> messages = new List<RouteMessage>();
foreach (RouteSolveResponse resp in batchResponse.Responses)
{
if (resp.Directions != null &&
resp.Directions.Length > 0)
{
// We use one request per route, so we get first directions element.
RouteDirections routeDirs = resp.Directions[0];
// Route id.
Guid routeId = new Guid(routeDirs.RouteName);
// Find route.
Route route = _FindRoute(routeId);
if (route == null)
throw new RouteException(Properties.Messages.Error_InvalidGPFeatureMapping);
// Set directions.
_SetDirections(route.Stops, routeDirs.Features);
}
if (resp.Messages != null)
messages.AddRange(resp.Messages);
}
return _CreateSolveResult(messages.ToArray());
}
/// <summary>
/// Method gets directions from routes collection.
/// </summary>
/// <param name="routes">Routes to get directions.</param>
/// <returns>Collection of directions data.</returns>
private List<DirRouteData> _GetDirRoutes(ICollection<Route> routes)
{
Debug.Assert(routes != null);
List<DirRouteData> rtList = new List<DirRouteData>();
foreach (Route route in routes)
{
DirRouteData rt = new DirRouteData();
rt.RouteId = route.Id;
rt.StartTime = route.StartTime;
rt.Stops = _GetStops(route);
rtList.Add(rt);
}
return rtList;
}
/// <summary>
/// Method gets stop point.
/// </summary>
/// <param name="stop">Stop.</param>
/// <returns>Stop point location.</returns>
private Point _GetStopPoint(Stop stop)
{
Debug.Assert(null != stop);
Debug.Assert(StopType.Lunch != stop.StopType);
Debug.Assert(null != stop.AssociatedObject);
var geocodable = stop.AssociatedObject as IGeocodable;
Debug.Assert(null != geocodable);
Point? pt = geocodable.GeoLocation;
Debug.Assert(pt != null);
return pt.Value;
}
/// <summary>
/// Method gets stops date from route.
/// </summary>
/// <param name="route">Route to get information.</param>
/// <returns>Collection of stops data.</returns>
private List<StopData> _GetStops(Route route)
{
Debug.Assert(route != null);
IDataObjectCollection<Stop> stops = route.Stops;
int stopsCount = stops.Count;
var stopDatas = new List<StopData>(stopsCount);
for (int index = 0; index < stopsCount; ++index)
{
Stop stop = stops[index];
StopData sd = new StopData();
sd.SequenceNumber = stop.SequenceNumber;
sd.Distance = stop.Distance;
sd.WaitTime = stop.WaitTime;
sd.TimeAtStop = stop.TimeAtStop;
sd.TravelTime = stop.TravelTime;
sd.ArriveTime = (DateTime)stop.ArriveTime;
if (stop.StopType == StopType.Lunch)
{
// Break.
// ToDo - need update logic - now find only first TWBreak.
var twBreaks =
from currBreak in route.Breaks
where
currBreak is TimeWindowBreak
select currBreak;
TimeWindowBreak rtBreak = twBreaks.FirstOrDefault() as TimeWindowBreak;
if (rtBreak != null && rtBreak.Duration > 0.0)
{
// TODO Break
//// Time window.
//DateTime? twStart = null;
//DateTime? twEnd = null;
//if (rtBreak.TimeWindow != null)
// _ConvertTW(rtBreak.TimeWindow, out twStart, out twEnd);
sd.TimeWindowStart1 = _TSToDate(rtBreak.From);
sd.TimeWindowEnd1 = _TSToDate(rtBreak.To);
}
}
else
{
Debug.Assert(stop.AssociatedObject != null);
// Associated object id.
sd.AssociatedObject = stop.AssociatedObject;
// Geometry.
Point pt = _GetStopPoint(stop);
sd.Geometry = GPObjectHelper.PointToGPPoint(pt);
// Time windows.
DateTime? twStart1 = null;
DateTime? twStart2 = null;
DateTime? twEnd1 = null;
DateTime? twEnd2 = null;
// Type-specific data.
if (stop.StopType == StopType.Order)
{
Order order = stop.AssociatedObject as Order;
Debug.Assert(order != null);
// Curbapproach.
sd.NACurbApproach =
CurbApproachConverter.ToNACurbApproach(
_context.SolverSettings.GetDepotCurbApproach());
// Time window 1.
if (order.TimeWindow != null)
_ConvertTW(order.TimeWindow, out twStart1, out twEnd1);
// Time window 2.
if (order.TimeWindow2 != null)
_ConvertTW(order.TimeWindow2, out twStart2, out twEnd2);
}
else if (stop.StopType == StopType.Location)
{
Location loc = stop.AssociatedObject as Location;
Debug.Assert(loc != null);
// Time window.
if (loc.TimeWindow != null)
_ConvertTW(loc.TimeWindow, out twStart1, out twEnd1);
}
sd.TimeWindowStart1 = twStart1;
sd.TimeWindowStart2 = twStart2;
sd.TimeWindowEnd1 = twEnd1;
sd.TimeWindowEnd2 = twEnd2;
}
sd.RouteId = route.Id;
sd.StopType = stop.StopType;
stopDatas.Add(sd);
}
SolveHelper.ConsiderArrivalDelayInStops(
_context.SolverSettings.ArriveDepartDelay, stopDatas);
return stopDatas;
}
/// <summary>
/// Method set directions to GP direction features.
/// </summary>
/// <param name="stops">Stops collection to get data.</param>
/// <param name="dirFeatures">Direction feature to set.</param>
private void _SetDirections(ICollection<Stop> stops, GPCompactGeomFeature[] dirFeatures)
{
Debug.Assert(stops != null);
Dictionary<Stop, StopData> dict = new Dictionary<Stop, StopData>();
foreach (Stop stop in stops)
dict.Add(stop, stop.GetData());
var directions = dirFeatures.Select(DirectionsHelper.ConvertToDirection);
DirectionsHelper.SetDirections(dict.Values, directions);
foreach (var entry in dict)
{
entry.Key.Path = entry.Value.Path;
entry.Key.Directions = entry.Value.Directions;
}
}
/// <summary>
/// Method converts TimeWindow to separate DataTimes for Start and End time ranges.
/// </summary>
/// <param name="tw">TimeWindow to convert.</param>
/// <param name="twStart">Output parameter for Start DateTime.</param>
/// <param name="twEnd">Output parameter for End DateTime.</param>
private void _ConvertTW(TimeWindow tw, out DateTime? twStart,
out DateTime? twEnd)
{
Debug.Assert(tw != null);
twStart = null;
twEnd = null;
if (!tw.IsWideOpen)
{
twStart = _TSToDate(tw.From);
twEnd = _TSToDate(tw.To);
if (twEnd < twStart)
// Set next day.
twEnd = ((DateTime)twEnd).AddDays(1);
}
}
/// <summary>
/// Method converts collection of Barriers into GPFeature collection of
/// BarrierGeometryType type.
/// </summary>
/// <param name="barriersByTypes">Typed Barriers collection.</param>
/// <param name="type">Type to convert.</param>
/// <param name="attributes">Network attributes used to get barrier attributes.</param>
/// <returns>GPFeature collection of specified barriers type.</returns>
private static GPFeature[] _ConvertBarriers(ILookup<BarrierGeometryType, Barrier> barriersByTypes,
BarrierGeometryType type, IEnumerable<NetworkAttribute> attributes)
{
Debug.Assert(barriersByTypes != null);
// Convert Lookup Table of barriers to enumerable
// collection of Barriers of specified type.
var barriers = barriersByTypes[type];
GPFeature[] result = null;
// Convert barriers to GPFeatures.
BarriersConverter converter = new BarriersConverter(attributes);
// Convert barrier by its type.
if (type == BarrierGeometryType.Point)
result = converter.ConvertToPointBarriersFeatures(barriers);
else if (type == BarrierGeometryType.Polygon)
result = converter.ConvertToPolygonBarriersFeatures(barriers);
else if (type == BarrierGeometryType.Polyline)
result = converter.ConvertToLineBarriersFeatures(barriers);
else
// Not supported type.
Debug.Assert(false);
return result;
}
/// <summary>
/// Method converts TimeSpan into DateTime.
/// </summary>
/// <param name="ts">TimeSpan to convert.</param>
/// <returns>DateTime converted object.</returns>
private DateTime _TSToDate(TimeSpan ts)
{
DateTime date = (DateTime)_schedule.PlannedDate;
return new DateTime(date.Year, date.Month, date.Day,
ts.Hours,
ts.Minutes,
ts.Seconds);
}
/// <summary>
/// Method searches for a route with Route Id in a collection of Input Routes.
/// </summary>
/// <param name="routeId">Route Id to find.</param>
/// <returns>Route object - if found, otherwise - null.</returns>
private Route _FindRoute(Guid routeId)
{
foreach (Route route in _inputParams.Routes)
{
if (route.Id == routeId)
return route;
}
return null;
}
/// <summary>
/// Method creates Solve Result from solver messages.
/// </summary>
/// <param name="messages">Route messages.</param>
/// <returns>Solve result.</returns>
private static SolveResult _CreateSolveResult(RouteMessage[] messages)
{
List<ServerMessage> msgList = new List<ServerMessage>();
if (messages != null)
{
// Convert messages.
foreach (RouteMessage msg in messages)
msgList.Add(_ConvertRouteMessage(msg));
}
return new SolveResult(msgList.ToArray(), null, false);
}
/// <summary>
/// Method converts route message from solver to server message.
/// </summary>
/// <param name="msg">Route message.</param>
/// <returns>Server message.</returns>
private static ServerMessage _ConvertRouteMessage(RouteMessage msg)
{
Debug.Assert(msg != null);
return new ServerMessage(ServerMessageType.Info,
String.Format(MSG_FORMAT, msg.Type, msg.Description));
}
#endregion
#region Private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Solver context.
/// </summary>
private SolverContext _context;
/// <summary>
/// Input parameters.
/// </summary>
private GenDirectionsParams _inputParams;
/// <summary>
/// Current schedule.
/// </summary>
private Schedule _schedule;
#endregion
#region Private constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Message format string.
/// </summary>
private const string MSG_FORMAT = "code: {0}. {1}";
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure.Management.SiteRecovery
{
/// <summary>
/// Definition of storage operations for the Site Recovery extension.
/// </summary>
internal partial class StorageOperations : IServiceOperations<SiteRecoveryManagementClient>, IStorageOperations
{
/// <summary>
/// Initializes a new instance of the StorageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal StorageOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get the list of all storages under the vault.
/// </summary>
/// <param name='serverId'>
/// Required. Server Id.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list storage operation.
/// </returns>
public async Task<StorageListResponse> ListAsync(string serverId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (serverId == null)
{
throw new ArgumentNullException("serverId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverId", serverId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/Storages";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
queryParameters.Add("ServerId=" + Uri.EscapeDataString(serverId));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
StorageListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new StorageListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfStorageSequenceElement = responseDoc.Element(XName.Get("ArrayOfStorage", "http://schemas.microsoft.com/windowsazure"));
if (arrayOfStorageSequenceElement != null)
{
foreach (XElement arrayOfStorageElement in arrayOfStorageSequenceElement.Elements(XName.Get("Storage", "http://schemas.microsoft.com/windowsazure")))
{
AsrStorage storageInstance = new AsrStorage();
result.Storages.Add(storageInstance);
XElement typeElement = arrayOfStorageElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
storageInstance.Type = typeInstance;
}
XElement fabricObjectIDElement = arrayOfStorageElement.Element(XName.Get("FabricObjectID", "http://schemas.microsoft.com/windowsazure"));
if (fabricObjectIDElement != null)
{
string fabricObjectIDInstance = fabricObjectIDElement.Value;
storageInstance.FabricObjectID = fabricObjectIDInstance;
}
XElement fabricTypeElement = arrayOfStorageElement.Element(XName.Get("FabricType", "http://schemas.microsoft.com/windowsazure"));
if (fabricTypeElement != null)
{
string fabricTypeInstance = fabricTypeElement.Value;
storageInstance.FabricType = fabricTypeInstance;
}
XElement serverIDElement = arrayOfStorageElement.Element(XName.Get("ServerID", "http://schemas.microsoft.com/windowsazure"));
if (serverIDElement != null)
{
string serverIDInstance = serverIDElement.Value;
storageInstance.ServerID = serverIDInstance;
}
XElement storagePoolsSequenceElement = arrayOfStorageElement.Element(XName.Get("StoragePools", "http://schemas.microsoft.com/windowsazure"));
if (storagePoolsSequenceElement != null)
{
foreach (XElement storagePoolsElement in storagePoolsSequenceElement.Elements(XName.Get("StoragePool", "http://schemas.microsoft.com/windowsazure")))
{
StoragePool storagePoolInstance = new StoragePool();
storageInstance.StoragePools.Add(storagePoolInstance);
XElement idElement = storagePoolsElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
storagePoolInstance.ID = idInstance;
}
XElement nameElement = storagePoolsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
storagePoolInstance.Name = nameInstance;
}
}
}
XElement nameElement2 = arrayOfStorageElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
storageInstance.Name = nameInstance2;
}
XElement idElement2 = arrayOfStorageElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement2 != null)
{
string idInstance2 = idElement2.Value;
storageInstance.ID = idInstance2;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all storages for the subscription
/// </summary>
/// <param name='subscriptionId'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Storage Accounts operation response.
/// </returns>
public async Task<StorageAccountListResponse> ListAzureStoragesAsync(string subscriptionId, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
TracingAdapter.Enter(invocationId, this, "ListAzureStoragesAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (subscriptionId != null)
{
url = url + Uri.EscapeDataString(subscriptionId);
}
url = url + "/services/storageservices";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
StorageAccountListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new StorageAccountListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement storageServicesSequenceElement = responseDoc.Element(XName.Get("StorageServices", "http://schemas.microsoft.com/windowsazure"));
if (storageServicesSequenceElement != null)
{
foreach (XElement storageServicesElement in storageServicesSequenceElement.Elements(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure")))
{
StorageAccountListResponse.StorageAccount storageServiceInstance = new StorageAccountListResponse.StorageAccount();
result.StorageAccounts.Add(storageServiceInstance);
XElement urlElement = storageServicesElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure"));
if (urlElement != null)
{
Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value);
storageServiceInstance.Uri = urlInstance;
}
XElement serviceNameElement = storageServicesElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure"));
if (serviceNameElement != null)
{
string serviceNameInstance = serviceNameElement.Value;
storageServiceInstance.Name = serviceNameInstance;
}
XElement storageServicePropertiesElement = storageServicesElement.Element(XName.Get("StorageServiceProperties", "http://schemas.microsoft.com/windowsazure"));
if (storageServicePropertiesElement != null)
{
StorageAccountListResponse.StorageAccountProperties storageServicePropertiesInstance = new StorageAccountListResponse.StorageAccountProperties();
storageServiceInstance.Properties = storageServicePropertiesInstance;
XElement descriptionElement = storageServicePropertiesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement != null)
{
bool isNil = false;
XAttribute nilAttribute = descriptionElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute != null)
{
isNil = nilAttribute.Value == "true";
}
if (isNil == false)
{
string descriptionInstance = descriptionElement.Value;
storageServicePropertiesInstance.Description = descriptionInstance;
}
}
XElement affinityGroupElement = storageServicePropertiesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure"));
if (affinityGroupElement != null)
{
string affinityGroupInstance = affinityGroupElement.Value;
storageServicePropertiesInstance.AffinityGroup = affinityGroupInstance;
}
XElement locationElement = storageServicePropertiesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
storageServicePropertiesInstance.Location = locationInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using log4net.Filter;
using log4net.helpers;
using log4net.Layout;
using log4net.spi;
namespace log4net.Appender
{
/// <summary>
/// Abstract base class implementation of <see cref="IAppender"/>.
/// </summary>
/// <remarks>
/// <para>
/// This class provides the code for common functionality, such
/// as support for threshold filtering and support for general filters.
/// </para>
/// <para>
/// Appenders can also implement the <see cref="IOptionHandler"/> interface. Therefore
/// they would require that the <see cref="IOptionHandler.ActivateOptions()"/> method
/// be called after the appenders properties have been configured.
/// </para>
/// </remarks>
public abstract class AppenderSkeleton : IAppender, IOptionHandler
{
#region Protected Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>Empty default constructor</para>
/// </remarks>
protected AppenderSkeleton()
{
m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name);
}
#endregion Protected Instance Constructors
#region Finalizer
/// <summary>
/// Finalizes this appender by calling the implementation's
/// <see cref="AppenderSkeleton.Close"/> method.
/// </summary>
~AppenderSkeleton()
{
// An appender might be closed then garbage collected.
// There is no point in closing twice.
if (!m_closed)
{
LogLog.Debug("AppenderSkeleton: Finalizing appender named ["+m_name+"].");
Close();
}
}
#endregion Finalizer
#region Public Instance Properties
/// <summary>
/// Gets or sets the threshold <see cref="Level"/> of this appender.
/// </summary>
/// <value>
/// The threshold <see cref="Level"/> of the appender.
/// </value>
/// <remarks>
/// <para>
/// All log events with lower level than the threshold level are ignored
/// by the appender.
/// </para>
/// <para>
/// In configuration files this option is specified by setting the
/// value of the <see cref="Threshold"/> option to a level
/// string, such as "DEBUG", "INFO" and so on.
/// </para>
/// </remarks>
public Level Threshold
{
get { return m_threshold; }
set { m_threshold = value; }
}
/// <summary>
/// Gets or sets the <see cref="IErrorHandler"/> for this appender.
/// </summary>
/// <value>The <see cref="IErrorHandler"/> of the appender</value>
/// <remarks>
/// <para>
/// The <see cref="AppenderSkeleton"/> provides a default
/// implementation for the <see cref="ErrorHandler"/> property.
/// </para>
/// </remarks>
virtual public IErrorHandler ErrorHandler
{
get { return this.m_errorHandler; }
set
{
lock(this)
{
if (value == null)
{
// We do not throw exception here since the cause is probably a
// bad config file.
LogLog.Warn("AppenderSkeleton: You have tried to set a null error-handler.");
}
else
{
m_errorHandler = value;
}
}
}
}
/// <summary>
/// The filter chain.
/// </summary>
/// <value>The head of the filter chain filter chain.</value>
/// <remarks>
/// <para>
/// Returns the head Filter. The Filters are organized in a linked list
/// and so all Filters on this Appender are available through the result.
/// </para>
/// </remarks>
virtual public IFilter FilterHead
{
get { return m_headFilter; }
}
/// <summary>
/// Gets or sets the <see cref="ILayout"/> for this appender.
/// </summary>
/// <value>The layout of the appender.</value>
/// <remarks>
/// <para>
/// See <see cref="RequiresLayout"/> for more information.
/// </para>
/// </remarks>
/// <seealso cref="RequiresLayout"/>
virtual public ILayout Layout
{
get { return m_layout; }
set { m_layout = value; }
}
/// <summary>
/// Gets or sets the name of this appender.
/// </summary>
/// <value>The name of the appender.</value>
/// <remarks>
/// <para>
/// The name uniquely identifies the appender.
/// </para>
/// </remarks>
public string Name
{
get { return m_name; }
set { m_name = value; }
}
#endregion
#region Implementation of IOptionHandler
/// <summary>
/// Initialise the appender based on the options set
/// </summary>
virtual public void ActivateOptions()
{
}
#endregion Implementation of IOptionHandler
#region Implementation of IAppender
/// <summary>
/// Closes the appender and release resources.
/// </summary>
/// <remarks>
/// <para>
/// Release any resources allocated within the appender such as file handles,
/// network connections, etc.
/// </para>
/// <para>
/// It is a programming error to append to a closed appender.
/// </para>
/// <para>
/// This method cannot be overridden by subclasses. This method
/// delegates the closing of the appender to the <see cref="OnClose"/>
/// method which must be overridden in the subclass.
/// </para>
/// </remarks>
public void Close()
{
// This lock prevents the appender being closed while it is still appending
lock(this)
{
if (!m_closed)
{
OnClose();
m_closed = true;
}
}
}
/// <summary>
/// Performs threshold checks and invokes filters before
/// delegating actual logging to the subclasses specific
/// <see cref="AppenderSkeleton.Append"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// This method cannot be overridden by derived classes. A
/// derived class should override the <see cref="Append"/> method
/// which is called by this method.
/// </para>
/// <para>
/// The implementation of this method is as follows:
/// </para>
/// <para>
/// <list type="bullet">
/// <item>
/// <description>
/// Checks that the severity of the <paramref name="loggingEvent"/>
/// is greater than or equal to the <see cref="Threshold"/> of this
/// appender.</description>
/// </item>
/// <item>
/// <description>
/// Checks that the <see cref="Filter"/> chain accepts the
/// <paramref name="loggingEvent"/>.
/// </description>
/// </item>
/// <item>
/// <description>
/// Calls <see cref="PreAppendCheck()"/> and checks that
/// it returns <c>true</c>.</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// If all of the above steps succeed then the <paramref name="loggingEvent"/>
/// will be passed to the abstract <see cref="Append"/> method.
/// </para>
/// </remarks>
public void DoAppend(LoggingEvent loggingEvent)
{
// This lock is absolutely critical for correct formatting
// of the message in a multi-threaded environment. Without
// this, the message may be broken up into elements from
// multiple thread contexts (like get the wrong thread ID).
lock(this)
{
if (m_closed)
{
ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"].");
return;
}
// prevent re-entry
if (m_recursiveGuard)
{
return;
}
try
{
m_recursiveGuard = true;
if (!IsAsSevereAsThreshold(loggingEvent.Level))
{
return;
}
IFilter f = this.FilterHead;
while(f != null)
{
switch(f.Decide(loggingEvent))
{
case FilterDecision.DENY:
return; // Return without appending
case FilterDecision.ACCEPT:
f = null; // Break out of the loop
break;
case FilterDecision.NEUTRAL:
f = f.Next; // Move to next filter
break;
}
}
if (PreAppendCheck())
{
this.Append(loggingEvent);
}
}
catch(Exception ex)
{
ErrorHandler.Error("Failed in DoAppend", ex);
}
finally
{
m_recursiveGuard = false;
}
}
}
#endregion Implementation of IAppender
#region Public Instance Methods
/// <summary>
/// Checks if the message level is below this appender's threshold.
/// </summary>
/// <param name="level"><see cref="Level"/> to test against.</param>
/// <remarks>
/// <para>
/// If there is no threshold set, then the return value is always <c>true</c>.
/// </para>
/// </remarks>
/// <returns>
/// <c>true</c> if the <paramref name="level"/> meets the <see cref="Threshold"/>
/// requirements of this appender.
/// </returns>
public bool IsAsSevereAsThreshold(Level level)
{
return ((m_threshold == null) || level >= m_threshold);
}
/// <summary>
/// Is called when the appender is closed. Derived classes should override
/// this method if resources need to be released.
/// </summary>
/// <remarks>
/// <para>
/// Releases any resources allocated within the appender such as file handles,
/// network connections, etc.
/// </para>
/// <para>
/// It is a programming error to append to a closed appender.
/// </para>
/// </remarks>
virtual public void OnClose()
{
// Do nothing by default
}
/// <summary>
/// Adds a filter to the end of the filter chain.
/// </summary>
/// <remarks>
/// <para>
/// The Filters are organized in a linked list.
/// </para>
/// <para>
/// Setting this property causes the new filter to be pushed onto the
/// back of the filter chain.
/// </para>
/// </remarks>
virtual public void AddFilter(IFilter filter)
{
if (filter == null)
{
throw new ArgumentNullException("filter param nust not be null");
}
if (m_headFilter == null)
{
m_headFilter = m_tailFilter = filter;
}
else
{
m_tailFilter.Next = filter;
m_tailFilter = filter;
}
}
/// <summary>
/// Clears the filter list for this appender.
/// </summary>
virtual public void ClearFilters()
{
m_headFilter = m_tailFilter = null;
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Subclasses of <see cref="AppenderSkeleton"/> should implement this method
/// to perform actual logging.
/// </summary>
/// <param name="loggingEvent">The event to append.</param>
/// <remarks>
/// <para>
/// A subclass must implement this method to perform
/// logging of the <paramref name="loggingEvent"/>.
/// </para>
/// <para>This method will be called by <see cref="AppenderSkeleton.DoAppend"/>
/// if all the conditions listed for that method are met.
/// </para>
/// <para>
/// To restrict the logging of events in the appender
/// override the <see cref="PreAppendCheck()"/> method.
/// </para>
/// </remarks>
abstract protected void Append(LoggingEvent loggingEvent);
/// <summary>
/// Called before <see cref="Append"/> as a precondition.
/// </summary>
/// <remarks>
/// <para>
/// This method is called by <see cref="AppenderSkeleton.DoAppend"/>
/// before the call to the abstract <see cref="Append"/> method.
/// </para>
/// <para>
/// This method can be overridden in a subclass to extend the checks
/// made before the event is passed to the <see cref="Append"/> method.
/// </para>
/// <para>
/// A subclass should ensure that they delegate this call to
/// this base class if it is overridden.
/// </para>
/// </remarks>
/// <returns><c>true</c> if the call to <see cref="Append"/> should proceed.</returns>
virtual protected bool PreAppendCheck()
{
if ((m_layout == null) && RequiresLayout)
{
ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named ["+m_name+"].");
return false;
}
return true;
}
/// <summary>
/// Renders the <see cref="LoggingEvent"/> to a string.
/// </summary>
/// <param name="loggingEvent">The event to render.</param>
/// <returns>The event rendered as a string.</returns>
/// <remarks>
/// <para>
/// Helper method to render a <see cref="LoggingEvent"/> to
/// a string. This appender must have a <see cref="Layout"/>
/// set to render the <paramref name="loggingEvent"/> to
/// a string.
/// </para>
/// <para>If there is exception data in the logging event and
/// the layout does not process the exception, this method
/// will append the exception text to the rendered string.
/// </para>
/// </remarks>
protected string RenderLoggingEvent(LoggingEvent loggingEvent)
{
if (m_layout == null)
{
throw new InvalidOperationException("A layout must be set");
}
if (m_layout.IgnoresException)
{
string exceptionStr = loggingEvent.GetExceptionStrRep();
if (exceptionStr != null && exceptionStr.Length > 0)
{
// render the event and the exception
return m_layout.Format(loggingEvent) + exceptionStr + SystemInfo.NewLine;
}
else
{
// there is no exception to render
return m_layout.Format(loggingEvent);
}
}
else
{
// The layout will render the exception
return m_layout.Format(loggingEvent);
}
}
/// <summary>
/// Tests if this appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <remarks>
/// <para>
/// In the rather exceptional case, where the appender
/// implementation admits a layout but can also work without it,
/// then the appender should return <c>true</c>.
/// </para>
/// <para>
/// This default implementation always returns <c>true</c>.
/// </para>
/// </remarks>
/// <returns>
/// <c>true</c> if the appender requires a layout object, otherwise <c>false</c>.
/// </returns>
virtual protected bool RequiresLayout
{
get { return false; }
}
#endregion
#region Private Instance Fields
/// <summary>
/// The layout of this appender.
/// </summary>
/// <remarks>
/// See <see cref="Layout"/> for more information.
/// </remarks>
private ILayout m_layout;
/// <summary>
/// The name of this appender.
/// </summary>
/// <remarks>
/// See <see cref="Name"/> for more information.
/// </remarks>
private string m_name;
/// <summary>
/// The level threshold of this appender.
/// </summary>
/// <remarks>
/// <para>
/// There is no level threshold filtering by default.
/// </para>
/// <para>
/// See <see cref="Threshold"/> for more information.
/// </para>
/// </remarks>
private Level m_threshold;
/// <summary>
/// It is assumed and enforced that errorHandler is never null.
/// </summary>
/// <remarks>
/// <para>
/// It is assumed and enforced that errorHandler is never null.
/// </para>
/// <para>
/// See <see cref="ErrorHandler"/> for more information.
/// </para>
/// </remarks>
private IErrorHandler m_errorHandler;
/// <summary>
/// The first filter in the filter chain.
/// </summary>
/// <remarks>
/// <para>
/// Set to <c>null</c> initially.
/// </para>
/// <para>
/// See <see cref="Filter"/> for more information.
/// </para>
/// </remarks>
private IFilter m_headFilter;
/// <summary>
/// The last filter in the filter chain.
/// </summary>
/// <remarks>
/// See <see cref="Filter"/> for more information.
/// </remarks>
private IFilter m_tailFilter;
/// <summary>
/// Flag indicating if this appender is closed.
/// </summary>
/// <remarks>
/// See <see cref="Close"/> for more information.
/// </remarks>
private bool m_closed = false;
/// <summary>
/// The guard prevents an appender from repeatedly calling its own DoAppend method
/// </summary>
private bool m_recursiveGuard = false;
#endregion Private Instance Fields
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SiaqodbCloudService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SafetySharp.Runtime.Serialization
{
using System.IO;
using System.Linq;
using System.Text;
using Analysis;
using ISSE.SafetyChecking.Formula;
using ISSE.SafetyChecking.Utilities;
using Modeling;
using Utilities;
/// <summary>
/// Serializes a <see cref="SafetySharpRuntimeModel" /> instance into a <see cref="Stream" />.
/// </summary>
internal class RuntimeModelSerializer
{
private readonly object _syncObject = new object();
private OpenSerializationDelegate _deserializer;
private byte[] _serializedModel;
internal StateVectorLayout StateVector { get; private set; }
#region Serialization
/// <summary>
/// Serializes the <paramref name="model" /> and the <paramref name="formulas" />.
/// </summary>
/// <param name="model">The model that should be serialized.</param>
/// <param name="formulas">The formulas that should be serialized.</param>
public void Serialize(ModelBase model, params Formula[] formulas)
{
Requires.NotNull(model, nameof(model));
Requires.NotNull(formulas, nameof(formulas));
using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true))
{
SerializeModel(writer, model, formulas);
lock (_syncObject)
_serializedModel = buffer.ToArray();
}
}
/// <summary>
/// Returns the serialized <paramref name="model" /> and the <paramref name="formulas" />.
/// </summary>
/// <param name="model">The model that should be serialized.</param>
/// <param name="formulas">The formulas that should be serialized.</param>
public static byte[] Save(ModelBase model, params Formula[] formulas)
{
var serializer = new RuntimeModelSerializer();
serializer.Serialize(model, formulas);
lock (serializer._syncObject)
return serializer._serializedModel;
}
/// <summary>
/// Serializes the <paramref name="model" />.
/// </summary>
private unsafe void SerializeModel(BinaryWriter writer, ModelBase model, Formula[] formulas)
{
// Collect all objects contained in the model
var objectTable = CreateObjectTable(model, formulas);
// Prepare the serialization of the model's initial state
lock (_syncObject)
{
StateVector = SerializationRegistry.Default.GetStateVectorLayout(model, objectTable, SerializationMode.Full);
_deserializer = null;
}
var stateVectorSize = StateVector.SizeInBytes;
var serializer = StateVector.CreateSerializer(objectTable);
// Serialize the object table
SerializeObjectTable(objectTable, writer);
// Serialize the object identifier of the model itself and the formulas
writer.Write(objectTable.GetObjectIdentifier(model));
writer.Write(formulas.Length);
foreach (var formula in formulas)
writer.Write(objectTable.GetObjectIdentifier(formula));
// Serialize the initial state
var serializedState = stackalloc byte[stateVectorSize];
serializer(serializedState);
// Copy the serialized state to the stream
writer.Write(stateVectorSize);
for (var i = 0; i < stateVectorSize; ++i)
writer.Write(serializedState[i]);
}
/// <summary>
/// Creates the object table for the <paramref name="model" /> and <paramref name="formulas" />.
/// </summary>
private static ObjectTable CreateObjectTable(ModelBase model, Formula[] formulas)
{
var objects = model.Roots.Cast<object>().Concat(formulas).Concat(new[] { model });
return new ObjectTable(SerializationRegistry.Default.GetReferencedObjects(objects.ToArray(), SerializationMode.Full));
}
/// <summary>
/// Serializes the <paramref name="objectTable" /> using the <paramref name="writer" />.
/// </summary>
/// <param name="objectTable">The object table that should be serialized.</param>
/// <param name="writer">The writer the serialized information should be written to.</param>
private static void SerializeObjectTable(ObjectTable objectTable, BinaryWriter writer)
{
Requires.NotNull(objectTable, nameof(objectTable));
Requires.NotNull(writer, nameof(writer));
// Serialize the objects contained in the table
writer.Write(objectTable.Count);
foreach (var obj in objectTable)
{
var serializerIndex = SerializationRegistry.Default.GetSerializerIndex(obj);
writer.Write(serializerIndex);
SerializationRegistry.Default.GetSerializer(serializerIndex).SerializeType(obj, writer);
}
}
#endregion
#region Deserialization
/// <summary>
/// Loads a <see cref="SerializedRuntimeModel" /> from the <paramref name="serializedModel" />.
/// </summary>
/// <param name="serializedModel">The serialized model that should be loaded.</param>
public static RuntimeModelSerializer LoadSerializedData(byte[] serializedModel)
{
Requires.NotNull(serializedModel, nameof(serializedModel));
return new RuntimeModelSerializer { _serializedModel = serializedModel };
}
/// <summary>
/// Loads a <see cref="SerializedRuntimeModel" /> instance.
/// </summary>
public SerializedRuntimeModel Load()
{
Requires.That(_serializedModel != null, "No model is loaded that could be serialized.");
using (var reader = new BinaryReader(new MemoryStream(_serializedModel), Encoding.UTF8, leaveOpen: true))
return DeserializeModel(_serializedModel, reader);
}
/// <summary>
/// Loads a <see cref="SafetySharpRuntimeModel" /> instance.
/// </summary>
public SafetySharpRuntimeModel Load(int stateHeaderBytes)
{
return new SafetySharpRuntimeModel(Load(), stateHeaderBytes);
}
/// <summary>
/// Deserializes a <see cref="SafetySharpRuntimeModel" /> from the <paramref name="reader" />.
/// </summary>
private unsafe SerializedRuntimeModel DeserializeModel(byte[] buffer, BinaryReader reader)
{
// Deserialize the object table
var objectTable = DeserializeObjectTable(reader);
// Deserialize the object identifiers of the model itself and the root formulas
var model = (ModelBase)objectTable.GetObject(reader.ReadUInt16());
var formulas = new Formula[reader.ReadInt32()];
for (var i = 0; i < formulas.Length; ++i)
formulas[i] = (Formula)objectTable.GetObject(reader.ReadUInt16());
// Copy the serialized initial state from the stream
var stateVectorSize = reader.ReadInt32();
var serializedState = stackalloc byte[stateVectorSize];
for (var i = 0; i < stateVectorSize; ++i)
serializedState[i] = reader.ReadByte();
// Deserialize the model's initial state
OpenSerializationDelegate deserializer;
lock (_syncObject)
{
if (StateVector == null)
StateVector = SerializationRegistry.Default.GetStateVectorLayout(model, objectTable, SerializationMode.Full);
if (_deserializer == null)
_deserializer = StateVector.CreateDeserializer();
deserializer = _deserializer;
}
deserializer(objectTable, serializedState);
// We instantiate the runtime type for each component and replace the original component
// instance with the new runtime instance; we also replace all of the component's fault effects
// with that instance and deserialize the initial state again. Afterwards, we have completely
// replaced the original instance with its runtime instance, taking over all serialized data
objectTable.SubstituteRuntimeInstances();
deserializer(objectTable, serializedState);
// We substitute the dummy delegate objects with the actual instances obtained from the DelegateMetadata instances
objectTable.SubstituteDelegates();
deserializer(objectTable, serializedState);
// Return the serialized model data
return new SerializedRuntimeModel(model, buffer, objectTable, formulas);
}
/// <summary>
/// Deserializes the <see cref="ObjectTable" /> from the <paramref name="reader" />.
/// </summary>
/// <param name="reader">The reader the objects should be deserialized from.</param>
private static ObjectTable DeserializeObjectTable(BinaryReader reader)
{
Requires.NotNull(reader, nameof(reader));
// Deserialize the objects contained in the table
var objects = new object[reader.ReadInt32()];
for (var i = 0; i < objects.Length; ++i)
{
var serializer = SerializationRegistry.Default.GetSerializer(reader.ReadInt32());
objects[i] = serializer.InstantiateType(reader);
}
return new ObjectTable(objects);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 InsertByte129()
{
var test = new InsertScalarTest__InsertByte129();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario();
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();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertScalarTest__InsertByte129
{
private struct TestStruct
{
public Vector128<Byte> _fld;
public Byte _scalarFldData;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
testStruct._scalarFldData = (byte)2;
return testStruct;
}
public void RunStructFldScenario(InsertScalarTest__InsertByte129 testClass)
{
var result = Sse41.Insert(_fld, _scalarFldData, 129);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data = new Byte[Op1ElementCount];
private static Byte _scalarClsData = (byte)2;
private static Vector128<Byte> _clsVar;
private Vector128<Byte> _fld;
private Byte _scalarFldData = (byte)2;
private SimpleUnaryOpTest__DataTable<Byte, Byte> _dataTable;
static InsertScalarTest__InsertByte129()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public InsertScalarTest__InsertByte129()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Byte, Byte>(_data, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr),
(byte)2,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, (byte)2, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
Byte localData = (byte)2;
Byte* ptr = &localData;
var result = Sse41.Insert(
Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)),
*ptr,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
Byte localData = (byte)2;
Byte* ptr = &localData;
var result = Sse41.Insert(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)),
*ptr,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Byte>), typeof(Byte), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr),
(byte)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, (byte)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Byte>), typeof(Byte), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)),
(byte)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, (byte)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Byte>), typeof(Byte), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)),
(byte)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, (byte)2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar,
_scalarClsData,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr);
}
public void RunLclVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario));
Byte localData = (byte)2;
var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr);
var result = Sse41.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
Byte localData = (byte)2;
var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
Byte localData = (byte)2;
var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertScalarTest__InsertByte129();
var result = Sse41.Insert(test._fld, test._scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld, _scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld, test._scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> firstOp, Byte scalarData, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(void* firstOp, Byte scalarData, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte scalarData, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Byte>(Vector128<Byte><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HttpListenerRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
internal enum ListenerClientCertState {
NotInitialized,
InProgress,
Completed
}
unsafe internal class ListenerClientCertAsyncResult : LazyAsyncResult {
private NativeOverlapped* m_pOverlapped;
private byte[] m_BackingBuffer;
private UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* m_MemoryBlob;
private uint m_Size;
internal NativeOverlapped* NativeOverlapped
{
get
{
return m_pOverlapped;
}
}
internal UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* RequestBlob
{
get
{
return m_MemoryBlob;
}
}
private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(WaitCallback);
internal ListenerClientCertAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint size) : base(asyncObject, userState, callback) {
// we will use this overlapped structure to issue async IO to ul
// the event handle will be put in by the BeginHttpApi2.ERROR_SUCCESS() method
Reset(size);
}
internal void Reset(uint size) {
if (size == m_Size)
{
return;
}
if (m_Size != 0)
{
Overlapped.Free(m_pOverlapped);
}
m_Size = size;
if (size == 0)
{
m_pOverlapped = null;
m_MemoryBlob = null;
m_BackingBuffer = null;
return;
}
m_BackingBuffer = new byte[checked((int) size)];
Overlapped overlapped = new Overlapped();
overlapped.AsyncResult = this;
m_pOverlapped = overlapped.Pack(s_IOCallback, m_BackingBuffer);
m_MemoryBlob = (UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*) Marshal.UnsafeAddrOfPinnedArrayElement(m_BackingBuffer, 0);
}
internal unsafe void IOCompleted(uint errorCode, uint numBytes)
{
IOCompleted(this, errorCode, numBytes);
}
private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult, uint errorCode, uint numBytes)
{
HttpListenerRequest httpListenerRequest = (HttpListenerRequest) asyncResult.AsyncObject;
object result = null;
try {
if (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA)
{
//There is a bug that has existed in http.sys since w2k3. Bytesreceived will only
//return the size of the inital cert structure. To get the full size,
//we need to add the certificate encoding size as well.
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
asyncResult.Reset(numBytes + pClientCertInfo->CertEncodedSize);
uint bytesReceived = 0;
errorCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate(
httpListenerRequest.HttpListenerContext.RequestQueueHandle,
httpListenerRequest.m_ConnectionId,
(uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE,
asyncResult.m_MemoryBlob,
asyncResult.m_Size,
&bytesReceived,
asyncResult.m_pOverlapped);
if(errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING ||
(errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && !HttpListener.SkipIOCPCallbackOnSuccess))
{
return;
}
}
if (errorCode!=UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
asyncResult.ErrorCode = (int)errorCode;
result = new HttpListenerException((int)errorCode);
}
else {
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.m_MemoryBlob;
if (pClientCertInfo!=null) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() pClientCertInfo:" + ValidationHelper.ToString((IntPtr)pClientCertInfo)
+ " pClientCertInfo->CertFlags:" + ValidationHelper.ToString(pClientCertInfo->CertFlags)
+ " pClientCertInfo->CertEncodedSize:" + ValidationHelper.ToString(pClientCertInfo->CertEncodedSize)
+ " pClientCertInfo->pCertEncoded:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->pCertEncoded)
+ " pClientCertInfo->Token:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->Token)
+ " pClientCertInfo->CertDeniedByMapper:" + ValidationHelper.ToString(pClientCertInfo->CertDeniedByMapper));
if (pClientCertInfo->pCertEncoded!=null) {
try {
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
result = httpListenerRequest.ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() caught CryptographicException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
result = exception;
}
catch (SecurityException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() caught SecurityException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
result = exception;
}
}
httpListenerRequest.SetClientCertificateError((int)pClientCertInfo->CertFlags);
}
}
// complete the async IO and invoke the callback
GlobalLog.Print("ListenerClientCertAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::WaitCallback() calling Complete()");
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
result = exception;
}
finally {
if(errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING){
httpListenerRequest.ClientCertState = ListenerClientCertState.Completed;
}
}
asyncResult.InvokeCallback(result);
}
private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) {
// take the ListenerClientCertAsyncResult object from the state
Overlapped callbackOverlapped = Overlapped.Unpack(nativeOverlapped);
ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult) callbackOverlapped.AsyncResult;
GlobalLog.Print("ListenerClientCertAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::WaitCallback() errorCode:[" + errorCode.ToString() + "] numBytes:[" + numBytes.ToString() + "] nativeOverlapped:[" + ((long)nativeOverlapped).ToString() + "]");
IOCompleted(asyncResult, errorCode, numBytes);
}
// Will be called from the base class upon InvokeCallback()
protected override void Cleanup()
{
if (m_pOverlapped != null)
{
m_MemoryBlob = null;
Overlapped.Free(m_pOverlapped);
m_pOverlapped = null;
}
GC.SuppressFinalize(this);
base.Cleanup();
}
~ListenerClientCertAsyncResult()
{
if (m_pOverlapped != null && !NclUtilities.HasShutdownStarted)
{
Overlapped.Free(m_pOverlapped);
m_pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize().
}
}
}
public sealed unsafe class HttpListenerRequest/* BaseHttpRequest, */ {
private Uri m_RequestUri;
private ulong m_RequestId;
internal ulong m_ConnectionId;
private SslStatus m_SslStatus;
private string m_RawUrl;
private string m_CookedUrlHost;
private string m_CookedUrlPath;
private string m_CookedUrlQuery;
private long m_ContentLength;
private Stream m_RequestStream;
private string m_HttpMethod;
private TriState m_KeepAlive;
private Version m_Version;
private WebHeaderCollection m_WebHeaders;
private IPEndPoint m_LocalEndPoint;
private IPEndPoint m_RemoteEndPoint;
private BoundaryType m_BoundaryType;
private ListenerClientCertState m_ClientCertState;
private X509Certificate2 m_ClientCertificate;
private int m_ClientCertificateError;
private RequestContextBase m_MemoryBlob;
private CookieCollection m_Cookies;
private HttpListenerContext m_HttpContext;
private bool m_IsDisposed = false;
internal const uint CertBoblSize = 1500;
private string m_ServiceName;
private enum SslStatus : byte
{
Insecure,
NoClientCert,
ClientCert
}
internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob)
{
if (Logging.On) Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpContext#" + ValidationHelper.HashString(httpContext) + " memoryBlob# " + ValidationHelper.HashString((IntPtr) memoryBlob.RequestBlob));
if(Logging.On)Logging.Associate(Logging.HttpListener, this, httpContext);
m_HttpContext = httpContext;
m_MemoryBlob = memoryBlob;
m_BoundaryType = BoundaryType.None;
// Set up some of these now to avoid refcounting on memory blob later.
m_RequestId = memoryBlob.RequestBlob->RequestId;
m_ConnectionId = memoryBlob.RequestBlob->ConnectionId;
m_SslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure :
memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert :
SslStatus.ClientCert;
if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0) {
m_RawUrl = Marshal.PtrToStringAnsi((IntPtr) memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength);
}
UnsafeNclNativeMethods.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl;
if (cookedUrl.pHost != null && cookedUrl.HostLength > 0) {
m_CookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2);
}
if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0) {
m_CookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2);
}
if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0) {
m_CookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2);
}
m_Version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion);
m_ClientCertState = ListenerClientCertState.NotInitialized;
m_KeepAlive = TriState.Unspecified;
GlobalLog.Print("HttpListenerContext#" + ValidationHelper.HashString(this) + "::.ctor() RequestId:" + RequestId + " ConnectionId:" + m_ConnectionId + " RawConnectionId:" + memoryBlob.RequestBlob->RawConnectionId + " UrlContext:" + memoryBlob.RequestBlob->UrlContext + " RawUrl:" + m_RawUrl + " Version:" + m_Version.ToString() + " Secure:" + m_SslStatus.ToString());
if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpContext#"+ ValidationHelper.HashString(httpContext)+ " RequestUri:" + ValidationHelper.ToString(RequestUri) + " Content-Length:" + ValidationHelper.ToString(ContentLength64) + " HTTP Method:" + ValidationHelper.ToString(HttpMethod));
// Log headers
if(Logging.On) {
StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n");
for (int i=0; i<Headers.Count; i++) {
sb.Append("\t");
sb.Append(Headers.GetKey(i));
sb.Append(" : ");
sb.Append(Headers.Get(i));
sb.Append("\n");
}
Logging.PrintInfo(Logging.HttpListener, this, ".ctor", sb.ToString());
}
}
internal HttpListenerContext HttpListenerContext {
get {
return m_HttpContext;
}
}
internal byte[] RequestBuffer
{
get
{
CheckDisposed();
return m_MemoryBlob.RequestBuffer;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
CheckDisposed();
return m_MemoryBlob.OriginalBlobAddress;
}
}
// Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be
// disposed.
internal void DetachBlob(RequestContextBase memoryBlob)
{
if (memoryBlob != null && (object) memoryBlob == (object) m_MemoryBlob)
{
m_MemoryBlob = null;
}
}
// Finalizes ownership of the memory blob. DetachBlob can't be called after this.
internal void ReleasePins()
{
m_MemoryBlob.ReleasePins();
}
public Guid RequestTraceIdentifier {
get {
Guid guid = new Guid();
*(1+ (ulong *) &guid) = RequestId;
return guid;
}
}
internal ulong RequestId {
get {
return m_RequestId;
}
}
public /* override */ string[] AcceptTypes {
get {
return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.Accept));
}
}
public /* override */ Encoding ContentEncoding {
get {
if (UserAgent!=null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) {
string postDataCharset = Headers["x-up-devcap-post-charset"];
if (postDataCharset!=null && postDataCharset.Length>0) {
try {
return Encoding.GetEncoding(postDataCharset);
}
catch (ArgumentException) {
}
}
}
if (HasEntityBody) {
if (ContentType!=null) {
string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset");
if (charSet!=null) {
try {
return Encoding.GetEncoding(charSet);
}
catch (ArgumentException) {
}
}
}
}
return Encoding.Default;
}
}
public /* override */ long ContentLength64 {
get {
if (m_BoundaryType==BoundaryType.None) {
if (HttpWebRequest.ChunkedHeader.Equals(GetKnownHeader(HttpRequestHeader.TransferEncoding),
StringComparison.OrdinalIgnoreCase)) {
m_BoundaryType = BoundaryType.Chunked;
m_ContentLength = -1;
}
else {
m_ContentLength = 0;
m_BoundaryType = BoundaryType.ContentLength;
string length = GetKnownHeader(HttpRequestHeader.ContentLength);
if (length!=null) {
bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out m_ContentLength);
if (!success) {
m_ContentLength = 0;
m_BoundaryType = BoundaryType.Invalid;
}
}
}
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ContentLength_get() returning m_ContentLength:" + m_ContentLength + " m_BoundaryType:" + m_BoundaryType);
return m_ContentLength;
}
}
public /* override */ string ContentType {
get {
return GetKnownHeader(HttpRequestHeader.ContentType);
}
}
public /* override */ NameValueCollection Headers {
get {
if (m_WebHeaders==null) {
m_WebHeaders = UnsafeNclNativeMethods.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::Headers_get() returning#" + ValidationHelper.HashString(m_WebHeaders));
return m_WebHeaders;
}
}
public /* override */ string HttpMethod {
get {
if (m_HttpMethod==null) {
m_HttpMethod = UnsafeNclNativeMethods.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::HttpMethod_get() returning m_HttpMethod:" + ValidationHelper.ToString(m_HttpMethod));
return m_HttpMethod;
}
}
public /* override */ Stream InputStream {
get {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "InputStream_get", "");
if (m_RequestStream==null) {
m_RequestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "InputStream_get", "");
return m_RequestStream;
}
}
// Requires ControlPrincipal permission if the request was authenticated with Negotiate, NTLM, or Digest.
public /* override */ bool IsAuthenticated {
get {
IPrincipal user = HttpListenerContext.User;
return user != null && user.Identity != null && user.Identity.IsAuthenticated;
}
}
public /* override */ bool IsLocal {
get {
return LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
}
}
public /* override */ bool IsSecureConnection {
get {
return m_SslStatus != SslStatus.Insecure;
}
}
public bool IsWebSocketRequest
{
get
{
if (!WebSocketProtocolComponent.IsSupported)
{
return false;
}
bool foundConnectionUpgradeHeader = false;
if (string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Upgrade]))
{
return false;
}
foreach (string connection in this.Headers.GetValues(HttpKnownHeaderNames.Connection))
{
if (string.Compare(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase) == 0)
{
foundConnectionUpgradeHeader = true;
break;
}
}
if (!foundConnectionUpgradeHeader)
{
return false;
}
foreach (string upgrade in this.Headers.GetValues(HttpKnownHeaderNames.Upgrade))
{
if (string.Compare(upgrade, WebSocketHelpers.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
return false;
}
}
public /* override */ NameValueCollection QueryString {
get {
NameValueCollection queryString = new NameValueCollection();
Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
return queryString;
}
}
public /* override */ string RawUrl {
get {
return m_RawUrl;
}
}
public string ServiceName
{
get { return m_ServiceName; }
internal set { m_ServiceName = value; }
}
public /* override */ Uri Url {
get {
return RequestUri;
}
}
public /* override */ Uri UrlReferrer {
get {
string referrer = GetKnownHeader(HttpRequestHeader.Referer);
if (referrer==null) {
return null;
}
Uri urlReferrer;
bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out urlReferrer);
return success ? urlReferrer : null;
}
}
public /* override */ string UserAgent {
get {
return GetKnownHeader(HttpRequestHeader.UserAgent);
}
}
public /* override */ string UserHostAddress {
get {
return LocalEndPoint.ToString();
}
}
public /* override */ string UserHostName {
get {
return GetKnownHeader(HttpRequestHeader.Host);
}
}
public /* override */ string[] UserLanguages {
get {
return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.AcceptLanguage));
}
}
public int ClientCertificateError {
get {
if (m_ClientCertState == ListenerClientCertState.NotInitialized)
throw new InvalidOperationException(SR.GetString(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()"));
else if (m_ClientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.GetString(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()"));
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ClientCertificateError_get() returning ClientCertificateError:" + ValidationHelper.ToString(m_ClientCertificateError));
return m_ClientCertificateError;
}
}
internal X509Certificate2 ClientCertificate {
set {
m_ClientCertificate = value;
}
}
internal ListenerClientCertState ClientCertState {
set {
m_ClientCertState = value;
}
}
internal void SetClientCertificateError(int clientCertificateError)
{
m_ClientCertificateError = clientCertificateError;
}
public X509Certificate2 GetClientCertificate() {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "GetClientCertificate", "");
try {
ProcessClientCertificate();
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::GetClientCertificate() returning m_ClientCertificate:" + ValidationHelper.ToString(m_ClientCertificate));
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "GetClientCertificate", ValidationHelper.ToString(m_ClientCertificate));
}
return m_ClientCertificate;
}
public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) {
if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, "BeginGetClientCertificate", "");
return AsyncProcessClientCertificate(requestCallback, state);
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "EndGetClientCertificate", "");
X509Certificate2 clientCertificate = null;
try {
if (asyncResult==null) {
throw new ArgumentNullException("asyncResult");
}
ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
if (clientCertAsyncResult==null || clientCertAsyncResult.AsyncObject!=this) {
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
if (clientCertAsyncResult.EndCalled) {
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndGetClientCertificate"));
}
clientCertAsyncResult.EndCalled = true;
clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::EndGetClientCertificate() returning m_ClientCertificate:" + ValidationHelper.ToString(m_ClientCertificate));
} finally {
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "EndGetClientCertificate", ValidationHelper.HashString(clientCertificate));
}
return clientCertificate;
}
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public Task<X509Certificate2> GetClientCertificateAsync()
{
return Task<X509Certificate2>.Factory.FromAsync(BeginGetClientCertificate, EndGetClientCertificate, null);
}
public TransportContext TransportContext
{
get
{
return new HttpListenerRequestContext(this);
}
}
private CookieCollection ParseCookies(Uri uri, string setCookieHeader) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ParseCookies() uri:" + uri + " setCookieHeader:" + setCookieHeader);
CookieCollection cookies = new CookieCollection();
CookieParser parser = new CookieParser(setCookieHeader);
for (;;) {
Cookie cookie = parser.GetServer();
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ParseCookies() CookieParser returned cookie:" + ValidationHelper.ToString(cookie));
if (cookie==null) {
// EOF, done.
break;
}
if (cookie.Name.Length==0) {
continue;
}
cookies.InternalAdd(cookie, true);
}
return cookies;
}
public CookieCollection Cookies {
get {
if (m_Cookies==null) {
string cookieString = GetKnownHeader(HttpRequestHeader.Cookie);
if (cookieString!=null && cookieString.Length>0) {
m_Cookies = ParseCookies(RequestUri, cookieString);
}
if (m_Cookies==null) {
m_Cookies = new CookieCollection();
}
if (HttpListenerContext.PromoteCookiesToRfc2965) {
for (int index=0; index<m_Cookies.Count; index++) {
if (m_Cookies[index].Variant==CookieVariant.Rfc2109) {
m_Cookies[index].Variant = CookieVariant.Rfc2965;
}
}
}
}
return m_Cookies;
}
}
public Version ProtocolVersion {
get {
return m_Version;
}
}
public /* override */ bool HasEntityBody {
get {
// accessing the ContentLength property delay creates m_BoundaryType
return (ContentLength64 > 0 && m_BoundaryType == BoundaryType.ContentLength) ||
m_BoundaryType == BoundaryType.Chunked || m_BoundaryType == BoundaryType.Multipart;
}
}
public /* override */ bool KeepAlive
{
get
{
if (m_KeepAlive == TriState.Unspecified)
{
string header = Headers[HttpKnownHeaderNames.ProxyConnection];
if (string.IsNullOrEmpty(header))
{
header = GetKnownHeader(HttpRequestHeader.Connection);
}
if (string.IsNullOrEmpty(header))
{
if (ProtocolVersion >= HttpVersion.Version11)
{
m_KeepAlive = TriState.True;
}
else
{
header = GetKnownHeader(HttpRequestHeader.KeepAlive);
m_KeepAlive = string.IsNullOrEmpty(header) ? TriState.False : TriState.True;
}
}
else
{
header = header.ToLower(CultureInfo.InvariantCulture);
m_KeepAlive = header.IndexOf("close") < 0 || header.IndexOf("keep-alive") >= 0 ? TriState.True : TriState.False;
}
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::KeepAlive_get() returning:" + m_KeepAlive);
return m_KeepAlive == TriState.True;
}
}
public /* override */ IPEndPoint RemoteEndPoint {
get {
if (m_RemoteEndPoint==null) {
m_RemoteEndPoint = UnsafeNclNativeMethods.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::RemoteEndPoint_get() returning:" + m_RemoteEndPoint);
return m_RemoteEndPoint;
}
}
public /* override */ IPEndPoint LocalEndPoint {
get {
if (m_LocalEndPoint==null) {
m_LocalEndPoint = UnsafeNclNativeMethods.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::LocalEndPoint_get() returning:" + m_LocalEndPoint);
return m_LocalEndPoint;
}
}
//should only be called from httplistenercontext
internal void Close() {
if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Close", "");
RequestContextBase memoryBlob = m_MemoryBlob;
if (memoryBlob != null)
{
memoryBlob.Close();
m_MemoryBlob = null;
}
m_IsDisposed = true;
if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Close", "");
}
private ListenerClientCertAsyncResult AsyncProcessClientCertificate(AsyncCallback requestCallback, object state) {
if (m_ClientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.GetString(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()"));
m_ClientCertState = ListenerClientCertState.InProgress;
HttpListenerContext.EnsureBoundHandle();
ListenerClientCertAsyncResult asyncResult = null;
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So intially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE
if (m_SslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
asyncResult = new ListenerClientCertAsyncResult(this, state, requestCallback, size);
try {
while (true)
{
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
m_ConnectionId,
(uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE,
asyncResult.RequestBlob,
size,
&bytesReceived,
asyncResult.NativeOverlapped);
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA)
{
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
size = bytesReceived + pClientCertInfo->CertEncodedSize;
asyncResult.Reset(size);
continue;
}
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING) {
// someother bad error, possible(?) return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
// Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required.
throw new HttpListenerException((int)statusCode);
}
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.IOCompleted(statusCode, bytesReceived);
}
break;
}
}
catch {
if (asyncResult!=null) {
asyncResult.InternalCleanup();
}
throw;
}
} else {
asyncResult = new ListenerClientCertAsyncResult(this, state, requestCallback, 0);
asyncResult.InvokeCallback();
}
return asyncResult;
}
private void ProcessClientCertificate() {
if (m_ClientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.GetString(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()"));
m_ClientCertState = ListenerClientCertState.InProgress;
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate()");
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So intially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE
if (m_SslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
while (true)
{
byte[] clientCertInfoBlob = new byte[checked((int) size)];
fixed (byte* pClientCertInfoBlob = clientCertInfoBlob)
{
UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*) pClientCertInfoBlob;
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
m_ConnectionId,
(uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE,
pClientCertInfo,
size,
&bytesReceived,
null);
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA) {
size = bytesReceived + pClientCertInfo->CertEncodedSize;
continue;
}
else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
if (pClientCertInfo!=null) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() pClientCertInfo:" + ValidationHelper.ToString((IntPtr)pClientCertInfo)
+ " pClientCertInfo->CertFlags:" + ValidationHelper.ToString(pClientCertInfo->CertFlags)
+ " pClientCertInfo->CertEncodedSize:" + ValidationHelper.ToString(pClientCertInfo->CertEncodedSize)
+ " pClientCertInfo->pCertEncoded:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->pCertEncoded)
+ " pClientCertInfo->Token:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->Token)
+ " pClientCertInfo->CertDeniedByMapper:" + ValidationHelper.ToString(pClientCertInfo->CertDeniedByMapper));
if (pClientCertInfo->pCertEncoded!=null) {
try {
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
m_ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() caught CryptographicException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
}
catch (SecurityException exception) {
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() caught SecurityException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception));
}
}
m_ClientCertificateError = (int)pClientCertInfo->CertFlags;
}
}
else {
GlobalLog.Assert(statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_NOT_FOUND, "HttpListenerRequest#{0}::ProcessClientCertificate()|Call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate() failed with statusCode {1}.", ValidationHelper.HashString(this), statusCode);
}
}
break;
}
}
m_ClientCertState = ListenerClientCertState.Completed;
}
private string RequestScheme {
get {
return IsSecureConnection ? "https" : "http";
}
}
private Uri RequestUri {
get {
if (m_RequestUri == null) {
m_RequestUri = HttpListenerRequestUriBuilder.GetRequestUri(
m_RawUrl, RequestScheme, m_CookedUrlHost, m_CookedUrlPath, m_CookedUrlQuery);
}
GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::RequestUri_get() returning m_RequestUri:" + ValidationHelper.ToString(m_RequestUri));
return m_RequestUri;
}
}
/*
private DateTime IfModifiedSince {
get {
string headerValue = GetKnownHeader(HttpRequestHeader.IfModifiedSince);
if (headerValue==null) {
return DateTime.Now;
}
return DateTime.Parse(headerValue, CultureInfo.InvariantCulture);
}
}
*/
private string GetKnownHeader(HttpRequestHeader header) {
return UnsafeNclNativeMethods.HttpApi.GetKnownHeader(RequestBuffer, OriginalBlobAddress, (int) header);
}
internal ChannelBinding GetChannelBinding()
{
return HttpListenerContext.Listener.GetChannelBindingFromTls(m_ConnectionId);
}
internal void CheckDisposed() {
if (m_IsDisposed) {
throw new ObjectDisposedException(this.GetType().FullName);
}
}
// <
static class Helpers {
//
// Get attribute off header value
//
internal static String GetAttributeFromHeader(String headerValue, String attrName) {
if (headerValue == null)
return null;
int l = headerValue.Length;
int k = attrName.Length;
// find properly separated attribute name
int i = 1; // start searching from 1
while (i < l) {
i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase);
if (i < 0)
break;
if (i+k >= l)
break;
char chPrev = headerValue[i-1];
char chNext = headerValue[i+k];
if ((chPrev == ';' || chPrev == ',' || Char.IsWhiteSpace(chPrev)) && (chNext == '=' || Char.IsWhiteSpace(chNext)))
break;
i += k;
}
if (i < 0 || i >= l)
return null;
// skip to '=' and the following whitespaces
i += k;
while (i < l && Char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l || headerValue[i] != '=')
return null;
i++;
while (i < l && Char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l)
return null;
// parse the value
String attrValue = null;
int j;
if (i < l && headerValue[i] == '"') {
if (i == l-1)
return null;
j = headerValue.IndexOf('"', i+1);
if (j < 0 || j == i+1)
return null;
attrValue = headerValue.Substring(i+1, j-i-1).Trim();
}
else {
for (j = i; j < l; j++) {
if (headerValue[j] == ' ' || headerValue[j] == ',')
break;
}
if (j == i)
return null;
attrValue = headerValue.Substring(i, j-i).Trim();
}
return attrValue;
}
internal static String[] ParseMultivalueHeader(String s) {
if (s == null)
return null;
int l = s.Length;
// collect comma-separated values into list
ArrayList values = new ArrayList();
int i = 0;
while (i < l) {
// find next ,
int ci = s.IndexOf(',', i);
if (ci < 0)
ci = l;
// append corresponding server value
values.Add(s.Substring(i, ci-i));
// move to next
i = ci+1;
// skip leading space
if (i < l && s[i] == ' ')
i++;
}
// return list as array of strings
int n = values.Count;
String[] strings;
// if n is 0 that means s was empty string
if (n == 0) {
strings = new String[1];
strings[0] = String.Empty;
}
else {
strings = new String[n];
values.CopyTo(0, strings, 0, n);
}
return strings;
}
private static string UrlDecodeStringFromStringInternal(string s, Encoding e) {
int count = s.Length;
UrlDecoder helper = new UrlDecoder(count, e);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++) {
char ch = s[pos];
if (ch == '+') {
ch = ' ';
}
else if (ch == '%' && pos < count-2) {
if (s[pos+1] == 'u' && pos < count-5) {
int h1 = HexToInt(s[pos+2]);
int h2 = HexToInt(s[pos+3]);
int h3 = HexToInt(s[pos+4]);
int h4 = HexToInt(s[pos+5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0) { // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else {
int h1 = HexToInt(s[pos+1]);
int h2 = HexToInt(s[pos+2]);
if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
else
helper.AddChar(ch);
}
return helper.GetString();
}
private static int HexToInt(char h) {
return( h >= '0' && h <= '9' ) ? h - '0' :
( h >= 'a' && h <= 'f' ) ? h - 'a' + 10 :
( h >= 'A' && h <= 'F' ) ? h - 'A' + 10 :
-1;
}
private class UrlDecoder {
private int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private Encoding _encoding;
private void FlushBytes() {
if (_numBytes > 0) {
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding) {
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch) {
if (_numBytes > 0)
FlushBytes();
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b) {
// if there are no pending bytes treat 7 bit bytes as characters
// this optimization is temp disable as it doesn't work for some encodings
/*
if (_numBytes == 0 && ((b & 0x80) == 0)) {
AddChar((char)b);
}
else
*/
{
if (_byteBuffer == null)
_byteBuffer = new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
}
internal String GetString() {
if (_numBytes > 0)
FlushBytes();
if (_numChars > 0)
return new String(_charBuffer, 0, _numChars);
else
return String.Empty;
}
}
internal static void FillFromString(NameValueCollection nvc, String s, bool urlencoded, Encoding encoding) {
int l = (s != null) ? s.Length : 0;
int i = (s.Length>0 && s[0]=='?') ? 1 : 0;
while (i < l) {
// find next & while noting first = on the way (and if there are more)
int si = i;
int ti = -1;
while (i < l) {
char ch = s[i];
if (ch == '=') {
if (ti < 0)
ti = i;
}
else if (ch == '&') {
break;
}
i++;
}
// extract the name / value pair
String name = null;
String value = null;
if (ti >= 0) {
name = s.Substring(si, ti-si);
value = s.Substring(ti+1, i-ti-1);
}
else {
value = s.Substring(si, i-si);
}
// add name / value pair to the collection
if (urlencoded)
nvc.Add(
name == null ? null : UrlDecodeStringFromStringInternal(name, encoding),
UrlDecodeStringFromStringInternal(value, encoding));
else
nvc.Add(name, value);
// trailing '&'
if (i == l-1 && s[i] == '&')
nvc.Add(null, "");
i++;
}
}
}
}
}
| |
/*
* Copyright 2001-2010 Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Common.Logging;
using Quartz.Impl.Matchers;
using Quartz.Spi;
using Quartz.Util;
using Quartz.Xml.JobSchedulingData20;
namespace Quartz.Xml
{
/// <summary>
/// Parses an XML file that declares Jobs and their schedules (Triggers).
/// </summary>
/// <remarks>
/// <para>
/// The xml document must conform to the format defined in "job_scheduling_data_2_0.xsd"
/// </para>
///
/// <para>
/// After creating an instance of this class, you should call one of the <see cref="ProcessFile()" />
/// functions, after which you may call the ScheduledJobs()
/// function to get a handle to the defined Jobs and Triggers, which can then be
/// scheduled with the <see cref="IScheduler" />. Alternatively, you could call
/// the <see cref="ProcessFileAndScheduleJobs(Quartz.IScheduler)" /> function to do all of this
/// in one step.
/// </para>
///
/// <para>
/// The same instance can be used again and again, with the list of defined Jobs
/// being cleared each time you call a <see cref="ProcessFile()" /> method,
/// however a single instance is not thread-safe.
/// </para>
/// </remarks>
/// <author><a href="mailto:bonhamcm@thirdeyeconsulting.com">Chris Bonham</a></author>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
public class XMLSchedulingDataProcessor
{
private readonly ILog log;
public const string PropertyQuartzSystemIdDir = "quartz.system.id.dir";
public const string QuartzXmlFileName = "quartz_jobs.xml";
public const string QuartzSchema = "http://quartznet.sourceforge.net/xml/job_scheduling_data_2_0.xsd";
public const string QuartzXsdResourceName = "Quartz.Xml.job_scheduling_data_2_0.xsd";
protected const string ThreadLocalKeyScheduler = "quartz_scheduler";
// pre-processing commands
private readonly IList<string> jobGroupsToDelete = new List<string>();
private readonly IList<string> triggerGroupsToDelete = new List<string>();
private readonly IList<JobKey> jobsToDelete = new List<JobKey>();
private readonly IList<TriggerKey> triggersToDelete = new List<TriggerKey>();
// scheduling commands
private readonly List<IJobDetail> loadedJobs = new List<IJobDetail>();
private readonly List<ITrigger> loadedTriggers = new List<ITrigger>();
// directives
private readonly IList<Exception> validationExceptions = new List<Exception>();
protected readonly ITypeLoadHelper typeLoadHelper;
private readonly IList<string> jobGroupsToNeverDelete = new List<string>();
private readonly IList<string> triggerGroupsToNeverDelete = new List<string>();
/// <summary>
/// Constructor for XMLSchedulingDataProcessor.
/// </summary>
public XMLSchedulingDataProcessor(ITypeLoadHelper typeLoadHelper)
{
OverWriteExistingData = true;
IgnoreDuplicates = false;
log = LogManager.GetLogger(GetType());
this.typeLoadHelper = typeLoadHelper;
}
/// <summary>
/// Whether the existing scheduling data (with same identifiers) will be
/// overwritten.
/// </summary>
/// <remarks>
/// If false, and <see cref="IgnoreDuplicates" /> is not false, and jobs or
/// triggers with the same names already exist as those in the file, an
/// error will occur.
/// </remarks>
/// <seealso cref="IgnoreDuplicates" />
public bool OverWriteExistingData { get; set; }
/// <summary>
/// If true (and <see cref="OverWriteExistingData" /> is false) then any
/// job/triggers encountered in this file that have names that already exist
/// in the scheduler will be ignored, and no error will be produced.
/// </summary>
/// <seealso cref="OverWriteExistingData"/>
public bool IgnoreDuplicates { get; set; }
/// <summary>
/// If true (and <see cref="OverWriteExistingData" /> is true) then any
/// job/triggers encountered in this file that already exist is scheduler
/// will be updated with start time relative to old trigger. Effectively
/// new trigger's last fire time will be updated to old trigger's last fire time
/// and trigger's next fire time will updated to be next from this last fire time.
/// </summary>
public bool ScheduleTriggerRelativeToReplacedTrigger { get; set; }
/// <summary>
/// Gets the log.
/// </summary>
/// <value>The log.</value>
protected ILog Log
{
get { return log; }
}
protected IList<IJobDetail> LoadedJobs
{
get { return loadedJobs.AsReadOnly(); }
}
protected IList<ITrigger> LoadedTriggers
{
get { return loadedTriggers.AsReadOnly(); }
}
/// <summary>
/// Process the xml file in the default location (a file named
/// "quartz_jobs.xml" in the current working directory).
/// </summary>
public virtual void ProcessFile()
{
ProcessFile(QuartzXmlFileName);
}
/// <summary>
/// Process the xml file named <see param="fileName" />.
/// </summary>
/// <param name="fileName">meta data file name.</param>
public virtual void ProcessFile(string fileName)
{
ProcessFile(fileName, fileName);
}
/// <summary>
/// Process the xmlfile named <see param="fileName" /> with the given system
/// ID.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="systemId">The system id.</param>
public virtual void ProcessFile(string fileName, string systemId)
{
// resolve file name first
fileName = FileUtil.ResolveFile(fileName);
Log.InfoFormat(CultureInfo.InvariantCulture, "Parsing XML file: {0} with systemId: {1}", fileName, systemId);
using (StreamReader sr = new StreamReader(fileName))
{
ProcessInternal(sr.ReadToEnd());
}
}
/// <summary>
/// Process the xmlfile named <see param="fileName" /> with the given system
/// ID.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="systemId">The system id.</param>
public virtual void ProcessStream(Stream stream, string systemId)
{
Log.InfoFormat(CultureInfo.InvariantCulture, "Parsing XML from stream with systemId: {0}", systemId);
using (StreamReader sr = new StreamReader(stream))
{
ProcessInternal(sr.ReadToEnd());
}
}
protected virtual void PrepForProcessing()
{
ClearValidationExceptions();
OverWriteExistingData = true;
IgnoreDuplicates = false;
jobGroupsToDelete.Clear();
jobsToDelete.Clear();
triggerGroupsToDelete.Clear();
triggersToDelete.Clear();
loadedJobs.Clear();
loadedTriggers.Clear();
}
protected virtual void ProcessInternal(string xml)
{
PrepForProcessing();
ValidateXml(xml);
MaybeThrowValidationException();
// deserialize as object model
XmlSerializer xs = new XmlSerializer(typeof (QuartzXmlConfiguration20));
QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20) xs.Deserialize(new StringReader(xml));
if (data == null)
{
throw new SchedulerConfigException("Job definition data from XML was null after deserialization");
}
//
// Extract pre-processing commands
//
if (data.preprocessingcommands != null)
{
foreach (preprocessingcommandsType command in data.preprocessingcommands)
{
if (command.deletejobsingroup != null)
{
foreach (string s in command.deletejobsingroup)
{
string deleteJobGroup = s.NullSafeTrim();
if (!String.IsNullOrEmpty(deleteJobGroup))
{
jobGroupsToDelete.Add(deleteJobGroup);
}
}
}
if (command.deletetriggersingroup != null)
{
foreach (string s in command.deletetriggersingroup)
{
string deleteTriggerGroup = s.NullSafeTrim();
if (!String.IsNullOrEmpty(deleteTriggerGroup))
{
triggerGroupsToDelete.Add(deleteTriggerGroup);
}
}
}
if (command.deletejob != null)
{
foreach (preprocessingcommandsTypeDeletejob s in command.deletejob)
{
string name = s.name.TrimEmptyToNull();
string group = s.group.TrimEmptyToNull();
if (name == null)
{
throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified.");
}
jobsToDelete.Add(new JobKey(name, group));
}
}
if (command.deletetrigger != null)
{
foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger)
{
string name = s.name.TrimEmptyToNull();
string group = s.group.TrimEmptyToNull();
if (name == null)
{
throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified.");
}
triggersToDelete.Add(new TriggerKey(name, group));
}
}
}
}
if (log.IsDebugEnabled)
{
log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands.");
log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands.");
log.Debug("Found " + jobsToDelete.Count + " delete job commands.");
log.Debug("Found " + triggersToDelete.Count + " delete trigger commands.");
}
//
// Extract directives
//
if (data.processingdirectives != null && data.processingdirectives.Length > 0)
{
bool overWrite = data.processingdirectives[0].overwriteexistingdata;
log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite);
OverWriteExistingData = overWrite;
}
else
{
log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates);
}
if (data.processingdirectives != null && data.processingdirectives.Length > 0)
{
bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates;
log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates);
IgnoreDuplicates = ignoreduplicates;
}
else
{
log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData);
}
if (data.processingdirectives != null && data.processingdirectives.Length > 0)
{
bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger;
log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative);
ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative;
}
else
{
log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger);
}
//
// Extract Job definitions...
//
List<jobdetailType> jobNodes = new List<jobdetailType>();
if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].job != null)
{
jobNodes.AddRange(data.schedule[0].job);
}
log.Debug("Found " + jobNodes.Count + " job definitions.");
foreach (jobdetailType jobDetailType in jobNodes)
{
string jobName = jobDetailType.name.TrimEmptyToNull();
string jobGroup = jobDetailType.group.TrimEmptyToNull();
string jobDescription = jobDetailType.description.TrimEmptyToNull();
string jobTypeName = jobDetailType.jobtype.TrimEmptyToNull();
bool jobDurability = jobDetailType.durable;
bool jobRecoveryRequested = jobDetailType.recover;
Type jobType = typeLoadHelper.LoadType(jobTypeName);
IJobDetail jobDetail = JobBuilder.Create(jobType)
.WithIdentity(jobName, jobGroup)
.WithDescription(jobDescription)
.StoreDurably(jobDurability)
.RequestRecovery(jobRecoveryRequested)
.Build();
if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null)
{
foreach (entryType entry in jobDetailType.jobdatamap.entry)
{
string key = entry.key.TrimEmptyToNull();
string value = entry.value.TrimEmptyToNull();
jobDetail.JobDataMap.Add(key, value);
}
}
if (log.IsDebugEnabled)
{
log.Debug("Parsed job definition: " + jobDetail);
}
AddJobToSchedule(jobDetail);
}
//
// Extract Trigger definitions...
//
List<triggerType> triggerEntries = new List<triggerType>();
if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].trigger != null)
{
triggerEntries.AddRange(data.schedule[0].trigger);
}
log.Debug("Found " + triggerEntries.Count + " trigger definitions.");
foreach (triggerType triggerNode in triggerEntries)
{
string triggerName = triggerNode.Item.name.TrimEmptyToNull();
string triggerGroup = triggerNode.Item.group.TrimEmptyToNull();
string triggerDescription = triggerNode.Item.description.TrimEmptyToNull();
string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull();
string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull();
string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull();
int triggerPriority = TriggerConstants.DefaultPriority;
if (!triggerNode.Item.priority.IsNullOrWhiteSpace())
{
triggerPriority = Convert.ToInt32(triggerNode.Item.priority);
}
DateTimeOffset triggerStartTime = SystemTime.UtcNow();
if (triggerNode.Item.Item != null)
{
if (triggerNode.Item.Item is DateTime)
{
triggerStartTime = new DateTimeOffset((DateTime) triggerNode.Item.Item);
}
else
{
triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item));
}
}
DateTime? triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?) null;
IScheduleBuilder sched;
if (triggerNode.Item is simpleTriggerType)
{
simpleTriggerType simpleTrigger = (simpleTriggerType) triggerNode.Item;
string repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull();
string repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull();
int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString);
TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString));
sched = SimpleScheduleBuilder.Create()
.WithInterval(repeatInterval)
.WithRepeatCount(repeatCount);
if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((SimpleScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction));
}
}
else if (triggerNode.Item is cronTriggerType)
{
cronTriggerType cronTrigger = (cronTriggerType) triggerNode.Item;
string cronExpression = cronTrigger.cronexpression.TrimEmptyToNull();
string timezoneString = cronTrigger.timezone.TrimEmptyToNull();
TimeZoneInfo tz = timezoneString != null ? TimeZoneInfo.FindSystemTimeZoneById(timezoneString) : null;
sched = CronScheduleBuilder.CronSchedule(cronExpression)
.InTimeZone(tz);
if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((CronScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction));
}
}
else if (triggerNode.Item is calendarIntervalTriggerType)
{
calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType) triggerNode.Item;
string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull();
IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull());
int repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString);
sched = CalendarIntervalScheduleBuilder.Create()
.WithInterval(repeatInterval, intervalUnit);
if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((CalendarIntervalScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction));
}
}
else
{
throw new SchedulerConfigException("Unknown trigger type in XML configuration");
}
IMutableTrigger trigger = (IMutableTrigger) TriggerBuilder.Create()
.WithIdentity(triggerName, triggerGroup)
.WithDescription(triggerDescription)
.ForJob(triggerJobName, triggerJobGroup)
.StartAt(triggerStartTime)
.EndAt(triggerEndTime)
.WithPriority(triggerPriority)
.ModifiedByCalendar(triggerCalendarRef)
.WithSchedule(sched)
.Build();
if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null)
{
foreach (entryType entry in triggerNode.Item.jobdatamap.entry)
{
string key = entry.key.TrimEmptyToNull();
string value = entry.value.TrimEmptyToNull();
trigger.JobDataMap.Add(key, value);
}
}
if (log.IsDebugEnabled)
{
log.Debug("Parsed trigger definition: " + trigger);
}
AddTriggerToSchedule(trigger);
}
}
protected virtual void AddJobToSchedule(IJobDetail job)
{
loadedJobs.Add(job);
}
protected virtual void AddTriggerToSchedule(IMutableTrigger trigger)
{
loadedTriggers.Add(trigger);
}
protected virtual int ParseSimpleTriggerRepeatCount(string repeatcount)
{
int value = Convert.ToInt32(repeatcount, CultureInfo.InvariantCulture);
return value;
}
protected virtual int ReadMisfireInstructionFromString(string misfireinstruction)
{
Constants c = new Constants(typeof (MisfireInstruction), typeof (MisfireInstruction.CronTrigger),
typeof (MisfireInstruction.SimpleTrigger));
return c.AsNumber(misfireinstruction);
}
protected virtual IntervalUnit ParseDateIntervalTriggerIntervalUnit(string intervalUnit)
{
if (String.IsNullOrEmpty(intervalUnit))
{
return IntervalUnit.Day;
}
IntervalUnit retValue;
if (!TryParseEnum(intervalUnit, out retValue))
{
throw new SchedulerConfigException("Unknown interval unit for DateIntervalTrigger: " + intervalUnit);
}
return retValue;
}
protected virtual bool TryParseEnum<T>(string str, out T value) where T : struct
{
var names = Enum.GetNames(typeof (T));
value = (Enum.GetValues(typeof (T)) as T[])[0];
foreach (var name in names)
{
if (name == str)
{
value = (T) Enum.Parse(typeof (T), name);
return true;
}
}
return false;
}
private void ValidateXml(string xml)
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
Stream stream = GetType().Assembly.GetManifestResourceStream(QuartzXsdResourceName);
XmlSchema schema = XmlSchema.Read(stream, XmlValidationCallBack);
settings.Schemas.Add(schema);
settings.ValidationEventHandler += XmlValidationCallBack;
// stream to validate
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
{
while (reader.Read())
{
}
}
}
catch (Exception ex)
{
log.Warn("Unable to validate XML with schema: " + ex.Message, ex);
}
}
private void XmlValidationCallBack(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error)
{
validationExceptions.Add(e.Exception);
}
else
{
Log.Warn(e.Message);
}
}
/// <summary>
/// Process the xml file in the default location, and schedule all of the jobs defined within it.
/// </summary>
/// <remarks>Note that we will set overWriteExistingJobs after the default xml is parsed.</remarks>
/// <param name="sched"></param>
/// <param name="overWriteExistingJobs"></param>
public void ProcessFileAndScheduleJobs(IScheduler sched, bool overWriteExistingJobs)
{
ProcessFile(QuartzXmlFileName, QuartzXmlFileName);
// The overWriteExistingJobs flag was set by processFile() -> prepForProcessing(), then by xml parsing, and then now
// we need to reset it again here by this method parameter to override it.
OverWriteExistingData = overWriteExistingJobs;
ExecutePreProcessCommands(sched);
ScheduleJobs(sched);
}
/// <summary>
/// Process the xml file in the default location, and schedule all of the
/// jobs defined within it.
/// </summary>
public virtual void ProcessFileAndScheduleJobs(IScheduler sched)
{
ProcessFileAndScheduleJobs(QuartzXmlFileName, sched);
}
/// <summary>
/// Process the xml file in the given location, and schedule all of the
/// jobs defined within it.
/// </summary>
/// <param name="fileName">meta data file name.</param>
/// <param name="sched">The scheduler.</param>
public virtual void ProcessFileAndScheduleJobs(string fileName, IScheduler sched)
{
ProcessFileAndScheduleJobs(fileName, fileName, sched);
}
/// <summary>
/// Process the xml file in the given location, and schedule all of the
/// jobs defined within it.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="systemId">The system id.</param>
/// <param name="sched">The sched.</param>
public virtual void ProcessFileAndScheduleJobs(string fileName, string systemId, IScheduler sched)
{
LogicalThreadContext.SetData(ThreadLocalKeyScheduler, sched);
try
{
ProcessFile(fileName, systemId);
ExecutePreProcessCommands(sched);
ScheduleJobs(sched);
}
finally
{
LogicalThreadContext.FreeNamedDataSlot(ThreadLocalKeyScheduler);
}
}
/// <summary>
/// Schedules the given sets of jobs and triggers.
/// </summary>
/// <param name="sched">The sched.</param>
public virtual void ScheduleJobs(IScheduler sched)
{
List<IJobDetail> jobs = new List<IJobDetail>(LoadedJobs);
List<ITrigger> triggers = new List<ITrigger>(LoadedTriggers);
log.Info("Adding " + jobs.Count + " jobs, " + triggers.Count + " triggers.");
IDictionary<JobKey, List<IMutableTrigger>> triggersByFQJobName = BuildTriggersByFQJobNameMap(triggers);
// add each job, and it's associated triggers
while (jobs.Count > 0)
{
// remove jobs as we handle them...
IJobDetail detail = jobs[0];
jobs.Remove(detail);
IJobDetail dupeJ = sched.GetJobDetail(detail.Key);
if ((dupeJ != null))
{
if (!OverWriteExistingData && IgnoreDuplicates)
{
log.Info("Not overwriting existing job: " + dupeJ.Key);
continue; // just ignore the entry
}
if (!OverWriteExistingData && !IgnoreDuplicates)
{
throw new ObjectAlreadyExistsException(detail);
}
}
if (dupeJ != null)
{
log.Info("Replacing job: " + detail.Key);
}
else
{
log.Info("Adding job: " + detail.Key);
}
List<IMutableTrigger> triggersOfJob;
triggersByFQJobName.TryGetValue(detail.Key, out triggersOfJob);
if (!detail.Durable && (triggersOfJob == null || triggersOfJob.Count == 0))
{
if (dupeJ == null)
{
throw new SchedulerException(
"A new job defined without any triggers must be durable: " +
detail.Key);
}
if ((dupeJ.Durable &&
(sched.GetTriggersOfJob(detail.Key).Count == 0)))
{
throw new SchedulerException(
"Can't change existing durable job without triggers to non-durable: " +
detail.Key);
}
}
if (dupeJ != null || detail.Durable)
{
sched.AddJob(detail, true); // add the job if a replacement or durable
}
else
{
bool addJobWithFirstSchedule = true;
// Add triggers related to the job...
while (triggersOfJob.Count > 0)
{
IMutableTrigger trigger = triggersOfJob[0];
// remove triggers as we handle them...
triggersOfJob.Remove(trigger);
ITrigger dupeT = sched.GetTrigger(trigger.Key);
if (dupeT != null)
{
if (OverWriteExistingData)
{
if (log.IsDebugEnabled)
{
log.DebugFormat("Rescheduling job: {0} with updated trigger: {1}", trigger.JobKey, trigger.Key);
}
}
else if (IgnoreDuplicates)
{
log.Info("Not overwriting existing trigger: " + dupeT.Key);
continue; // just ignore the trigger (and possibly job)
}
else
{
throw new ObjectAlreadyExistsException(trigger);
}
if (!dupeT.JobKey.Equals(trigger.JobKey))
{
log.WarnFormat("Possibly duplicately named ({0}) triggers in jobs xml file! ", trigger.Key);
}
DoRescheduleJob(sched, trigger, dupeT);
}
else
{
if (log.IsDebugEnabled)
{
log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key);
}
try
{
if (addJobWithFirstSchedule)
{
sched.ScheduleJob(detail, trigger); // add the job if it's not in yet...
addJobWithFirstSchedule = false;
}
else
{
sched.ScheduleJob(trigger);
}
}
catch (ObjectAlreadyExistsException)
{
if (log.IsDebugEnabled)
{
log.DebugFormat("Adding trigger: {0} for job: {1} failed because the trigger already existed. "
+ "This is likely due to a race condition between multiple instances "
+ "in the cluster. Will try to reschedule instead.", trigger.Key, detail.Key);
}
// Let's try one more time as reschedule.
DoRescheduleJob(sched, trigger, sched.GetTrigger(trigger.Key));
}
}
}
}
}
// add triggers that weren't associated with a new job... (those we already handled were removed above)
foreach (IMutableTrigger trigger in triggers)
{
ITrigger dupeT = sched.GetTrigger(trigger.Key);
if (dupeT != null)
{
if (OverWriteExistingData)
{
if (log.IsDebugEnabled)
{
log.DebugFormat("Rescheduling job: " + trigger.JobKey + " with updated trigger: " + trigger.Key);
}
}
else if (IgnoreDuplicates)
{
log.Info("Not overwriting existing trigger: " + dupeT.Key);
continue; // just ignore the trigger
}
else
{
throw new ObjectAlreadyExistsException(trigger);
}
if (!dupeT.JobKey.Equals(trigger.JobKey))
{
log.WarnFormat("Possibly duplicately named ({0}) triggers in jobs xml file! ", trigger.Key);
}
DoRescheduleJob(sched, trigger, dupeT);
}
else
{
if (log.IsDebugEnabled)
{
log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key);
}
try
{
sched.ScheduleJob(trigger);
}
catch (ObjectAlreadyExistsException)
{
if (log.IsDebugEnabled)
{
log.Debug(
"Adding trigger: " + trigger.Key + " for job: " + trigger.JobKey +
" failed because the trigger already existed. " +
"This is likely due to a race condition between multiple instances " +
"in the cluster. Will try to reschedule instead.");
}
// Let's rescheduleJob one more time.
DoRescheduleJob(sched, trigger, sched.GetTrigger(trigger.Key));
}
}
}
}
private void DoRescheduleJob(IScheduler sched, IMutableTrigger trigger, ITrigger oldTrigger)
{
// if this is a trigger with default start time we can consider relative scheduling
if (oldTrigger != null && trigger.StartTimeUtc - SystemTime.UtcNow() < TimeSpan.FromSeconds(5) && ScheduleTriggerRelativeToReplacedTrigger)
{
Log.DebugFormat("Using relative scheduling for trigger with key {0}", trigger.Key);
var oldTriggerPreviousFireTime = oldTrigger.GetPreviousFireTimeUtc();
trigger.StartTimeUtc = oldTrigger.StartTimeUtc;
((IOperableTrigger)trigger).SetPreviousFireTimeUtc(oldTriggerPreviousFireTime);
((IOperableTrigger)trigger).SetNextFireTimeUtc(trigger.GetFireTimeAfter(oldTriggerPreviousFireTime));
}
sched.RescheduleJob(trigger.Key, trigger);
}
protected virtual IDictionary<JobKey, List<IMutableTrigger>> BuildTriggersByFQJobNameMap(List<ITrigger> triggers)
{
IDictionary<JobKey, List<IMutableTrigger>> triggersByFQJobName = new Dictionary<JobKey, List<IMutableTrigger>>();
foreach (IMutableTrigger trigger in triggers)
{
List<IMutableTrigger> triggersOfJob;
if (!triggersByFQJobName.TryGetValue(trigger.JobKey, out triggersOfJob))
{
triggersOfJob = new List<IMutableTrigger>();
triggersByFQJobName[trigger.JobKey] = triggersOfJob;
}
triggersOfJob.Add(trigger);
}
return triggersByFQJobName;
}
protected void ExecutePreProcessCommands(IScheduler scheduler)
{
foreach (string group in jobGroupsToDelete)
{
if (group.Equals("*"))
{
log.Info("Deleting all jobs in ALL groups.");
foreach (string groupName in scheduler.GetJobGroupNames())
{
if (!jobGroupsToNeverDelete.Contains(groupName))
{
foreach (JobKey key in scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName)))
{
scheduler.DeleteJob(key);
}
}
}
}
else
{
if (!jobGroupsToNeverDelete.Contains(group))
{
log.InfoFormat("Deleting all jobs in group: {}", group);
foreach (JobKey key in scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(group)))
{
scheduler.DeleteJob(key);
}
}
}
}
foreach (string group in triggerGroupsToDelete)
{
if (group.Equals("*"))
{
log.Info("Deleting all triggers in ALL groups.");
foreach (string groupName in scheduler.GetTriggerGroupNames())
{
if (!triggerGroupsToNeverDelete.Contains(groupName))
{
foreach (TriggerKey key in scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(groupName)))
{
scheduler.UnscheduleJob(key);
}
}
}
}
else
{
if (!triggerGroupsToNeverDelete.Contains(group))
{
log.InfoFormat("Deleting all triggers in group: {0}", group);
foreach (TriggerKey key in scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(group)))
{
scheduler.UnscheduleJob(key);
}
}
}
}
foreach (JobKey key in jobsToDelete)
{
if (!jobGroupsToNeverDelete.Contains(key.Group))
{
log.InfoFormat("Deleting job: {0}", key);
scheduler.DeleteJob(key);
}
}
foreach (TriggerKey key in triggersToDelete)
{
if (!triggerGroupsToNeverDelete.Contains(key.Group))
{
log.InfoFormat("Deleting trigger: {0}", key);
scheduler.UnscheduleJob(key);
}
}
}
/// <summary>
/// Adds a detected validation exception.
/// </summary>
/// <param name="e">The exception.</param>
protected virtual void AddValidationException(XmlException e)
{
validationExceptions.Add(e);
}
/// <summary>
/// Resets the the number of detected validation exceptions.
/// </summary>
protected virtual void ClearValidationExceptions()
{
validationExceptions.Clear();
}
/// <summary>
/// Throws a ValidationException if the number of validationExceptions
/// detected is greater than zero.
/// </summary>
/// <exception cref="ValidationException">
/// DTD validation exception.
/// </exception>
protected virtual void MaybeThrowValidationException()
{
if (validationExceptions.Count > 0)
{
throw new ValidationException(validationExceptions);
}
}
public void AddJobGroupToNeverDelete(string jobGroupName)
{
jobGroupsToNeverDelete.Add(jobGroupName);
}
public void AddTriggerGroupToNeverDelete(string triggerGroupName)
{
triggerGroupsToNeverDelete.Add(triggerGroupName);
}
/// <summary>
/// Helper class to map constant names to their values.
/// </summary>
internal class Constants
{
private readonly Type[] types;
public Constants(params Type[] reflectedTypes)
{
types = reflectedTypes;
}
public int AsNumber(string field)
{
foreach (Type type in types)
{
FieldInfo fi = type.GetField(field);
if (fi != null)
{
return Convert.ToInt32(fi.GetValue(null), CultureInfo.InvariantCulture);
}
}
// not found
throw new Exception(string.Format(CultureInfo.InvariantCulture, "Unknown field '{0}'", field));
}
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Statistics;
namespace OpenSim.Region.UserStatistics
{
public class ActiveConnectionsAJAX : IStatsController
{
private Vector3 DefaultNeighborPosition = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 70);
#region IStatsController Members
public string ReportName
{
get { return ""; }
}
public Hashtable ProcessModel(Hashtable pParams)
{
List<Scene> m_scene = (List<Scene>)pParams["Scenes"];
Hashtable nh = new Hashtable();
nh.Add("hdata", m_scene);
return nh;
}
public string RenderView(Hashtable pModelResult)
{
List<Scene> all_scenes = (List<Scene>) pModelResult["hdata"];
StringBuilder output = new StringBuilder();
HTMLUtil.OL_O(ref output, "");
foreach (Scene scene in all_scenes)
{
List<ScenePresence> avatarInScene = scene.GetScenePresences();
HTMLUtil.LI_O(ref output, "");
output.Append(scene.RegionInfo.RegionName);
HTMLUtil.OL_O(ref output, "");
foreach (ScenePresence av in avatarInScene)
{
Dictionary<string,string> queues = new Dictionary<string, string>();
if (av.ControllingClient is IStatsCollector)
{
IStatsCollector isClient = (IStatsCollector) av.ControllingClient;
queues = decodeQueueReport(isClient.Report());
}
HTMLUtil.LI_O(ref output, "");
output.Append(av.Name);
output.Append(" ");
output.Append((av.IsChildAgent ? "Child" : "Root"));
if (av.AbsolutePosition == DefaultNeighborPosition)
{
output.Append("<br />Position: ?");
}
else
{
output.Append(string.Format("<br /><NOBR>Position: <{0},{1},{2}></NOBR>", (int)av.AbsolutePosition.X,
(int) av.AbsolutePosition.Y,
(int) av.AbsolutePosition.Z));
}
Dictionary<string, int> throttles = DecodeClientThrottles(av.ControllingClient.GetThrottlesPacked(1));
HTMLUtil.UL_O(ref output, "");
foreach (string throttlename in throttles.Keys)
{
HTMLUtil.LI_O(ref output, "");
output.Append(throttlename);
output.Append(":");
output.Append(throttles[throttlename].ToString());
if (queues.ContainsKey(throttlename))
{
output.Append("/");
output.Append(queues[throttlename]);
}
HTMLUtil.LI_C(ref output);
}
if (queues.ContainsKey("Incoming") && queues.ContainsKey("Outgoing"))
{
HTMLUtil.LI_O(ref output, "red");
output.Append("SEND:");
output.Append(queues["Outgoing"]);
output.Append("/");
output.Append(queues["Incoming"]);
HTMLUtil.LI_C(ref output);
}
HTMLUtil.UL_C(ref output);
HTMLUtil.LI_C(ref output);
}
HTMLUtil.OL_C(ref output);
}
HTMLUtil.OL_C(ref output);
return output.ToString();
}
public Dictionary<string, int> DecodeClientThrottles(byte[] throttle)
{
Dictionary<string, int> returndict = new Dictionary<string, int>();
// From mantis http://opensimulator.org/mantis/view.php?id=1374
// it appears that sometimes we are receiving empty throttle byte arrays.
// TODO: Investigate this behaviour
if (throttle.Length == 0)
{
return new Dictionary<string, int>();
}
int tResend = -1;
int tLand = -1;
int tWind = -1;
int tCloud = -1;
int tTask = -1;
int tTexture = -1;
int tAsset = -1;
int tall = -1;
const int singlefloat = 4;
//Agent Throttle Block contains 7 single floatingpoint values.
int j = 0;
// Some Systems may be big endian...
// it might be smart to do this check more often...
if (!BitConverter.IsLittleEndian)
for (int i = 0; i < 7; i++)
Array.Reverse(throttle, j + i * singlefloat, singlefloat);
// values gotten from OpenMetaverse.org/wiki/Throttle. Thanks MW_
// bytes
// Convert to integer, since.. the full fp space isn't used.
tResend = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Resend", tResend);
j += singlefloat;
tLand = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Land", tLand);
j += singlefloat;
tWind = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Wind", tWind);
j += singlefloat;
tCloud = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Cloud", tCloud);
j += singlefloat;
tTask = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Task", tTask);
j += singlefloat;
tTexture = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Texture", tTexture);
j += singlefloat;
tAsset = (int)BitConverter.ToSingle(throttle, j);
returndict.Add("Asset", tAsset);
tall = tResend + tLand + tWind + tCloud + tTask + tTexture + tAsset;
returndict.Add("All", tall);
return returndict;
}
public Dictionary<string,string> decodeQueueReport(string rep)
{
Dictionary<string, string> returndic = new Dictionary<string, string>();
if (rep.Length == 79)
{
int pos = 1;
returndic.Add("All", rep.Substring((6 * pos), 8)); pos++;
returndic.Add("Incoming", rep.Substring((7 * pos), 8)); pos++;
returndic.Add("Outgoing", rep.Substring((7 * pos) , 8)); pos++;
returndic.Add("Resend", rep.Substring((7 * pos) , 8)); pos++;
returndic.Add("Land", rep.Substring((7 * pos) , 8)); pos++;
returndic.Add("Wind", rep.Substring((7 * pos) , 8)); pos++;
returndic.Add("Cloud", rep.Substring((7 * pos) , 8)); pos++;
returndic.Add("Task", rep.Substring((7 * pos) , 8)); pos++;
returndic.Add("Texture", rep.Substring((7 * pos), 8)); pos++;
returndic.Add("Asset", rep.Substring((7 * pos), 8));
/*
* return string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}",
SendQueue.Count(),
IncomingPacketQueue.Count,
OutgoingPacketQueue.Count,
ResendOutgoingPacketQueue.Count,
LandOutgoingPacketQueue.Count,
WindOutgoingPacketQueue.Count,
CloudOutgoingPacketQueue.Count,
TaskOutgoingPacketQueue.Count,
TextureOutgoingPacketQueue.Count,
AssetOutgoingPacketQueue.Count);
*/
}
return returndic;
}
#endregion
}
}
| |
/*=============================================================================
*
* (C) Copyright 2013, Michael Carlisle (mike.carlisle@thecodeking.co.uk)
*
* http://www.TheCodeKing.co.uk
*
* All rights reserved.
* The code and information is provided "as-is" without waranty of any kind,
* either expressed or implied.
*
*=============================================================================
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using XDMessaging;
using XDMessaging.Messages;
using XDMessaging.Transport.Amazon.Entities;
namespace TheCodeKing.Demo
{
/// <summary>
/// A demo messaging application which demostrates the cross AppDomain Messaging API.
/// This independent instances of the application to receive and send messages between
/// each other.
/// </summary>
public partial class Messenger : Form
{
#region Constants and Fields
/// <summary>
/// The instance used to broadcast messages on a particular channel.
/// </summary>
private IXDBroadcaster broadcast;
/// <summary>
/// The XDMessaging client API.
/// </summary>
private XDMessagingClient client;
/// <summary>
/// The instance used to listen to broadcast messages.
/// </summary>
private IXDListener listener;
/// <summary>
/// Uniqe name for this application instance.
/// </summary>
private string uniqueInstanceName;
#endregion
#region Constructors and Destructors
/// <summary>
/// Default constructor.
/// </summary>
public Messenger()
{
InitializeComponent();
}
#endregion
#region Methods
/// <summary>
/// The closing overrride used to broadcast on the status channel that the window is
/// closing.
/// </summary>
/// <param name = "e"></param>
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
var message = string.Format("{0} is shutting down", Handle);
broadcast.SendToChannel("Status", message);
}
/// <summary>
/// The onload event which initializes the messaging API by registering
/// for the Status and Message channels. This also assigns a delegate for
/// processing messages received.
/// </summary>
/// <param name = "e"></param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
uniqueInstanceName = string.Format("{0}-{1}", Environment.MachineName, Handle);
// create instance of the XDmessaging client and set region, crendentials should be in app.config
client = new XDMessagingClient().WithAmazonSettings(RegionEndPoint.EUWest1);
if (!client.HasValidAmazonSettings())
{
MessageBox.Show("Azazon AWS crendentials not set. Enter your credentials in the app.config.",
"Missing AWS Crendentials",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
propagateCheck.CheckState = CheckState.Unchecked;
propagateCheck.Enabled = false;
mailRadio.Enabled = false;
}
var tooltips = new ToolTip();
tooltips.SetToolTip(sendBtn, "Broadcast message on Channel 1\r\nand Channel2");
tooltips.SetToolTip(groupBox1, "Choose which channels\r\nthis instance will\r\nlisten on");
tooltips.SetToolTip(Mode, "Choose which mode\r\nto use for sending\r\nand receiving");
UpdateDisplayText(
"Launch multiple instances of this application to demo interprocess communication. Run multiple instances on different machines to demo network propogation.\r\n",
Color.Gray);
// set the handle id in the form title
Text += string.Format(" - {0}", uniqueInstanceName);
InitializeMode(XDTransportMode.HighPerformanceUI);
// broadcast on the status channel that we have loaded
var message = string.Format("{0} has joined", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
/// <summary>
/// Wire up the enter key to submit a message.
/// </summary>
/// <param name = "m"></param>
/// <param name = "k"></param>
/// <returns></returns>
protected override bool ProcessCmdKey(ref Message m, Keys k)
{
// allow enter to send message
if (m.Msg == 256 && k == Keys.Enter)
{
SendMessage();
return true;
}
return base.ProcessCmdKey(ref m, k);
}
/// <summary>
/// Initialize the broadcast and listener mode.
/// </summary>
/// <param name = "mode">The new mode.</param>
private void InitializeMode(XDTransportMode mode)
{
if (listener != null)
{
// ensure we dispose any previous listeners, dispose should aways be
// called on IDisposable objects when we are done with it to avoid leaks
listener.Dispose();
}
// creates an instance of the IXDListener object using the given implementation
listener = client.Listeners.GetListenerForMode(mode);
// attach the message handler
listener.MessageReceived += OnMessageReceived;
// register the channels we want to listen on
if (statusCheckBox.Checked)
{
listener.RegisterChannel("Status");
}
// register if checkbox is checked
if (channel1Check.Checked)
{
listener.RegisterChannel("BinaryChannel1");
}
// register if checkbox is checked
if (channel2Check.Checked)
{
listener.RegisterChannel("BinaryChannel2");
}
// if we already have a broadcast instance
if (broadcast != null)
{
// send in plain text
var message = string.Format("{0} is changing mode to {1}", uniqueInstanceName, mode);
broadcast.SendToChannel("Status", message);
}
// create an instance of IXDBroadcast using the given mode
broadcast = client.Broadcasters.GetBroadcasterForMode(mode, propagateCheck.Checked);
}
/// <summary>
/// The delegate which processes all cross AppDomain messages and writes them to screen.
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void OnMessageReceived(object sender, XDMessageEventArgs e)
{
// If called from a seperate thread, rejoin so that be can update form elements.
if (InvokeRequired && !IsDisposed)
{
try
{
// onClosing messages may fail if the form is being disposed.
Invoke((MethodInvoker) (() => OnMessageReceived(sender, e)));
}
catch (ObjectDisposedException)
{
}
catch (InvalidOperationException)
{
}
}
else
{
switch (e.DataGram.Channel.ToLower())
{
case "status":
// pain text
UpdateDisplayText(e.DataGram.Channel, e.DataGram.Message);
break;
default:
// all other channels contain serialized FormattedUserMessage object
if (e.DataGram.AssemblyQualifiedName == typeof(FormattedUserMessage).AssemblyQualifiedName)
{
TypedDataGram<FormattedUserMessage> typedDataGram = e.DataGram;
UpdateDisplayText(typedDataGram.Channel, typedDataGram.Message.FormattedTextMessage);
}
else
{
throw new NotSupportedException(string.Format("Unknown message type: {0}", e.DataGram.AssemblyQualifiedName));
}
break;
}
}
}
/// <summary>
/// Helper method for sending message.
/// </summary>
private void SendMessage()
{
if (inputTextBox.Text.Length > 0)
{
// send FormattedUserMessage object to all channels
var message = new FormattedUserMessage("{0} says {1}", uniqueInstanceName, inputTextBox.Text);
if (channel1Check.Checked)
{
broadcast.SendToChannel("BinaryChannel1", message);
}
if (channel2Check.Checked)
{
broadcast.SendToChannel("BinaryChannel2", message);
}
inputTextBox.Text = "";
}
}
private void SetMode()
{
if (wmRadio.Checked)
{
InitializeMode(XDTransportMode.HighPerformanceUI);
}
else if (ioStreamRadio.Checked)
{
InitializeMode(XDTransportMode.Compatibility);
}
else
{
InitializeMode(XDTransportMode.RemoteNetwork);
}
}
/// <summary>
/// A helper method used to update the Windows Form.
/// </summary>
/// <param name = "channelName">The channel to display</param>
/// <param name = "displayText">The message to display</param>
private void UpdateDisplayText(string channelName, string displayText)
{
if (string.IsNullOrEmpty(channelName) || string.IsNullOrEmpty(displayText))
{
return;
}
Color textColor;
switch (channelName.ToLower())
{
case "status":
textColor = Color.Green;
break;
default:
textColor = Color.Blue;
break;
}
var msg = string.Format("{0}: {1}\r\n", channelName, displayText);
UpdateDisplayText(msg, textColor);
}
/// <summary>
/// A helper method used to update the Windows Form.
/// </summary>
/// <param name = "message">The message to be displayed on the form.</param>
/// <param name = "textColor">The colour text to use for the message.</param>
private void UpdateDisplayText(string message, Color textColor)
{
if (!IsDisposed)
{
displayTextBox.AppendText(message);
displayTextBox.Select(displayTextBox.Text.Length - message.Length + 1, displayTextBox.Text.Length);
displayTextBox.SelectionColor = textColor;
displayTextBox.Select(displayTextBox.Text.Length, displayTextBox.Text.Length);
displayTextBox.ScrollToCaret();
}
}
/// <summary>
/// Adds or removes the Message channel from the messaging API. This effects whether messages
/// sent on this channel will be received by the application. Status messages are broadcast
/// on the Status channel whenever this setting is changed.
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void Channel1CheckedChanged(object sender, EventArgs e)
{
if (channel1Check.Checked)
{
listener.RegisterChannel("BinaryChannel1");
// send in pain text
var message = string.Format("{0} is registering Channel1.", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
else
{
listener.UnRegisterChannel("BinaryChannel1");
// send in pain text
var message = string.Format("{0} is unregistering Channel1.", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
}
/// <summary>
/// Adds or removes the Message channel from the messaging API. This effects whether messages
/// sent on this channel will be received by the application. Status messages are broadcast
/// on the Status channel whenever this setting is changed.
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void Channel2CheckedChanged(object sender, EventArgs e)
{
if (channel2Check.Checked)
{
listener.RegisterChannel("BinaryChannel2");
// send in pain text
var message = string.Format("{0} is registering Channel2.", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
else
{
listener.UnRegisterChannel("BinaryChannel2");
// send in pain text
var message = string.Format("{0} is unregistering Channel2.", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
}
/// <summary>
/// On form changed mode.
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void ModeCheckedChanged(object sender, EventArgs e)
{
if (((RadioButton) sender).Checked)
{
SetMode();
}
}
private void PropagateCheckCheckedChanged(object sender, EventArgs e)
{
if (propagateCheck.Checked)
{
UpdateDisplayText("Messages will be propagated across the network to all listeners.\r\n",
Color.Red);
}
else
{
UpdateDisplayText("Message are restricted to the current machine.\r\n", Color.Red);
}
SetMode();
}
/// <summary>
/// Sends a user input string on the Message channel. A message is not sent if
/// the string is empty.
/// </summary>
/// <param name = "sender">The event sender.</param>
/// <param name = "e">The event args.</param>
private void SendBtnClick(object sender, EventArgs e)
{
SendMessage();
}
/// <summary>
/// Adds or removes the Status channel from the messaging API. This effects whether messages
/// sent on this channel will be received by the application. Status messages are broadcast
/// on the Status channel whenever this setting is changed.
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void StatusChannelCheckedChanged(object sender, EventArgs e)
{
if (statusCheckBox.Checked)
{
listener.RegisterChannel("Status");
// send in plain text
var message = string.Format("{0} is registering Status.", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
else
{
listener.UnRegisterChannel("Status");
// send in plain text
var message = string.Format("{0} is unregistering Status.", uniqueInstanceName);
broadcast.SendToChannel("Status", message);
}
}
#endregion
}
}
| |
namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using Ioke.Lang.Util;
public class DefaultSyntax : IokeData, Named, Inspectable, AssociatedCode {
string name;
IokeObject context;
IokeObject code;
public DefaultSyntax(string name) {
this.name = name;
}
public DefaultSyntax(IokeObject context, IokeObject code) : this((string)null) {
this.context = context;
this.code = code;
}
public override void Init(IokeObject obj) {
obj.Kind = "DefaultSyntax";
obj.RegisterCell("activatable", obj.runtime.True);
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the name of the syntax",
new TypeCheckingNativeMethod.WithNoArguments("name", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(((DefaultSyntax)IokeObject.dataOf(on)).name);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("activates this syntax with the arguments given to call",
new NativeMethod("call", DefaultArgumentsDefinition.builder()
.WithRestUnevaluated("arguments")
.Arguments,
(method, _context, message, on, outer) => {
return IokeObject.As(on, _context).Activate(_context, message, _context.RealContext);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the result of activating this syntax without actually doing the replacement or execution part.",
new NativeMethod("expand", DefaultArgumentsDefinition.builder()
.WithRestUnevaluated("arguments")
.Arguments,
(method, _context, message, on, outer) => {
object onAsSyntax = _context.runtime.DefaultSyntax.ConvertToThis(on, message, _context);
return ((DefaultSyntax)IokeObject.dataOf(onAsSyntax)).Expand(IokeObject.As(onAsSyntax, context), context, message, context.RealContext, null);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the message chain for this syntax",
new TypeCheckingNativeMethod.WithNoArguments("message", obj,
(method, on, args, keywords, _context, message) => {
return ((AssociatedCode)IokeObject.dataOf(on)).Code;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the code for the argument definition",
new TypeCheckingNativeMethod.WithNoArguments("argumentsCode", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).ArgumentsCode);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("inspect", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(DefaultSyntax.GetInspect(on));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("notice", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(DefaultSyntax.GetNotice(on));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the full code of this syntax, as a Text",
new TypeCheckingNativeMethod.WithNoArguments("code", obj,
(method, on, args, keywords, _context, message) => {
IokeData data = IokeObject.dataOf(on);
if(data is DefaultSyntax) {
return _context.runtime.NewText(((DefaultSyntax)data).CodeString);
} else {
return _context.runtime.NewText(((AliasMethod)data).CodeString);
}
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns idiomatically formatted code for this syntax",
new TypeCheckingNativeMethod.WithNoArguments("formattedCode", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).FormattedCode(method));
})));
}
public string Name {
get { return this.name; }
set { this.name = value; }
}
public static string GetInspect(object on) {
return ((Inspectable)(IokeObject.dataOf(on))).Inspect(on);
}
public static string GetNotice(object on) {
return ((Inspectable)(IokeObject.dataOf(on))).Notice(on);
}
public string Inspect(object self) {
if(name == null) {
return "syntax(" + Message.Code(code) + ")";
} else {
return name + ":syntax(" + Message.Code(code) + ")";
}
}
public string Notice(object self) {
if(name == null) {
return "syntax(...)";
} else {
return name + ":syntax(...)";
}
}
public string ArgumentsCode {
get { return "..."; }
}
public IokeObject Code {
get { return code; }
}
public string CodeString {
get { return "syntax(" + Message.Code(code) + ")"; }
}
public string FormattedCode(object self) {
return "syntax(\n " + Message.FormattedCode(code, 2, (IokeObject)self) + ")";
}
private object Expand(IokeObject self, IokeObject context, IokeObject message, object on, IDictionary<string, object> data) {
if(code == null) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotActivatable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("method", self);
condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultSyntax kind by referring to it without wrapping it inside a call to cell?"));
context.runtime.ErrorCondition(condition);
return null;
}
IokeObject c = context.runtime.Locals.Mimic(message, context);
c.SetCell("self", on);
c.SetCell("@", on);
c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing syntax receiver", new NativeMethod.WithNoArguments("@@",
(method, _context, _message, _on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>());
return self;
})));
c.SetCell("currentMessage", message);
c.SetCell("surroundingContext", context);
c.SetCell("call", context.runtime.NewCallFrom(c, message, context, IokeObject.As(on, context)));
if(data != null) {
foreach(var d in data) {
string s = d.Key;
c.SetCell(s.Substring(0, s.Length-1), d.Value);
}
}
object result = null;
try {
result = ((Message)IokeObject.dataOf(code)).EvaluateCompleteWith(code, c, on);
} catch(ControlFlow.Return e) {
if(e.context == c) {
result = e.Value;
} else {
throw e;
}
}
return result;
}
private object ExpandWithCall(IokeObject self, IokeObject context, IokeObject message, object on, object call, IDictionary<string, object> data) {
if(code == null) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotActivatable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("method", self);
condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultSyntax kind by referring to it without wrapping it inside a call to cell?"));
context.runtime.ErrorCondition(condition);
return null;
}
IokeObject c = context.runtime.Locals.Mimic(message, context);
c.SetCell("self", on);
c.SetCell("@", on);
c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing syntax receiver", new NativeMethod.WithNoArguments("@@",
(method, _context, _message, _on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>());
return self;
})));
c.SetCell("currentMessage", message);
c.SetCell("surroundingContext", context);
c.SetCell("call", call);
if(data != null) {
foreach(var d in data) {
string s = d.Key;
c.SetCell(s.Substring(0, s.Length-1), d.Value);
}
}
object result = null;
try {
result = ((Message)IokeObject.dataOf(code)).EvaluateCompleteWith(code, c, on);
} catch(ControlFlow.Return e) {
if(e.context == c) {
result = e.Value;
} else {
throw e;
}
}
return result;
}
public override object ActivateWithCallAndData(IokeObject self, IokeObject context, IokeObject message, object on, object call, IDictionary<string, object> data) {
object result = ExpandWithCall(self, context, message, on, call, data);
if(result == context.runtime.nil) {
// Remove chain completely
IokeObject prev = Message.GetPrev(message);
IokeObject next = Message.GetNext(message);
if(prev != null) {
Message.SetNext(prev, next);
if(next != null) {
Message.SetPrev(next, prev);
}
} else {
message.Become(next, message, context);
Message.SetPrev(next, null);
}
return null;
} else {
// Insert resulting value into chain, wrapping it if it's not a message
IokeObject newObj = null;
if(IokeObject.dataOf(result) is Message) {
newObj = IokeObject.As(result, context);
} else {
newObj = context.runtime.CreateMessage(Message.Wrap(IokeObject.As(result, context)));
}
IokeObject prev = Message.GetPrev(message);
IokeObject next = Message.GetNext(message);
message.Become(newObj, message, context);
IokeObject last = newObj;
while(Message.GetNext(last) != null) {
last = Message.GetNext(last);
}
Message.SetNext(last, next);
if(next != null) {
Message.SetPrev(next, last);
}
Message.SetPrev(newObj, prev);
return ((Message)IokeObject.dataOf(message)).SendTo(message, context, context);
}
}
public override object ActivateWithCall(IokeObject self, IokeObject context, IokeObject message, object on, object call) {
return ActivateWithCallAndData(self, context, message, on, call, null);
}
public override object Activate(IokeObject self, IokeObject context, IokeObject message, object on) {
return ActivateWithData(self, context, message, on, null);
}
public override object ActivateWithData(IokeObject self, IokeObject context, IokeObject message, object on, IDictionary<string, object> data) {
object result = Expand(self, context, message, on, data);
if(result == context.runtime.nil) {
// Remove chain completely
IokeObject prev = Message.GetPrev(message);
IokeObject next = Message.GetNext(message);
if(prev != null) {
Message.SetNext(prev, next);
if(next != null) {
Message.SetPrev(next, prev);
}
} else {
message.Become(next, message, context);
Message.SetPrev(next, null);
}
return null;
} else {
// Insert resulting value into chain, wrapping it if it's not a message
IokeObject newObj = null;
if(IokeObject.dataOf(result) is Message) {
newObj = IokeObject.As(result, context);
} else {
newObj = context.runtime.CreateMessage(Message.Wrap(IokeObject.As(result, context)));
}
IokeObject prev = Message.GetPrev(message);
IokeObject next = Message.GetNext(message);
message.Become(newObj, message, context);
IokeObject last = newObj;
while(Message.GetNext(last) != null) {
last = Message.GetNext(last);
}
Message.SetNext(last, next);
if(next != null) {
Message.SetPrev(next, last);
}
Message.SetPrev(newObj, prev);
return ((Message)IokeObject.dataOf(message)).SendTo(message, context, context);
}
}
}
}
| |
namespace android.service.wallpaper
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.service.wallpaper.WallpaperService_))]
public abstract partial class WallpaperService : android.app.Service
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected WallpaperService(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class Engine : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Engine(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void onCreate(android.view.SurfaceHolder arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onCreate", "(Landroid/view/SurfaceHolder;)V", ref global::android.service.wallpaper.WallpaperService.Engine._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void onDestroy()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onDestroy", "()V", ref global::android.service.wallpaper.WallpaperService.Engine._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual bool isVisible()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "isVisible", "()Z", ref global::android.service.wallpaper.WallpaperService.Engine._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void onTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)V", ref global::android.service.wallpaper.WallpaperService.Engine._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void onVisibilityChanged(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onVisibilityChanged", "(Z)V", ref global::android.service.wallpaper.WallpaperService.Engine._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int DesiredMinimumWidth
{
get
{
return getDesiredMinimumWidth();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual int getDesiredMinimumWidth()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "getDesiredMinimumWidth", "()I", ref global::android.service.wallpaper.WallpaperService.Engine._m5);
}
public new int DesiredMinimumHeight
{
get
{
return getDesiredMinimumHeight();
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual int getDesiredMinimumHeight()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "getDesiredMinimumHeight", "()I", ref global::android.service.wallpaper.WallpaperService.Engine._m6);
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void onSurfaceCreated(android.view.SurfaceHolder arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onSurfaceCreated", "(Landroid/view/SurfaceHolder;)V", ref global::android.service.wallpaper.WallpaperService.Engine._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void onSurfaceChanged(android.view.SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onSurfaceChanged", "(Landroid/view/SurfaceHolder;III)V", ref global::android.service.wallpaper.WallpaperService.Engine._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
public new global::android.view.SurfaceHolder SurfaceHolder
{
get
{
return getSurfaceHolder();
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::android.view.SurfaceHolder getSurfaceHolder()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.SurfaceHolder>(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "getSurfaceHolder", "()Landroid/view/SurfaceHolder;", ref global::android.service.wallpaper.WallpaperService.Engine._m9) as android.view.SurfaceHolder;
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual bool isPreview()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "isPreview", "()Z", ref global::android.service.wallpaper.WallpaperService.Engine._m10);
}
public new bool TouchEventsEnabled
{
set
{
setTouchEventsEnabled(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void setTouchEventsEnabled(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "setTouchEventsEnabled", "(Z)V", ref global::android.service.wallpaper.WallpaperService.Engine._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void onOffsetsChanged(float arg0, float arg1, float arg2, float arg3, int arg4, int arg5)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onOffsetsChanged", "(FFFFII)V", ref global::android.service.wallpaper.WallpaperService.Engine._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual global::android.os.Bundle onCommand(java.lang.String arg0, int arg1, int arg2, int arg3, android.os.Bundle arg4, bool arg5)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onCommand", "(Ljava/lang/String;IIILandroid/os/Bundle;Z)Landroid/os/Bundle;", ref global::android.service.wallpaper.WallpaperService.Engine._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)) as android.os.Bundle;
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void onDesiredSizeChanged(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onDesiredSizeChanged", "(II)V", ref global::android.service.wallpaper.WallpaperService.Engine._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void onSurfaceDestroyed(android.view.SurfaceHolder arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.Engine.staticClass, "onSurfaceDestroyed", "(Landroid/view/SurfaceHolder;)V", ref global::android.service.wallpaper.WallpaperService.Engine._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public Engine(android.service.wallpaper.WallpaperService arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.service.wallpaper.WallpaperService.Engine._m16.native == global::System.IntPtr.Zero)
global::android.service.wallpaper.WallpaperService.Engine._m16 = @__env.GetMethodIDNoThrow(global::android.service.wallpaper.WallpaperService.Engine.staticClass, "<init>", "(Landroid/service/wallpaper/WallpaperService;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.service.wallpaper.WallpaperService.Engine.staticClass, global::android.service.wallpaper.WallpaperService.Engine._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static Engine()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.service.wallpaper.WallpaperService.Engine.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/service/wallpaper/WallpaperService$Engine"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public sealed override global::android.os.IBinder onBind(android.content.Intent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.IBinder>(this, global::android.service.wallpaper.WallpaperService.staticClass, "onBind", "(Landroid/content/Intent;)Landroid/os/IBinder;", ref global::android.service.wallpaper.WallpaperService._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.IBinder;
}
private static global::MonoJavaBridge.MethodId _m1;
public override void onCreate()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.staticClass, "onCreate", "()V", ref global::android.service.wallpaper.WallpaperService._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public override void onDestroy()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.service.wallpaper.WallpaperService.staticClass, "onDestroy", "()V", ref global::android.service.wallpaper.WallpaperService._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public abstract global::android.service.wallpaper.WallpaperService.Engine onCreateEngine();
private static global::MonoJavaBridge.MethodId _m4;
public WallpaperService() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.service.wallpaper.WallpaperService._m4.native == global::System.IntPtr.Zero)
global::android.service.wallpaper.WallpaperService._m4 = @__env.GetMethodIDNoThrow(global::android.service.wallpaper.WallpaperService.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.service.wallpaper.WallpaperService.staticClass, global::android.service.wallpaper.WallpaperService._m4);
Init(@__env, handle);
}
public static global::java.lang.String SERVICE_INTERFACE
{
get
{
return "android.service.wallpaper.WallpaperService";
}
}
public static global::java.lang.String SERVICE_META_DATA
{
get
{
return "android.service.wallpaper";
}
}
static WallpaperService()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.service.wallpaper.WallpaperService.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/service/wallpaper/WallpaperService"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.service.wallpaper.WallpaperService))]
internal sealed partial class WallpaperService_ : android.service.wallpaper.WallpaperService
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal WallpaperService_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::android.service.wallpaper.WallpaperService.Engine onCreateEngine()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.service.wallpaper.WallpaperService_.staticClass, "onCreateEngine", "()Landroid/service/wallpaper/WallpaperService$Engine;", ref global::android.service.wallpaper.WallpaperService_._m0) as android.service.wallpaper.WallpaperService.Engine;
}
static WallpaperService_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.service.wallpaper.WallpaperService_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/service/wallpaper/WallpaperService"));
}
}
}
| |
/*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using HttpServer;
using HttpServer.FormDecoders;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenSim.Framework.Servers.HttpServer;
namespace OpenSim.Framework.Servers.Tests
{
[TestFixture]
public class OSHttpTests
{
// we need an IHttpClientContext for our tests
public class TestHttpClientContext: IHttpClientContext
{
private bool _secured;
public bool Secured
{
get { return _secured; }
}
public TestHttpClientContext(bool secured)
{
_secured = secured;
}
public void Disconnect(SocketError error) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {}
public void Respond(string body) {}
public void Send(byte[] buffer) {}
public void Send(byte[] buffer, int offset, int size) {}
}
public class TestHttpRequest: IHttpRequest
{
public bool BodyIsComplete
{
get { return true; }
}
public string[] AcceptTypes
{
get {return _acceptTypes; }
}
private string[] _acceptTypes;
public Stream Body
{
get { return _body; }
set { _body = value;}
}
private Stream _body;
public ConnectionType Connection
{
get { return _connection; }
set { _connection = value; }
}
private ConnectionType _connection;
public int ContentLength
{
get { return _contentLength; }
set { _contentLength = value; }
}
private int _contentLength;
public NameValueCollection Headers
{
get { return _headers; }
}
private NameValueCollection _headers = new NameValueCollection();
public string HttpVersion
{
get { return _httpVersion; }
set { _httpVersion = value; }
}
private string _httpVersion = null;
public string Method
{
get { return _method; }
set { _method = value; }
}
private string _method = null;
public HttpInput QueryString
{
get { return _queryString; }
}
private HttpInput _queryString = null;
public Uri Uri
{
get { return _uri; }
set { _uri = value; }
}
private Uri _uri = null;
public string[] UriParts
{
get { return _uri.Segments; }
}
public HttpParam Param
{
get { return null; }
}
public HttpForm Form
{
get { return null; }
}
public bool IsAjax
{
get { return false; }
}
public RequestCookies Cookies
{
get { return null; }
}
public TestHttpRequest() {}
public TestHttpRequest(string contentEncoding, string contentType, string userAgent,
string remoteAddr, string remotePort, string[] acceptTypes,
ConnectionType connectionType, int contentLength, Uri uri)
{
_headers["content-encoding"] = contentEncoding;
_headers["content-type"] = contentType;
_headers["user-agent"] = userAgent;
_headers["remote_addr"] = remoteAddr;
_headers["remote_port"] = remotePort;
_acceptTypes = acceptTypes;
_connection = connectionType;
_contentLength = contentLength;
_uri = uri;
}
public void DecodeBody(FormDecoderProvider providers) {}
public void SetCookies(RequestCookies cookies) {}
public void AddHeader(string name, string value)
{
_headers.Add(name, value);
}
public int AddToBody(byte[] bytes, int offset, int length)
{
return 0;
}
public void Clear() {}
public object Clone()
{
TestHttpRequest clone = new TestHttpRequest();
clone._acceptTypes = _acceptTypes;
clone._connection = _connection;
clone._contentLength = _contentLength;
clone._uri = _uri;
clone._headers = new NameValueCollection(_headers);
return clone;
}
}
public class TestHttpResponse: IHttpResponse
{
public Stream Body
{
get { return _body; }
set { _body = value; }
}
private Stream _body;
public string ProtocolVersion
{
get { return _protocolVersion; }
set { _protocolVersion = value; }
}
private string _protocolVersion;
public bool Chunked
{
get { return _chunked; }
set { _chunked = value; }
}
private bool _chunked;
public ConnectionType Connection
{
get { return _connection; }
set { _connection = value; }
}
private ConnectionType _connection;
public Encoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
private Encoding _encoding;
public int KeepAlive
{
get { return _keepAlive; }
set { _keepAlive = value; }
}
private int _keepAlive;
public HttpStatusCode Status
{
get { return _status; }
set { _status = value; }
}
private HttpStatusCode _status;
public string Reason
{
get { return _reason; }
set { _reason = value; }
}
private string _reason;
public long ContentLength
{
get { return _contentLength; }
set { _contentLength = value; }
}
private long _contentLength;
public string ContentType
{
get { return _contentType; }
set { _contentType = value; }
}
private string _contentType;
public bool HeadersSent
{
get { return _headersSent; }
}
private bool _headersSent;
public bool Sent
{
get { return _sent; }
}
private bool _sent;
public ResponseCookies Cookies
{
get { return _cookies; }
}
private ResponseCookies _cookies = null;
public TestHttpResponse()
{
_headersSent = false;
_sent = false;
}
public void AddHeader(string name, string value) {}
public void Send()
{
if (!_headersSent) SendHeaders();
if (_sent) throw new InvalidOperationException("stuff already sent");
_sent = true;
}
public void SendBody(byte[] buffer, int offset, int count)
{
if (!_headersSent) SendHeaders();
_sent = true;
}
public void SendBody(byte[] buffer)
{
if (!_headersSent) SendHeaders();
_sent = true;
}
public void SendHeaders()
{
if (_headersSent) throw new InvalidOperationException("headers already sent");
_headersSent = true;
}
public void Redirect(Uri uri) {}
public void Redirect(string url) {}
}
public OSHttpRequest req0;
public OSHttpRequest req1;
public OSHttpResponse rsp0;
public IPEndPoint ipEP0;
[TestFixtureSetUp]
public void Init()
{
TestHttpRequest threq0 = new TestHttpRequest("utf-8", "text/xml", "OpenSim Test Agent", "192.168.0.1", "4711",
new string[] {"text/xml"},
ConnectionType.KeepAlive, 4711,
new Uri("http://127.0.0.1/admin/inventory/Dr+Who/Tardis"));
threq0.Method = "GET";
threq0.HttpVersion = HttpHelper.HTTP10;
TestHttpRequest threq1 = new TestHttpRequest("utf-8", "text/xml", "OpenSim Test Agent", "192.168.0.1", "4711",
new string[] {"text/xml"},
ConnectionType.KeepAlive, 4711,
new Uri("http://127.0.0.1/admin/inventory/Dr+Who/Tardis?a=0&b=1&c=2"));
threq1.Method = "POST";
threq1.HttpVersion = HttpHelper.HTTP11;
threq1.Headers["x-wuff"] = "wuffwuff";
threq1.Headers["www-authenticate"] = "go away";
req0 = new OSHttpRequest(new TestHttpClientContext(false), threq0);
req1 = new OSHttpRequest(new TestHttpClientContext(false), threq1);
rsp0 = new OSHttpResponse(new TestHttpResponse());
ipEP0 = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 4711);
}
[Test]
public void T000_OSHttpRequest()
{
Assert.That(req0.HttpMethod, Is.EqualTo("GET"));
Assert.That(req0.ContentType, Is.EqualTo("text/xml"));
Assert.That(req0.ContentLength, Is.EqualTo(4711));
Assert.That(req1.HttpMethod, Is.EqualTo("POST"));
}
[Test]
public void T001_OSHttpRequestHeaderAccess()
{
Assert.That(req1.Headers["x-wuff"], Is.EqualTo("wuffwuff"));
Assert.That(req1.Headers.Get("x-wuff"), Is.EqualTo("wuffwuff"));
Assert.That(req1.Headers["www-authenticate"], Is.EqualTo("go away"));
Assert.That(req1.Headers.Get("www-authenticate"), Is.EqualTo("go away"));
Assert.That(req0.RemoteIPEndPoint, Is.EqualTo(ipEP0));
}
[Test]
public void T002_OSHttpRequestUriParsing()
{
Assert.That(req0.RawUrl, Is.EqualTo("/admin/inventory/Dr+Who/Tardis"));
Assert.That(req1.Url.ToString(), Is.EqualTo("http://127.0.0.1/admin/inventory/Dr+Who/Tardis?a=0&b=1&c=2"));
}
[Test]
public void T100_OSHttpResponse()
{
rsp0.ContentType = "text/xml";
Assert.That(rsp0.ContentType, Is.EqualTo("text/xml"));
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// The purpose of DesignPropertyDescriptor is to allow us to customize the
/// display name of the property in the property grid. None of the CLR
/// implementations of PropertyDescriptor allow you to change the DisplayName.
/// </summary>
public class DesignPropertyDescriptor : PropertyDescriptor
{
private string displayName; // Custom display name
private PropertyDescriptor property; // Base property descriptor
private Hashtable editors = new Hashtable(); // Type -> editor instance
private TypeConverter converter;
/// <summary>
/// Delegates to base.
/// </summary>
public override string DisplayName
{
get
{
return this.displayName;
}
}
/// <summary>
/// Delegates to base.
/// </summary>
public override Type ComponentType
{
get
{
return this.property.ComponentType;
}
}
/// <summary>
/// Delegates to base.
/// </summary>
public override bool IsReadOnly
{
get
{
return this.property.IsReadOnly;
}
}
/// <summary>
/// Delegates to base.
/// </summary>
public override Type PropertyType
{
get
{
return this.property.PropertyType;
}
}
/// <summary>
/// Delegates to base.
/// </summary>
public override object GetEditor(Type editorBaseType)
{
object editor = this.editors[editorBaseType];
if(editor == null)
{
for(int i = 0; i < this.Attributes.Count; i++)
{
EditorAttribute attr = Attributes[i] as EditorAttribute;
if(attr == null)
{
continue;
}
Type editorType = Type.GetType(attr.EditorBaseTypeName);
if(editorBaseType == editorType)
{
Type type = GetTypeFromNameProperty(attr.EditorTypeName);
if(type != null)
{
editor = CreateInstance(type);
this.editors[type] = editor; // cache it
break;
}
}
}
}
return editor;
}
/// <summary>
/// Return type converter for property
/// </summary>
public override TypeConverter Converter
{
get
{
if(converter == null)
{
PropertyPageTypeConverterAttribute attr = (PropertyPageTypeConverterAttribute)Attributes[typeof(PropertyPageTypeConverterAttribute)];
if(attr != null && attr.ConverterType != null)
{
converter = (TypeConverter)CreateInstance(attr.ConverterType);
}
if(converter == null)
{
converter = TypeDescriptor.GetConverter(this.PropertyType);
}
}
return converter;
}
}
/// <summary>
/// Convert name to a Type object.
/// </summary>
public virtual Type GetTypeFromNameProperty(string typeName)
{
return Type.GetType(typeName);
}
/// <summary>
/// Delegates to base.
/// </summary>
public override bool CanResetValue(object component)
{
bool result = this.property.CanResetValue(component);
return result;
}
/// <summary>
/// Delegates to base.
/// </summary>
public override object GetValue(object component)
{
object value = this.property.GetValue(component);
return value;
}
/// <summary>
/// Delegates to base.
/// </summary>
public override void ResetValue(object component)
{
this.property.ResetValue(component);
}
/// <summary>
/// Delegates to base.
/// </summary>
public override void SetValue(object component, object value)
{
this.property.SetValue(component, value);
}
/// <summary>
/// Delegates to base.
/// </summary>
public override bool ShouldSerializeValue(object component)
{
bool result = this.property.ShouldSerializeValue(component);
return result;
}
/// <summary>
/// Constructor. Copy the base property descriptor and also hold a pointer
/// to it for calling its overridden abstract methods.
/// </summary>
public DesignPropertyDescriptor(PropertyDescriptor prop)
: base(prop)
{
if (prop == null)
{
throw new ArgumentNullException("prop");
}
this.property = prop;
DisplayNameAttribute attr = prop.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
if(attr != null)
{
this.displayName = attr.DisplayName;
}
else
{
this.displayName = prop.Name;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.Arm.Arm64
{
/// <summary>
/// This class provides access to the Arm64 AdvSIMD intrinsics
///
/// Arm64 CPU indicate support for this feature by setting
/// ID_AA64PFR0_EL1.AdvSIMD == 0 or better.
/// </summary>
[CLSCompliant(false)]
public static class Simd
{
/// <summary>
/// IsSupported property indicates whether any method provided
/// by this class is supported by the current runtime.
/// </summary>
public static bool IsSupported { [Intrinsic] get { return false; }}
/// <summary>
/// Vector abs
/// Corresponds to vector forms of ARM64 ABS & FABS
/// </summary>
public static Vector64<byte> Abs(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector64<ushort> Abs(Vector64<short> value) { throw new PlatformNotSupportedException(); }
public static Vector64<uint> Abs(Vector64<int> value) { throw new PlatformNotSupportedException(); }
public static Vector64<float> Abs(Vector64<float> value) { throw new PlatformNotSupportedException(); }
public static Vector128<byte> Abs(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<ushort> Abs(Vector128<short> value) { throw new PlatformNotSupportedException(); }
public static Vector128<uint> Abs(Vector128<int> value) { throw new PlatformNotSupportedException(); }
public static Vector128<ulong> Abs(Vector128<long> value) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Abs(Vector128<float> value) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Abs(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector add
/// Corresponds to vector forms of ARM64 ADD & FADD
/// </summary>
public static Vector64<T> Add<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> Add<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector and
/// Corresponds to vector forms of ARM64 AND
/// </summary>
public static Vector64<T> And<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> And<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector and not
/// Corresponds to vector forms of ARM64 BIC
/// </summary>
public static Vector64<T> AndNot<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> AndNot<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector BitwiseSelect
/// For each bit in the vector result[bit] = sel[bit] ? left[bit] : right[bit]
/// Corresponds to vector forms of ARM64 BSL (Also BIF & BIT)
/// </summary>
public static Vector64<T> BitwiseSelect<T>(Vector64<T> sel, Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> BitwiseSelect<T>(Vector128<T> sel, Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareEqual
/// For each element result[elem] = (left[elem] == right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMEQ & FCMEQ
/// </summary>
public static Vector64<T> CompareEqual<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareEqual<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareEqualZero
/// For each element result[elem] = (left[elem] == 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMEQ & FCMEQ
/// </summary>
public static Vector64<T> CompareEqualZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareEqualZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareGreaterThan
/// For each element result[elem] = (left[elem] > right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT/CMHI & FCMGT
/// </summary>
public static Vector64<T> CompareGreaterThan<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareGreaterThan<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareGreaterThanZero
/// For each element result[elem] = (left[elem] > 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT & FCMGT
/// </summary>
public static Vector64<T> CompareGreaterThanZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareGreaterThanZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareGreaterThanOrEqual
/// For each element result[elem] = (left[elem] >= right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGE/CMHS & FCMGE
/// </summary>
public static Vector64<T> CompareGreaterThanOrEqual<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareGreaterThanOrEqual<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareGreaterThanOrEqualZero
/// For each element result[elem] = (left[elem] >= 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGE & FCMGE
/// </summary>
public static Vector64<T> CompareGreaterThanOrEqualZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareGreaterThanOrEqualZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareLessThanZero
/// For each element result[elem] = (left[elem] < 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT & FCMGT
/// </summary>
public static Vector64<T> CompareLessThanZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareLessThanZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareLessThanOrEqualZero
/// For each element result[elem] = (left[elem] < 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT & FCMGT
/// </summary>
public static Vector64<T> CompareLessThanOrEqualZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareLessThanOrEqualZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector CompareTest
/// For each element result[elem] = (left[elem] & right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMTST
/// </summary>
public static Vector64<T> CompareTest<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> CompareTest<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// TBD Convert...
/// <summary>
/// Vector Divide
/// Corresponds to vector forms of ARM64 FDIV
/// </summary>
public static Vector64<float> Divide(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector extract item
///
/// result = vector[index]
///
/// Note: In order to be inlined, index must be a JIT time const expression which can be used to
/// populate the literal immediate field. Use of a non constant will result in generation of a switch table
///
/// Corresponds to vector forms of ARM64 MOV
/// </summary>
public static T Extract<T>(Vector64<T> vector, byte index) where T : struct { throw new PlatformNotSupportedException(); }
public static T Extract<T>(Vector128<T> vector, byte index) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector insert item
///
/// result = vector;
/// result[index] = data;
///
/// Note: In order to be inlined, index must be a JIT time const expression which can be used to
/// populate the literal immediate field. Use of a non constant will result in generation of a switch table
///
/// Corresponds to vector forms of ARM64 INS
/// </summary>
public static Vector64<T> Insert<T>(Vector64<T> vector, byte index, T data) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> Insert<T>(Vector128<T> vector, byte index, T data) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector LeadingSignCount
/// Corresponds to vector forms of ARM64 CLS
/// </summary>
public static Vector64<sbyte> LeadingSignCount(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector64<short> LeadingSignCount(Vector64<short> value) { throw new PlatformNotSupportedException(); }
public static Vector64<int> LeadingSignCount(Vector64<int> value) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> LeadingSignCount(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<short> LeadingSignCount(Vector128<short> value) { throw new PlatformNotSupportedException(); }
public static Vector128<int> LeadingSignCount(Vector128<int> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector LeadingZeroCount
/// Corresponds to vector forms of ARM64 CLZ
/// </summary>
public static Vector64<byte> LeadingZeroCount(Vector64<byte> value) { throw new PlatformNotSupportedException(); }
public static Vector64<sbyte> LeadingZeroCount(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector64<ushort> LeadingZeroCount(Vector64<ushort> value) { throw new PlatformNotSupportedException(); }
public static Vector64<short> LeadingZeroCount(Vector64<short> value) { throw new PlatformNotSupportedException(); }
public static Vector64<uint> LeadingZeroCount(Vector64<uint> value) { throw new PlatformNotSupportedException(); }
public static Vector64<int> LeadingZeroCount(Vector64<int> value) { throw new PlatformNotSupportedException(); }
public static Vector128<byte> LeadingZeroCount(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> LeadingZeroCount(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<ushort> LeadingZeroCount(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
public static Vector128<short> LeadingZeroCount(Vector128<short> value) { throw new PlatformNotSupportedException(); }
public static Vector128<uint> LeadingZeroCount(Vector128<uint> value) { throw new PlatformNotSupportedException(); }
public static Vector128<int> LeadingZeroCount(Vector128<int> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector max
/// Corresponds to vector forms of ARM64 SMAX, UMAX & FMAX
/// </summary>
public static Vector64<byte> Max(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); }
public static Vector64<sbyte> Max(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); }
public static Vector64<ushort> Max(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); }
public static Vector64<short> Max(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); }
public static Vector64<uint> Max(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); }
public static Vector64<int> Max(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); }
public static Vector64<float> Max(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector min
/// Corresponds to vector forms of ARM64 SMIN, UMIN & FMIN
/// </summary>
public static Vector64<byte> Min(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); }
public static Vector64<sbyte> Min(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); }
public static Vector64<ushort> Min(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); }
public static Vector64<short> Min(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); }
public static Vector64<uint> Min(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); }
public static Vector64<int> Min(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); }
public static Vector64<float> Min(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); }
/// TBD MOV, FMOV
/// <summary>
/// Vector multiply
///
/// For each element result[elem] = left[elem] * right[elem]
///
/// Corresponds to vector forms of ARM64 MUL & FMUL
/// </summary>
public static Vector64<byte> Multiply(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); }
public static Vector64<sbyte> Multiply(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); }
public static Vector64<ushort> Multiply(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); }
public static Vector64<short> Multiply(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); }
public static Vector64<uint> Multiply(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); }
public static Vector64<int> Multiply(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); }
public static Vector64<float> Multiply(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<byte> Multiply(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> Multiply(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static Vector128<ushort> Multiply(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static Vector128<short> Multiply(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static Vector128<uint> Multiply(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static Vector128<int> Multiply(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector negate
/// Corresponds to vector forms of ARM64 NEG & FNEG
/// </summary>
public static Vector64<sbyte> Negate(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector64<short> Negate(Vector64<short> value) { throw new PlatformNotSupportedException(); }
public static Vector64<int> Negate(Vector64<int> value) { throw new PlatformNotSupportedException(); }
public static Vector64<float> Negate(Vector64<float> value) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> Negate(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<short> Negate(Vector128<short> value) { throw new PlatformNotSupportedException(); }
public static Vector128<int> Negate(Vector128<int> value) { throw new PlatformNotSupportedException(); }
public static Vector128<long> Negate(Vector128<long> value) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Negate(Vector128<float> value) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Negate(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector not
/// Corresponds to vector forms of ARM64 NOT
/// </summary>
public static Vector64<T> Not<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> Not<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector or
/// Corresponds to vector forms of ARM64 ORR
/// </summary>
public static Vector64<T> Or<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> Or<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector or not
/// Corresponds to vector forms of ARM64 ORN
/// </summary>
public static Vector64<T> OrNot<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> OrNot<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector PopCount
/// Corresponds to vector forms of ARM64 CNT
/// </summary>
public static Vector64<byte> PopCount(Vector64<byte> value) { throw new PlatformNotSupportedException(); }
public static Vector64<sbyte> PopCount(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<byte> PopCount(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
public static Vector128<sbyte> PopCount(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// SetVector* Fill vector elements by replicating element value
///
/// Corresponds to vector forms of ARM64 DUP (general), DUP (element 0), FMOV (vector, immediate)
/// </summary>
public static Vector64<T> SetAllVector64<T>(T value) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> SetAllVector128<T>(T value) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector square root
/// Corresponds to vector forms of ARM64 FRSQRT
/// </summary>
public static Vector64<float> Sqrt(Vector64<float> value) { throw new PlatformNotSupportedException(); }
public static Vector128<float> Sqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); }
public static Vector128<double> Sqrt(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector subtract
/// Corresponds to vector forms of ARM64 SUB & FSUB
/// </summary>
public static Vector64<T> Subtract<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> Subtract<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// Vector exclusive or
/// Corresponds to vector forms of ARM64 EOR
/// </summary>
public static Vector64<T> Xor<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); }
public static Vector128<T> Xor<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); }
}
}
| |
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 React_Kendo_WebApp.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>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return 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 to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (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) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (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.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private 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 (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Applications;
using Sce.Sled.Resources;
using Sce.Sled.Shared.Document;
using Sce.Sled.Shared.Scmp;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled
{
/// <summary>
/// SledDebugFileService Class
/// </summary>
[Export(typeof(IInitializable))]
[Export(typeof(SledDebugFileService))]
[PartCreationPolicy(CreationPolicy.Shared)]
class SledDebugFileService : IInitializable
{
[ImportingConstructor]
public SledDebugFileService(MainForm mainForm)
{
m_mainForm = mainForm;
}
#region IInitializable Interface
void IInitializable.Initialize()
{
m_debugService =
SledServiceInstance.Get<ISledDebugService>();
m_debugService.DebugConnect += DebugServiceDebugConnect;
m_debugService.DebugDisconnect += DebugServiceDebugDisconnect;
m_debugService.DebugStart += DebugServiceDebugStart;
m_debugService.DebugCurrentStatement += DebugServiceDebugCurrentStatement;
m_debugService.DebugStepInto += DebugServiceDebugStepInto;
m_debugService.DebugStepOver += DebugServiceDebugStepOver;
m_debugService.DebugStepOut += DebugServiceDebugStepOut;
m_debugService.BreakpointHitting += DebugServiceBreakpointHitting;
m_debugService.BreakpointHit += DebugServiceBreakpointHit;
m_debugService.BreakpointContinue += DebugServiceBreakpointContinue;
m_debugService.Disconnected += DebugServiceDisconnected;
m_documentService =
SledServiceInstance.Get<ISledDocumentService>();
m_documentService.Opened += DocumentServiceOpened;
m_documentService.Saving += DocumentServiceSaving;
m_documentService.Saved += DocumentServiceSaved;
m_documentService.Closing += DocumentServiceClosing;
m_projectService =
SledServiceInstance.Get<ISledProjectService>();
m_projectService.FileAdded += ProjectServiceFileAdded;
m_projectService.FileRemoving += ProjectServiceFileRemoving;
}
#endregion
#region ISledDebugService Events
private void DebugServiceDebugConnect(object sender, SledDebugServiceEventArgs e)
{
SaveOpenDocuments();
MarkProjectDocsReadOnly(true);
}
private void DebugServiceDebugDisconnect(object sender, EventArgs e)
{
MarkProjectDocsReadOnly(false);
}
private void DebugServiceDebugStart(object sender, EventArgs e)
{
SaveOpenDocuments();
MarkProjectDocsReadOnly(true);
}
private void DebugServiceDebugCurrentStatement(object sender, EventArgs e)
{
if (m_curBreakpoint == null)
return;
var szAbsPath = SledUtil.GetAbsolutePath(m_curBreakpoint.File, m_projectService.AssetDirectory);
if (string.IsNullOrEmpty(szAbsPath))
return;
m_gotoService.Get.GotoLine(szAbsPath, m_curBreakpoint.Line, true);
}
private void DebugServiceDebugStepInto(object sender, EventArgs e)
{
SaveOpenDocuments();
MarkProjectDocsReadOnly(true);
}
private void DebugServiceDebugStepOver(object sender, EventArgs e)
{
SaveOpenDocuments();
MarkProjectDocsReadOnly(true);
}
private void DebugServiceDebugStepOut(object sender, EventArgs e)
{
SaveOpenDocuments();
MarkProjectDocsReadOnly(true);
}
private void DebugServiceBreakpointHitting(object sender, SledDebugServiceBreakpointEventArgs e)
{
m_curBreakpoint = e.Breakpoint.Clone() as SledNetworkBreakpoint;
if (m_curBreakpoint.IsUnknownFile())
return;
// Get absolute path to file
var szAbsPath = SledUtil.GetAbsolutePath(e.Breakpoint.File, m_projectService.AssetDirectory);
if (string.IsNullOrEmpty(szAbsPath) || !File.Exists(szAbsPath))
return;
// Check if file is in the project
var projFile = m_projectFileFinderService.Get.Find(szAbsPath);
// Try and add file to project
if (projFile == null)
m_projectService.AddFile(szAbsPath, out projFile);
}
private void DebugServiceBreakpointHit(object sender, SledDebugServiceBreakpointEventArgs e)
{
if (string.IsNullOrEmpty(e.Breakpoint.File))
{
// TODO: open a faux document saying something about unknown file?
return;
}
// Get absolute path to file
var szAbsPath = SledUtil.GetAbsolutePath(e.Breakpoint.File, m_projectService.AssetDirectory);
if (!string.IsNullOrEmpty(szAbsPath) && File.Exists(szAbsPath))
{
ISledDocument sd;
var uri = new Uri(szAbsPath);
// If already open jump to line otherwise open the file
if (m_documentService.IsOpen(uri, out sd))
{
m_gotoService.Get.GotoLine(sd, m_curBreakpoint.Line, true);
}
else
{
m_documentService.Open(uri, out sd);
}
}
MarkProjectDocsReadOnly(false);
}
private void DebugServiceBreakpointContinue(object sender, SledDebugServiceBreakpointEventArgs e)
{
m_curBreakpoint = e.Breakpoint.Clone() as SledNetworkBreakpoint;
RemoveCurrentStatementIndicators();
}
private void DebugServiceDisconnected(object sender, SledDebugServiceEventArgs e)
{
RemoveCurrentStatementIndicators();
MarkProjectDocsReadOnly(false);
}
#endregion
#region ISledDocumentService Events
private void DocumentServiceOpened(object sender, SledDocumentServiceEventArgs e)
{
// We do a couple of things here:
// 1) Draw current statement indicator if opened document matches breakpoint document
// 2) Draw lock icon on documents opened while not stopped on a breakpoint
var sd = e.Document;
if (sd == null)
return;
// Don't care about non-project documents as they're not being debugged
if (sd.SledProjectFile == null)
return;
// Don't care if disconnected
if (m_debugService.IsDisconnected)
return;
if (m_debugService.IsDebugging)
{
// Not stopped on a breakpoint
// Draw lock on document
((SledDocument)sd).IsReadOnly = true;
}
else
{
// Stopped on a breakpoint
// Haven't hit a breakpoint yet so no where to jump to
if (m_curBreakpoint == null)
return;
// Check if the opened document is the breakpoint document
// and if it is draw the current statement indicator and jump
// to the breakpoint line
if (string.Compare(sd.SledProjectFile.Path, m_curBreakpoint.File, true) == 0)
{
// Jump to line & draw current statement indicator
m_gotoService.Get.GotoLine(e.Document, m_curBreakpoint.Line, true);
}
}
}
private void DocumentServiceSaving(object sender, SledDocumentServiceEventArgs e)
{
m_sd = null;
// Not connected (so can't edit & continue)
if (!m_debugService.IsConnected)
return;
// File not in project
if (e.Document.SledProjectFile == null)
return;
// File has no changes so nothing to update
if (!e.Document.Dirty)
return;
// Store for edit & continue
m_sd = e.Document;
}
private void DocumentServiceSaved(object sender, SledDocumentServiceEventArgs e)
{
// No document to deal with
if (m_sd == null)
return;
// Out of whack somehow?
if (m_sd != e.Document)
return;
HandleEditAndContinue(m_sd);
// Reset
m_sd = null;
}
private void DocumentServiceClosing(object sender, SledDocumentServiceEventArgs e)
{
// Remove any current statement indicators
RemoveCurrentStatementIndicators(e.Document);
}
#endregion
#region ISledProjectService Events
private void ProjectServiceFileRemoving(object sender, SledProjectServiceFileEventArgs e)
{
if (!m_debugService.IsDebugging)
return;
var sd = e.File.SledDocument;
if (sd == null)
return;
((SledDocument)sd).IsReadOnly = false;
}
private void ProjectServiceFileAdded(object sender, SledProjectServiceFileEventArgs e)
{
if (!m_debugService.IsDebugging)
return;
var sd = e.File.SledDocument;
if (sd == null)
return;
((SledDocument)sd).IsReadOnly = true;
}
#endregion
#region Member Methods
private void SaveOpenDocuments()
{
// Find any opened docs that are in the
// project and also dirty
var openedDirtyProjectDocs =
from sd in m_documentService.OpenDocuments
where sd.SledProjectFile != null && sd.Dirty
select sd;
foreach (var sd in openedDirtyProjectDocs)
m_documentService.Save(sd);
}
private void MarkProjectDocsReadOnly(bool bReadOnly)
{
// Go through project documents telling them they need to
// adjust their read only property and indicator(s)
var openedProjectDocs =
from sd in m_documentService.OpenDocuments
where sd.SledProjectFile != null
select sd;
// Notify of read only state
foreach (var sd in openedProjectDocs)
((SledDocument)sd).IsReadOnly = bReadOnly;
}
private void RemoveCurrentStatementIndicators()
{
// Remove all current statement indicators from open documents
foreach (var sd in m_documentService.OpenDocuments)
{
RemoveCurrentStatementIndicators(sd);
}
}
private static void RemoveCurrentStatementIndicators(ISledDocument sd)
{
if (sd == null)
return;
foreach (var line in sd.Editor.CurrentStatements)
{
sd.Editor.CurrentStatement(line, false);
}
}
private void HandleEditAndContinue(ISledDocument sd)
{
var res =
MessageBox.Show(
m_mainForm,
Localization.SledEditAndContinueReloadFileQuestion,
Localization.SledEditAndContinueTitle,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
// Tell target to reload the file
m_debugService.SendScmp(
new EditAndContinue(
sd.SledProjectFile.LanguagePlugin.LanguageId,
sd.SledProjectFile.Path.Replace(
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar)));
}
else
{
// Show message to user
MessageBox.Show(
m_mainForm,
Localization.SledEditAndContinueFileNotSentError,
Localization.SledEditAndContinueTitle,
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
#endregion
private ISledDocument m_sd;
private SledNetworkBreakpoint m_curBreakpoint;
private readonly MainForm m_mainForm;
private ISledDebugService m_debugService;
private ISledDocumentService m_documentService;
private ISledProjectService m_projectService;
private readonly SledServiceReference<ISledGotoService> m_gotoService =
new SledServiceReference<ISledGotoService>();
private readonly SledServiceReference<ISledProjectFileFinderService> m_projectFileFinderService =
new SledServiceReference<ISledProjectFileFinderService>();
}
}
| |
using System;
using System.Collections.Generic;
using System.Security.Claims;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Schokotaler.Api.Controllers;
using Schokotaler.Api.Models;
using Schokotaler.Api.Models.Controllers.Users;
using Schokotaler.Api.Producers;
using Schokotaler.Api.Repository;
using Schokotaler.Api.Tests.Common;
using Xunit;
using Microsoft.Extensions.Logging;
namespace Schokotaler.Api.Tests {
public class UsersControllerTest : IDisposable
{
private Mock<IUserRepository> mockUserRepo;
private UserProducer userProducer;
private Schokotaler.Api.Common.Utility utility;
private ILogger<UsersController> logger;
public UsersControllerTest() {
utility = new Schokotaler.Api.Common.Utility();
userProducer = new UserProducer(utility);
mockUserRepo = new Mock<IUserRepository>();
logger = new Mock<ILogger<UsersController>>().Object;
}
[Fact]
public void CreateBadRequest() {
//Given
UserCreate user1 = null;
UserCreate user2 = new UserCreate();
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
//When
var res1 = con.Create(user1);
var res2 = con.Create(user2);
//Then
res1.Should().NotBeNull();
var resBr1 = res1.Should().BeOfType<BadRequestObjectResult>().Subject;
resBr1.StatusCode.Should().Be(400);
int errno = TestUtility.GetProperty<int>("Errno", resBr1.Value);
errno.Should().Be(2);
res2.Should().NotBeNull();
var resBr2 = res2.Should().BeOfType<BadRequestObjectResult>().Subject;
resBr2.StatusCode.Should().Be(400);
errno = TestUtility.GetProperty<int>("Errno", resBr2.Value);
errno.Should().Be(2);
}
[Fact]
public void CreatePass() {
//Given
var model = new UserCreate{
Name = "name",
Email = "email",
Password = "password"
};
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
//When
var res = con.Create(model);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<CreatedResult>();
}
[Fact]
public void GetUnauthorized() {
//Given
ClaimsPrincipal user = new ClaimsPrincipal();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(1, user)).Returns(false);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", false);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext{
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
//When
var res = con.GetById(1);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<UnauthorizedResult>();
}
[Fact]
public void GetNotFound() {
//Given
User model = null;
ClaimsPrincipal user = new ClaimsPrincipal();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(2, user)).Returns(true);
mockUserRepo.Setup(r => r.Get(2)).Returns(model);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
//When
var res = con.GetById(2);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<NotFoundResult>();
}
[Fact]
public void GetPass() {
//Given
User model = new User{
Name = "testname",
Email = "testEmail",
Password = "testPw",
Active = true
};
ClaimsPrincipal user = new ClaimsPrincipal();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(3, user)).Returns(true);
mockUserRepo.Setup(r => r.Get(3)).Returns(model);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
//When
var res = con.GetById(3);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<JsonResult>();
}
[Fact]
public void UpdateUnauthorized() {
//Given
ClaimsPrincipal user = new ClaimsPrincipal();
UserUpdate model = new UserUpdate();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(1, user)).Returns(false);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
//When
var res = con.UpdateById(1, model);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<UnauthorizedResult>();
}
[Fact]
public void UpdateNotFound() {
//Given
ClaimsPrincipal user = new ClaimsPrincipal();
UserUpdate model = new UserUpdate {
Name = "testName",
Email = "testEmail",
Password = "testPw",
Active = true
};
User modelUser = null;
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(2, user)).Returns(true);
mockUserRepo.Setup(r => r.Get(2)).Returns(modelUser);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
//When
var res = con.UpdateById(2, model);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<NotFoundResult>();
}
[Fact]
public void UpdatePass() {
//Given
ClaimsPrincipal user = new ClaimsPrincipal();
UserUpdate model = new UserUpdate {
Name = "testName",
Email = "testEmail",
Password = "testPw",
Active = true
};
User modelUser = new User();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(3, user)).Returns(true);
mockUserRepo.Setup(r => r.Get(3)).Returns(modelUser);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
//When
var res = con.UpdateById(3, model);
//Then
res.Should().NotBeNull();
res.Should().BeOfType<OkResult>();
}
[Fact]
public void UpdateBadRequest() {
// Given
ClaimsPrincipal user = new ClaimsPrincipal();
UserUpdate model = new UserUpdate {
Name = "testName",
Password = "testPw",
Active = true
};
User modelUser = new User();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(4, user)).Returns(true);
mockUserRepo.Setup(r => r.Get(4)).Returns(modelUser);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
// When
var res = con.UpdateById(4, model);
// Then
res.Should().NotBeNull();
res.Should().BeOfType<BadRequestResult>();
}
[Fact]
public void UpdateEmptyPassword() {
// Given
ClaimsPrincipal user = new ClaimsPrincipal();
UserUpdate model = new UserUpdate {
Name = "testName",
Email = "testEmail",
Active = true
};
User modelUser = new User();
mockUserRepo.Setup(r => r.UserIsNotAdminAndCurrentUser(5, user)).Returns(true);
mockUserRepo.Setup(r => r.Get(5)).Returns(modelUser);
IDictionary<object, object> items = new Dictionary<object, object>();
items.Add("Active", true);
items.Add("UID", 1);
var con = new UsersController(mockUserRepo.Object, userProducer, utility, logger);
con.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext {
User = user,
Items = items
}
};
// When
var res = con.UpdateById(5, model);
// Then
res.Should().NotBeNull();
res.Should().BeOfType<OkResult>();
}
public void Dispose()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using pinch;
using pinch.Http.Request;
using pinch.Http.Response;
using pinch.Http.Client;
using pinch.Models;
namespace pinch.Controllers
{
public partial class TicketController: BaseController
{
#region Singleton Pattern
//private static variables for the singleton pattern
private static object syncObject = new object();
private static TicketController instance = null;
/// <summary>
/// Singleton pattern implementation
/// </summary>
internal static TicketController Instance
{
get
{
lock (syncObject)
{
if (null == instance)
{
instance = new TicketController();
}
}
return instance;
}
}
#endregion Singleton Pattern
/// <summary>
/// List all the opened tickets of every clients you are working for
/// </summary>
/// <return>Returns the List<Ticket> response from the API call</return>
public List<Ticket> List()
{
Task<List<Ticket>> t = ListAsync();
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// List all the opened tickets of every clients you are working for
/// </summary>
/// <return>Returns the List<Ticket> response from the API call</return>
public async Task<List<Ticket>> ListAsync()
{
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets");
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Get(_queryUrl,_headers);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<List<Ticket>>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// This method returns no result but the status code tells you if the operation succedded
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket AcceptIntervention(string ticketId)
{
Task<Ticket> t = AcceptInterventionAsync(ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// This method returns no result but the status code tells you if the operation succedded
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> AcceptInterventionAsync(string ticketId)
{
//validating required parameters
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/accept");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, null);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="interventionDate">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket SetInterventionDate(DateTime interventionDate, string ticketId)
{
Task<Ticket> t = SetInterventionDateAsync(interventionDate, ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="interventionDate">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> SetInterventionDateAsync(DateTime interventionDate, string ticketId)
{
//validating required parameters
if (null == interventionDate)
throw new ArgumentNullException("interventionDate", "The parameter \"interventionDate\" is a required parameter and cannot be null.");
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/set_intervention_date");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "intervention_date", interventionDate }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket UploadQuote(FileStreamInfo file, string ticketId)
{
Task<Ticket> t = UploadQuoteAsync(file, ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> UploadQuoteAsync(FileStreamInfo file, string ticketId)
{
//validating required parameters
if (null == file)
throw new ArgumentNullException("file", "The parameter \"file\" is a required parameter and cannot be null.");
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/quote_upload");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "file", file }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="body">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket SendMessage(string body, string ticketId)
{
Task<Ticket> t = SendMessageAsync(body, ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="body">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> SendMessageAsync(string body, string ticketId)
{
//validating required parameters
if (null == body)
throw new ArgumentNullException("body", "The parameter \"body\" is a required parameter and cannot be null.");
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/message");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "body", body }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <param name="interventionDate">Optional parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket DeclareInterventionDone(string ticketId, DateTime? interventionDate = null)
{
Task<Ticket> t = DeclareInterventionDoneAsync(ticketId, interventionDate);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <param name="interventionDate">Optional parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> DeclareInterventionDoneAsync(string ticketId, DateTime? interventionDate = null)
{
//validating required parameters
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/intervention_done");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "intervention_date", interventionDate }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// The document should not be an invoice nor a quote
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket UploadDocument(FileStreamInfo file, string ticketId)
{
Task<Ticket> t = UploadDocumentAsync(file, ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// The document should not be an invoice nor a quote
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> UploadDocumentAsync(FileStreamInfo file, string ticketId)
{
//validating required parameters
if (null == file)
throw new ArgumentNullException("file", "The parameter \"file\" is a required parameter and cannot be null.");
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/document_upload");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "file", file }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket UploadPicture(FileStreamInfo file, string ticketId)
{
Task<Ticket> t = UploadPictureAsync(file, ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> UploadPictureAsync(FileStreamInfo file, string ticketId)
{
//validating required parameters
if (null == file)
throw new ArgumentNullException("file", "The parameter \"file\" is a required parameter and cannot be null.");
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/picture_upload");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "file", file }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public Ticket Get(string ticketId)
{
Task<Ticket> t = GetAsync(ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the Ticket response from the API call</return>
public async Task<Ticket> GetAsync(string ticketId)
{
//validating required parameters
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Get(_queryUrl,_headers);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Ticket>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the string response from the API call</return>
public string UploadInvoice(FileStreamInfo file, string ticketId)
{
Task<string> t = UploadInvoiceAsync(file, ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="file">Required parameter: Example: </param>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the string response from the API call</return>
public async Task<string> UploadInvoiceAsync(FileStreamInfo file, string ticketId)
{
//validating required parameters
if (null == file)
throw new ArgumentNullException("file", "The parameter \"file\" is a required parameter and cannot be null.");
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/invoice_upload");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//append form/field parameters
var _fields = new Dictionary<string,object>()
{
{ "file", file }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return _response.Body;
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// Get the documents of a ticket related to the intervention (No invoice, no quote)
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the List<Document> response from the API call</return>
public List<Document> Documents(string ticketId)
{
Task<List<Document>> t = DocumentsAsync(ticketId);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// Get the documents of a ticket related to the intervention (No invoice, no quote)
/// </summary>
/// <param name="ticketId">Required parameter: Example: </param>
/// <return>Returns the List<Document> response from the API call</return>
public async Task<List<Document>> DocumentsAsync(string ticketId)
{
//validating required parameters
if (null == ticketId)
throw new ArgumentNullException("ticketId", "The parameter \"ticketId\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{ticket_id}/documents");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "ticket_id", ticketId }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Get(_queryUrl,_headers);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<List<Document>>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="id">Required parameter: Example: </param>
/// <return>Returns the List<Message> response from the API call</return>
public List<Message> Messages(string id)
{
Task<List<Message>> t = MessagesAsync(id);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// TODO: type endpoint description here
/// </summary>
/// <param name="id">Required parameter: Example: </param>
/// <return>Returns the List<Message> response from the API call</return>
public async Task<List<Message>> MessagesAsync(string id)
{
//validating required parameters
if (null == id)
throw new ArgumentNullException("id", "The parameter \"id\" is a required parameter and cannot be null.");
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/tickets/{id}/messages");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "id", id }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
_headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
_headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Get(_queryUrl,_headers);
//Custom Authentication to be added for authorization
AuthUtility.AppendCustomAuthParams(_request);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//return null on 404
if (_response.StatusCode == 404)
return null;
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<List<Message>>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: SpellerHighlightLayer.cs
//
// Description: Highlight rendering for the Speller.
//
//---------------------------------------------------------------------------
using System;
using MS.Internal;
using System.Windows.Documents;
using System.Windows.Media;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace System.Windows.Documents
{
// Highlight rendering for the Speller.
// The speller tags errors with red squigglies.
internal class SpellerHighlightLayer : HighlightLayer
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Static constructor.
static SpellerHighlightLayer()
{
_errorTextDecorations = GetErrorTextDecorations();
}
// Constructor.
internal SpellerHighlightLayer(Speller speller)
{
_speller = speller;
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Returns a TextDecorationCollection used to tag spelling errors,
// or DependencyProperty.UnsetValue if there's no error at the specified position.
internal override object GetHighlightValue(StaticTextPointer textPosition, LogicalDirection direction)
{
object value;
if (IsContentHighlighted(textPosition, direction))
{
value = _errorTextDecorations;
}
else
{
value = DependencyProperty.UnsetValue;
}
return value;
}
// Returns true iff the indicated content has scoping highlights.
internal override bool IsContentHighlighted(StaticTextPointer textPosition, LogicalDirection direction)
{
return _speller.StatusTable.IsRunType(textPosition, direction, SpellerStatusTable.RunType.Error);
}
// Returns the position of the next highlight start or end in an
// indicated direction, or null if there is no such position.
internal override StaticTextPointer GetNextChangePosition(StaticTextPointer textPosition, LogicalDirection direction)
{
return _speller.StatusTable.GetNextErrorTransition(textPosition, direction);
}
// Raises a Changed event for any listeners, covering the
// specified text.
internal void FireChangedEvent(ITextPointer start, ITextPointer end)
{
if (Changed != null)
{
Changed(this, new SpellerHighlightChangedEventArgs(start, end));
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// Type identifying this layer for Highlights.GetHighlightValue calls.
internal override Type OwnerType
{
get
{
return typeof(SpellerHighlightLayer);
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
#region Internal Events
/// <summary>
/// Event raised when a highlight range is inserted, removed, moved, or
/// has a local property value change.
/// </summary>
internal override event HighlightChangedEventHandler Changed;
#endregion Internal Events
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// Calculates TextDecorations for speller errors.
private static TextDecorationCollection GetErrorTextDecorations()
{
//
// Build a "squiggle" Brush.
//
// This works by hard-coding a 3 pixel high TextDecoration, and
// then tiling horizontally. (We can't scale the squiggle in
// the vertical direction, there's no support to limit tiling
// to just the horizontal from the MIL.)
//
DrawingGroup drawingGroup = new DrawingGroup();
DrawingContext drawingContext = drawingGroup.Open();
Pen pen = new Pen(Brushes.Red, 0.33);
// This is our tile:
//
// x x
// x x
// x
//
drawingContext.DrawLine(pen, new Point(0.0, 0.0), new Point(0.5, 1.0));
drawingContext.DrawLine(pen, new Point(0.5, 1.0), new Point(1.0, 0.0));
drawingContext.Close();
DrawingBrush brush = new DrawingBrush(drawingGroup);
brush.TileMode = TileMode.Tile;
brush.Viewport = new Rect(0, 0, 3, 3);
brush.ViewportUnits = BrushMappingMode.Absolute;
TextDecoration textDecoration = new TextDecoration(
TextDecorationLocation.Underline,
new Pen(brush, 3),
0,
TextDecorationUnit.FontRecommended,
TextDecorationUnit.Pixel);
TextDecorationCollection decorationCollection = new TextDecorationCollection();
decorationCollection.Add(textDecoration);
decorationCollection.Freeze();
return decorationCollection;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// Argument for the Changed event, encapsulates a highlight change.
private class SpellerHighlightChangedEventArgs : HighlightChangedEventArgs
{
// Constructor.
internal SpellerHighlightChangedEventArgs(ITextPointer start, ITextPointer end)
{
List<TextSegment> list;
Invariant.Assert(start.CompareTo(end) < 0, "Bogus start/end combination!");
list = new List<TextSegment>(1);
list.Add(new TextSegment(start, end));
_ranges = new ReadOnlyCollection<TextSegment>(list);
}
// Collection of changed content ranges.
internal override IList Ranges
{
get
{
return _ranges;
}
}
// Type identifying the owner of the changed layer.
internal override Type OwnerType
{
get
{
return typeof(SpellerHighlightLayer);
}
}
// Collection of changed content ranges.
private readonly ReadOnlyCollection<TextSegment> _ranges;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Assocated Speller.
private readonly Speller _speller;
// Decorations for text flagged with a spelling error.
private static readonly TextDecorationCollection _errorTextDecorations;
#endregion Private Fields
}
}
| |
// 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 ShiftRightLogicalUInt641()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalUInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalUInt641
{
private struct TestStruct
{
public Vector256<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalUInt641 testClass)
{
var result = Avx2.ShiftRightLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector256<UInt64> _clsVar;
private Vector256<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalUInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public ImmUnaryOpTest__ShiftRightLogicalUInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightLogical(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightLogical(
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightLogical(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalUInt641();
var result = Avx2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ulong)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt64>(Vector256<UInt64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.AutomatonymousIntegration.Tests
{
using System;
using System.Threading.Tasks;
using Automatonymous;
using GreenPipes;
using GreenPipes.Introspection;
using NUnit.Framework;
using Saga;
using TestFramework;
using Testing;
[TestFixture]
public class When_a_remove_expression_is_specified :
InMemoryTestFixture
{
[Test]
public async Task Should_handle_the_initial_state()
{
Guid sagaId = Guid.NewGuid();
await Bus.Publish(new Start
{
CorrelationId = sagaId
});
Guid? saga =
await _repository.ShouldContainSaga(x => x.CorrelationId == sagaId && x.CurrentState == _machine.Running, TestTimeout);
Assert.IsTrue(saga.HasValue);
}
[Test, Explicit]
public void Should_return_a_wonderful_breakdown_of_the_guts_inside_it()
{
ProbeResult result = Bus.GetProbeResult();
Console.WriteLine(result.ToJsonString());
}
[Test]
public async Task Should_remove_the_saga_once_completed()
{
Guid sagaId = Guid.NewGuid();
await Bus.Publish(new Start
{
CorrelationId = sagaId
});
Guid? saga = await _repository.ShouldContainSaga(sagaId, TestTimeout);
Assert.IsTrue(saga.HasValue);
await Bus.Publish(new Stop
{
CorrelationId = sagaId
});
saga = await _repository.ShouldNotContainSaga(sagaId, TestTimeout);
Assert.IsFalse(saga.HasValue);
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.StateMachineSaga(_machine, _repository);
}
readonly TestStateMachine _machine;
readonly InMemorySagaRepository<Instance> _repository;
public When_a_remove_expression_is_specified()
{
_machine = new TestStateMachine();
_repository = new InMemorySagaRepository<Instance>();
}
class Instance :
SagaStateMachineInstance
{
public Instance(Guid correlationId)
{
CorrelationId = correlationId;
}
protected Instance()
{
}
public State CurrentState { get; set; }
public Guid CorrelationId { get; set; }
}
class TestStateMachine :
MassTransitStateMachine<Instance>
{
public TestStateMachine()
{
Initially(
When(Started)
.TransitionTo(Running));
During(Running,
When(Stopped)
.Finalize());
SetCompletedWhenFinalized();
}
public State Running { get; private set; }
public Event<Start> Started { get; private set; }
public Event<Stop> Stopped { get; private set; }
}
class Start :
CorrelatedBy<Guid>
{
public Guid CorrelationId { get; set; }
}
class Stop :
CorrelatedBy<Guid>
{
public Guid CorrelationId { get; set; }
}
}
[TestFixture]
public class When_a_saga_goes_straight_to_finalized :
InMemoryTestFixture
{
[Test]
public async Task Should_remove_the_saga_once_completed()
{
Guid sagaId = Guid.NewGuid();
var response = await Bus.Request<Ask, Answer>(InputQueueAddress, new Ask {CorrelationId = sagaId}, TestCancellationToken);
await Task.Delay(50);
Guid? saga = await _repository.ShouldNotContainSaga(sagaId, TestTimeout);
Assert.IsFalse(saga.HasValue);
Assert.AreEqual(sagaId, response.CorrelationId);
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
configurator.StateMachineSaga(_machine, _repository);
}
readonly TestStateMachine _machine;
readonly InMemorySagaRepository<Instance> _repository;
public When_a_saga_goes_straight_to_finalized()
{
_machine = new TestStateMachine();
_repository = new InMemorySagaRepository<Instance>();
}
class Instance :
SagaStateMachineInstance
{
public Instance(Guid correlationId)
{
CorrelationId = correlationId;
}
protected Instance()
{
}
public State CurrentState { get; set; }
public Guid CorrelationId { get; set; }
}
class TestStateMachine :
MassTransitStateMachine<Instance>
{
public TestStateMachine()
{
Event(() => Asked, x => x.CorrelateById(context => context.Message.CorrelationId));
Initially(
When(Asked)
.Respond(context => new Answer {CorrelationId = context.Data.CorrelationId})
.Finalize());
SetCompletedWhenFinalized();
}
public Event<Ask> Asked { get; private set; }
}
class Ask
{
public Guid CorrelationId { get; set; }
}
class Answer
{
public Guid CorrelationId { get; set; }
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ZeroMQ;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace Apache.NMS.ZMQ
{
/// <summary>
/// Represents a NMS connection ZMQ.
/// </summary>
///
public class Connection : IConnection
{
private class ProducerRef
{
public ZmqSocket producer = null;
public int refCount = 1;
}
private AcknowledgementMode acknowledgementMode = AcknowledgementMode.AutoAcknowledge;
private IRedeliveryPolicy redeliveryPolicy;
private ConnectionMetaData metaData = null;
private bool closed = true;
private string clientId;
private Uri brokerUri;
private string producerContextBinding;
private string consumerContextBinding;
/// <summary>
/// ZMQ context
/// </summary>
private static object contextLock = new object();
private static int instanceCount = 0;
private static ZmqContext _context;
private static Dictionary<string, ProducerRef> producerCache = new Dictionary<string, ProducerRef>();
private static object producerCacheLock = new object();
private TimeSpan zeroTimeout = new TimeSpan(0);
private bool disposed = false;
private static void InitContext()
{
lock(contextLock)
{
if(0 == instanceCount++)
{
Connection._context = ZmqContext.Create();
}
}
}
private static void DestroyContext()
{
lock(contextLock)
{
if(0 == --instanceCount)
{
Connection._context.Dispose();
}
}
}
public Connection(Uri connectionUri)
{
InitContext();
this.brokerUri = connectionUri;
switch (this.brokerUri.Scheme.ToLower())
{
case "tcp":
this.producerContextBinding = string.Format("{0}://*:{1}", this.brokerUri.Scheme, this.brokerUri.Port);
this.consumerContextBinding = string.Format("{0}://{1}:{2}", brokerUri.Scheme, brokerUri.Host, this.brokerUri.Port);
break;
case "inproc":
this.producerContextBinding = string.Format("{0}://{1}", this.brokerUri.Scheme, this.brokerUri.Host);
this.consumerContextBinding = this.producerContextBinding;
break;
case "ipc":
this.producerContextBinding = string.Format("{0}:///{1}", this.brokerUri.Scheme, this.brokerUri.AbsolutePath);
this.consumerContextBinding = this.producerContextBinding;
break;
case "pgm":
case "epgm":
throw new NotImplementedException(string.Format("Scheme '{0}' is not supported.", this.brokerUri.Scheme));
default:
throw new NotSupportedException(string.Format("Scheme '{0}' is not supported.", this.brokerUri.Scheme));
}
}
~Connection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(disposed)
{
return;
}
if(disposing)
{
try
{
OnDispose();
}
catch(Exception ex)
{
Tracer.ErrorFormat("Exception disposing Connection {0}: {1}", this.brokerUri.AbsoluteUri, ex.Message);
}
}
disposed = true;
}
/// <summary>
/// Child classes can override this method to perform clean-up logic.
/// </summary>
protected virtual void OnDispose()
{
Close();
DestroyContext();
}
/// <summary>
/// Starts message delivery for this connection.
/// </summary>
public void Start()
{
closed = false;
}
/// <summary>
/// This property determines if the asynchronous message delivery of incoming
/// messages has been started for this connection.
/// </summary>
public bool IsStarted
{
get { return !closed; }
}
/// <summary>
/// Stop message delivery for this connection.
/// </summary>
public void Stop()
{
closed = true;
}
/// <summary>
/// Creates a new session to work on this connection
/// </summary>
public ISession CreateSession()
{
return CreateSession(acknowledgementMode);
}
/// <summary>
/// Creates a new session to work on this connection
/// </summary>
public ISession CreateSession(AcknowledgementMode mode)
{
return new Session(this, mode);
}
internal ZmqSocket GetProducer()
{
ProducerRef producerRef;
string contextBinding = GetProducerContextBinding();
lock(producerCacheLock)
{
if(!producerCache.TryGetValue(contextBinding, out producerRef))
{
producerRef = new ProducerRef();
producerRef.producer = this.Context.CreateSocket(SocketType.PUB);
if(null == producerRef.producer)
{
throw new ResourceAllocationException();
}
producerRef.producer.Bind(contextBinding);
producerCache.Add(contextBinding, producerRef);
}
else
{
producerRef.refCount++;
}
}
return producerRef.producer;
}
internal void ReleaseProducer(ZmqSocket endpoint)
{
// UNREFERENCED_PARAM(endpoint);
ProducerRef producerRef;
string contextBinding = GetProducerContextBinding();
lock(producerCacheLock)
{
if(producerCache.TryGetValue(contextBinding, out producerRef))
{
producerRef.refCount--;
if(producerRef.refCount < 1)
{
producerCache.Remove(contextBinding);
producerRef.producer.Unbind(contextBinding);
producerRef.producer.Dispose();
}
}
}
}
internal ZmqSocket GetConsumer()
{
ZmqSocket endpoint = this.Context.CreateSocket(SocketType.SUB);
if(null == endpoint)
{
throw new ResourceAllocationException();
}
return endpoint;
}
internal void ReleaseConsumer(ZmqSocket endpoint)
{
endpoint.Disconnect(GetConsumerBindingPath());
endpoint.Dispose();
}
internal string GetProducerContextBinding()
{
return this.producerContextBinding;
}
internal string GetConsumerBindingPath()
{
return this.consumerContextBinding;
}
public void Close()
{
Stop();
lock(producerCacheLock)
{
foreach(KeyValuePair<string, ProducerRef> cacheItem in producerCache)
{
cacheItem.Value.producer.Unbind(cacheItem.Key);
}
producerCache.Clear();
}
}
public void PurgeTempDestinations()
{
}
/// <summary>
/// The default timeout for network requests.
/// </summary>
public TimeSpan RequestTimeout
{
get { return NMSConstants.defaultRequestTimeout; }
set { }
}
public AcknowledgementMode AcknowledgementMode
{
get { return acknowledgementMode; }
set { acknowledgementMode = value; }
}
/// <summary>
/// Get/or set the broker Uri.
/// </summary>
public Uri BrokerUri
{
get { return brokerUri; }
}
/// <summary>
/// Get/or set the client Id
/// </summary>
public string ClientId
{
get { return clientId; }
set { clientId = value; }
}
/// <summary>
/// Get/or set the redelivery policy for this connection.
/// </summary>
public IRedeliveryPolicy RedeliveryPolicy
{
get { return this.redeliveryPolicy; }
set { this.redeliveryPolicy = value; }
}
private ConsumerTransformerDelegate consumerTransformer;
public ConsumerTransformerDelegate ConsumerTransformer
{
get { return this.consumerTransformer; }
set { this.consumerTransformer = value; }
}
private ProducerTransformerDelegate producerTransformer;
public ProducerTransformerDelegate ProducerTransformer
{
get { return this.producerTransformer; }
set { this.producerTransformer = value; }
}
/// <summary>
/// Gets ZMQ connection context
/// </summary>
internal ZmqContext Context
{
get { return Connection._context; }
}
/// <summary>
/// Gets the Meta Data for the NMS Connection instance.
/// </summary>
public IConnectionMetaData MetaData
{
get { return this.metaData ?? (this.metaData = new ConnectionMetaData()); }
}
/// <summary>
/// A delegate that can receive transport level exceptions.
/// </summary>
public event ExceptionListener ExceptionListener;
/// <summary>
/// An asynchronous listener that is notified when a Fault tolerant connection
/// has been interrupted.
/// </summary>
public event ConnectionInterruptedListener ConnectionInterruptedListener;
/// <summary>
/// An asynchronous listener that is notified when a Fault tolerant connection
/// has been resumed.
/// </summary>
public event ConnectionResumedListener ConnectionResumedListener;
public void HandleException(System.Exception e)
{
if(ExceptionListener != null && !this.closed)
{
ExceptionListener(e);
}
else
{
Tracer.Error(e);
}
}
public void HandleTransportInterrupted()
{
Tracer.Debug("Transport has been Interrupted.");
if(this.ConnectionInterruptedListener != null && !this.closed)
{
try
{
this.ConnectionInterruptedListener();
}
catch
{
}
}
}
public void HandleTransportResumed()
{
Tracer.Debug("Transport has resumed normal operation.");
if(this.ConnectionResumedListener != null && !this.closed)
{
try
{
this.ConnectionResumedListener();
}
catch
{
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class RequestStreamTest
{
readonly byte[] buffer = new byte[1];
#region Write
[Fact]
public async Task Write_BufferIsNull_ThrowsArgumentNullException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => stream.Write(null, 0, 1));
});
}
[Fact]
public async Task Write_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.Write(buffer, -1, buffer.Length));
});
}
[Fact]
public async Task Write_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.Write(buffer, 0, -1));
});
}
[Fact]
public async Task Write_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.Write(buffer, 0, buffer.Length + 1));
});
}
[Fact]
public async Task Write_OffsetPlusCountMaxValueExceedsBufferLength_Throws()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.Write(buffer, int.MaxValue, int.MaxValue));
});
}
#endregion
#region WriteAsync
[Fact]
public async Task WriteAsync_BufferIsNull_ThrowsArgumentNullException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { Task t = stream.WriteAsync(null, 0, 1); });
});
}
[Fact]
public async Task WriteAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { Task t = stream.WriteAsync(buffer, -1, buffer.Length); });
});
}
[Fact]
public async Task WriteAsync_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => { Task t = stream.WriteAsync(buffer, 0, -1); });
});
}
[Fact]
public async Task WriteAsync_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => { Task t = stream.WriteAsync(buffer, 0, buffer.Length + 1); });
});
}
[Fact]
public async Task WriteAsync_OffsetPlusCountMaxValueExceedsBufferLength_Throws()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { Task t = stream.WriteAsync(buffer, int.MaxValue, int.MaxValue); });
});
}
[Fact]
public async Task WriteAsync_ValidParameters_TaskRanToCompletion()
{
await GetRequestStream((stream) =>
{
Task t = stream.WriteAsync(buffer, 0, buffer.Length);
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
});
}
[Fact]
public async Task WriteAsync_TokenIsCanceled_TaskIsCanceled()
{
await GetRequestStream((stream) =>
{
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = stream.WriteAsync(buffer, 0, buffer.Length, cts.Token);
Assert.True(t.IsCanceled);
});
}
#endregion
#region BeginWrite
[Fact]
public async Task BeginWriteAsync_BufferIsNull_ThrowsArgumentNullException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => stream.BeginWrite(null, 0, 1, null, null));
});
}
[Fact]
public async Task BeginWriteAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.BeginWrite(buffer, -1, buffer.Length, null, null));
});
}
[Fact]
public async Task BeginWriteAsync_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.BeginWrite(buffer, 0, -1, null, null));
});
}
[Fact]
public async Task BeginWriteAsync_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.BeginWrite(buffer, 0, buffer.Length + 1, null, null));
});
}
[Fact]
public async Task BeginWriteAsync_OffsetPlusCountMaxValueExceedsBufferLength_Throws()
{
await GetRequestStream((stream) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.BeginWrite(buffer, int.MaxValue, int.MaxValue, null, null));
});
}
[Fact]
public async Task BeginWriteAsync_ValidParameters_TaskRanToCompletion()
{
await GetRequestStream((stream) =>
{
object state = new object();
IAsyncResult result = stream.BeginWrite(buffer, 0, buffer.Length, null, state);
stream.EndWrite(result);
Assert.True(result.IsCompleted);
});
}
#endregion
[Fact]
public async Task FlushAsync_TaskRanToCompletion()
{
await GetRequestStream((stream) =>
{
Task t = stream.FlushAsync();
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "cancellation token ignored on netfx")]
[Fact]
public async Task FlushAsync_TokenIsCanceled_TaskIsCanceled()
{
await GetRequestStream((stream) =>
{
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = stream.FlushAsync(cts.Token);
Assert.True(t.IsCanceled);
});
}
private async Task GetRequestStream(Action<Stream> requestAction)
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
requestAction(requestStream);
}
return Task.FromResult<object>(null);
});
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.