context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: [email protected] (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.v201502;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201502 {
/// <summary>
/// UnitTests for <see cref="LineItemCreativeAssociationServiceTests"/> class.
/// </summary>
[TestFixture]
public class LineItemCreativeAssociationServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="LineItemCreativeAssociationService"/> class.
/// </summary>
private LineItemCreativeAssociationService licaService;
/// <summary>
/// Advertiser company id for running tests.
/// </summary>
private long advertiserId;
/// <summary>
/// Salesperson user id for running tests.
/// </summary>
private long salespersonId;
/// <summary>
/// Trafficker user id for running tests.
/// </summary>
private long traffickerId;
/// <summary>
/// Order id for running tests.
/// </summary>
private long orderId;
/// <summary>
/// Ad unit id for running tests.
/// </summary>
private string adUnitId;
/// <summary>
/// Creative id 1 for running tests.
/// </summary>
private long creativeId1;
/// <summary>
/// Creative id 2 for running tests.
/// </summary>
private long creativeId2;
/// <summary>
/// Creative id 3 for running tests.
/// </summary>
private long creativeId3;
/// <summary>
/// Creative id 4 for running tests.
/// </summary>
private long creativeId4;
/// <summary>
/// Line item id 1 for running tests.
/// </summary>
private long lineItemId1;
/// <summary>
/// Line item id 2 for running tests.
/// </summary>
private long lineItemId2;
/// <summary>
/// Line item id 3 for running tests.
/// </summary>
private long lineItemId3;
/// <summary>
/// Line item id 4 for running tests.
/// </summary>
private long lineItemId4;
/// <summary>
/// Line item creative association 1 for running tests.
/// </summary>
private LineItemCreativeAssociation lica1;
/// <summary>
/// Line item creative association 2 for running tests.
/// </summary>
private LineItemCreativeAssociation lica2;
/// <summary>
/// Default public constructor.
/// </summary>
public LineItemCreativeAssociationServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
licaService = (LineItemCreativeAssociationService) user.GetService(
DfpService.v201502.LineItemCreativeAssociationService);
advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
salespersonId = utils.GetSalesperson(user).id;
traffickerId = utils.GetTrafficker(user).id;
orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
adUnitId = utils.CreateAdUnit(user).id;
lineItemId1 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId2 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId3 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId4 = utils.CreateLineItem(user, orderId, adUnitId).id;
creativeId1 = utils.CreateCreative(user, advertiserId).id;
creativeId2 = utils.CreateCreative(user, advertiserId).id;
creativeId3 = utils.CreateCreative(user, advertiserId).id;
creativeId4 = utils.CreateCreative(user, advertiserId).id;
lica1 = utils.CreateLica(user, lineItemId3, creativeId3);
lica2 = utils.CreateLica(user, lineItemId4, creativeId4);
}
/// <summary>
/// Test whether we can create a list of line item creative associations.
/// </summary>
[Test]
public void TestCreateLineItemCreativeAssociations() {
LineItemCreativeAssociation localLica1 = new LineItemCreativeAssociation();
localLica1.creativeId = creativeId1;
localLica1.lineItemId = lineItemId1;
LineItemCreativeAssociation localLica2 = new LineItemCreativeAssociation();
localLica2.creativeId = creativeId2;
localLica2.lineItemId = lineItemId2;
LineItemCreativeAssociation[] newLicas = null;
Assert.DoesNotThrow(delegate() {
newLicas = licaService.createLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {localLica1, localLica2});
});
Assert.NotNull(newLicas);
Assert.AreEqual(newLicas.Length, 2);
Assert.NotNull(newLicas[0]);
Assert.AreEqual(newLicas[0].creativeId, localLica1.creativeId);
Assert.AreEqual(newLicas[0].lineItemId, localLica1.lineItemId);
Assert.NotNull(newLicas[1]);
Assert.AreEqual(newLicas[1].creativeId, localLica2.creativeId);
Assert.AreEqual(newLicas[1].lineItemId, localLica2.lineItemId);
}
/// <summary>
/// Test whether we can fetch a list of existing line item creative
/// associations that match given statement.
/// </summary>
[Test]
public void TestGetLineItemCreativeAssociationsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 500", lineItemId3);
LineItemCreativeAssociationPage page = null;
Assert.DoesNotThrow(delegate() {
page = licaService.getLineItemCreativeAssociationsByStatement(statement);
});
Assert.NotNull(page);
Assert.NotNull(page.results);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results[0]);
Assert.AreEqual(page.results[0].creativeId, lica1.creativeId);
Assert.AreEqual(page.results[0].lineItemId, lica1.lineItemId);
}
/// <summary>
/// Test whether we can deactivate a line item create association.
/// </summary>
[Test]
public void TestPerformLineItemCreativeAssociationAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 1", lineItemId3);
DeactivateLineItemCreativeAssociations action = new DeactivateLineItemCreativeAssociations();
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = licaService.performLineItemCreativeAssociationAction(action, statement);
});
Assert.NotNull(result);
Assert.AreEqual(result.numChanges, 1);
}
/// <summary>
/// Test whether we can update a list of line item creative associations.
/// </summary>
[Test]
public void TestUpdateLineItemCreativeAssociations() {
lica1.destinationUrl = "http://news.google.com";
lica2.destinationUrl = "http://news.google.com";
LineItemCreativeAssociation[] newLicas = null;
Assert.DoesNotThrow(delegate() {
newLicas = licaService.updateLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {lica1, lica2});
});
Assert.NotNull(newLicas);
Assert.AreEqual(newLicas.Length, 2);
Assert.NotNull(newLicas[0]);
Assert.AreEqual(newLicas[0].creativeId, lica1.creativeId);
Assert.AreEqual(newLicas[0].lineItemId, lica1.lineItemId);
Assert.NotNull(newLicas[1]);
Assert.AreEqual(newLicas[1].creativeId, lica2.creativeId);
Assert.AreEqual(newLicas[1].lineItemId, lica2.lineItemId);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Dns
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RecordSetsOperations operations.
/// </summary>
public partial interface IRecordSetsOperations
{
/// <summary>
/// Updates a record set within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the record set, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record in this record set. Possible values include:
/// 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of the record set. Omit this value to always overwrite the
/// current record set. Specify the last-seen etag value to prevent
/// accidentally overwritting concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RecordSet>> UpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a record set within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the record set, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record in this record set. Record sets of type SOA
/// can be updated but not created (they are created when the DNS zone
/// is created). Possible values include: 'A', 'AAAA', 'CNAME', 'MX',
/// 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of the record set. Omit this value to always overwrite the
/// current record set. Specify the last-seen etag value to prevent
/// accidentally overwritting any concurrent changes.
/// </param>
/// <param name='ifNoneMatch'>
/// Set to '*' to allow a new record set to be created, but to prevent
/// updating an existing record set. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RecordSet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a record set from a DNS zone. This operation cannot be
/// undone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the record set, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record in this record set. Record sets of type SOA
/// cannot be deleted (they are deleted when the DNS zone is deleted).
/// Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR',
/// 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='ifMatch'>
/// The etag of the record set. Omit this value to always delete the
/// current record set. Specify the last-seen etag value to prevent
/// accidentally deleting any concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a record set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the record set, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record in this record set. Possible values include:
/// 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RecordSet>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the record sets of a specified type in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='recordType'>
/// The type of record sets to enumerate. Possible values include: 'A',
/// 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='top'>
/// The maximum number of record sets to return. If not specified,
/// returns up to 100 record sets.
/// </param>
/// <param name='recordsetnamesuffix'>
/// The suffix label of the record set name that has to be used to
/// filter the record set enumerations. If this parameter is specified,
/// Enumeration will return only records that end with
/// .<recordSetNameSuffix>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeWithHttpMessagesAsync(string resourceGroupName, string zoneName, RecordType recordType, int? top = default(int?), string recordsetnamesuffix = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all record sets in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='top'>
/// The maximum number of record sets to return. If not specified,
/// returns up to 100 record sets.
/// </param>
/// <param name='recordsetnamesuffix'>
/// The suffix label of the record set name that has to be used to
/// filter the record set enumerations. If this parameter is specified,
/// Enumeration will return only records that end with
/// .<recordSetNameSuffix>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RecordSet>>> ListByDnsZoneWithHttpMessagesAsync(string resourceGroupName, string zoneName, int? top = default(int?), string recordsetnamesuffix = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the record sets of a specified type in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all record sets in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RecordSet>>> ListByDnsZoneNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Impl;
using NHibernate.Linq;
using Orchard.ContentManagement.Records;
using Orchard.Data;
using NHibernate.Transform;
using NHibernate.SqlCommand;
using Orchard.Utility.Extensions;
using Orchard.Caching;
namespace Orchard.ContentManagement {
public class DefaultContentQuery : IContentQuery {
private readonly ITransactionManager _transactionManager;
private ISession _session;
private ICriteria _itemVersionCriteria;
private VersionOptions _versionOptions;
private ICacheManager _cacheManager;
private ISignals _signals;
private IRepository<ContentTypeRecord> _contentTypeRepository;
private IEnumerable<IGlobalCriteriaProvider> _globalCriteriaList;
public DefaultContentQuery(
IContentManager contentManager,
ITransactionManager transactionManager,
ICacheManager cacheManager,
ISignals signals,
IRepository<ContentTypeRecord> contentTypeRepository,
IEnumerable<IGlobalCriteriaProvider> globalCriteriaList) {
_transactionManager = transactionManager;
ContentManager = contentManager;
_cacheManager = cacheManager;
_signals = signals;
_contentTypeRepository = contentTypeRepository;
_globalCriteriaList = globalCriteriaList;
}
public IContentManager ContentManager { get; private set; }
private void BeforeExecuteQuery(ICriteria contentItemVersionCriteria) {
foreach(var criteria in _globalCriteriaList) {
criteria.AddCriteria(contentItemVersionCriteria);
}
}
ISession BindSession() {
if (_session == null)
_session = _transactionManager.GetSession();
return _session;
}
ICriteria BindCriteriaByPath(ICriteria criteria, string path) {
return criteria.GetCriteriaByPath(path) ?? criteria.CreateCriteria(path);
}
//ICriteria BindTypeCriteria() {
// // ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType]
// return BindCriteriaByPath(BindItemCriteria(), "ContentType");
//}
ICriteria BindItemCriteria() {
// [ContentItemVersionRecord] >join> [ContentItemRecord]
return BindCriteriaByPath(BindItemVersionCriteria(), "ContentItemRecord");
}
ICriteria BindItemVersionCriteria() {
if (_itemVersionCriteria == null) {
_itemVersionCriteria = BindSession().CreateCriteria<ContentItemVersionRecord>();
_itemVersionCriteria.SetCacheable(true);
}
return _itemVersionCriteria;
}
ICriteria BindPartCriteria<TRecord>() where TRecord : ContentPartRecord {
if (typeof(TRecord).IsSubclassOf(typeof(ContentPartVersionRecord))) {
return BindCriteriaByPath(BindItemVersionCriteria(), typeof(TRecord).Name);
}
return BindCriteriaByPath(BindItemCriteria(), typeof(TRecord).Name);
}
private int GetContentTypeRecordId(string contentType) {
return _cacheManager.Get(contentType + "_Record", true, ctx => {
ctx.Monitor(_signals.When(contentType + "_Record"));
var contentTypeRecord = _contentTypeRepository.Get(x => x.Name == contentType);
if (contentTypeRecord == null) {
//TEMP: this is not safe... ContentItem types could be created concurrently?
contentTypeRecord = new ContentTypeRecord { Name = contentType };
_contentTypeRepository.Create(contentTypeRecord);
}
return contentTypeRecord.Id;
});
}
private void ForType(params string[] contentTypeNames) {
if (contentTypeNames != null) {
var contentTypeIds = contentTypeNames.Select(GetContentTypeRecordId).ToArray();
// don't use the IN operator if not needed for performance reasons
if (contentTypeNames.Length == 1) {
BindItemCriteria().Add(Restrictions.Eq("ContentType.Id", contentTypeIds[0]));
}
else {
BindItemCriteria().Add(Restrictions.InG("ContentType.Id", contentTypeIds));
}
}
}
public void ForVersion(VersionOptions options) {
_versionOptions = options;
}
private void ForContentItems(IEnumerable<int> ids) {
if (ids == null) throw new ArgumentNullException("ids");
// Converting to array as otherwise an exception "Expression argument must be of type ICollection." is thrown.
Where<ContentItemRecord>(record => ids.ToArray().Contains(record.Id), BindCriteriaByPath(BindItemCriteria(), typeof(ContentItemRecord).Name));
}
private void Where<TRecord>() where TRecord : ContentPartRecord {
// this simply demands an inner join
BindPartCriteria<TRecord>();
}
private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate) where TRecord : ContentPartRecord {
Where<TRecord>(predicate, BindPartCriteria<TRecord>());
}
private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate, ICriteria bindCriteria) {
// build a linq to nhibernate expression
var options = new QueryOptions();
var queryProvider = new NHibernateQueryProvider(BindSession(), options);
var queryable = new Query<TRecord>(queryProvider, options).Where(predicate);
// translate it into the nhibernate ICriteria implementation
var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression);
// attach the criterion from the predicate to this query's criteria for the record
var recordCriteria = bindCriteria;
foreach (var expressionEntry in criteria.IterateExpressionEntries()) {
recordCriteria.Add(expressionEntry.Criterion);
}
}
private void OrderBy<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord {
// build a linq to nhibernate expression
var options = new QueryOptions();
var queryProvider = new NHibernateQueryProvider(BindSession(), options);
var queryable = new Query<TRecord>(queryProvider, options).OrderBy(keySelector);
// translate it into the nhibernate ordering
var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression);
// attaching orderings to the query's criteria
var recordCriteria = BindPartCriteria<TRecord>();
foreach (var ordering in criteria.IterateOrderings()) {
recordCriteria.AddOrder(ordering.Order);
}
}
private void OrderByDescending<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord {
// build a linq to nhibernate expression
var options = new QueryOptions();
var queryProvider = new NHibernateQueryProvider(BindSession(), options);
var queryable = new Query<TRecord>(queryProvider, options).OrderByDescending(keySelector);
// translate it into the nhibernate ICriteria implementation
var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression);
// attaching orderings to the query's criteria
var recordCriteria = BindPartCriteria<TRecord>();
foreach (var ordering in criteria.IterateOrderings()) {
recordCriteria.AddOrder(ordering.Order);
}
}
private IEnumerable<ContentItem> Slice(int skip, int count) {
var criteria = BindItemVersionCriteria();
criteria.ApplyVersionOptionsRestrictions(_versionOptions);
criteria.Fetch(SelectMode.Fetch, "ContentItemRecord");
criteria.Fetch(SelectMode.Fetch, "ContentItemRecord.ContentType");
// TODO: put 'removed false' filter in place
if (skip != 0) {
criteria = criteria.SetFirstResult(skip);
}
if (count != 0) {
criteria = criteria.SetMaxResults(count);
}
BeforeExecuteQuery(criteria);
return criteria
.List<ContentItemVersionRecord>()
.Select(x => ContentManager.Get(x.ContentItemRecord.Id, _versionOptions != null && _versionOptions.IsDraftRequired ? _versionOptions : VersionOptions.VersionRecord(x.Id)))
.ToReadOnlyCollection();
}
int Count() {
var criteria = (ICriteria)BindItemVersionCriteria().Clone();
criteria.ClearOrders();
criteria.ApplyVersionOptionsRestrictions(_versionOptions);
BeforeExecuteQuery(criteria);
return criteria.SetProjection(Projections.RowCount()).UniqueResult<Int32>();
}
void WithQueryHints(QueryHints hints) {
if (hints == QueryHints.Empty) {
return;
}
var contentItemVersionCriteria = BindItemVersionCriteria();
var contentItemCriteria = BindItemCriteria();
var contentItemMetadata = _session.SessionFactory.GetClassMetadata(typeof(ContentItemRecord));
var contentItemVersionMetadata = _session.SessionFactory.GetClassMetadata(typeof(ContentItemVersionRecord));
// break apart and group hints by their first segment
var hintDictionary = hints.Records
.Select(hint => new { Hint = hint, Segments = hint.Split('.') })
.GroupBy(item => item.Segments.FirstOrDefault())
.ToDictionary(grouping => grouping.Key, StringComparer.InvariantCultureIgnoreCase);
// locate hints that match properties in the ContentItemVersionRecord
foreach (var hit in contentItemVersionMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) {
contentItemVersionCriteria.Fetch(SelectMode.Fetch, hit.Hint);
hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemVersionCriteria, ExtendCriteria);
}
// locate hints that match properties in the ContentItemRecord
foreach (var hit in contentItemMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) {
contentItemVersionCriteria.Fetch(SelectMode.Fetch, "ContentItemRecord." + hit.Hint);
hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemCriteria, ExtendCriteria);
}
if (hintDictionary.SelectMany(x => x.Value).Any(x => x.Segments.Count() > 1))
contentItemVersionCriteria.SetResultTransformer(new DistinctRootEntityResultTransformer());
}
void WithQueryHintsFor(string contentType) {
var contentItem = ContentManager.New(contentType);
var contentPartRecords = new List<string>();
foreach (var part in contentItem.Parts) {
var partType = part.GetType().BaseType;
if (partType.IsGenericType && partType.GetGenericTypeDefinition() == typeof(ContentPart<>)) {
var recordType = partType.GetGenericArguments().Single();
contentPartRecords.Add(recordType.Name);
}
}
WithQueryHints(new QueryHints().ExpandRecords(contentPartRecords));
}
private static ICriteria ExtendCriteria(ICriteria criteria, string segment) {
return criteria.GetCriteriaByPath(segment) ?? criteria.CreateCriteria(segment, JoinType.LeftOuterJoin);
}
IContentQuery<TPart> IContentQuery.ForPart<TPart>() {
return new ContentQuery<TPart>(this);
}
class ContentQuery<T> : IContentQuery<T> where T : IContent {
protected readonly DefaultContentQuery _query;
public ContentQuery(DefaultContentQuery query) {
_query = query;
}
public IContentManager ContentManager {
get { return _query.ContentManager; }
}
IContentQuery<TPart> IContentQuery.ForPart<TPart>() {
return new ContentQuery<TPart>(_query);
}
IContentQuery<T> IContentQuery<T>.ForType(params string[] contentTypes) {
_query.ForType(contentTypes);
return this;
}
IContentQuery<T> IContentQuery<T>.ForVersion(VersionOptions options) {
_query.ForVersion(options);
return this;
}
IContentQuery<T> IContentQuery<T>.ForContentItems(IEnumerable<int> ids) {
_query.ForContentItems(ids);
return this;
}
IEnumerable<T> IContentQuery<T>.List() {
return _query.Slice(0, 0).AsPart<T>();
}
IEnumerable<T> IContentQuery<T>.Slice(int skip, int count) {
return _query.Slice(skip, count).AsPart<T>();
}
int IContentQuery<T>.Count() {
return _query.Count();
}
IContentQuery<T, TRecord> IContentQuery<T>.Join<TRecord>() {
_query.Where<TRecord>();
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T, TRecord> IContentQuery<T>.Where<TRecord>(Expression<Func<TRecord, bool>> predicate) {
_query.Where(predicate);
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T, TRecord> IContentQuery<T>.OrderBy<TRecord>(Expression<Func<TRecord, object>> keySelector) {
_query.OrderBy(keySelector);
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T, TRecord> IContentQuery<T>.OrderByDescending<TRecord>(Expression<Func<TRecord, object>> keySelector) {
_query.OrderByDescending(keySelector);
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T> IContentQuery<T>.WithQueryHints(QueryHints hints) {
_query.WithQueryHints(hints);
return this;
}
IContentQuery<T> IContentQuery<T>.WithQueryHintsFor(string contentType) {
_query.WithQueryHintsFor(contentType);
return this;
}
}
class ContentQuery<T, TR> : ContentQuery<T>, IContentQuery<T, TR>
where T : IContent
where TR : ContentPartRecord {
public ContentQuery(DefaultContentQuery query)
: base(query) {
}
IContentQuery<T, TR> IContentQuery<T, TR>.ForVersion(VersionOptions options) {
_query.ForVersion(options);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.Where(Expression<Func<TR, bool>> predicate) {
_query.Where(predicate);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.OrderBy<TKey>(Expression<Func<TR, TKey>> keySelector) {
_query.OrderBy(keySelector);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.OrderByDescending<TKey>(Expression<Func<TR, TKey>> keySelector) {
_query.OrderByDescending(keySelector);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.WithQueryHints(QueryHints hints) {
_query.WithQueryHints(hints);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.WithQueryHintsFor(string contentType) {
_query.WithQueryHintsFor(contentType);
return this;
}
}
}
internal static class CriteriaExtensions {
internal static void ApplyVersionOptionsRestrictions(this ICriteria criteria, VersionOptions versionOptions) {
if (versionOptions == null) {
criteria.Add(Restrictions.Eq("Published", true));
}
else if (versionOptions.IsPublished) {
criteria.Add(Restrictions.Eq("Published", true));
}
else if (versionOptions.IsLatest) {
criteria.Add(Restrictions.Eq("Latest", true));
}
else if (versionOptions.IsDraft && !versionOptions.IsDraftRequired) {
criteria.Add(Restrictions.And(
Restrictions.Eq("Latest", true),
Restrictions.Eq("Published", false)));
}
else if (versionOptions.IsDraft || versionOptions.IsDraftRequired) {
criteria.Add(Restrictions.Eq("Latest", true));
}
else if (versionOptions.IsAllVersions) {
// no-op... all versions will be returned by default
}
else {
throw new ApplicationException("Invalid VersionOptions for content query");
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using Hammock.Model;
using Hammock.Tasks;
using Newtonsoft.Json;
namespace TweetSharp
{
#if !SILVERLIGHT
/// <summary>
/// Represents the API limiting imposed on a user or unauthenticated IP address.
/// </summary>
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
[DebuggerDisplay("{RemainingHits} / {HourlyLimit} remaining.")]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterRateLimitStatus :
PropertyChangedBase,
IComparable<TwitterRateLimitStatus>,
IEquatable<TwitterRateLimitStatus>,
IRateLimitStatus,
ITwitterModel
{
private int _remainingHits;
private int _hourlyLimit;
private long _resetTimeInSeconds;
private DateTime _resetTime;
/// <summary>
/// Gets or sets the remaining API hits allowed.
/// </summary>
/// <value>The remaining API hits allowed.</value>
[JsonProperty("remaining_hits")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual int RemainingHits
{
get { return _remainingHits; }
set
{
if (_remainingHits == value)
{
return;
}
_remainingHits = value;
OnPropertyChanged("RemainingHits");
}
}
/// <summary>
/// Gets or sets the API hits hourly limit.
/// You can compare this to <see cref="RemainingHits" /> to get a
/// percentage of usage remaining.
/// </summary>
/// <value>The hourly limit.</value>
[JsonProperty("hourly_limit")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual int HourlyLimit
{
get { return _hourlyLimit; }
set
{
if (_hourlyLimit == value)
{
return;
}
_hourlyLimit = value;
OnPropertyChanged("HourlyLimit");
}
}
/// <summary>
/// Gets or sets the UNIX time representing the time
/// this rate limit will reset.
/// This is not the number of seconds until the rate limit
/// resets.
/// </summary>
/// <value>The reset time in seconds.</value>
[JsonProperty("reset_time_in_seconds")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long ResetTimeInSeconds
{
get { return _resetTimeInSeconds; }
set
{
if (_resetTimeInSeconds == value)
{
return;
}
_resetTimeInSeconds = value;
OnPropertyChanged("ResetTimeInSeconds");
}
}
/// <summary>
/// Gets or sets the reset time for this rate limit constraint.
/// </summary>
/// <value>The reset time.</value>
[JsonProperty("reset_time")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual DateTime ResetTime
{
get { return _resetTime; }
set
{
if (_resetTime == value)
{
return;
}
_resetTime = value;
OnPropertyChanged("ResetTime");
}
}
#region Implementation of IComparable<TwitterRateLimitStatus>
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(TwitterRateLimitStatus other)
{
return other.HourlyLimit.CompareTo(HourlyLimit) == 0 &&
other.ResetTime.CompareTo(ResetTime) == 0 &&
other.RemainingHits.CompareTo(RemainingHits) == 0
? 0
: 1;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == typeof (TwitterRateLimitStatus) &&
Equals((TwitterRateLimitStatus) obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
unchecked
{
var result = _remainingHits;
result = (result*397) ^ _hourlyLimit;
result = (result*397) ^ _resetTimeInSeconds.GetHashCode();
result = (result*397) ^ _resetTime.GetHashCode();
return result;
}
}
#endregion
#region Implementation of IEquatable<TwitterRateLimitStatus>
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(TwitterRateLimitStatus other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other._remainingHits == _remainingHits &&
other._hourlyLimit == _hourlyLimit &&
other._resetTimeInSeconds == _resetTimeInSeconds &&
other._resetTime.Equals(_resetTime);
}
#endregion
#region IRateLimitStatus Members
/// <summary>
/// Gets the next reset time.
/// </summary>
/// <value>The next reset time.</value>
DateTime IRateLimitStatus.NextReset
{
get { return ResetTime; }
}
/// <summary>
/// Gets the remaining API uses.
/// </summary>
/// <value>The remaining API uses.</value>
int IRateLimitStatus.RemainingUses
{
get { return RemainingHits; }
}
#endregion
#if !Smartphone && !NET20
/// <summary>
/// The source content used to deserialize the model entity instance.
/// Can be XML or JSON, depending on the endpoint used.
/// </summary>
[DataMember]
#endif
public virtual string RawSource { get; set; }
}
}
| |
// 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.KeyVault
{
using System.Threading;
using System.Threading.Tasks;
using Models;
using System.Net.Http;
using Rest.Azure;
using System.Collections.Generic;
using Rest;
using System;
using System.Net;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Client class to perform cryptographic key operations and vault
/// operations against the Key Vault service.
/// </summary>
public partial class KeyVaultClient
{
/// <summary>
/// The authentication callback delegate which is to be implemented by the client code
/// </summary>
/// <param name="authority"> Identifier of the authority, a URL. </param>
/// <param name="resource"> Identifier of the target resource that is the recipient of the requested token, a URL. </param>
/// <param name="scope"> The scope of the authentication request. </param>
/// <returns> access token </returns>
public delegate Task<string> AuthenticationCallback(string authority, string resource, string scope);
/// <summary>
/// Constructor
/// </summary>
/// <param name="authenticationCallback">The authentication callback</param>
/// <param name='handlers'>Optional. The delegating handlers to add to the http client pipeline.</param>
public KeyVaultClient(AuthenticationCallback authenticationCallback, params DelegatingHandler[] handlers)
: this(new KeyVaultCredential(authenticationCallback), handlers)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="authenticationCallback">The authentication callback</param>
/// <param name="httpClient">Customized HTTP client </param>
public KeyVaultClient(AuthenticationCallback authenticationCallback, HttpClient httpClient)
: this(new KeyVaultCredential(authenticationCallback), httpClient)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="credential">Credential for key vault operations</param>
/// <param name="httpClient">Customized HTTP client </param>
public KeyVaultClient(KeyVaultCredential credential, HttpClient httpClient)
// clone the KeyVaultCredential to ensure the instance is only used by this client since it
// will use this client's HttpClient for unauthenticated calls to retrieve the auth challange
: this(credential.Clone())
{
base.HttpClient = httpClient;
}
/// <summary>
/// Gets the pending certificate signing request response.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<string>> GetPendingCertificateSigningRequestWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultBaseUrl == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultBaseUrl");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (this.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("vaultBaseUrl", vaultBaseUrl);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPendingCertificateSigningRequest", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "certificates/{certificate-name}/pending";
_url = _url.Replace("{vaultBaseUrl}", vaultBaseUrl);
_url = _url.Replace("{certificate-name}", Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (this.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
_httpRequest.Headers.Add("Accept", "application/pkcs10");
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new KeyVaultErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
KeyVaultError _errorBody = SafeJsonConvert.DeserializeObject<KeyVaultError>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
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 AzureOperationResponse<string>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata.Tests;
using System.Reflection.PortableExecutable;
using Xunit;
namespace System.Reflection.Metadata.Decoding.Tests
{
public partial class SignatureDecoderTests
{
[Fact]
public unsafe void VerifyMultipleOptionalModifiers()
{
// Type 1: int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl)
// Type 2: char*
// Type 3: uint32
// Type 4: char modopt([mscorlib]System.Runtime.CompilerServices.IsConst)*
var testSignature = new byte[] { 0x20, 0x45, 0x20, 0x69, 0x08, 0x0F, 0x03, 0x09, 0x0F, 0x20, 0x55, 0x03 };
var types = new string[]
{
"int32 modopt(100001A) modopt(1000011)",
"char*",
"uint32",
"char modopt(1000015)*"
};
fixed (byte* testSignaturePtr = &testSignature[0])
{
var signatureBlob = new BlobReader(testSignaturePtr, testSignature.Length);
var provider = new OpaqueTokenTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, metadataReader: null, genericContext: null);
foreach (string typeString in types)
{
// Verify that each type is decoded as expected
Assert.Equal(typeString, decoder.DecodeType(ref signatureBlob));
}
// And that nothing is left over to decode
Assert.True(signatureBlob.RemainingBytes == 0);
Assert.Throws<BadImageFormatException>(() => decoder.DecodeType(ref signatureBlob));
}
}
[Theory]
[InlineData(new string[] { "int32", "string" }, new byte[] { 0x0A /*GENERICINST*/, 2 /*count*/, 0x8 /*I4*/, 0xE /*STRING*/ })]
public unsafe void DecodeValidMethodSpecificationSignature(string[] expectedTypes, byte[] testSignature)
{
fixed (byte* testSignaturePtr = &testSignature[0])
{
var signatureBlob = new BlobReader(testSignaturePtr, testSignature.Length);
var provider = new OpaqueTokenTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, metadataReader: null, genericContext: null);
IEnumerable<string> actualTypes = decoder.DecodeMethodSpecificationSignature(ref signatureBlob);
Assert.Equal(expectedTypes, actualTypes);
Assert.True(signatureBlob.RemainingBytes == 0);
Assert.Throws<BadImageFormatException>(() => decoder.DecodeType(ref signatureBlob));
}
}
[Theory]
[InlineData(new byte[] { 0 })] // bad header
[InlineData(new byte[] { 0x0A /*GENERICINST*/, 0 /*count*/ })] // no type parameters
public unsafe void DecodeInvalidMethodSpecificationSignature(byte[] testSignature)
{
fixed (byte* testSignaturePtr = &testSignature[0])
{
var signatureBlob = new BlobReader(testSignaturePtr, testSignature.Length);
var provider = new OpaqueTokenTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, metadataReader: null, genericContext: null);
}
}
[Fact]
public void DecodeVarArgsDefAndRef()
{
using (FileStream stream = File.OpenRead(typeof(VarArgsToDecode).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader metadataReader = peReader.GetMetadataReader();
TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(metadataReader, typeof(VarArgsToDecode));
TypeDefinition typeDef = metadataReader.GetTypeDefinition(typeDefHandle);
MethodDefinition methodDef = metadataReader.GetMethodDefinition(typeDef.GetMethods().First());
Assert.Equal("VarArgsCallee", metadataReader.GetString(methodDef.Name));
var provider = new OpaqueTokenTypeProvider();
MethodSignature<string> defSignature = methodDef.DecodeSignature(provider, null);
Assert.Equal(SignatureCallingConvention.VarArgs, defSignature.Header.CallingConvention);
Assert.Equal(1, defSignature.RequiredParameterCount);
Assert.Equal(new[] { "int32" }, defSignature.ParameterTypes);
int refCount = 0;
foreach (MemberReferenceHandle memberRefHandle in metadataReader.MemberReferences)
{
MemberReference memberRef = metadataReader.GetMemberReference(memberRefHandle);
if (metadataReader.StringComparer.Equals(memberRef.Name, "VarArgsCallee"))
{
Assert.Equal(MemberReferenceKind.Method, memberRef.GetKind());
MethodSignature<string> refSignature = memberRef.DecodeMethodSignature(provider, null);
Assert.Equal(SignatureCallingConvention.VarArgs, refSignature.Header.CallingConvention);
Assert.Equal(1, refSignature.RequiredParameterCount);
Assert.Equal(new[] { "int32", "bool", "string", "float64" }, refSignature.ParameterTypes);
refCount++;
}
}
Assert.Equal(1, refCount);
}
}
private static class VarArgsToDecode
{
public static void VarArgsCallee(int i, __arglist)
{
}
public static void VarArgsCaller()
{
VarArgsCallee(1, __arglist(true, "hello", 0.42));
}
}
// Test as much as we can with simple C# examples inline below.
[Fact]
public void SimpleSignatureProviderCoverage()
{
using (FileStream stream = File.OpenRead(typeof(SignaturesToDecode<>).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new DisassemblingTypeProvider();
TypeDefinitionHandle typeHandle = TestMetadataResolver.FindTestType(reader, typeof(SignaturesToDecode<>));
Assert.Equal("System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1", provider.GetTypeFromHandle(reader, genericContext: null, handle: typeHandle));
TypeDefinition type = reader.GetTypeDefinition(typeHandle);
Dictionary<string, string> expectedFields = GetExpectedFieldSignatures();
ImmutableArray<string> genericTypeParameters = type.GetGenericParameters().Select(h => reader.GetString(reader.GetGenericParameter(h).Name)).ToImmutableArray();
var genericTypeContext = new DisassemblingGenericContext(genericTypeParameters, ImmutableArray<string>.Empty);
foreach (var fieldHandle in type.GetFields())
{
FieldDefinition field = reader.GetFieldDefinition(fieldHandle);
string fieldName = reader.GetString(field.Name);
string expected;
Assert.True(expectedFields.TryGetValue(fieldName, out expected), "Unexpected field: " + fieldName);
Assert.Equal(expected, field.DecodeSignature(provider, genericTypeContext));
}
Dictionary<string, string> expectedMethods = GetExpectedMethodSignatures();
foreach (var methodHandle in type.GetMethods())
{
MethodDefinition method = reader.GetMethodDefinition(methodHandle);
ImmutableArray<string> genericMethodParameters = method.GetGenericParameters().Select(h => reader.GetString(reader.GetGenericParameter(h).Name)).ToImmutableArray();
var genericMethodContext = new DisassemblingGenericContext(genericTypeParameters, genericMethodParameters);
string methodName = reader.GetString(method.Name);
string expected;
Assert.True(expectedMethods.TryGetValue(methodName, out expected), "Unexpected method: " + methodName);
MethodSignature<string> signature = method.DecodeSignature(provider, genericMethodContext);
Assert.True(signature.Header.Kind == SignatureKind.Method);
if (methodName.StartsWith("Generic"))
{
Assert.Equal(1, signature.GenericParameterCount);
}
else
{
Assert.Equal(0, signature.GenericParameterCount);
}
Assert.True(signature.GenericParameterCount <= 1 && (methodName != "GenericMethodParameter" || signature.GenericParameterCount == 1));
Assert.Equal(expected, provider.GetFunctionPointerType(signature));
}
Dictionary<string, string> expectedProperties = GetExpectedPropertySignatures();
foreach (var propertyHandle in type.GetProperties())
{
PropertyDefinition property = reader.GetPropertyDefinition(propertyHandle);
string propertyName = reader.GetString(property.Name);
string expected;
Assert.True(expectedProperties.TryGetValue(propertyName, out expected), "Unexpected property: " + propertyName);
MethodSignature<string> signature = property.DecodeSignature(provider, genericTypeContext);
Assert.True(signature.Header.Kind == SignatureKind.Property);
Assert.Equal(expected, provider.GetFunctionPointerType(signature));
}
Dictionary<string, string> expectedEvents = GetExpectedEventSignatures();
foreach (var eventHandle in type.GetEvents())
{
EventDefinition @event = reader.GetEventDefinition(eventHandle);
string eventName = reader.GetString(@event.Name);
string expected;
Assert.True(expectedEvents.TryGetValue(eventName, out expected), "Unexpected event: " + eventName);
Assert.Equal(expected, provider.GetTypeFromHandle(reader, genericTypeContext, @event.Type));
}
Assert.Equal("[System.Collections]System.Collections.Generic.List`1<!T>", provider.GetTypeFromHandle(reader, genericTypeContext, handle: type.BaseType));
}
}
public unsafe class SignaturesToDecode<T> : List<T>
{
public sbyte SByte;
public byte Byte;
public short Int16;
public ushort UInt16;
public int Int32;
public uint UInt32;
public long Int64;
public ulong UInt64;
public string String;
public object Object;
public float Single;
public double Double;
public IntPtr IntPtr;
public UIntPtr UIntPtr;
public bool Boolean;
public char Char;
public volatile int ModifiedType;
public int* Pointer;
public int[] SZArray;
public int[,] Array;
public void ByReference(ref int i) { }
public T GenericTypeParameter;
public U GenericMethodParameter<U>() { throw null; }
public List<int> GenericInstantiation;
public struct Nested { }
public Nested Property { get { throw null; } }
public event EventHandler<EventArgs> Event { add { } remove { } }
}
[Fact]
public void PinnedAndUnpinnedLocals()
{
using (FileStream stream = File.OpenRead(typeof(PinnedAndUnpinnedLocalsToDecode).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new DisassemblingTypeProvider();
TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, typeof(PinnedAndUnpinnedLocalsToDecode));
TypeDefinition typeDef = reader.GetTypeDefinition(typeDefHandle);
MethodDefinition methodDef = reader.GetMethodDefinition(typeDef.GetMethods().First());
Assert.Equal("DoSomething", reader.GetString(methodDef.Name));
MethodBodyBlock body = peReader.GetMethodBody(methodDef.RelativeVirtualAddress);
StandaloneSignature localSignature = reader.GetStandaloneSignature(body.LocalSignature);
ImmutableArray<string> localTypes = localSignature.DecodeLocalSignature(provider, genericContext: null);
// Compiler can generate temporaries or re-order so just check the ones we expect are there.
// (They could get optimized away too. If that happens in practice, change this test to use hard-coded signatures.)
Assert.Contains("uint8[] pinned", localTypes);
Assert.Contains("uint8[]", localTypes);
}
}
public static class PinnedAndUnpinnedLocalsToDecode
{
public static unsafe int DoSomething()
{
byte[] bytes = new byte[] { 1, 2, 3 };
fixed (byte* bytePtr = bytes)
{
return *bytePtr;
}
}
}
[Fact]
public void WrongSignatureType()
{
using (FileStream stream = File.OpenRead(typeof(VarArgsToDecode).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new DisassemblingTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, reader, genericContext: null);
BlobReader fieldSignature = reader.GetBlobReader(reader.GetFieldDefinition(MetadataTokens.FieldDefinitionHandle(1)).Signature);
BlobReader methodSignature = reader.GetBlobReader(reader.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).Signature);
BlobReader propertySignature = reader.GetBlobReader(reader.GetPropertyDefinition(MetadataTokens.PropertyDefinitionHandle(1)).Signature);
Assert.Throws<BadImageFormatException>(() => decoder.DecodeMethodSignature(ref fieldSignature));
Assert.Throws<BadImageFormatException>(() => decoder.DecodeFieldSignature(ref methodSignature));
Assert.Throws<BadImageFormatException>(() => decoder.DecodeLocalSignature(ref propertySignature));
}
}
private static Dictionary<string, string> GetExpectedFieldSignatures()
{
// Field name -> signature
return new Dictionary<string, string>()
{
{ "SByte", "int8" },
{ "Byte", "uint8" },
{ "Int16", "int16" },
{ "UInt16", "uint16" },
{ "Int32", "int32" },
{ "UInt32", "uint32" },
{ "Int64", "int64" },
{ "UInt64", "uint64" },
{ "String", "string" },
{ "Object", "object" },
{ "Single", "float32" },
{ "Double", "float64" },
{ "IntPtr", "native int" },
{ "UIntPtr", "native uint" },
{ "Boolean", "bool" },
{ "Char", "char" },
{ "ModifiedType", "int32 modreq([System.Runtime]System.Runtime.CompilerServices.IsVolatile)" },
{ "Pointer", "int32*" },
{ "SZArray", "int32[]" },
{ "Array", "int32[0...,0...]" },
{ "GenericTypeParameter", "!T" },
{ "GenericInstantiation", "[System.Collections]System.Collections.Generic.List`1<int32>" },
};
}
private static Dictionary<string, string> GetExpectedMethodSignatures()
{
// method name -> signature
return new Dictionary<string, string>()
{
{ "ByReference", "method void *(int32&)" },
{ "GenericMethodParameter", "method !!U *()" },
{ ".ctor", "method void *()" },
{ "get_Property", "method System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1/Nested<!T> *()" },
{ "add_Event", "method void *([System.Runtime]System.EventHandler`1<[System.Runtime]System.EventArgs>)" },
{ "remove_Event", "method void *([System.Runtime]System.EventHandler`1<[System.Runtime]System.EventArgs>)" },
};
}
private static Dictionary<string, string> GetExpectedPropertySignatures()
{
// field name -> signature
return new Dictionary<string, string>()
{
{ "Property", "method System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1/Nested<!T> *()" },
};
}
private static Dictionary<string, string> GetExpectedEventSignatures()
{
// event name -> signature
return new Dictionary<string, string>()
{
{ "Event", "[System.Runtime]System.EventHandler`1<[System.Runtime]System.EventArgs>" },
};
}
[Theory]
[InlineData(new byte[] { 0x12 /*CLASS*/, 0x06 /*encoded type spec*/ })] // not def or ref
[InlineData(new byte[] { 0x11 /*VALUETYPE*/, 0x06 /*encoded type spec*/})] // not def or ref
[InlineData(new byte[] { 0x60 })] // Bad type code
public unsafe void BadTypeSignature(byte[] signature)
{
fixed (byte* bytes = signature)
{
BlobReader reader = new BlobReader(bytes, signature.Length);
Assert.Throws<BadImageFormatException>(() => new SignatureDecoder<string, DisassemblingGenericContext>(new OpaqueTokenTypeProvider(), metadataReader: null, genericContext: null).DecodeType(ref reader));
}
}
[Theory]
[InlineData("method void *()", new byte[] { 0x1B /*FNPTR*/, 0 /*default calling convention*/, 0 /*parameters count*/, 0x1 /* return type (VOID)*/ })]
[InlineData("int32[...]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 1 /*rank*/, 0 /*sizes*/, 0 /*lower bounds*/ })]
[InlineData("int32[...,...,...]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 3 /*rank*/, 0 /*sizes*/, 0/*lower bounds*/ })]
[InlineData("int32[-1...1]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 1 /*rank*/, 1 /*sizes*/, 3 /*size*/, 1 /*lower bounds*/, 0x7F /*lower bound (compressed -1)*/ })]
[InlineData("int32[1...]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 1 /*rank*/, 0 /*sizes*/, 1 /*lower bounds*/, 2 /*lower bound (compressed +1)*/ })]
public unsafe void ExoticTypeSignature(string expected, byte[] signature)
{
fixed (byte* bytes = signature)
{
BlobReader reader = new BlobReader(bytes, signature.Length);
Assert.Equal(expected, new SignatureDecoder<string, DisassemblingGenericContext>(new OpaqueTokenTypeProvider(), metadataReader: null, genericContext: null).DecodeType(ref reader));
}
}
[Fact]
public void ProviderCannotBeNull()
{
AssertExtensions.Throws<ArgumentNullException>("provider", () => new SignatureDecoder<int, object>(provider: null, metadataReader: null, genericContext: null));
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using Moq;
using NUnit.Framework;
using SquishIt.Framework.CSS;
using SquishIt.Framework.Minifiers.CSS;
using SquishIt.Framework.Files;
using SquishIt.Framework.Renderers;
using SquishIt.Framework.Resolvers;
using SquishIt.Framework.Utilities;
using SquishIt.Tests.Helpers;
using SquishIt.Tests.Stubs;
using HttpContext = SquishIt.AspNet.HttpContext;
namespace SquishIt.Tests
{
[TestFixture]
public class CSSBundleTests : ConfigurationEstablishingTest
{
string css = TestUtilities.NormalizeLineEndings(@" li {
margin-bottom:0.1em;
margin-left:0;
margin-top:0.1em;
}
th {
font-weight:normal;
vertical-align:bottom;
}
.FloatRight {
float:right;
}
.FloatLeft {
float:left;
}");
string minifiedCss = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}";
string css2 = TestUtilities.NormalizeLineEndings(@" li {
margin-bottom:0.1em;
margin-left:0;
margin-top:0.1em;
}
th {
font-weight:normal;
vertical-align:bottom;
}");
string minifiedCss2 =
"li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}";
CSSBundleFactory cssBundleFactory;
IHasher stubHasher;
[SetUp]
public void Setup()
{
stubHasher = new StubHasher("hash");
cssBundleFactory = new CSSBundleFactory()
.WithHasher(stubHasher);
}
[Test]
public void CanRenderEmptyBundle_WithHashInFilename()
{
cssBundleFactory.Create().Render("~/css/output_#.css");
}
[Test]
public void CanBundleCss()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]);
}
[Test]
public void CanBundleCssWithMinifiedFiles()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.AddMinified(secondPath)
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
var output = TestUtilities.NormalizeLineEndings(cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]);
Assert.IsTrue(output.StartsWith(minifiedCss));
Assert.IsTrue(output.EndsWith(css2));
}
[Test]
public void CanBundleCssWithMinifiedStrings()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
string tag = cssBundle
.AddString(css)
.AddMinifiedString(css2)
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
var output = TestUtilities.NormalizeLineEndings(cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]);
Assert.IsTrue(output.StartsWith(minifiedCss));
Assert.IsTrue(output.EndsWith(css2));
}
[Test]
public void CanBundleCssWithMinifiedDirectories()
{
var path = Guid.NewGuid().ToString();
var path2 = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css");
var file2 = TestUtilities.PrepareRelativePath(path2 + "\\file2.css");
var resolver = new Mock<IResolver>(MockBehavior.Strict);
resolver.Setup(r => r.IsDirectory(It.IsAny<string>())).Returns(true);
resolver.Setup(r =>
r.ResolveFolder(TestUtilities.PrepareRelativePath(path), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>()))
.Returns(new[] { file1 });
resolver.Setup(r =>
r.ResolveFolder(TestUtilities.PrepareRelativePath(path2), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>()))
.Returns(new[] { file2 });
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, resolver.Object))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, css2);
frf.SetContentsForFile(file2, css);
var writerFactory = new StubFileWriterFactory();
var tag = cssBundleFactory.WithDebuggingEnabled(false)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.AddDirectory(path)
.AddMinifiedDirectory(path2)
.Render("~/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hashy\" />", tag);
var content = writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.css")];
Assert.True(content.StartsWith(minifiedCss2));
Assert.True(content.EndsWith(css));
}
}
[Test]
public void CanBundleCssSpecifyingOutputLinkPath()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithOutputBaseHref("http//subdomain.domain.com")
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http//subdomain.domain.com/css/output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]);
}
[Test]
public void CanBundleCssVaryingOutputBaseHrefRendersIndependentUrl()
{
//Verify that depending on basehref, we get independently cached and returned URLs
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithOutputBaseHref("http://subdomain.domain.com")
.Render("/css/output.css");
CSSBundle cssBundleNoBaseHref = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
string tagNoBaseHref = cssBundleNoBaseHref
.Add(firstPath)
.Add(secondPath)
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://subdomain.domain.com/css/output.css?r=hash\" />", tag);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tagNoBaseHref);
}
[Test]
public void RenderNamedUsesOutputBaseHref()
{
//Verify that depending on basehref, we get independantly cached and returned URLs
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
cssBundleFactory.FileReaderFactory.SetContents(css);
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
cssBundle
.Add(firstPath)
.Add(secondPath)
.WithOutputBaseHref("http://subdomain.domain.com")
.AsNamed("leBundle", "/css/output.css");
var tag = cssBundleFactory
.WithDebuggingEnabled(false)
.Create()
.WithOutputBaseHref("http://subdomain.domain.com")
.RenderNamed("leBundle");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://subdomain.domain.com/css/output.css?r=hash\" />", tag);
}
[Test]
public void CanBundleCssWithQueryStringParameter()
{
CSSBundle cssBundle = cssBundleFactory
.WithContents(css)
.WithDebuggingEnabled(false)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.Render("/css/output_querystring.css?v=1");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_querystring.css?v=1&r=hash\" />", tag);
}
[Test]
public void CanBundleCssWithoutRevisionHash()
{
CSSBundle cssBundle = cssBundleFactory
.WithContents(css)
.WithDebuggingEnabled(false)
.Create();
string tag = cssBundle
.Add("/css/first.css")
.Add("/css/second.css")
.WithoutRevisionHash()
.Render("/css/output_querystring.css?v=1");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_querystring.css?v=1\" />", tag);
}
[Test]
public void CanBundleCssWithMediaAttribute()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithAttribute("media", "screen")
.Render("/css/css_with_media_output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/css_with_media_output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}"
, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\css_with_media_output.css")]);
}
[Test]
public void CanBundleCssWithRemote()
{
//this is rendering tag correctly but incorrectly(?) merging both files
using(new ResolverFactoryScope(typeof(HttpResolver).FullName, StubResolver.ForFile("http://www.someurl.com/css/first.css")))
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
string tag = cssBundle
.AddRemote("/css/first.css", "http://www.someurl.com/css/first.css")
.Add("/css/second.css")
.Render("/css/output_remote.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.someurl.com/css/first.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_remote.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_remote.css")]);
}
}
[Test]
public void CanBundleCssWithEmbeddedResource()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
string tag = cssBundle
.AddEmbeddedResource("/css/first.css", "SquishIt.Tests://EmbeddedResource.Embedded.css")
.Render("/css/output_embedded.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_embedded.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_embedded.css")]);
}
[Test]
public void CanBundleCssWithEmbeddedResourceAndPathRewrites()
{
var cssWithRelativePath = @".lightbox {
background:url(images/button-loader.gif) #ccc;
}";
var expectedCss = @".lightbox{background:url(css/images/button-loader.gif) #ccc}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(cssWithRelativePath)
.Create();
string tag = cssBundle
.AddEmbeddedResource("/css/first.css", "SquishIt.Tests://EmbeddedResource.Embedded.css")
.Render("/output_embedded.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/output_embedded.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(expectedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"output_embedded.css")]);
}
[Test]
public void CanBundleCssWithRootEmbeddedResource()
{
//this only tests that the resource can be resolved
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
string tag = cssBundle
.AddRootEmbeddedResource("~/css/test.css", "SquishIt.Tests://RootEmbedded.css")
.Render("/css/output_embedded.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_embedded.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_embedded.css")]);
}
[Test]
public void CanDebugBundleCssWithEmbedded()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag = cssBundle
.AddEmbeddedResource("/css/first.css", "SquishIt.Tests://EmbeddedResource.Embedded.css")
.Render("/css/output_embedded.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
}
[Test]
public void CanCreateNamedBundle()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
cssBundle
.Add("~/css/temp.css")
.AsNamed("Test", "~/css/output.css");
string tag = cssBundle.RenderNamed("Test");
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/output.css?r=hash\" />", tag);
}
[Test]
public void CanCreateNamedBundleWithDebug()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
cssBundle
.Add("~/css/temp1.css")
.Add("~/css/temp2.css")
.AsNamed("TestWithDebug", "~/css/output.css");
string tag = cssBundle.RenderNamed("TestWithDebug");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp1.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp2.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateNamedBundleWithMediaAttribute()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
cssBundle
.Add("~/css/temp.css")
.WithAttribute("media", "screen")
.AsNamed("TestWithMedia", "~/css/output.css");
string tag = cssBundle.RenderNamed("TestWithMedia");
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"css/output.css?r=hash\" />", tag);
}
[Test]
public void CanRenderDebugTags()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag = cssBundle
.Add("/css/first.css")
.Add("/css/second.css")
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanRenderPreprocessedDebugTags()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag = cssBundle
.WithPreprocessor(new StubStylePreprocessor())
.Add("~/first.style.css")
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"first.style.css.squishit.debug.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanRenderDebugTagsTwice()
{
CSSBundle cssBundle1 = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
CSSBundle cssBundle2 = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag1 = cssBundle1
.Add("/css/first.css")
.Add("/css/second.css")
.Render("/css/output.css");
string tag2 = cssBundle2
.Add("/css/first.css")
.Add("/css/second.css")
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag1));
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag2));
}
[Test]
public void CanRenderDebugTagsWithMediaAttribute()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag = cssBundle
.Add("/css/first.css")
.Add("/css/second.css")
.WithAttribute("media", "screen")
.Render("/css/output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanBundleCssWithCompressorAttribute()
{
var cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
var tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithMinifier<YuiMinifier>()
.Render("/css/css_with_compressor_output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/css_with_compressor_output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}"
, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\css_with_compressor_output.css")]);
}
[Test]
public void CanBundleCssWithNullCompressorAttribute()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithMinifier<NullMinifier>()
.Render("/css/css_with_null_compressor_output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/css_with_null_compressor_output.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(css + "\n" + css2 + "\n", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\css_with_null_compressor_output.css")]);
}
[Test]
public void CanBundleCssWithCompressorInstance()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithMinifier<MsMinifier>()
.Render("/css/compressor_instance.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/compressor_instance.css?r=hash\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}"
, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\compressor_instance.css")]);
}
[Test]
public void CanRenderOnlyIfFileMissing()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
cssBundleFactory.FileReaderFactory.SetFileExists(false);
cssBundle
.Add("/css/first.css")
.Render("~/css/can_render_only_if_file_missing.css");
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_render_only_if_file_missing.css")]);
cssBundleFactory.FileReaderFactory.SetContents(css2);
cssBundleFactory.FileReaderFactory.SetFileExists(true);
cssBundle.ClearCache();
cssBundle
.Add("/css/first.css")
.RenderOnlyIfOutputFileMissing()
.Render("~/css/can_render_only_if_file_missing.css");
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_render_only_if_file_missing.css")]);
}
[Test]
public void CanRerenderFiles()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
cssBundleFactory.FileReaderFactory.SetFileExists(false);
cssBundle.ClearCache();
cssBundle
.Add("/css/first.css")
.Render("~/css/can_rerender_files.css");
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_rerender_files.css")]);
CSSBundle cssBundle2 = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css2)
.Create();
cssBundleFactory.FileReaderFactory.SetFileExists(true);
cssBundleFactory.FileWriterFactory.Files.Clear();
cssBundle.ClearCache();
cssBundle2
.Add("/css/first.css")
.Render("~/css/can_rerender_files.css");
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_rerender_files.css")]);
}
[Test]
public void CanRenderCssFileWithHashInFileName()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.Render("/css/output_#.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_hash.css\" />", tag);
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_hash.css")]);
}
[Test]
public void CanRenderCssFileWithUnprocessedImportStatement()
{
string importCss =
@"
@import url(""/css/other.css"");
#header {
color: #4D926F;
}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(importCss)
.Create();
cssBundleFactory.FileReaderFactory.SetContents(importCss);
cssBundleFactory.FileReaderFactory.SetContentsForFile(@"C:\css\other.css", "#footer{color:#ffffff}");
cssBundle
.Add("/css/first.css")
.Render("/css/unprocessed_import.css");
Assert.AreEqual(@"@import url(""/css/other.css"");#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\unprocessed_import.css")]);
}
[Test]
public void CanRenderCssFileWithImportStatement()
{
string importCss =
@"
@import url(""/css/other.css"");
#header {
color: #4D926F;
}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(importCss)
.Create();
cssBundleFactory.FileReaderFactory.SetContents(importCss);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}");
cssBundle
.Add("/css/first.css")
.ProcessImports()
.Render("/css/processed_import.css");
Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import.css")]);
}
[Test]
public void CanRenderCssFileWithRelativeImportStatement()
{
string importCss =
@"
@import url(""other.css"");
#header {
color: #4D926F;
}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(importCss)
.Create();
cssBundleFactory.FileReaderFactory.SetContents(importCss);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}");
cssBundle
.Add("/css/first.css")
.ProcessImports()
.Render("/css/processed_import.css");
Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import.css")]);
}
[Test]
public void CanRenderCssFileWithImportStatementNoQuotes()
{
string importCss =
@"
@import url(/css/other.css);
#header {
color: #4D926F;
}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(importCss)
.Create();
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}");
cssBundle
.Add("/css/first.css")
.ProcessImports()
.Render("/css/processed_import_noquotes.css");
Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import_noquotes.css")]);
}
[Test]
public void CanRenderCssFileWithImportStatementSingleQuotes()
{
string importCss =
@"
@import url('/css/other.css');
#header {
color: #4D926F;
}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(importCss)
.Create();
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}");
cssBundle
.Add("/css/first.css")
.ProcessImports()
.Render("/css/processed_import_singlequotes.css");
Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import_singlequotes.css")]);
}
[Test]
public void CanRenderCssFileWithImportStatementUppercase()
{
string importCss =
@"
@IMPORT URL(/css/other.css);
#header {
color: #4D926F;
}";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(importCss)
.Create();
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}");
cssBundle
.Add("/css/first.css")
.ProcessImports()
.Render("/css/processed_import_uppercase.css");
Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import_uppercase.css")]);
}
[Test]
public void CanCreateNamedBundleWithForceRelease()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
cssBundle
.Add("~/css/temp.css")
.ForceRelease()
.AsNamed("TestForce", "~/css/named_withforce.css");
string tag = cssBundle.RenderNamed("TestForce");
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\named_withforce.css")]);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/named_withforce.css?r=hash\" />", tag);
}
[Test]
public void CanBundleCssWithArbitraryAttributes()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
var firstPath = "first.css";
var secondPath = "second.css";
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css);
cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2);
string tag = cssBundle
.Add(firstPath)
.Add(secondPath)
.WithAttribute("media", "screen")
.WithAttribute("test", "other")
.Render("/css/css_with_attribute_output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" test=\"other\" href=\"/css/css_with_attribute_output.css?r=hash\" />", tag);
}
[Test]
public void CanBundleDebugCssWithArbitraryAttributes()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag = cssBundle
.Add("/css/first.css")
.Add("/css/second.css")
.WithAttribute("media", "screen")
.WithAttribute("test", "other")
.Render("/css/css_with_debugattribute_output.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" test=\"other\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" test=\"other\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateCachedBundle()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
string tag = cssBundle
.Add("~/css/temp.css")
.AsCached("TestCached", "~/static/css/TestCached.css");
string contents = cssBundle.RenderCached("TestCached");
Assert.AreEqual(minifiedCss, contents);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"static/css/TestCached.css?r=hash\" />", tag);
}
[Test]
public void CanCreateCachedBundleAssetTag()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
cssBundle
.Add("~/css/temp.css")
.AsCached("TestCached", "~/static/css/TestCached.css");
string contents = cssBundle.RenderCached("TestCached");
cssBundle.ClearCache();
string tag = cssBundle.RenderCachedAssetTag("TestCached");
Assert.AreEqual(minifiedCss, contents);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"static/css/TestCached.css?r=hash\" />", tag);
}
[Test]
public void CanCreateCachedBundleAssetTag_When_Debugging()
{
var cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.Create();
cssBundle
.Add("~/css/temp.css")
.AsCached("TestCached", "~/static/css/TestCached.css");
var tag = cssBundle.RenderCachedAssetTag("TestCached");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateCachedBundleInDebugMode()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
string tag = cssBundle
.Add("~/css/temp.css")
.AsCached("TestCached", "~/static/css/TestCached.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp.css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanBundleDirectoryContentsInDebug()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, css2);
frf.SetContentsForFile(file2, css);
var writerFactory = new StubFileWriterFactory();
var tag = cssBundleFactory.WithDebuggingEnabled(true)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.Create()
.Add(path)
.Render("~/output.css");
var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file1.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file2.css\" />\n", path);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void CanBundleDirectoryContentsInDebug_Ignores_Duplicates()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, css2);
frf.SetContentsForFile(file2, css);
var writerFactory = new StubFileWriterFactory();
var tag = cssBundleFactory.WithDebuggingEnabled(true)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.Create()
.Add(path)
.Render("~/output.css");
var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file1.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file2.css\" />\n", path);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void CanBundleDirectoryContentsInDebug_Writes_And_Ignores_Preprocessed_Debug_Files()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.style.css");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file1.style.squishit.debug.css");
var content = "some stuffs";
var preprocessor = new StubStylePreprocessor();
using(new StylePreprocessorScope<StubStylePreprocessor>(preprocessor))
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, content);
var writerFactory = new StubFileWriterFactory();
var tag = cssBundleFactory.WithDebuggingEnabled(true)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.Create()
.Add(path)
.Render("~/output.css");
var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file1.style.css.squishit.debug.css\" />\n", path);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
Assert.AreEqual(content, preprocessor.CalledWith);
Assert.AreEqual(1, writerFactory.Files.Count);
Assert.AreEqual("styley", writerFactory.Files[file1 + ".squishit.debug.css"]);
}
}
[Test]
public void CanBundleDirectoryContentsInRelease()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, css2);
frf.SetContentsForFile(file2, css);
var writerFactory = new StubFileWriterFactory();
var tag = cssBundleFactory.WithDebuggingEnabled(false)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.Create()
.Add(path)
.Render("~/output.css");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, tag);
var combined = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}";
Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.css")]);
}
}
[Test]
public void CanBundleDirectoryContentsInRelease_Ignores_Duplicates()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, css2);
frf.SetContentsForFile(file2, css);
var writerFactory = new StubFileWriterFactory();
var tag = cssBundleFactory.WithDebuggingEnabled(false)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.Create()
.Add(path)
.Add(file1)
.Render("~/output.css");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, tag);
var combined = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}";
Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.css")]);
}
}
[Test]
public void CanRenderArbitraryStringsInDebug()
{
var css2Format = "{0}{1}";
var hrColor = "hr {color:sienna;}";
var p = "p {margin-left:20px;}";
var tag = new CSSBundleFactory()
.WithDebuggingEnabled(true)
.Create()
.AddString(css)
.AddString(css2Format, new[] { hrColor, p })
.Render("doesn't matter where...");
var expectedTag = string.Format("<style type=\"text/css\">{0}</style>\n<style type=\"text/css\">{1}</style>\n", css, string.Format(css2Format, hrColor, p));
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanMaintainOrderBetweenArbitraryAndFileAssetsInRelease()
{
var file1 = "somefile.css";
var file2 = "anotherfile.css";
var arbitraryCss = ".someClass { color:red }";
var minifiedArbitraryCss = ".someClass{color:#f00}";
var readerFactory = new StubFileReaderFactory();
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file1), css);
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file2), css2);
var writerFactory = new StubFileWriterFactory();
var tag = new CSSBundleFactory()
.WithFileReaderFactory(readerFactory)
.WithFileWriterFactory(writerFactory)
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.AddString(arbitraryCss)
.Add(file2)
.Render("test.css");
var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css?r=hash\" />");
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
var combined = minifiedCss + minifiedArbitraryCss + minifiedCss2;
Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"test.css")]);
}
[Test]
public void CanMaintainOrderBetweenArbitraryAndFileAssetsInDebug()
{
var file1 = "somefile.css";
var file2 = "anotherfile.css";
var arbitraryCss = ".someClass { color:red }";
var readerFactory = new StubFileReaderFactory();
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file1), css);
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file2), css2);
var writerFactory = new StubFileWriterFactory();
var tag = new CSSBundleFactory()
.WithFileReaderFactory(readerFactory)
.WithFileWriterFactory(writerFactory)
.WithDebuggingEnabled(true)
.Create()
.Add(file1)
.AddString(arbitraryCss)
.Add(file2)
.Render("test.css");
var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"somefile.css\" />\n<style type=\"text/css\">{0}</style>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anotherfile.css\" />\n"
, arbitraryCss);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanRenderArbitraryStringsInDebugWithoutType()
{
var css2Format = "{0}{1}";
var hrColor = "hr {color:sienna;}";
var p = "p {margin-left:20px;}";
var tag = new CSSBundleFactory()
.WithDebuggingEnabled(true)
.Create()
.AddString(css)
.AddString(css2Format, new[] { hrColor, p })
.WithoutTypeAttribute()
.Render("doesn't matter where...");
var expectedTag = string.Format("<style>{0}</style>\n<style>{1}</style>\n", css, string.Format(css2Format, hrColor, p));
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void DoesNotRenderDuplicateArbitraryStringsInDebug()
{
var tag = new CSSBundleFactory()
.WithDebuggingEnabled(true)
.Create()
.AddString(css)
.AddString(css)
.Render("doesn't matter where...");
var expectedTag = string.Format("<style type=\"text/css\">{0}</style>\n", css);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanBundleArbitraryContentsInRelease()
{
var css2Format = "{0}{1}";
var hrColor = "hr {color:sienna;}";
var p = "p {margin-left:20px;}";
var writerFactory = new StubFileWriterFactory();
var tag = new CSSBundleFactory()
.WithDebuggingEnabled(false)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.AddString(css)
.AddString(css2Format, new[] { hrColor, p })
.Render("~/output.css");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hashy\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
var minifiedScript = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}hr{color:#a0522d}p{margin-left:20px}";
Assert.AreEqual(minifiedScript, writerFactory.Files[TestUtilities.PrepareRelativePath("output.css")]);
}
[Test]
public void PathRewritingDoesNotAffectClassesNamedUrl()
{
string css =
@"
a.url {
color: #4D926F;
}
";
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
cssBundle
.Add("~/css/something/test.css")
.Render("~/css/output_rewriting_url.css");
string contents =
cssBundleFactory.FileWriterFactory.Files[
TestUtilities.PrepareRelativePath(@"css\output_rewriting_url.css")];
Assert.AreEqual("a.url{color:#4d926f}", contents);
}
[Test]
public void CanUseArbitraryReleaseFileRenderer()
{
var renderer = new Mock<IRenderer>();
var content = "content";
cssBundleFactory
.WithDebuggingEnabled(false)
.Create()
.WithReleaseFileRenderer(renderer.Object)
.AddString(content)
.Render("test.css");
renderer.Verify(r => r.Render(content, TestUtilities.PrepareRelativePath("test.css")));
}
[Test]
public void CanIgnoreArbitraryReleaseFileRendererIfDebugging()
{
var renderer = new Mock<IRenderer>(MockBehavior.Strict);
var content = "content";
cssBundleFactory
.WithDebuggingEnabled(true)
.Create()
.WithReleaseFileRenderer(renderer.Object)
.AddString(content)
.Render("test.css");
renderer.VerifyAll();
}
[Test]
public void CanIgnoreArbitraryReleaseRendererInDebug()
{
var renderer = new Mock<IRenderer>();
var content = "content";
cssBundleFactory
.WithDebuggingEnabled(true)
.Create()
.WithReleaseFileRenderer(renderer.Object)
.AddString(content)
.Render("test.css");
renderer.VerifyAll();
}
[Test]
public void CanIncludeDynamicContentInDebug()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.Url).Returns(new Uri("http://example.com"));
context.SetupGet(c => c.Request).Returns(request.Object);
var bundle = cssBundleFactory
.WithDebuggingEnabled(true)
.Create();
using(new HttpContextScope(context.Object))
{
bundle.AddDynamic("/some/dynamic/css");
}
var tag = bundle.Render("~/combined_#.css");
Assert.AreEqual(0, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/some/dynamic/css\" />\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanIncludeDynamicContentInRelease()
{
//this doesn't really test the nitty-gritty details (http resolver, download etc...) but its a start
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.Url).Returns(new Uri("http://example.com"));
context.SetupGet(c => c.Request).Returns(request.Object);
var bundle = cssBundleFactory
.WithContents(css)
.WithDebuggingEnabled(false)
.Create();
using(new HttpContextScope(context.Object))
{
//some/dynamic/css started returning 404's
bundle.AddDynamic("/");
}
var tag = bundle.Render("~/combined.css");
Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath("combined.css")]);
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"combined.css?r=hash\" />", tag);
}
[Test]
public void RenderRelease_OmitsRenderedTag_IfOnlyRemoteAssets()
{
//this is rendering tag correctly but incorrectly(?) merging both files
using(new ResolverFactoryScope(typeof(Framework.Resolvers.HttpResolver).FullName, StubResolver.ForFile("http://www.someurl.com/css/first.css")))
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
string tag = cssBundle
.ForceRelease()
.AddRemote("/css/first.css", "http://www.someurl.com/css/first.css")
.Render("/css/output_remote.css");
Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.someurl.com/css/first.css\" />", tag);
Assert.AreEqual(0, cssBundleFactory.FileWriterFactory.Files.Count);
}
}
[Test]
public void CanRenderDistinctBundlesIfSameOutputButDifferentFileNames()
{
var hasher = new Hasher(new RetryableFileOpener());
CSSBundle cssBundle = cssBundleFactory
.WithHasher(hasher)
.WithDebuggingEnabled(false)
.Create();
CSSBundle cssBundle2 = cssBundleFactory
.WithHasher(hasher)
.WithDebuggingEnabled(false)
.Create();
cssBundleFactory.FileReaderFactory.SetContents(css);
string tag = cssBundle
.Add("/css/first.css")
.Render("/css/output#.css");
cssBundleFactory.FileReaderFactory.SetContents(css2);
string tag2 = cssBundle2
.Add("/css/second.css")
.Render("/css/output#.css");
Assert.AreNotEqual(tag, tag2);
}
[Test]
public void CanRenderDistinctBundlesIfSameOutputButDifferentArbitrary()
{
var hasher = new Hasher(new RetryableFileOpener());
CSSBundle cssBundle = cssBundleFactory
.WithHasher(hasher)
.WithDebuggingEnabled(false)
.Create();
CSSBundle cssBundle2 = cssBundleFactory
.WithHasher(hasher)
.WithDebuggingEnabled(false)
.Create();
string tag = cssBundle
.AddString(css)
.Render("/css/output#.css");
string tag2 = cssBundle2
.AddString(css2)
.Render("/css/output#.css");
Assert.AreNotEqual(tag, tag2);
}
[Test]
public void ForceDebugIf()
{
cssBundleFactory.FileReaderFactory.SetContents(css);
var file1 = "test.css";
var file2 = "anothertest.css";
Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true";
var nonDebugContext = new Mock<HttpContextBase>();
nonDebugContext.Setup(hcb => hcb.Request.ApplicationPath).Returns(string.Empty);
nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection());
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css"));
CSSBundle bundle;
using(new HttpContextScope(nonDebugContext.Object))
{
bundle = cssBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.Add(file2)
.ForceDebugIf(queryStringPredicate);
var tag = bundle.Render("~/output.css");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
var debugContext = new Mock<HttpContextBase>();
debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } });
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
debugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css"));
using(new HttpContextScope(debugContext.Object))
{
var tag = bundle.Render("~/output.css");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anothertest.css\" />\n";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(nonDebugContext.Object))
{
var tag = bundle.Render("~/output.css");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void ForceDebugIf_Named()
{
cssBundleFactory.FileReaderFactory.SetContents(css);
var file1 = "test.css";
var file2 = "anothertest.css";
Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true";
var debugContext = new Mock<HttpContextBase>();
debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } });
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
debugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css"));
var nonDebugContext = new Mock<HttpContextBase>();
nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection());
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css"));
using(new HttpContextScope(nonDebugContext.Object))
{
cssBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.Add(file2)
.ForceDebugIf(queryStringPredicate)
.AsNamed("test", "~/output.css");
var tag = cssBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(debugContext.Object))
{
var tag = cssBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anothertest.css\" />\n";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(nonDebugContext.Object))
{
var tag = cssBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void ForceDebugIf_Cached()
{
cssBundleFactory.FileReaderFactory.SetContents(css);
var file1 = "test.css";
var file2 = "anothertest.css";
Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true";
var debugContext = new Mock<HttpContextBase>();
debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } });
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
debugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css"));
var nonDebugContext = new Mock<HttpContextBase>();
nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection());
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css"));
using(new HttpContextScope(nonDebugContext.Object))
{
cssBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.Add(file2)
.ForceDebugIf(queryStringPredicate)
.AsCached("test", "~/output.css");
var tag = cssBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(debugContext.Object))
{
var tag = cssBundleFactory
.Create()
.RenderCachedAssetTag("test");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anothertest.css\" />\n";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(nonDebugContext.Object))
{
var tag = cssBundleFactory
.Create()
.RenderCachedAssetTag("test");
var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void CanRenderRawContent_Release()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(false)
.WithContents(css)
.Create();
var contents = cssBundle.Add("~/test/sample.js").RenderRawContent("testrelease");
Assert.AreEqual(minifiedCss, contents);
Assert.AreEqual(contents, cssBundleFactory.Create().RenderCachedRawContent("testrelease"));
}
[Test]
public void CanRenderRawContent_Debug()
{
CSSBundle cssBundle = cssBundleFactory
.WithDebuggingEnabled(true)
.WithContents(css)
.Create();
var contents = cssBundle.Add("~/test/sample.js").RenderRawContent("testdebug");
Assert.AreEqual(css, contents);
Assert.AreEqual(contents, cssBundleFactory.Create().RenderCachedRawContent("testdebug"));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class GetValuesIntTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
string[] vls; // Values array
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] GetValues() on empty collection
//
try
{
vls = nvc.GetValues(-1);
Assert.False(true, "Error, no exception");
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
try
{
vls = nvc.GetValues(0);
Assert.False(true, "Error, no exception");
}
catch (ArgumentException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
//
// [] GetValues() on collection filled with simple strings
//
cnt = nvc.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
//
for (int i = 0; i < len; i++)
{
vls = nvc.GetValues(i);
if (vls.Length != 1)
{
Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
}
if (String.Compare(vls[0], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, vls[0], values[i]));
}
}
//
// Intl strings
// [] GetValues() on collection filled with Intl strings
//
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]);
}
if (nvc.Count != (len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
}
for (int i = 0; i < len; i++)
{
//
vls = nvc.GetValues(i);
if (vls.Length != 1)
{
Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
}
if (String.Compare(vls[0], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[0], intlValues[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
//
vls = nvc.GetValues(i);
if (vls.Length != 1)
{
Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
}
if (String.Compare(vls[0], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[0], intlValues[i]));
}
if (!caseInsensitive && String.Compare(vls[0], intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
}
}
// [] GetValues() on filled collection - with multiple items with the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
string k1 = "hm1";
string exp = "";
string exp1 = "";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
nvc.Add(k1, "iTem" + i);
if (i < len - 1)
{
exp += "Value" + i + ",";
exp1 += "iTem" + i + ",";
}
else
{
exp += "Value" + i;
exp1 += "iTem" + i;
}
}
if (nvc.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
}
vls = nvc.GetValues(0);
if (vls.Length != len)
{
Assert.False(true, string.Format("Error, returned number of strings {0} instead of {1}", vls.Length, len));
}
for (int i = 0; i < len; i++)
{
if (String.Compare(vls[i], "Value" + i) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", vls[i], "Value" + i));
}
}
vls = nvc.GetValues(1);
if (vls.Length != len)
{
Assert.False(true, string.Format("Error, returned number of strings {0} instead of {1}", vls.Length, len));
}
for (int i = 0; i < len; i++)
{
if (String.Compare(vls[i], "iTem" + i) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", vls[i], "iTem" + i));
}
}
//
// [] GetValues(-1)
//
cnt = nvc.Count;
Assert.Throws<ArgumentOutOfRangeException>(() => { vls = nvc.GetValues(-1); });
//
// [] GetValues(count)
//
if (nvc.Count < 1)
{
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
}
cnt = nvc.Count;
Assert.Throws<ArgumentOutOfRangeException>(() => { vls = nvc.GetValues(cnt); });
//
// [] GetValues(count+1)
//
if (nvc.Count < 1)
{
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
}
cnt = nvc.Count;
Assert.Throws<ArgumentOutOfRangeException>(() => { vls = nvc.GetValues(cnt + 1); });
//
// [] GetValues(null)
// GetValues(null) - calls other overloaded version of GetValues - GetValues(string) - no exception
//
vls = nvc.GetValues(null);
if (vls != null)
{
Assert.False(true, "Error, returned non-null ");
}
}
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using Xunit;
using Should;
namespace AutoMapper.UnitTests
{
namespace ConditionalMapping
{
public class When_configuring_a_member_to_skip_based_on_the_property_value : AutoMapperSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.Condition(src => src.Value > 0));
});
}
[Fact]
public void Should_skip_the_mapping_when_the_condition_is_true()
{
var destination = Mapper.Map<Source, Destination>(new Source {Value = -1});
destination.Value.ShouldEqual(0);
}
[Fact]
public void Should_execute_the_mapping_when_the_condition_is_false()
{
var destination = Mapper.Map<Source, Destination>(new Source { Value = 7 });
destination.Value.ShouldEqual(7);
}
}
public class When_configuring_a_member_to_skip_based_on_the_property_value_with_custom_mapping : AutoMapperSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt =>
{
opt.Condition(src => src.Value > 0);
opt.ResolveUsing((Source src) =>
{
return 10;
});
});
});
}
[Fact]
public void Should_skip_the_mapping_when_the_condition_is_true()
{
var destination = Mapper.Map<Source, Destination>(new Source { Value = -1 });
destination.Value.ShouldEqual(0);
}
[Fact]
public void Should_execute_the_mapping_when_the_condition_is_false()
{
Mapper.Map<Source, Destination>(new Source { Value = 7 }).Value.ShouldEqual(10);
}
}
public class When_configuring_a_member_to_skip_based_on_the_property_metadata : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
[Skip]
public int Value2 { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForAllMembers(opt => opt.Condition(CustomCondition));
});
}
private static bool CustomCondition(ResolutionContext context)
{
return !context.PropertyMap.DestinationProperty.MemberInfo.GetCustomAttributes(true).Any(attr => attr is SkipAttribute);
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Value = 5, Value2 = 10});
}
[Fact]
public void Should_include_the_normal_members_by_default()
{
_destination.Value.ShouldEqual(5);
}
[Fact]
public void Should_skip_any_members_based_on_the_skip_condition()
{
_destination.Value2.ShouldEqual(default(int));
}
public class SkipAttribute : System.Attribute { }
}
#if !SILVERLIGHT
public class When_configuring_a_map_to_ignore_all_properties_with_an_inaccessible_setter : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Id { get; set; }
public string Title { get; set; }
public string CodeName { get; set; }
public string Nickname { get; set; }
public string ScreenName { get; set; }
}
public class Destination
{
private double _height;
public int Id { get; set; }
public virtual string Name { get; protected set; }
public string Title { get; internal set; }
public string CodeName { get; private set; }
public string Nickname { get; private set; }
public string ScreenName { get; private set; }
public int Age { get; private set; }
public double Height
{
get { return _height; }
}
public Destination()
{
_height = 60;
}
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.ScreenName, opt => opt.MapFrom(src => src.ScreenName))
.IgnoreAllPropertiesWithAnInaccessibleSetter()
.ForMember(dest => dest.Nickname, opt => opt.MapFrom(src => src.Nickname));
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Id = 5, CodeName = "007", Nickname = "Jimmy", ScreenName = "jbogard" });
}
[Fact]
public void Should_consider_the_configuration_valid_even_if_some_properties_with_an_inaccessible_setter_are_unmapped()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
[Fact]
public void Should_map_a_property_with_an_inaccessible_setter_if_a_specific_mapping_is_configured_after_the_ignore_method()
{
_destination.Nickname.ShouldEqual("Jimmy");
}
[Fact]
public void Should_not_map_a_property_with_an_inaccessible_setter_if_no_specific_mapping_is_configured_even_though_name_and_type_match()
{
_destination.CodeName.ShouldBeNull();
}
[Fact]
public void Should_not_map_a_property_with_no_public_setter_if_a_specific_mapping_is_configured_before_the_ignore_method()
{
_destination.ScreenName.ShouldBeNull();
}
}
public class When_configuring_a_reverse_map_to_ignore_all_source_properties_with_an_inaccessible_setter : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class Source
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Force { get; set; }
public string ReverseForce { get; private set; }
public string Respect { get; private set; }
public int Foo { get; private set; }
public int Bar { get; protected set; }
public void Initialize()
{
ReverseForce = "You With";
Respect = "R-E-S-P-E-C-T";
}
}
public class Destination
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsVisible { get; set; }
public string Force { get; private set; }
public string ReverseForce { get; set; }
public string Respect { get; set; }
public int Foz { get; private set; }
public int Baz { get; protected set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.IgnoreAllPropertiesWithAnInaccessibleSetter()
.ForMember(dest => dest.IsVisible, opt => opt.Ignore())
.ForMember(dest => dest.Force, opt => opt.MapFrom(src => src.Force))
.ReverseMap()
.IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
.ForMember(dest => dest.ReverseForce, opt => opt.MapFrom(src => src.ReverseForce))
.ForSourceMember(dest => dest.IsVisible, opt => opt.Ignore());
});
}
protected override void Because_of()
{
var source = new Source { Id = 5, Name = "Bob", Age = 35, Force = "With You" };
source.Initialize();
_destination = Mapper.Map<Source, Destination>(source);
_source = Mapper.Map<Destination, Source>(_destination);
}
[Fact]
public void Should_consider_the_configuration_valid_even_if_some_properties_with_an_inaccessible_setter_are_unmapped()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
[Fact]
public void Should_forward_and_reverse_map_a_property_that_is_accessible_on_both_source_and_destination()
{
_source.Name.ShouldEqual("Bob");
}
[Fact]
public void Should_forward_and_reverse_map_an_inaccessible_destination_property_if_a_mapping_is_defined()
{
_source.Force.ShouldEqual("With You");
}
[Fact]
public void Should_forward_and_reverse_map_an_inaccessible_source_property_if_a_mapping_is_defined()
{
_source.ReverseForce.ShouldEqual("You With");
}
[Fact]
public void Should_forward_and_reverse_map_an_inaccessible_source_property_even_if_a_mapping_is_not_defined()
{
_source.Respect.ShouldEqual("R-E-S-P-E-C-T"); // justification: if the mapping works one way, it should work in reverse
}
}
#endif
}
}
| |
/* ****************************************************************************
*
* 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.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using IServiceProvider = System.IServiceProvider;
using XSharpModel;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false)]
public class SolutionListenerForProjectReferenceUpdate : SolutionListener
{
#region ctor
public SolutionListenerForProjectReferenceUpdate(IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
#endregion
#region overridden methods
/// <summary>
/// Delete this project from the references of projects of this type, if it is found.
/// </summary>
/// <param name="hierarchy"></param>
/// <param name="removed"></param>
/// <returns></returns>
public override int OnBeforeCloseProject(IVsHierarchy hierarchy, int removed)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (removed != 0)
{
List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(hierarchy);
foreach(ProjectReferenceNode projectReference in projectReferences)
{
projectReference.Remove(false);
// Set back the remove state on the project refererence. The reason why we are doing this is that the OnBeforeUnloadProject immedaitely calls
// OnBeforeCloseProject, thus we would be deleting references when we should not. Unload should not remove references.
projectReference.CanRemoveReference = true;
}
}
return VSConstants.S_OK;
}
/// <summary>
/// Needs to update the dangling reference on projects that contain this hierarchy as project reference.
/// </summary>
/// <param name="stubHierarchy"></param>
/// <param name="realHierarchy"></param>
/// <returns></returns>
public override int OnAfterLoadProject(IVsHierarchy stubHierarchy, IVsHierarchy realHierarchy)
{
ThreadHelper.ThrowIfNotOnUIThread();
List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(realHierarchy);
// Refersh the project reference node. That should trigger the drawing of the normal project reference icon.
foreach(ProjectReferenceNode projectReference in projectReferences)
{
projectReference.CanRemoveReference = true;
projectReference.OnInvalidateItems(projectReference.Parent);
}
return VSConstants.S_OK;
}
public override int OnAfterRenameProject(IVsHierarchy hierarchy)
{
if(hierarchy == null)
{
return VSConstants.E_INVALIDARG;
}
ThreadHelper.ThrowIfNotOnUIThread();
try
{
List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(hierarchy);
// Collect data that is needed to initialize the new project reference node.
string projectRef;
ErrorHandler.ThrowOnFailure(this.Solution.GetProjrefOfProject(hierarchy, out projectRef));
object nameAsObject;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Name, out nameAsObject));
string projectName = (string)nameAsObject;
string projectPath = String.Empty;
IVsProject3 project = hierarchy as IVsProject3;
if(project != null)
{
ErrorHandler.ThrowOnFailure(project.GetMkDocument(VSConstants.VSITEMID_ROOT, out projectPath));
projectPath = Path.GetDirectoryName(projectPath);
}
// Remove and re add the node.
foreach(ProjectReferenceNode projectReference in projectReferences)
{
ProjectNode projectMgr = projectReference.ProjectMgr;
IReferenceContainer refContainer = projectMgr.GetReferenceContainer();
projectReference.Remove(false);
VSCOMPONENTSELECTORDATA selectorData = new VSCOMPONENTSELECTORDATA();
selectorData.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project;
selectorData.bstrTitle = projectName;
selectorData.bstrFile = projectPath;
selectorData.bstrProjRef = projectRef;
refContainer.AddReferenceFromSelectorData(selectorData);
}
}
catch(COMException e)
{
XSettings.LogException(e, "OnAfterRenameProject");
return e.ErrorCode;
}
return VSConstants.S_OK;
}
public override int OnBeforeUnloadProject(IVsHierarchy realHierarchy, IVsHierarchy stubHierarchy)
{
ThreadHelper.ThrowIfNotOnUIThread();
List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(realHierarchy);
// Refresh the project reference node. That should trigger the drawing of the dangling project reference icon.
foreach(ProjectReferenceNode projectReference in projectReferences)
{
projectReference.IsNodeValid = true;
projectReference.OnInvalidateItems(projectReference.Parent);
projectReference.CanRemoveReference = false;
projectReference.IsNodeValid = false;
projectReference.DropReferencedProjectCache();
}
return VSConstants.S_OK;
}
#endregion
#region helper methods
private List<ProjectReferenceNode> GetProjectReferencesContainingThisProject(IVsHierarchy inputHierarchy)
{
List<ProjectReferenceNode> projectReferences = new List<ProjectReferenceNode>();
if(this.Solution == null || inputHierarchy == null)
{
return projectReferences;
}
uint flags = (uint)(__VSENUMPROJFLAGS.EPF_ALLPROJECTS | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION);
Guid enumOnlyThisType = Guid.Empty;
IEnumHierarchies enumHierarchies = null;
ThreadHelper.ThrowIfNotOnUIThread();
ErrorHandler.ThrowOnFailure(this.Solution.GetProjectEnum(flags, ref enumOnlyThisType, out enumHierarchies));
Debug.Assert(enumHierarchies != null, "Could not get list of hierarchies in solution");
IVsHierarchy[] hierarchies = new IVsHierarchy[1];
uint fetched;
int returnValue = VSConstants.S_OK;
do
{
returnValue = enumHierarchies.Next(1, hierarchies, out fetched);
Debug.Assert(fetched <= 1, "We asked one project to be fetched VSCore gave more than one. We cannot handle that");
if(returnValue == VSConstants.S_OK && fetched == 1)
{
IVsHierarchy hierarchy = hierarchies[0];
Debug.Assert(hierarchy != null, "Could not retrieve a hierarchy");
IReferenceContainerProvider provider = hierarchy as IReferenceContainerProvider;
if(provider != null)
{
IReferenceContainer referenceContainer = provider.GetReferenceContainer();
Debug.Assert(referenceContainer != null, "Could not found the References virtual node");
ProjectReferenceNode projectReferenceNode = GetProjectReferenceOnNodeForHierarchy(referenceContainer.EnumReferences(), inputHierarchy);
if(projectReferenceNode != null)
{
projectReferences.Add(projectReferenceNode);
}
}
}
} while(returnValue == VSConstants.S_OK && fetched == 1);
return projectReferences;
}
private static ProjectReferenceNode GetProjectReferenceOnNodeForHierarchy(IList<ReferenceNode> references, IVsHierarchy inputHierarchy)
{
if(references == null)
{
return null;
}
ThreadHelper.ThrowIfNotOnUIThread();
Guid projectGuid;
inputHierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectGuid);
string canonicalName;
ThreadHelper.ThrowIfNotOnUIThread();
inputHierarchy.GetCanonicalName(VSConstants.VSITEMID_ROOT, out canonicalName);
foreach(ReferenceNode refNode in references)
{
ProjectReferenceNode projRefNode = refNode as ProjectReferenceNode;
if(projRefNode != null)
{
if(projRefNode.ReferencedProjectGuid == projectGuid)
{
return projRefNode;
}
// Try with canonical names, if the project that is removed is an unloaded project than the above criteria will not pass.
if(!String.IsNullOrEmpty(projRefNode.Url) && NativeMethods.IsSamePath(projRefNode.Url, canonicalName))
{
return projRefNode;
}
}
}
return null;
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComProduction.DCP.DS
{
public class PRO_ChangeCategoryDetailDS
{
public PRO_ChangeCategoryDetailDS()
{
}
private const string THIS = "PCSComProduction.DCP.DS.DS.PRO_ChangeCategoryDetailDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to PRO_ChangeCategoryDetail
/// </Description>
/// <Inputs>
/// PRO_ChangeCategoryDetailVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, September 07, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
PRO_ChangeCategoryDetailVO objObject = (PRO_ChangeCategoryDetailVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO PRO_ChangeCategoryDetail("
+ PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ","
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD + ")"
+ "VALUES(?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ChangeCategoryDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_ChangeCategoryDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD].Value = objObject.ChangeCategoryMasterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from PRO_ChangeCategoryDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + PRO_ChangeCategoryDetailTable.TABLE_NAME + " WHERE " + "ChangeCategoryDetailID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from PRO_ChangeCategoryDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// PRO_ChangeCategoryDetailVO
/// </Outputs>
/// <Returns>
/// PRO_ChangeCategoryDetailVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, September 07, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD + ","
+ PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ","
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD
+ " FROM " + PRO_ChangeCategoryDetailTable.TABLE_NAME
+" WHERE " + PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
PRO_ChangeCategoryDetailVO objObject = new PRO_ChangeCategoryDetailVO();
while (odrPCS.Read())
{
objObject.ChangeCategoryDetailID = int.Parse(odrPCS[PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD].ToString().Trim());
objObject.ProductID = int.Parse(odrPCS[PRO_ChangeCategoryDetailTable.PRODUCTID_FLD].ToString().Trim());
objObject.ChangeCategoryMasterID = int.Parse(odrPCS[PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to PRO_ChangeCategoryDetail
/// </Description>
/// <Inputs>
/// PRO_ChangeCategoryDetailVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
PRO_ChangeCategoryDetailVO objObject = (PRO_ChangeCategoryDetailVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE PRO_ChangeCategoryDetail SET "
+ PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + "= ?" + ","
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD + "= ?"
+" WHERE " + PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ChangeCategoryDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_ChangeCategoryDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD].Value = objObject.ChangeCategoryMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD].Value = objObject.ChangeCategoryDetailID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from PRO_ChangeCategoryDetail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, September 07, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD + ","
+ PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ","
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD + ","
+ "(SELECT " + ITM_ProductTable.CODE_FLD + " FROM " + ITM_ProductTable.TABLE_NAME + " WHERE " + ITM_ProductTable.PRODUCTID_FLD + "=" + PRO_ChangeCategoryDetailTable.TABLE_NAME + "." + PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ") as " + ITM_ProductTable.CODE_FLD + ","
+ "(SELECT " + ITM_ProductTable.DESCRIPTION_FLD + " FROM " + ITM_ProductTable.TABLE_NAME + " WHERE " + ITM_ProductTable.PRODUCTID_FLD + "=" + PRO_ChangeCategoryDetailTable.TABLE_NAME + "." + PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ") as " + ITM_ProductTable.DESCRIPTION_FLD + ","
+ "(SELECT " + ITM_ProductTable.REVISION_FLD + " FROM " + ITM_ProductTable.TABLE_NAME + " WHERE " + ITM_ProductTable.PRODUCTID_FLD + "=" + PRO_ChangeCategoryDetailTable.TABLE_NAME + "." + PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ") as " + ITM_ProductTable.REVISION_FLD
+ " FROM " + PRO_ChangeCategoryDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_ChangeCategoryDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from PRO_ChangeCategoryDetail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, September 07, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List(int pintChangeCategoryMasterID)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT ChangeCategoryDetailID, PRO_ChangeCategoryDetail.ProductID, ChangeCategoryMasterID,"
+ " ITM_Category.Code AS ITM_CategoryCode, ITM_Product.Code, ITM_Product.Description, ITM_Product.Revision"
+ " FROM PRO_ChangeCategoryDetail"
+ " JOIN ITM_Product"
+ " ON PRO_ChangeCategoryDetail.ProductID = ITM_Product.ProductID"
+ " LEFT JOIN ITM_Category"
+ " ON ITM_Product.CategoryID = ITM_Category.CategoryID"
+ " WHERE ChangeCategoryMasterID = " + pintChangeCategoryMasterID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_ChangeCategoryDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, September 07, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYDETAILID_FLD + ","
+ PRO_ChangeCategoryDetailTable.PRODUCTID_FLD + ","
+ PRO_ChangeCategoryDetailTable.CHANGECATEGORYMASTERID_FLD
+ " FROM " + PRO_ChangeCategoryDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,PRO_ChangeCategoryDetailTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
using System;
/// <summary>
/// Convert.ToBoolean(Double)
/// Converts the value of the specified double float value to an equivalent Boolean value.
/// </summary>
public class ConvertToBoolean
{
public static int Main()
{
ConvertToBoolean testObj = new ConvertToBoolean();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToBoolean(Double)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = TestLibrary.Generator.GetDouble(-55);
TestLibrary.TestFramework.BeginScenario("PosTest1: Random double value between 0.0 and 1.0.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("002", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = double.MaxValue;
TestLibrary.TestFramework.BeginScenario("PosTest2: value is double.MaxValue.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("003", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("004", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = double.MinValue;
TestLibrary.TestFramework.BeginScenario("PosTest3: value is double.MinValue.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("005", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("006", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = double.Epsilon;
TestLibrary.TestFramework.BeginScenario("PosTest4: value is double.Epsilon.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("007", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("008", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = -1 * TestLibrary.Generator.GetDouble(-55);
TestLibrary.TestFramework.BeginScenario("PosTest5: Random double value between -0.0 and -1.0.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("009", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("010", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = double.NaN;
TestLibrary.TestFramework.BeginScenario("PosTest6: value is double.NaN.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("011", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("012", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = double.NegativeInfinity;
TestLibrary.TestFramework.BeginScenario("PosTest7: value is double.NegativeInfinity.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("013", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("014", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = double.PositiveInfinity;
TestLibrary.TestFramework.BeginScenario("PosTest8: value is double.PositiveInfinity.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("015", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("016", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string errorDesc;
double d;
bool expectedValue;
bool actualValue;
d = -1 * double.Epsilon;
TestLibrary.TestFramework.BeginScenario("PosTest9: value is negative double.Epsilon.");
try
{
actualValue = Convert.ToBoolean(d);
expectedValue = 0 != d;
if (actualValue != expectedValue)
{
errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("017", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe double value is " + d;
TestLibrary.TestFramework.LogError("018", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Baseline;
using Marten.Exceptions;
using Marten.Linq.Filters;
using Marten.Linq.Parsing;
using Marten.Linq.SqlGeneration;
using Weasel.Postgresql;
using Marten.Schema;
using Marten.Schema.Arguments;
using Marten.Storage;
using Marten.Util;
using NpgsqlTypes;
using Weasel.Postgresql.Tables;
namespace Marten.Linq.Fields
{
public class DuplicatedField: IField
{
private readonly Func<Expression, object> _parseObject = expression => expression.Value();
private readonly bool useTimestampWithoutTimeZoneForDateTime;
private string _columnName;
public DuplicatedField(EnumStorage enumStorage, IField innerField,
bool useTimestampWithoutTimeZoneForDateTime = true, bool notNull = false)
{
InnerField = innerField;
MemberName = InnerField.Members.Select(x => x.Name).Join("");
NotNull = notNull;
ColumnName = MemberName.ToTableAlias();
this.useTimestampWithoutTimeZoneForDateTime = useTimestampWithoutTimeZoneForDateTime;
PgType = TypeMappings.GetPgType(FieldType, enumStorage);
if (FieldType.IsEnum)
{
if (enumStorage == EnumStorage.AsString)
{
DbType = NpgsqlDbType.Varchar;
PgType = "varchar";
_parseObject = expression =>
{
var raw = expression.Value();
if (raw == null)
{
return null;
}
return Enum.GetName(FieldType, raw);
};
}
else
{
DbType = NpgsqlDbType.Integer;
PgType = "integer";
}
}
else if (FieldType.IsDateTime())
{
PgType = this.useTimestampWithoutTimeZoneForDateTime
? "timestamp without time zone"
: "timestamp with time zone";
DbType = this.useTimestampWithoutTimeZoneForDateTime
? NpgsqlDbType.Timestamp
: NpgsqlDbType.TimestampTz;
}
else if (FieldType == typeof(DateTimeOffset) || FieldType == typeof(DateTimeOffset?))
{
PgType = "timestamp with time zone";
DbType = NpgsqlDbType.TimestampTz;
}
else
{
DbType = TypeMappings.ToDbType(FieldType);
}
}
public bool NotNull { get; }
public bool OnlyForSearching { get; set; } = false;
/// <summary>
/// Used to override the assigned DbType used by Npgsql when a parameter
/// is used in a query against this column
/// </summary>
public NpgsqlDbType DbType { get; set; }
public UpsertArgument UpsertArgument => new UpsertArgument
{
Arg = "arg_" + ColumnName.ToLower(),
Column = ColumnName.ToLower(),
PostgresType = PgType,
Members = Members,
DbType = DbType
};
public string ColumnName
{
get => _columnName;
set
{
_columnName = value;
TypedLocator = "d." + _columnName;
}
}
internal IField InnerField { get; }
public string RawLocator => TypedLocator;
public object GetValueForCompiledQueryParameter(Expression valueExpression)
{
return _parseObject(valueExpression);
}
public bool ShouldUseContainmentOperator()
{
return false;
}
string IField.SelectorForDuplication(string pgType)
{
throw new NotSupportedException();
}
public ISqlFragment CreateComparison(string op, ConstantExpression value, Expression memberExpression)
{
if (value.Value == null)
{
return op switch
{
"=" => new IsNullFilter(this),
"!=" => new IsNotNullFilter(this),
_ => throw new BadLinqExpressionException($"Can only compare property {MemberName} by '=' or '!=' with null value")
};
}
return new ComparisonFilter(this, new CommandParameter(_parseObject(value), DbType), op);
}
public string JSONBLocator { get; set; }
public string LocatorForIncludedDocumentId => TypedLocator;
public string LocatorFor(string rootTableAlias)
{
return $"{rootTableAlias}.{_columnName}";
}
public string TypedLocator { get; set; }
// TODO -- have this take in CommandBuilder
public string UpdateSqlFragment()
{
return $"{ColumnName} = {InnerField.SelectorForDuplication(PgType)}";
}
public static DuplicatedField For<T>(StoreOptions options, Expression<Func<T, object>> expression,
bool useTimestampWithoutTimeZoneForDateTime = true)
{
var inner = new DocumentMapping<T>(options).FieldFor(expression);
// Hokey, but it's just for testing for now.
if (inner.Members.Length > 1)
throw new NotSupportedException("Not yet supporting deep properties yet. Soon.");
return new DuplicatedField(options.EnumStorage, inner, useTimestampWithoutTimeZoneForDateTime);
}
// I say you don't need a ForeignKey
public virtual TableColumn ToColumn()
{
return new TableColumn(ColumnName, PgType);
}
void ISqlFragment.Apply(CommandBuilder builder)
{
builder.Append(TypedLocator);
}
bool ISqlFragment.Contains(string sqlText)
{
return TypedLocator.Contains(sqlText);
}
public Type FieldType => InnerField.FieldType;
public MemberInfo[] Members => InnerField.Members;
public string MemberName { get; }
public string PgType { get; set; } // settable so it can be overidden by users
public string ToOrderExpression(Expression expression)
{
return TypedLocator;
}
}
}
| |
/*
[nwazet Open Source Software & Open Source Hardware
Authors: Fabien Royer
Software License Agreement (BSD License)
Copyright (c) 2010-2012, Nwazet, LLC. 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 Nwazet, LLC. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* The names '[nwazet', 'nwazet', the ASCII hazelnut in the [nwazet logo and the color of the logo are Trademarks of nwazet, LLC. and cannot be used to endorse or promote products derived from this software or any hardware designs without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.SPOT.Hardware;
namespace Nwazet.Go.Helpers {
public class BasicTypeDeSerializerContext : IDisposable {
public int ContentSize {
get {
return _contentSize;
}
}
public bool MoreData {
get {
return (_currentIndex < _contentSize);
}
}
public const int BufferStartOffsetDefault = 2;
private int _bufferStartOffset;
public BasicTypeDeSerializerContext() {
_bufferStartOffset = BufferStartOffsetDefault;
}
public BasicTypeDeSerializerContext(byte[] buffer, int BufferStartOffset = BufferStartOffsetDefault) {
Bind(buffer, BufferStartOffset);
}
public BasicTypeDeSerializerContext(FileStream file, int BufferStartOffset = BufferStartOffsetDefault) {
Bind(file, BufferStartOffset);
}
public void Bind(byte[] buffer, int BufferStartOffset) {
if (buffer == null) throw new ArgumentNullException("buffer");
_buffer = buffer;
_readFunction = ReadFromBuffer;
ReadHeader(BufferStartOffset);
}
public void Bind(FileStream file, int BufferStartOffset) {
if (file == null) throw new ArgumentNullException("file");
_file = file;
_readFunction = ReadFromFile;
_file.Seek(_bufferStartOffset, SeekOrigin.Begin);
ReadHeader(BufferStartOffset);
}
private void ReadHeader(int BufferStartOffset) {
_bufferStartOffset = BufferStartOffset;
_currentIndex = _bufferStartOffset;
_headerVersion = Retrieve();
if (_headerVersion != 3) throw new ApplicationException("_headerVersion");
if (_buffer != null) {
_contentSize = (int)(Retrieve() << 8);
_contentSize |= (int)Retrieve();
} else {
// Skip the 'content size' part of the header when dealing with a file stream
Retrieve();
Retrieve();
_contentSize = (int)_file.Length;
}
if (_contentSize == 0) throw new ApplicationException("_contentSize");
}
public byte Retrieve() {
return _readFunction();
}
private byte ReadFromBuffer() {
return _buffer[_currentIndex++];
}
private byte ReadFromFile() {
_currentIndex++;
return (byte)_file.ReadByte();
}
public bool IsLittleEndian {
get {
return _isLittleEndian;
}
}
public void Wipe() {
Array.Clear(_buffer, 0, _buffer.Length);
}
public void CopyBytesFromInternalBuffer(byte[] bytes, int offset, int length) {
if (length == 0) return;
Array.Copy(_buffer, _currentIndex, bytes, offset, length);
_currentIndex += length;
}
public void Dispose() {
_encoding = null;
_file = null;
_buffer = null;
_readFunction = null;
}
private delegate byte ReadByte();
private UTF8Encoding _encoding = new UTF8Encoding();
private FileStream _file;
private byte[] _buffer;
private int _currentIndex;
private int _contentSize;
private byte _headerVersion;
private bool _isLittleEndian = Utility.ExtractValueFromArray(new byte[] { 0xBE, 0xEF }, 0, 2) == 0xEFBE;
private ReadByte _readFunction;
}
public static class BasicTypeDeSerializer {
public static UInt16 Get(BasicTypeDeSerializerContext context, UInt16 data) {
data = Get(context);
data <<= 8;
data |= Get(context);
return data;
}
public static Int16 Get(BasicTypeDeSerializerContext context, Int16 data) {
UInt16 temp;
temp = Get(context);
temp <<= 8;
temp |= Get(context);
return (Int16)temp;
}
public static UInt32 Get(BasicTypeDeSerializerContext context, UInt32 data) {
data = Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
return data;
}
public static unsafe float Get(BasicTypeDeSerializerContext context, float data) {
var temp = new byte[4];
if (context.IsLittleEndian) {
// Reverse the buffer going from Big Endian (network byte order) to Little Endian
temp[3] = context.Retrieve();
temp[2] = context.Retrieve();
temp[1] = context.Retrieve();
temp[0] = context.Retrieve();
} else { // Already in Big Endian format
temp[0] = context.Retrieve();
temp[1] = context.Retrieve();
temp[2] = context.Retrieve();
temp[3] = context.Retrieve();
}
UInt32 value = Utility.ExtractValueFromArray(temp, 0, 4);
return *((float*)&value);
}
public static Int32 Get(BasicTypeDeSerializerContext context, Int32 data) {
data = Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
return data;
}
public static UInt64 Get(BasicTypeDeSerializerContext context, UInt64 data) {
data = Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
data <<= 8;
data |= Get(context);
return data;
}
public static Int64 Get(BasicTypeDeSerializerContext context, Int64 data) {
return (Int64)Get(context, (UInt64)data);
}
public static string Get(BasicTypeDeSerializerContext context, string text) {
byte IsASCII = 0;
IsASCII = Get(context);
ushort length = 0;
length = Get(context, length);
if (length != 0) {
if (IsASCII == 1) {
var bytes = new byte[length];
var index = 0;
while (length-- != 0) {
bytes[index++] = Get(context);
}
Get(context); // Skip null byte terminator
return new string(Encoding.UTF8.GetChars(bytes));
} else {
var unicodeChars = new char[length];
var index = 0;
ushort unicodeChar = 0;
while (length-- != 0) {
unicodeChars[index++] = (char)Get(context, unicodeChar);
}
Get(context, unicodeChar); // Skip null character terminator
return new string(unicodeChars);
}
}
Get(context); // Skip null character terminator
return "";
}
public static byte[] Get(BasicTypeDeSerializerContext context, byte[] bytes) {
ushort length = 0;
length = Get(context, length);
if (length != 0) {
var buffer = new byte[length];
var index = 0;
while (length-- != 0) {
buffer[index++] = Get(context);
}
return buffer;
}
return null;
}
public static ushort[] Get(BasicTypeDeSerializerContext context, ushort[] array) {
ushort length = 0;
length = Get(context, length);
if (length != 0) {
var buffer = new ushort[length];
var index = 0;
UInt16 data = 0;
while (length-- != 0) {
buffer[index++] = Get(context, data);
}
return buffer;
}
return null;
}
public static UInt32[] Get(BasicTypeDeSerializerContext context, UInt32[] array) {
ushort length = 0;
length = Get(context, length);
if (length != 0) {
var buffer = new UInt32[length];
var index = 0;
UInt32 data = 0;
while (length-- != 0) {
buffer[index++] = Get(context, data);
}
return buffer;
}
return null;
}
public static UInt64[] Get(BasicTypeDeSerializerContext context, UInt64[] array) {
ushort length = 0;
length = Get(context, length);
if (length != 0) {
var buffer = new UInt64[length];
var index = 0;
UInt64 data = 0;
while (length-- != 0) {
buffer[index++] = Get(context, data);
}
return buffer;
}
return null;
}
public static byte Get(BasicTypeDeSerializerContext context) {
return context.Retrieve();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
// This class allows you to create an opaque, GC handle to any
// COM+ object. A GC handle is used when an object reference must be
// reachable from unmanaged memory. There are 3 kinds of roots:
// Normal - keeps the object from being collected.
// Weak - allows object to be collected and handle contents will be zeroed.
// Weak references are zeroed before the finalizer runs, so if the
// object is resurrected in the finalizer the weak reference is
// still zeroed.
// WeakTrackResurrection - Same as weak, but stays until after object is
// really gone.
// Pinned - same as normal, but allows the address of the actual object
// to be taken.
//
[StructLayout(LayoutKind.Sequential)]
public struct GCHandle
{
// IMPORTANT: This must be kept in sync with the GCHandleType enum.
private const GCHandleType MaxHandleType = GCHandleType.Pinned;
// Allocate a handle storing the object and the type.
internal GCHandle(Object value, GCHandleType type)
{
// Make sure the type parameter is within the valid range for the enum.
if ((uint)type > (uint)MaxHandleType)
{
throw new ArgumentOutOfRangeException(); // "type", SR.ArgumentOutOfRange_Enum;
}
if (type == GCHandleType.Pinned)
GCHandleValidatePinnedObject(value);
_handle = RuntimeImports.RhHandleAlloc(value, type);
// Record if the handle is pinned.
if (type == GCHandleType.Pinned)
SetIsPinned();
}
// Used in the conversion functions below.
internal GCHandle(IntPtr handle)
{
_handle = handle;
}
// Creates a new GC handle for an object.
//
// value - The object that the GC handle is created for.
// type - The type of GC handle to create.
//
// returns a new GC handle that protects the object.
public static GCHandle Alloc(Object value)
{
return new GCHandle(value, GCHandleType.Normal);
}
public static GCHandle Alloc(Object value, GCHandleType type)
{
return new GCHandle(value, type);
}
// Frees a GC handle.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public void Free()
{
// Copy the handle instance member to a local variable. This is required to prevent
// race conditions releasing the handle.
IntPtr handle = _handle;
// Free the handle if it hasn't already been freed.
if (handle != default(IntPtr) && Interlocked.CompareExchange(ref _handle, default(IntPtr), handle) == handle)
{
#if BIT64
RuntimeImports.RhHandleFree((IntPtr)(((long)handle) & ~1L));
#else
RuntimeImports.RhHandleFree((IntPtr)(((int)handle) & ~1));
#endif
}
else
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
}
// Target property - allows getting / updating of the handle's referent.
public Object Target
{
get
{
// Check if the handle was never initialized or was freed.
if (_handle == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
return RuntimeImports.RhHandleGet(GetHandleValue());
}
set
{
// Check if the handle was never initialized or was freed.
if (_handle == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
#if CORERT // TODO: Higher level ProjectN frameworks took dependency on this validation missing
if (IsPinned())
GCHandleValidatePinnedObject(value);
#endif
RuntimeImports.RhHandleSet(GetHandleValue(), value);
}
}
// Retrieve the address of an object in a Pinned handle. This throws
// an exception if the handle is any type other than Pinned.
public IntPtr AddrOfPinnedObject()
{
// Check if the handle was not a pinned handle.
if (!IsPinned())
{
// Check if the handle was never initialized for was freed.
if (_handle == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
// You can only get the address of pinned handles.
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotPinned);
}
unsafe
{
// Get the address of the pinned object.
// The layout of String and Array is different from Object
Object target = this.Target;
if (target == null)
return default(IntPtr);
String targetAsString = target as String;
if (targetAsString != null)
{
fixed (char* ptr = targetAsString)
{
return (IntPtr)ptr;
}
}
Array targetAsArray = target as Array;
if (targetAsArray != null)
{
fixed (IntPtr* pTargetEEType = &targetAsArray.m_pEEType)
{
return (IntPtr)Array.GetAddrOfPinnedArrayFromEETypeField(pTargetEEType);
}
}
else
{
fixed (IntPtr* pTargetEEType = &target.m_pEEType)
{
return (IntPtr)Object.GetAddrOfPinnedObjectFromEETypeField(pTargetEEType);
}
}
}
}
// Determine whether this handle has been allocated or not.
public bool IsAllocated
{
get
{
return _handle != default(IntPtr);
}
}
// Used to create a GCHandle from an int. This is intended to
// be used with the reverse conversion.
public static explicit operator GCHandle(IntPtr value)
{
return FromIntPtr(value);
}
public static GCHandle FromIntPtr(IntPtr value)
{
if (value == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
return new GCHandle(value);
}
// Used to get the internal integer representation of the handle out.
public static explicit operator IntPtr(GCHandle value)
{
return ToIntPtr(value);
}
public static IntPtr ToIntPtr(GCHandle value)
{
return value._handle;
}
public override int GetHashCode()
{
return _handle.GetHashCode();
}
public override bool Equals(Object o)
{
GCHandle hnd;
// Check that o is a GCHandle first
if (o == null || !(o is GCHandle))
return false;
else
hnd = (GCHandle)o;
return _handle == hnd._handle;
}
public static bool operator ==(GCHandle a, GCHandle b)
{
return a._handle == b._handle;
}
public static bool operator !=(GCHandle a, GCHandle b)
{
return a._handle != b._handle;
}
internal IntPtr GetHandleValue()
{
#if BIT64
return new IntPtr(((long)_handle) & ~1L);
#else
return new IntPtr(((int)_handle) & ~1);
#endif
}
internal bool IsPinned()
{
#if BIT64
return (((long)_handle) & 1) != 0;
#else
return (((int)_handle) & 1) != 0;
#endif
}
internal void SetIsPinned()
{
#if BIT64
_handle = new IntPtr(((long)_handle) | 1L);
#else
_handle = new IntPtr(((int)_handle) | 1);
#endif
}
//
// C# port of GCHandleValidatePinnedObject(OBJECTREF) in MarshalNative.cpp.
//
private static void GCHandleValidatePinnedObject(Object obj)
{
if (obj == null)
return;
if (obj is String)
return;
EETypePtr eeType = obj.EETypePtr;
if (eeType.IsArray)
{
EETypePtr elementEEType = eeType.ArrayElementType;
if (elementEEType.IsPrimitive)
return;
if (elementEEType.IsValueType && elementEEType.MightBeBlittable())
return;
}
else if (eeType.MightBeBlittable())
{
return;
}
throw new ArgumentException(SR.Argument_NotIsomorphic);
}
// The actual integer handle value that the EE uses internally.
private IntPtr _handle;
}
}
| |
namespace android.text
{
[global::MonoJavaBridge.JavaInterface(typeof(global::android.text.Editable_))]
public interface Editable : java.lang.CharSequence, GetChars, Spannable, java.lang.Appendable
{
new global::android.text.Editable append(java.lang.CharSequence arg0, int arg1, int arg2);
new global::android.text.Editable append(java.lang.CharSequence arg0);
new global::android.text.Editable append(char arg0);
void clear();
global::android.text.Editable replace(int arg0, int arg1, java.lang.CharSequence arg2, int arg3, int arg4);
global::android.text.Editable replace(int arg0, int arg1, java.lang.CharSequence arg2);
global::android.text.Editable delete(int arg0, int arg1);
global::android.text.Editable insert(int arg0, java.lang.CharSequence arg1);
global::android.text.Editable insert(int arg0, java.lang.CharSequence arg1, int arg2, int arg3);
void setFilters(android.text.InputFilter[] arg0);
global::android.text.InputFilter[] getFilters();
void clearSpans();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.Editable))]
public sealed partial class Editable_ : java.lang.Object, Editable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Editable_()
{
InitJNI();
}
internal Editable_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _append7654;
global::android.text.Editable android.text.Editable.append(java.lang.CharSequence arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._append7654, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._append7654, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _append7655;
global::android.text.Editable android.text.Editable.append(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._append7655, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._append7655, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _append7656;
global::android.text.Editable android.text.Editable.append(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._append7656, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._append7656, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _clear7657;
void android.text.Editable.clear()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Editable_._clear7657);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._clear7657);
}
internal static global::MonoJavaBridge.MethodId _replace7658;
global::android.text.Editable android.text.Editable.replace(int arg0, int arg1, java.lang.CharSequence arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._replace7658, 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))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._replace7658, 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))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _replace7659;
global::android.text.Editable android.text.Editable.replace(int arg0, int arg1, java.lang.CharSequence arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._replace7659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._replace7659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _delete7660;
global::android.text.Editable android.text.Editable.delete(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._delete7660, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._delete7660, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _insert7661;
global::android.text.Editable android.text.Editable.insert(int arg0, java.lang.CharSequence arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._insert7661, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._insert7661, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _insert7662;
global::android.text.Editable android.text.Editable.insert(int arg0, java.lang.CharSequence arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._insert7662, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.text.Editable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.text.Editable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._insert7662, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.text.Editable;
}
internal static global::MonoJavaBridge.MethodId _setFilters7663;
void android.text.Editable.setFilters(android.text.InputFilter[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Editable_._setFilters7663, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._setFilters7663, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFilters7664;
global::android.text.InputFilter[] android.text.Editable.getFilters()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.text.InputFilter>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._getFilters7664)) as android.text.InputFilter[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.text.InputFilter>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._getFilters7664)) as android.text.InputFilter[];
}
internal static global::MonoJavaBridge.MethodId _clearSpans7665;
void android.text.Editable.clearSpans()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Editable_._clearSpans7665);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._clearSpans7665);
}
internal static global::MonoJavaBridge.MethodId _toString7666;
global::java.lang.String java.lang.CharSequence.toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._toString7666)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._toString7666)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _length7667;
int java.lang.CharSequence.length()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Editable_._length7667);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._length7667);
}
internal static global::MonoJavaBridge.MethodId _charAt7668;
char java.lang.CharSequence.charAt(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallCharMethod(this.JvmHandle, global::android.text.Editable_._charAt7668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._charAt7668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _subSequence7669;
global::java.lang.CharSequence java.lang.CharSequence.subSequence(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._subSequence7669, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._subSequence7669, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getChars7670;
void android.text.GetChars.getChars(int arg0, int arg1, char[] arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Editable_._getChars7670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._getChars7670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _setSpan7671;
void android.text.Spannable.setSpan(java.lang.Object arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Editable_._setSpan7671, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._setSpan7671, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _removeSpan7672;
void android.text.Spannable.removeSpan(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Editable_._removeSpan7672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._removeSpan7672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSpans7673;
global::java.lang.Object[] android.text.Spanned.getSpans(int arg0, int arg1, java.lang.Class arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._getSpans7673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Object[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._getSpans7673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Object[];
}
internal static global::MonoJavaBridge.MethodId _getSpanStart7674;
int android.text.Spanned.getSpanStart(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Editable_._getSpanStart7674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._getSpanStart7674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSpanEnd7675;
int android.text.Spanned.getSpanEnd(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Editable_._getSpanEnd7675, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._getSpanEnd7675, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSpanFlags7676;
int android.text.Spanned.getSpanFlags(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Editable_._getSpanFlags7676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._getSpanFlags7676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _nextSpanTransition7677;
int android.text.Spanned.nextSpanTransition(int arg0, int arg1, java.lang.Class arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Editable_._nextSpanTransition7677, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._nextSpanTransition7677, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _append7678;
global::java.lang.Appendable java.lang.Appendable.append(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._append7678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Appendable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._append7678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Appendable;
}
internal static global::MonoJavaBridge.MethodId _append7679;
global::java.lang.Appendable java.lang.Appendable.append(java.lang.CharSequence arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._append7679, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Appendable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._append7679, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Appendable;
}
internal static global::MonoJavaBridge.MethodId _append7680;
global::java.lang.Appendable java.lang.Appendable.append(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Editable_._append7680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Appendable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Editable_.staticClass, global::android.text.Editable_._append7680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Appendable;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Editable_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Editable"));
global::android.text.Editable_._append7654 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "append", "(Ljava/lang/CharSequence;II)Landroid/text/Editable;");
global::android.text.Editable_._append7655 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "append", "(Ljava/lang/CharSequence;)Landroid/text/Editable;");
global::android.text.Editable_._append7656 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "append", "(C)Landroid/text/Editable;");
global::android.text.Editable_._clear7657 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "clear", "()V");
global::android.text.Editable_._replace7658 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "replace", "(IILjava/lang/CharSequence;II)Landroid/text/Editable;");
global::android.text.Editable_._replace7659 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "replace", "(IILjava/lang/CharSequence;)Landroid/text/Editable;");
global::android.text.Editable_._delete7660 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "delete", "(II)Landroid/text/Editable;");
global::android.text.Editable_._insert7661 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "insert", "(ILjava/lang/CharSequence;)Landroid/text/Editable;");
global::android.text.Editable_._insert7662 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "insert", "(ILjava/lang/CharSequence;II)Landroid/text/Editable;");
global::android.text.Editable_._setFilters7663 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "setFilters", "([Landroid/text/InputFilter;)V");
global::android.text.Editable_._getFilters7664 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "getFilters", "()[Landroid/text/InputFilter;");
global::android.text.Editable_._clearSpans7665 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "clearSpans", "()V");
global::android.text.Editable_._toString7666 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "toString", "()Ljava/lang/String;");
global::android.text.Editable_._length7667 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "length", "()I");
global::android.text.Editable_._charAt7668 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "charAt", "(I)C");
global::android.text.Editable_._subSequence7669 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "subSequence", "(II)Ljava/lang/CharSequence;");
global::android.text.Editable_._getChars7670 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "getChars", "(II[CI)V");
global::android.text.Editable_._setSpan7671 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "setSpan", "(Ljava/lang/Object;III)V");
global::android.text.Editable_._removeSpan7672 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "removeSpan", "(Ljava/lang/Object;)V");
global::android.text.Editable_._getSpans7673 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "getSpans", "(IILjava/lang/Class;)[Ljava/lang/Object;");
global::android.text.Editable_._getSpanStart7674 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "getSpanStart", "(Ljava/lang/Object;)I");
global::android.text.Editable_._getSpanEnd7675 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "getSpanEnd", "(Ljava/lang/Object;)I");
global::android.text.Editable_._getSpanFlags7676 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "getSpanFlags", "(Ljava/lang/Object;)I");
global::android.text.Editable_._nextSpanTransition7677 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "nextSpanTransition", "(IILjava/lang/Class;)I");
global::android.text.Editable_._append7678 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "append", "(Ljava/lang/CharSequence;)Ljava/lang/Appendable;");
global::android.text.Editable_._append7679 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "append", "(Ljava/lang/CharSequence;II)Ljava/lang/Appendable;");
global::android.text.Editable_._append7680 = @__env.GetMethodIDNoThrow(global::android.text.Editable_.staticClass, "append", "(C)Ljava/lang/Appendable;");
}
}
}
| |
#region License
/*
* Copyright (C) 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections.Generic;
#endregion
namespace Java.Util
{
/// <summary>
/// This class provides skeletal implementations for some of <see cref="IQueue{T}"/>
/// operations.
/// </summary>
/// <remarks>
/// <para>
/// The methods <see cref="Add"/>, <see cref="Remove"/>, and
/// <see cref="Element()"/> are based on the <see cref="Offer"/>,
/// <see cref="Poll"/>, and <see cref="Peek"/> methods respectively but
/// throw exceptions instead of indicating failure via
/// <see langword="false"/> returns.
/// </para>
/// </remarks>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio (.NET)</author>
/// <author>Kenneth Xu</author>
[Serializable]
public abstract class AbstractQueue<T> : AbstractCollection<T>, IQueue<T> //JDK_1_6
{
/// <summary>
/// Returns the remaining capacity of this queue.
/// </summary>
public abstract int RemainingCapacity { get; }
#region IQueue<T> Members
/// <summary>
/// Inserts the specified element into this queue if it is possible to
/// do so immediately without violating capacity restrictions.
/// </summary>
/// <remarks>
/// When using a capacity-restricted queue, this method is generally
/// preferable to <see cref="Add"/>, which can fail to
/// insert an element only by throwing an exception.
/// </remarks>
/// <param name="element">The element to add.</param>
/// <returns>
/// <c>true</c> if the element was added to this queue. Otherwise
/// <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If the <paramref name="element"/> is <c>null</c> and the queue
/// implementation doesn't allow <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// If some property of the supplied <paramref name="element"/>
/// prevents it from being added to this queue.
/// </exception>
public abstract bool Offer(T element);
/// <summary>
/// Retrieves, but does not remove, the head of this queue.
/// </summary>
/// <remarks>
/// <para>
/// This method differs from <see cref="Peek(out T)"/> in that it throws an
/// exception if this queue is empty.
/// </para>
/// <para>
/// this implementation returns the result of <see cref="Peek"/>
/// unless the queue is empty.
/// </para>
/// </remarks>
/// <returns>The head of this queue.</returns>
/// <exception cref="InvalidOperationException">
/// If this queue is empty.
/// </exception>
public virtual T Element()
{
T element;
if (Peek(out element))
{
return element;
}
else
{
throw new InvalidOperationException("Queue is empty.");
}
}
/// <summary>
/// Retrieves, but does not remove, the head of this queue into out
/// parameter <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// The head of this queue. <c>default(T)</c> if queue is empty.
/// </param>
/// <returns>
/// <c>false</c> is the queue is empty. Otherwise <c>true</c>.
/// </returns>
public abstract bool Peek(out T element);
/// <summary>
/// Retrieves and removes the head of this queue.
/// </summary>
/// <returns>The head of this queue</returns>
/// <exception cref="InvalidOperationException">
/// If this queue is empty.
/// </exception>
public virtual T Remove()
{
T element;
if (Poll(out element))
{
return element;
}
else
{
throw new InvalidOperationException("Queue is empty.");
}
}
/// <summary>
/// Retrieves and removes the head of this queue into out parameter
/// <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// Set to the head of this queue. <c>default(T)</c> if queue is empty.
/// </param>
/// <returns>
/// <c>false</c> if the queue is empty. Otherwise <c>true</c>.
/// </returns>
public abstract bool Poll(out T element);
#endregion
#region ICollection<T> Members
/// <summary>
/// Inserts the specified <paramref name="element"/> into this queue
/// if it is possible to do so immediately without violating capacity
/// restrictions. Throws an <see cref="InvalidOperationException"/>
/// if no space is currently available.
/// </summary>
/// <param name="element">The element to add.</param>
/// <exception cref="InvalidOperationException">
/// If the <paramref name="element"/> cannot be added at this time due
/// to capacity restrictions.
/// </exception>
public override void Add(T element)
{
if (!Offer(element))
{
throw new InvalidOperationException("Queue full.");
}
}
/// <summary>
/// Removes all items from the queue.
/// </summary>
/// <remarks>
/// This implementation repeatedly calls the <see cref="Poll"/> moethod
/// until it returns <c>false</c>.
/// </remarks>
public override void Clear()
{
T element;
while (Poll(out element)) {}
}
#endregion
#region IQueue Members
/// <summary>
/// Returns <see langword="true"/> if there are no elements in the
/// <see cref="IQueue{T}"/>, <see langword="false"/> otherwise.
/// </summary>
public virtual bool IsEmpty
{
get { return Count==0; }
}
/// <summary>
/// Returns the current capacity of this queue.
/// </summary>
public abstract int Capacity { get; }
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// This implementation always return true;
/// </summary>
///
/// <returns>
/// true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// This implementation always return false as typically a queue should not
/// be read only.
/// </returns>
///
public override bool IsReadOnly
{
get
{
return false;
}
}
#endregion
/// <summary>
/// Removes all available elements from this queue and invoke the given
/// <paramref name="action"/> on each element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// <example> Drain to a non-generic list.
/// <code language="c#">
/// IList c = ...;
/// int count = Drain(delegate(T e) {c.Add(e);});
/// </code>
/// </example>
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(Action{T}, int)"/>
public virtual int Drain(Action<T> action)
{
return Drain(action, null);
}
/// <summary>
/// Removes all elements that pass the given <paramref name="criteria"/>
/// from this queue and invoke the given <paramref name="action"/> on
/// each element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// <example> Drain to a non-generic list.
/// <code language="c#">
/// IList c = ...;
/// int count = Drain(delegate(T e) {c.Add(e);});
/// </code>
/// </example>
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <param name="criteria">
/// The criteria to select the elements. <c>null</c> selects any element.
/// </param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(Action{T}, int)"/>
public virtual int Drain(Action<T> action, Predicate<T> criteria)
{
if (action == null) throw new ArgumentNullException("action");
return DoDrain(action, criteria);
}
/// <summary>
/// Removes at most the given number of available elements from this
/// queue and invoke the given <paramref name="action"/> on each
/// element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <param name="maxElements">the maximum number of elements to transfer</param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(System.Action{T})"/>
public virtual int Drain(Action<T> action, int maxElements)
{
return Drain(action, maxElements, null);
}
/// <summary>
/// Removes at most the given number of elements that pass the given
/// <paramref name="criteria"/>from this queue and invoke the given
/// <paramref name="action"/> on each element in order.
/// </summary>
/// <remarks>
/// This operation may be more efficient than repeatedly polling this
/// queue. A failure encountered while attempting to invoke the
/// <paramref name="action"/> on the elements may result in elements
/// being neither, either or both in the queue or processed when the
/// associated exception is thrown.
/// </remarks>
/// <param name="action">The action to performe on each element.</param>
/// <param name="maxElements">the maximum number of elements to transfer</param>
/// <param name="criteria">
/// The criteria to select the elements. <c>null</c> selects any element.
/// </param>
/// <returns>The number of elements processed.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified action is <see langword="null"/>.
/// </exception>
/// <seealso cref="IQueue{T}.Drain(System.Action{T})"/>
public virtual int Drain(Action<T> action, int maxElements, Predicate<T> criteria)
{
if (action == null) throw new ArgumentNullException("action");
if (maxElements <= 0) return 0;
return DoDrain(action, maxElements, criteria);
}
/// <summary>
/// Does the real work for all drain methods. Caller must
/// guarantee the <paramref name="action"/> is not <c>null</c> and
/// <paramref name="maxElements"/> is greater then zero (0).
/// </summary>
/// <seealso cref="IQueue{T}.Drain(System.Action{T})"/>
/// <seealso cref="IQueue{T}.Drain(System.Action{T}, int)"/>
/// <seealso cref="IQueue{T}.Drain(System.Action{T}, Predicate{T})"/>
/// <seealso cref="IQueue{T}.Drain(System.Action{T}, int, Predicate{T})"/>
internal protected abstract int DoDrain(Action<T> action, int maxElements, Predicate<T> criteria);
/// <summary>
/// Does the real work for the <see cref="AbstractQueue{T}.Drain(System.Action{T})"/>
/// and <see cref="AbstractQueue{T}.Drain(System.Action{T},Predicate{T})"/>.
/// </summary>
internal protected virtual int DoDrain(Action<T> action, Predicate<T> criteria)
{
return DoDrain(action, int.MaxValue, criteria);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Types of breakpoints.
/// </summary>
public enum BreakpointType
{
/// <summary>Breakpoint on a line within a script</summary>
Line,
/// <summary>
/// Breakpoint on a variable</summary>
Variable,
/// <summary>Breakpoint on a command</summary>
Command
};
/// <summary>
/// This class implements Remove-PSBreakpoint.
/// </summary>
[Cmdlet(VerbsCommon.Get, "PSBreakpoint", DefaultParameterSetName = "Script", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113325")]
[OutputType(typeof(Breakpoint))]
public class GetPSBreakpointCommand : PSCmdlet
{
#region parameters
/// <summary>
/// Scripts of the breakpoints to output.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")]
[Parameter(ParameterSetName = "Script", Position = 0, ValueFromPipeline = true)]
[Parameter(ParameterSetName = "Variable")]
[Parameter(ParameterSetName = "Command")]
[Parameter(ParameterSetName = "Type")]
[ValidateNotNullOrEmpty()]
public string[] Script
{
get
{
return _script;
}
set
{
_script = value;
}
}
private string[] _script;
/// <summary>
/// IDs of the breakpoints to output.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")]
[Parameter(ParameterSetName = "Id", Mandatory = true, Position = 0, ValueFromPipeline = true)]
[ValidateNotNull]
public int[] Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
private int[] _id;
/// <summary>
/// Variables of the breakpoints to output.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")]
[Parameter(ParameterSetName = "Variable", Mandatory = true)]
[ValidateNotNull]
public string[] Variable
{
get
{
return _variable;
}
set
{
_variable = value;
}
}
private string[] _variable;
/// <summary>
/// Commands of the breakpoints to output.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")]
[Parameter(ParameterSetName = "Command", Mandatory = true)]
[ValidateNotNull]
public string[] Command
{
get
{
return _command;
}
set
{
_command = value;
}
}
private string[] _command;
/// <summary>
/// Commands of the breakpoints to output.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")]
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Type is OK for a cmdlet parameter")]
[Parameter(ParameterSetName = "Type", Mandatory = true, Position = 0, ValueFromPipeline = true)]
[ValidateNotNull]
public BreakpointType[] Type
{
get
{
return _type;
}
set
{
_type = value;
}
}
private BreakpointType[] _type;
#endregion parameters
/// <summary>
/// Remove breakpoints.
/// </summary>
protected override void ProcessRecord()
{
List<Breakpoint> breakpoints = Context.Debugger.GetBreakpoints();
//
// Filter by parameter set
//
if (this.ParameterSetName.Equals("Script", StringComparison.OrdinalIgnoreCase))
{
// no filter
}
else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
breakpoints = Filter(
breakpoints,
_id,
delegate (Breakpoint breakpoint, int id)
{
return breakpoint.Id == id;
}
);
}
else if (this.ParameterSetName.Equals("Command", StringComparison.OrdinalIgnoreCase))
{
breakpoints = Filter(
breakpoints,
_command,
delegate (Breakpoint breakpoint, string command)
{
CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint;
if (commandBreakpoint == null)
{
return false;
}
return commandBreakpoint.Command.Equals(command, StringComparison.OrdinalIgnoreCase);
});
}
else if (this.ParameterSetName.Equals("Variable", StringComparison.OrdinalIgnoreCase))
{
breakpoints = Filter(
breakpoints,
_variable,
delegate (Breakpoint breakpoint, string variable)
{
VariableBreakpoint variableBreakpoint = breakpoint as VariableBreakpoint;
if (variableBreakpoint == null)
{
return false;
}
return variableBreakpoint.Variable.Equals(variable, StringComparison.OrdinalIgnoreCase);
});
}
else if (this.ParameterSetName.Equals("Type", StringComparison.OrdinalIgnoreCase))
{
breakpoints = Filter(
breakpoints,
_type,
delegate (Breakpoint breakpoint, BreakpointType type)
{
switch (type)
{
case BreakpointType.Line:
if (breakpoint is LineBreakpoint)
{
return true;
}
break;
case BreakpointType.Command:
if (breakpoint is CommandBreakpoint)
{
return true;
}
break;
case BreakpointType.Variable:
if (breakpoint is VariableBreakpoint)
{
return true;
}
break;
}
return false;
});
}
else
{
Diagnostics.Assert(false, "Invalid parameter set: {0}", this.ParameterSetName);
}
//
// Filter by script
//
if (_script != null)
{
breakpoints = Filter(
breakpoints,
_script,
delegate (Breakpoint breakpoint, string script)
{
if (breakpoint.Script == null)
{
return false;
}
return string.Compare(
SessionState.Path.GetUnresolvedProviderPathFromPSPath(breakpoint.Script),
SessionState.Path.GetUnresolvedProviderPathFromPSPath(script),
StringComparison.OrdinalIgnoreCase
) == 0;
});
}
//
// Output results
//
foreach (Breakpoint b in breakpoints)
{
WriteObject(b);
}
}
/// <summary>
/// Gives the criteria to filter breakpoints.
/// </summary>
private delegate bool FilterSelector<T>(Breakpoint breakpoint, T target);
/// <summary>
/// Returns the items in the input list that match an item in the filter array according to
/// the given selection criterion.
/// </summary>
private List<Breakpoint> Filter<T>(List<Breakpoint> input, T[] filter, FilterSelector<T> selector)
{
List<Breakpoint> output = new List<Breakpoint>();
for (int i = 0; i < input.Count; i++)
{
for (int j = 0; j < filter.Length; j++)
{
if (selector(input[i], filter[j]))
{
output.Add(input[i]);
break;
}
}
}
return output;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.Chat
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ChatModule")]
public class ChatModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int DEBUG_CHANNEL = 2147483647;
private bool m_enabled = true;
private int m_saydistance = 20;
private int m_shoutdistance = 100;
private int m_whisperdistance = 10;
private List<Scene> m_scenes = new List<Scene>();
private List<string> FreezeCache = new List<string>();
private string m_adminPrefix = "";
internal object m_syncy = new object();
internal IConfig m_config;
#region ISharedRegionModule Members
public virtual void Initialise(IConfigSource config)
{
m_config = config.Configs["Chat"];
if (m_config != null)
{
if (!m_config.GetBoolean("enabled", true))
{
m_log.Info("[CHAT]: plugin disabled by configuration");
m_enabled = false;
return;
}
m_whisperdistance = m_config.GetInt("whisper_distance", m_whisperdistance);
m_saydistance = m_config.GetInt("say_distance", m_saydistance);
m_shoutdistance = m_config.GetInt("shout_distance", m_shoutdistance);
m_adminPrefix = m_config.GetString("admin_prefix", "");
}
}
public virtual void AddRegion(Scene scene)
{
if (!m_enabled) return;
lock (m_syncy)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
scene.EventManager.OnChatBroadcast += OnChatBroadcast;
}
}
m_log.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName,
m_whisperdistance, m_saydistance, m_shoutdistance);
}
public virtual void RegionLoaded(Scene scene)
{
if (!m_enabled)
return;
ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>();
if (featuresModule != null)
featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest;
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_enabled) return;
lock (m_syncy)
{
if (m_scenes.Contains(scene))
{
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnChatFromWorld -= OnChatFromWorld;
scene.EventManager.OnChatBroadcast -= OnChatBroadcast;
m_scenes.Remove(scene);
}
}
}
public virtual void Close()
{
}
public virtual void PostInitialise()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "ChatModule"; }
}
#endregion
public virtual void OnNewClient(IClientAPI client)
{
client.OnChatFromClient += OnChatFromClient;
}
protected OSChatMessage FixPositionOfChatMessage(OSChatMessage c)
{
ScenePresence avatar;
Scene scene = (Scene)c.Scene;
if ((avatar = scene.GetScenePresence(c.Sender.AgentId)) != null)
c.Position = avatar.AbsolutePosition;
return c;
}
public virtual void OnChatFromClient(Object sender, OSChatMessage c)
{
c = FixPositionOfChatMessage(c);
// redistribute to interested subscribers
Scene scene = (Scene)c.Scene;
scene.EventManager.TriggerOnChatFromClient(sender, c);
// early return if not on public or debug channel
if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return;
// sanity check:
if (c.Sender == null)
{
m_log.ErrorFormat("[CHAT]: OnChatFromClient from {0} has empty Sender field!", sender);
return;
}
if (FreezeCache.Contains(c.Sender.AgentId.ToString()))
{
if (c.Type != ChatTypeEnum.StartTyping || c.Type != ChatTypeEnum.StopTyping)
c.Sender.SendAgentAlertMessage("You may not talk as you are frozen.", false);
}
else
{
DeliverChatToAvatars(ChatSourceType.Agent, c);
}
}
public virtual void OnChatFromWorld(Object sender, OSChatMessage c)
{
// early return if not on public or debug channel
if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return;
DeliverChatToAvatars(ChatSourceType.Object, c);
}
protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c)
{
string fromName = c.From;
string fromNamePrefix = "";
UUID fromID = UUID.Zero;
UUID ownerID = UUID.Zero;
string message = c.Message;
IScene scene = c.Scene;
UUID destination = c.Destination;
Vector3 fromPos = c.Position;
Vector3 regionPos = new Vector3(scene.RegionInfo.WorldLocX, scene.RegionInfo.WorldLocY, 0);
bool checkParcelHide = false;
UUID sourceParcelID = UUID.Zero;
Vector3 hidePos = fromPos;
if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel;
switch (sourceType)
{
case ChatSourceType.Agent:
if (!(scene is Scene))
{
m_log.WarnFormat("[CHAT]: scene {0} is not a Scene object, cannot obtain scene presence for {1}",
scene.RegionInfo.RegionName, c.Sender.AgentId);
return;
}
ScenePresence avatar = (scene as Scene).GetScenePresence(c.Sender.AgentId);
fromPos = avatar.AbsolutePosition;
fromName = avatar.Name;
fromID = c.Sender.AgentId;
if (avatar.GodLevel >= 200)
{ // let gods speak to outside or things may get confusing
fromNamePrefix = m_adminPrefix;
checkParcelHide = false;
}
else
{
checkParcelHide = true;
}
destination = UUID.Zero; // Avatars cant "SayTo"
ownerID = c.Sender.AgentId;
hidePos = fromPos;
break;
case ChatSourceType.Object:
fromID = c.SenderUUID;
if (c.SenderObject != null && c.SenderObject is SceneObjectPart)
{
ownerID = ((SceneObjectPart)c.SenderObject).OwnerID;
if (((SceneObjectPart)c.SenderObject).ParentGroup.IsAttachment)
{
checkParcelHide = true;
hidePos = ((SceneObjectPart)c.SenderObject).ParentGroup.AbsolutePosition;
}
}
break;
}
// TODO: iterate over message
if (message.Length >= 1000) // libomv limit
message = message.Substring(0, 1000);
// m_log.DebugFormat(
// "[CHAT]: DCTA: fromID {0} fromName {1}, region{2}, cType {3}, sType {4}",
// fromID, fromName, scene.RegionInfo.RegionName, c.Type, sourceType);
HashSet<UUID> receiverIDs = new HashSet<UUID>();
if (checkParcelHide)
{
checkParcelHide = false;
if (c.Type < ChatTypeEnum.DebugChannel && destination == UUID.Zero)
{
ILandObject srcland = (scene as Scene).LandChannel.GetLandObject(hidePos.X, hidePos.Y);
if (srcland != null && !srcland.LandData.SeeAVs)
{
sourceParcelID = srcland.LandData.GlobalID;
checkParcelHide = true;
}
}
}
foreach (Scene s in m_scenes)
{
// This should use ForEachClient, but clients don't have a position.
// If camera is moved into client, then camera position can be used
// MT: No, it can't, as chat is heard from the avatar position, not
// the camera position.
s.ForEachScenePresence(
delegate(ScenePresence presence)
{
if (destination != UUID.Zero && presence.UUID != destination)
return;
ILandObject Presencecheck = s.LandChannel.GetLandObject(presence.AbsolutePosition.X, presence.AbsolutePosition.Y);
if (Presencecheck != null)
{
// This will pass all chat from objects. Not
// perfect, but it will do. For now. Better
// than the prior behavior of muting all
// objects on a parcel with access restrictions
if (checkParcelHide)
{
if (sourceParcelID != Presencecheck.LandData.GlobalID && presence.GodLevel < 200)
return;
}
if (c.Sender == null || Presencecheck.IsEitherBannedOrRestricted(c.Sender.AgentId) != true)
{
if (TrySendChatMessage(presence, fromPos, regionPos, fromID,
ownerID, fromNamePrefix + fromName, c.Type,
message, sourceType, (destination != UUID.Zero)))
receiverIDs.Add(presence.UUID);
}
}
else if(!checkParcelHide && (presence.IsChildAgent))
{
if (TrySendChatMessage(presence, fromPos, regionPos, fromID,
ownerID, fromNamePrefix + fromName, c.Type,
message, sourceType, (destination != UUID.Zero)))
receiverIDs.Add(presence.UUID);
}
}
);
}
(scene as Scene).EventManager.TriggerOnChatToClients(
fromID, receiverIDs, message, c.Type, fromPos, fromName, sourceType, ChatAudibleLevel.Fully);
}
static private Vector3 CenterOfRegion = new Vector3(128, 128, 30);
public virtual void OnChatBroadcast(Object sender, OSChatMessage c)
{
if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return;
ChatTypeEnum cType = c.Type;
if (c.Channel == DEBUG_CHANNEL)
cType = ChatTypeEnum.DebugChannel;
if (cType == ChatTypeEnum.Region)
cType = ChatTypeEnum.Say;
if (c.Message.Length > 1100)
c.Message = c.Message.Substring(0, 1000);
// broadcast chat works by redistributing every incoming chat
// message to each avatar in the scene.
string fromName = c.From;
UUID fromID = UUID.Zero;
UUID ownerID = UUID.Zero;
ChatSourceType sourceType = ChatSourceType.Object;
if (null != c.Sender)
{
ScenePresence avatar = (c.Scene as Scene).GetScenePresence(c.Sender.AgentId);
fromID = c.Sender.AgentId;
fromName = avatar.Name;
ownerID = c.Sender.AgentId;
sourceType = ChatSourceType.Agent;
}
else if (c.SenderUUID != UUID.Zero)
{
fromID = c.SenderUUID;
ownerID = ((SceneObjectPart)c.SenderObject).OwnerID;
}
// m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType);
HashSet<UUID> receiverIDs = new HashSet<UUID>();
if (c.Scene != null)
{
((Scene)c.Scene).ForEachRootClient
(
delegate(IClientAPI client)
{
// don't forward SayOwner chat from objects to
// non-owner agents
if ((c.Type == ChatTypeEnum.Owner) &&
(null != c.SenderObject) &&
(((SceneObjectPart)c.SenderObject).OwnerID != client.AgentId))
return;
client.SendChatMessage(c.Message, (byte)cType, CenterOfRegion, fromName, fromID, fromID,
(byte)sourceType, (byte)ChatAudibleLevel.Fully);
receiverIDs.Add(client.AgentId);
}
);
(c.Scene as Scene).EventManager.TriggerOnChatToClients(
fromID, receiverIDs, c.Message, cType, CenterOfRegion, fromName, sourceType, ChatAudibleLevel.Fully);
}
}
/// <summary>
/// Try to send a message to the given presence
/// </summary>
/// <param name="presence">The receiver</param>
/// <param name="fromPos"></param>
/// <param name="regionPos">/param>
/// <param name="fromAgentID"></param>
/// <param name='ownerID'>
/// Owner of the message. For at least some messages from objects, this has to be correctly filled with the owner's UUID.
/// This is the case for script error messages in viewer 3 since LLViewer change EXT-7762
/// </param>
/// <param name="fromName"></param>
/// <param name="type"></param>
/// <param name="message"></param>
/// <param name="src"></param>
/// <returns>true if the message was sent to the receiver, false if it was not sent due to failing a
/// precondition</returns>
protected virtual bool TrySendChatMessage(
ScenePresence presence, Vector3 fromPos, Vector3 regionPos,
UUID fromAgentID, UUID ownerID, string fromName, ChatTypeEnum type,
string message, ChatSourceType src, bool ignoreDistance)
{
if (presence.LifecycleState != ScenePresenceState.Running)
return false;
if (!ignoreDistance)
{
Vector3 fromRegionPos = fromPos + regionPos;
Vector3 toRegionPos = presence.AbsolutePosition +
new Vector3(presence.Scene.RegionInfo.WorldLocX, presence.Scene.RegionInfo.WorldLocY, 0);
int dis = (int)Util.GetDistanceTo(toRegionPos, fromRegionPos);
if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance ||
type == ChatTypeEnum.Say && dis > m_saydistance ||
type == ChatTypeEnum.Shout && dis > m_shoutdistance)
{
return false;
}
}
// TODO: should change so the message is sent through the avatar rather than direct to the ClientView
presence.ControllingClient.SendChatMessage(
message, (byte) type, fromPos, fromName,
fromAgentID, ownerID, (byte)src, (byte)ChatAudibleLevel.Fully);
return true;
}
Dictionary<UUID, System.Threading.Timer> Timers = new Dictionary<UUID, System.Threading.Timer>();
public void ParcelFreezeUser(IClientAPI client, UUID parcelowner, uint flags, UUID target)
{
System.Threading.Timer Timer;
if (flags == 0)
{
FreezeCache.Add(target.ToString());
System.Threading.TimerCallback timeCB = new System.Threading.TimerCallback(OnEndParcelFrozen);
Timer = new System.Threading.Timer(timeCB, target, 30000, 0);
Timers.Add(target, Timer);
}
else
{
FreezeCache.Remove(target.ToString());
Timers.TryGetValue(target, out Timer);
Timers.Remove(target);
Timer.Dispose();
}
}
private void OnEndParcelFrozen(object avatar)
{
UUID target = (UUID)avatar;
FreezeCache.Remove(target.ToString());
System.Threading.Timer Timer;
Timers.TryGetValue(target, out Timer);
Timers.Remove(target);
Timer.Dispose();
}
#region SimulatorFeaturesRequest
static OSDInteger m_SayRange, m_WhisperRange, m_ShoutRange;
private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features)
{
OSD extras = new OSDMap();
if (features.ContainsKey("OpenSimExtras"))
extras = features["OpenSimExtras"];
else
features["OpenSimExtras"] = extras;
if (m_SayRange == null)
{
// Do this only once
m_SayRange = new OSDInteger(m_saydistance);
m_WhisperRange = new OSDInteger(m_whisperdistance);
m_ShoutRange = new OSDInteger(m_shoutdistance);
}
((OSDMap)extras)["say-range"] = m_SayRange;
((OSDMap)extras)["whisper-range"] = m_WhisperRange;
((OSDMap)extras)["shout-range"] = m_ShoutRange;
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Online.API;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens;
using osu.Game.Storyboards;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestScene : TestScene
{
protected Bindable<WorkingBeatmap> Beatmap { get; private set; }
protected Bindable<RulesetInfo> Ruleset;
protected Bindable<IReadOnlyList<Mod>> SelectedMods;
protected new OsuScreenDependencies Dependencies { get; private set; }
private Lazy<Storage> localStorage;
protected Storage LocalStorage => localStorage.Value;
private readonly Lazy<DatabaseContextFactory> contextFactory;
protected IAPIProvider API
{
get
{
if (UseOnlineAPI)
throw new InvalidOperationException($"Using the {nameof(OsuTestScene)} dummy API is not supported when {nameof(UseOnlineAPI)} is true");
return dummyAPI;
}
}
private DummyAPIAccess dummyAPI;
protected DatabaseContextFactory ContextFactory => contextFactory.Value;
/// <summary>
/// Whether this test scene requires real-world API access.
/// If true, this will bypass the local <see cref="DummyAPIAccess"/> and use the <see cref="OsuGameBase"/> provided one.
/// </summary>
protected virtual bool UseOnlineAPI => false;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
Dependencies = new OsuScreenDependencies(false, base.CreateChildDependencies(parent));
Beatmap = Dependencies.Beatmap;
Beatmap.SetDefault();
Ruleset = Dependencies.Ruleset;
Ruleset.SetDefault();
SelectedMods = Dependencies.Mods;
SelectedMods.SetDefault();
if (!UseOnlineAPI)
{
dummyAPI = new DummyAPIAccess();
Dependencies.CacheAs<IAPIProvider>(dummyAPI);
Add(dummyAPI);
}
return Dependencies;
}
protected override Container<Drawable> Content => content ?? base.Content;
private readonly Container content;
protected OsuTestScene()
{
RecycleLocalStorage();
contextFactory = new Lazy<DatabaseContextFactory>(() =>
{
var factory = new DatabaseContextFactory(LocalStorage);
factory.ResetDatabase();
using (var usage = factory.Get())
usage.Migrate();
return factory;
});
base.Content.Add(content = new DrawSizePreservingFillContainer());
}
public virtual void RecycleLocalStorage()
{
if (localStorage?.IsValueCreated == true)
{
try
{
localStorage.Value.DeleteDirectory(".");
}
catch
{
// we don't really care if this fails; it will just leave folders lying around from test runs.
}
}
localStorage = new Lazy<Storage>(() => new NativeStorage($"{GetType().Name}-{Guid.NewGuid()}"));
}
[Resolved]
protected AudioManager Audio { get; private set; }
protected virtual IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset);
protected WorkingBeatmap CreateWorkingBeatmap(RulesetInfo ruleset) =>
CreateWorkingBeatmap(CreateBeatmap(ruleset), null);
protected virtual WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null) =>
new ClockBackedTestWorkingBeatmap(beatmap, storyboard, Clock, Audio);
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
Ruleset.Value = rulesets.AvailableRulesets.First();
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (Beatmap?.Value.TrackLoaded == true)
Beatmap.Value.Track.Stop();
if (contextFactory.IsValueCreated)
contextFactory.Value.ResetDatabase();
RecycleLocalStorage();
}
protected override ITestSceneTestRunner CreateRunner() => new OsuTestSceneTestRunner();
public class ClockBackedTestWorkingBeatmap : TestWorkingBeatmap
{
private readonly Track track;
private readonly TrackVirtualStore store;
/// <summary>
/// Create an instance which creates a <see cref="TestBeatmap"/> for the provided ruleset when requested.
/// </summary>
/// <param name="ruleset">The target ruleset.</param>
/// <param name="referenceClock">A clock which should be used instead of a stopwatch for virtual time progression.</param>
/// <param name="audio">Audio manager. Required if a reference clock isn't provided.</param>
public ClockBackedTestWorkingBeatmap(RulesetInfo ruleset, IFrameBasedClock referenceClock, AudioManager audio)
: this(new TestBeatmap(ruleset), null, referenceClock, audio)
{
}
/// <summary>
/// Create an instance which provides the <see cref="IBeatmap"/> when requested.
/// </summary>
/// <param name="beatmap">The beatmap</param>
/// <param name="storyboard">The storyboard.</param>
/// <param name="referenceClock">An optional clock which should be used instead of a stopwatch for virtual time progression.</param>
/// <param name="audio">Audio manager. Required if a reference clock isn't provided.</param>
/// <param name="length">The length of the returned virtual track.</param>
public ClockBackedTestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard, IFrameBasedClock referenceClock, AudioManager audio, double length = 60000)
: base(beatmap, storyboard)
{
if (referenceClock != null)
{
store = new TrackVirtualStore(referenceClock);
audio.AddItem(store);
track = store.GetVirtual(length);
}
else
track = audio?.Tracks.GetVirtual(length);
}
~ClockBackedTestWorkingBeatmap()
{
// Remove the track store from the audio manager
store?.Dispose();
}
protected override Track GetTrack() => track;
public class TrackVirtualStore : AudioCollectionManager<Track>, ITrackStore
{
private readonly IFrameBasedClock referenceClock;
public TrackVirtualStore(IFrameBasedClock referenceClock)
{
this.referenceClock = referenceClock;
}
public Track Get(string name) => throw new NotImplementedException();
public Task<Track> GetAsync(string name) => throw new NotImplementedException();
public Stream GetStream(string name) => throw new NotImplementedException();
public IEnumerable<string> GetAvailableResources() => throw new NotImplementedException();
public Track GetVirtual(double length = double.PositiveInfinity)
{
var track = new TrackVirtualManual(referenceClock) { Length = length };
AddItem(track);
return track;
}
}
/// <summary>
/// A virtual track which tracks a reference clock.
/// </summary>
public class TrackVirtualManual : Track
{
private readonly IFrameBasedClock referenceClock;
private bool running;
public TrackVirtualManual(IFrameBasedClock referenceClock)
{
this.referenceClock = referenceClock;
Length = double.PositiveInfinity;
}
public override bool Seek(double seek)
{
accumulated = Math.Clamp(seek, 0, Length);
lastReferenceTime = null;
return accumulated == seek;
}
public override void Start()
{
running = true;
}
public override void Reset()
{
Seek(0);
base.Reset();
}
public override void Stop()
{
if (running)
{
running = false;
lastReferenceTime = null;
}
}
public override bool IsRunning => running;
private double? lastReferenceTime;
private double accumulated;
public override double CurrentTime => Math.Min(accumulated, Length);
protected override void UpdateState()
{
base.UpdateState();
if (running)
{
double refTime = referenceClock.CurrentTime;
if (lastReferenceTime.HasValue)
accumulated += (refTime - lastReferenceTime.Value) * Rate;
lastReferenceTime = refTime;
}
if (CurrentTime >= Length)
{
Stop();
RaiseCompleted();
}
}
}
}
public class OsuTestSceneTestRunner : OsuGameBase, ITestSceneTestRunner
{
private TestSceneTestRunner.TestRunner runner;
protected override void LoadAsyncComplete()
{
// this has to be run here rather than LoadComplete because
// TestScene.cs is checking the IsLoaded state (on another thread) and expects
// the runner to be loaded at that point.
Add(runner = new TestSceneTestRunner.TestRunner());
}
public void RunTestBlocking(TestScene test) => runner.RunTestBlocking(test);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace _1._3.Web_Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// System.Web.Services.Description.WebServicesInteroperability.cs
//
// Author:
// Lluis Sanchez ([email protected])
//
// Copyright (C) Novell, Inc., 2004
//
//
// 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 NET_2_0
using System.Collections;
using System.Xml.Schema;
namespace System.Web.Services.Description
{
public sealed class WebServicesInteroperability
{
private WebServicesInteroperability ()
{
}
[MonoTODO]
public static bool CheckConformance (WsiClaims claims, ServiceDescription service, BasicProfileViolationCollection violations)
{
ServiceDescriptionCollection col = new ServiceDescriptionCollection ();
col.Add (service);
ConformanceCheckContext ctx = new ConformanceCheckContext (col, violations);
return Check (claims, ctx, col);
}
[MonoTODO]
public static bool CheckConformance (WsiClaims claims, ServiceDescriptionCollection services, BasicProfileViolationCollection violations)
{
ConformanceCheckContext ctx = new ConformanceCheckContext (services, violations);
return Check (claims, ctx, services);
}
[MonoTODO]
public static bool CheckConformance (WsiClaims claims, WebReference webReference, BasicProfileViolationCollection violations)
{
ConformanceCheckContext ctx = new ConformanceCheckContext (webReference, violations);
return Check (claims, ctx, webReference.Documents.Values);
}
static bool Check (WsiClaims claims, ConformanceCheckContext ctx, IEnumerable documents)
{
ConformanceChecker[] checkers = GetCheckers (claims);
if (checkers == null) return true;
foreach (object doc in documents) {
if (!(doc is ServiceDescription)) continue;
foreach (ConformanceChecker c in checkers)
Check (ctx, c, (ServiceDescription)doc);
}
return ctx.Violations.Count == 0;
}
static ConformanceChecker[] GetCheckers (WsiClaims claims)
{
if ((claims & WsiClaims.BP10) != 0)
return new ConformanceChecker[] { BasicProfileChecker.Instance };
return null;
}
static void Check (ConformanceCheckContext ctx, ConformanceChecker checker, ServiceDescription sd)
{
ctx.ServiceDescription = sd;
ctx.Checker = checker;
checker.Check (ctx, sd);
CheckExtensions (ctx, checker, sd.Extensions);
foreach (Import i in sd.Imports) {
checker.Check (ctx, i);
}
foreach (Service s in sd.Services) {
checker.Check (ctx, s);
foreach (Port p in s.Ports) {
checker.Check (ctx, p);
CheckExtensions (ctx, checker, p.Extensions);
}
}
foreach (Binding b in sd.Bindings)
{
checker.Check (ctx, b);
CheckExtensions (ctx, checker, b.Extensions);
foreach (OperationBinding oper in b.Operations) {
CheckExtensions (ctx, checker, oper.Extensions);
foreach (MessageBinding mb in oper.Faults) {
checker.Check (ctx, mb);
CheckExtensions (ctx, checker, mb.Extensions);
}
checker.Check (ctx, oper.Input);
CheckExtensions (ctx, checker, oper.Input.Extensions);
checker.Check (ctx, oper.Output);
CheckExtensions (ctx, checker, oper.Output.Extensions);
}
}
foreach (PortType pt in sd.PortTypes)
{
checker.Check (ctx, pt);
foreach (Operation oper in pt.Operations) {
checker.Check (ctx, oper);
foreach (OperationMessage msg in oper.Messages)
checker.Check (ctx, msg);
foreach (OperationMessage msg in oper.Faults)
checker.Check (ctx, msg);
}
}
foreach (Message msg in sd.Messages)
{
checker.Check (ctx, msg);
foreach (MessagePart part in msg.Parts)
checker.Check (ctx, part);
}
if (sd.Types != null) {
checker.Check (ctx, sd.Types);
if (sd.Types.Schemas != null) {
foreach (XmlSchema s in sd.Types.Schemas) {
ctx.CurrentSchema = s;
checker.Check (ctx, s);
CheckObjects (ctx, checker, new Hashtable (), s.Items);
}
}
}
}
static void CheckObjects (ConformanceCheckContext ctx, ConformanceChecker checker, Hashtable visitedObjects, XmlSchemaObjectCollection col)
{
foreach (XmlSchemaObject item in col)
Check (ctx, checker, visitedObjects, item);
}
static void Check (ConformanceCheckContext ctx, ConformanceChecker checker, Hashtable visitedObjects, XmlSchemaObject value)
{
if (value == null) return;
if (visitedObjects.Contains (value)) return;
visitedObjects.Add (value, value);
if (value is XmlSchemaImport) {
XmlSchemaImport so = (XmlSchemaImport) value;
checker.Check (ctx, so);
}
else if (value is XmlSchemaAll) {
XmlSchemaAll so = (XmlSchemaAll) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Items);
}
else if (value is XmlSchemaAnnotation) {
XmlSchemaAnnotation so = (XmlSchemaAnnotation) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Items);
}
else if (value is XmlSchemaAttribute) {
XmlSchemaAttribute so = (XmlSchemaAttribute) value;
checker.Check (ctx, so);
}
else if (value is XmlSchemaAttributeGroup) {
XmlSchemaAttributeGroup so = (XmlSchemaAttributeGroup) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Attributes);
Check (ctx, checker, visitedObjects, so.AnyAttribute);
Check (ctx, checker, visitedObjects, so.RedefinedAttributeGroup);
}
else if (value is XmlSchemaAttributeGroupRef) {
XmlSchemaAttributeGroupRef so = (XmlSchemaAttributeGroupRef) value;
checker.Check (ctx, so);
}
else if (value is XmlSchemaChoice) {
XmlSchemaChoice so = (XmlSchemaChoice) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Items);
}
else if (value is XmlSchemaComplexContent) {
XmlSchemaComplexContent so = (XmlSchemaComplexContent) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.Content);
}
else if (value is XmlSchemaComplexContentExtension) {
XmlSchemaComplexContentExtension so = (XmlSchemaComplexContentExtension) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.Particle);
CheckObjects (ctx, checker, visitedObjects, so.Attributes);
Check (ctx, checker, visitedObjects, so.AnyAttribute);
}
else if (value is XmlSchemaComplexContentRestriction) {
XmlSchemaComplexContentRestriction so = (XmlSchemaComplexContentRestriction) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.Particle);
CheckObjects (ctx, checker, visitedObjects, so.Attributes);
Check (ctx, checker, visitedObjects, so.AnyAttribute);
}
else if (value is XmlSchemaComplexType) {
XmlSchemaComplexType so = (XmlSchemaComplexType) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.ContentModel);
Check (ctx, checker, visitedObjects, so.Particle);
CheckObjects (ctx, checker, visitedObjects, so.Attributes);
Check (ctx, checker, visitedObjects, so.AnyAttribute);
Check (ctx, checker, visitedObjects, so.ContentTypeParticle);
Check (ctx, checker, visitedObjects, so.AttributeWildcard);
}
else if (value is XmlSchemaElement) {
XmlSchemaElement so = (XmlSchemaElement) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.SchemaType);
CheckObjects (ctx, checker, visitedObjects, so.Constraints);
}
else if (value is XmlSchemaGroup) {
XmlSchemaGroup so = (XmlSchemaGroup) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.Particle);
}
else if (value is XmlSchemaGroupRef) {
XmlSchemaGroupRef so = (XmlSchemaGroupRef) value;
checker.Check (ctx, so);
}
else if (value is XmlSchemaIdentityConstraint) {
XmlSchemaIdentityConstraint so = (XmlSchemaIdentityConstraint) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Fields);
Check (ctx, checker, visitedObjects, so.Selector);
}
else if (value is XmlSchemaKeyref) {
XmlSchemaKeyref so = (XmlSchemaKeyref) value;
checker.Check (ctx, so);
}
else if (value is XmlSchemaRedefine) {
XmlSchemaRedefine so = (XmlSchemaRedefine) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Items);
}
else if (value is XmlSchemaSequence) {
XmlSchemaSequence so = (XmlSchemaSequence) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Items);
}
else if (value is XmlSchemaSimpleContent) {
XmlSchemaSimpleContent so = (XmlSchemaSimpleContent) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.Content);
}
else if (value is XmlSchemaSimpleContentExtension) {
XmlSchemaSimpleContentExtension so = (XmlSchemaSimpleContentExtension) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Attributes);
Check (ctx, checker, visitedObjects, so.AnyAttribute);
}
else if (value is XmlSchemaSimpleContentRestriction) {
XmlSchemaSimpleContentRestriction so = (XmlSchemaSimpleContentRestriction) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Attributes);
Check (ctx, checker, visitedObjects, so.AnyAttribute);
CheckObjects (ctx, checker, visitedObjects, so.Facets);
}
else if (value is XmlSchemaSimpleType) {
XmlSchemaSimpleType so = (XmlSchemaSimpleType) value;
checker.Check (ctx, so);
Check (ctx, checker, visitedObjects, so.Content);
}
else if (value is XmlSchemaSimpleTypeList) {
XmlSchemaSimpleTypeList so = (XmlSchemaSimpleTypeList) value;
checker.Check (ctx, so);
}
else if (value is XmlSchemaSimpleTypeRestriction) {
XmlSchemaSimpleTypeRestriction so = (XmlSchemaSimpleTypeRestriction) value;
checker.Check (ctx, so);
CheckObjects (ctx, checker, visitedObjects, so.Facets);
}
else if (value is XmlSchemaSimpleTypeUnion) {
XmlSchemaSimpleTypeUnion so = (XmlSchemaSimpleTypeUnion) value;
checker.Check (ctx, so);
}
}
static void CheckExtensions (ConformanceCheckContext ctx, ConformanceChecker checker, ServiceDescriptionFormatExtensionCollection extensions)
{
foreach (ServiceDescriptionFormatExtension ext in extensions)
checker.Check (ctx, ext);
}
}
}
#endif
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// ScreenRecordingResponse
/// </summary>
[DataContract]
public partial class ScreenRecordingResponse : IEquatable<ScreenRecordingResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ScreenRecordingResponse" /> class.
/// </summary>
/// <param name="checkoutOnly">checkoutOnly.</param>
/// <param name="error">error.</param>
/// <param name="metadata">metadata.</param>
/// <param name="screenRecording">screenRecording.</param>
/// <param name="success">Indicates if API call was successful.</param>
/// <param name="warning">warning.</param>
public ScreenRecordingResponse(bool? checkoutOnly = default(bool?), Error error = default(Error), ResponseMetadata metadata = default(ResponseMetadata), ScreenRecording screenRecording = default(ScreenRecording), bool? success = default(bool?), Warning warning = default(Warning))
{
this.CheckoutOnly = checkoutOnly;
this.Error = error;
this.Metadata = metadata;
this.ScreenRecording = screenRecording;
this.Success = success;
this.Warning = warning;
}
/// <summary>
/// Gets or Sets CheckoutOnly
/// </summary>
[DataMember(Name="checkout_only", EmitDefaultValue=false)]
public bool? CheckoutOnly { get; set; }
/// <summary>
/// Gets or Sets Error
/// </summary>
[DataMember(Name="error", EmitDefaultValue=false)]
public Error Error { get; set; }
/// <summary>
/// Gets or Sets Metadata
/// </summary>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public ResponseMetadata Metadata { get; set; }
/// <summary>
/// Gets or Sets ScreenRecording
/// </summary>
[DataMember(Name="screen_recording", EmitDefaultValue=false)]
public ScreenRecording ScreenRecording { get; set; }
/// <summary>
/// Indicates if API call was successful
/// </summary>
/// <value>Indicates if API call was successful</value>
[DataMember(Name="success", EmitDefaultValue=false)]
public bool? Success { get; set; }
/// <summary>
/// Gets or Sets Warning
/// </summary>
[DataMember(Name="warning", EmitDefaultValue=false)]
public Warning Warning { 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 ScreenRecordingResponse {\n");
sb.Append(" CheckoutOnly: ").Append(CheckoutOnly).Append("\n");
sb.Append(" Error: ").Append(Error).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" ScreenRecording: ").Append(ScreenRecording).Append("\n");
sb.Append(" Success: ").Append(Success).Append("\n");
sb.Append(" Warning: ").Append(Warning).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ScreenRecordingResponse);
}
/// <summary>
/// Returns true if ScreenRecordingResponse instances are equal
/// </summary>
/// <param name="input">Instance of ScreenRecordingResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ScreenRecordingResponse input)
{
if (input == null)
return false;
return
(
this.CheckoutOnly == input.CheckoutOnly ||
(this.CheckoutOnly != null &&
this.CheckoutOnly.Equals(input.CheckoutOnly))
) &&
(
this.Error == input.Error ||
(this.Error != null &&
this.Error.Equals(input.Error))
) &&
(
this.Metadata == input.Metadata ||
(this.Metadata != null &&
this.Metadata.Equals(input.Metadata))
) &&
(
this.ScreenRecording == input.ScreenRecording ||
(this.ScreenRecording != null &&
this.ScreenRecording.Equals(input.ScreenRecording))
) &&
(
this.Success == input.Success ||
(this.Success != null &&
this.Success.Equals(input.Success))
) &&
(
this.Warning == input.Warning ||
(this.Warning != null &&
this.Warning.Equals(input.Warning))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CheckoutOnly != null)
hashCode = hashCode * 59 + this.CheckoutOnly.GetHashCode();
if (this.Error != null)
hashCode = hashCode * 59 + this.Error.GetHashCode();
if (this.Metadata != null)
hashCode = hashCode * 59 + this.Metadata.GetHashCode();
if (this.ScreenRecording != null)
hashCode = hashCode * 59 + this.ScreenRecording.GetHashCode();
if (this.Success != null)
hashCode = hashCode * 59 + this.Success.GetHashCode();
if (this.Warning != null)
hashCode = hashCode * 59 + this.Warning.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="AdScheduleViewServiceClient"/> instances.</summary>
public sealed partial class AdScheduleViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdScheduleViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdScheduleViewServiceSettings"/>.</returns>
public static AdScheduleViewServiceSettings GetDefault() => new AdScheduleViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdScheduleViewServiceSettings"/> object with default settings.
/// </summary>
public AdScheduleViewServiceSettings()
{
}
private AdScheduleViewServiceSettings(AdScheduleViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdScheduleViewSettings = existing.GetAdScheduleViewSettings;
OnCopy(existing);
}
partial void OnCopy(AdScheduleViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdScheduleViewServiceClient.GetAdScheduleView</c> and
/// <c>AdScheduleViewServiceClient.GetAdScheduleViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdScheduleViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdScheduleViewServiceSettings"/> object.</returns>
public AdScheduleViewServiceSettings Clone() => new AdScheduleViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdScheduleViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdScheduleViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdScheduleViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdScheduleViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdScheduleViewServiceClientBuilder()
{
UseJwtAccessWithScopes = AdScheduleViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdScheduleViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdScheduleViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdScheduleViewServiceClient Build()
{
AdScheduleViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdScheduleViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdScheduleViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdScheduleViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdScheduleViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdScheduleViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdScheduleViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdScheduleViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdScheduleViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdScheduleViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdScheduleViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch ad schedule views.
/// </remarks>
public abstract partial class AdScheduleViewServiceClient
{
/// <summary>
/// The default endpoint for the AdScheduleViewService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdScheduleViewService scopes.</summary>
/// <remarks>
/// The default AdScheduleViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdScheduleViewServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdScheduleViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdScheduleViewServiceClient"/>.</returns>
public static stt::Task<AdScheduleViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdScheduleViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdScheduleViewServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdScheduleViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdScheduleViewServiceClient"/>.</returns>
public static AdScheduleViewServiceClient Create() => new AdScheduleViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdScheduleViewServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdScheduleViewServiceSettings"/>.</param>
/// <returns>The created <see cref="AdScheduleViewServiceClient"/>.</returns>
internal static AdScheduleViewServiceClient Create(grpccore::CallInvoker callInvoker, AdScheduleViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdScheduleViewService.AdScheduleViewServiceClient grpcClient = new AdScheduleViewService.AdScheduleViewServiceClient(callInvoker);
return new AdScheduleViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdScheduleViewService client</summary>
public virtual AdScheduleViewService.AdScheduleViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdScheduleView GetAdScheduleView(GetAdScheduleViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(GetAdScheduleViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(GetAdScheduleViewRequest request, st::CancellationToken cancellationToken) =>
GetAdScheduleViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad schedule view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdScheduleView GetAdScheduleView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdScheduleView(new GetAdScheduleViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad schedule view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdScheduleViewAsync(new GetAdScheduleViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad schedule view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdScheduleViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad schedule view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdScheduleView GetAdScheduleView(gagvr::AdScheduleViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdScheduleView(new GetAdScheduleViewRequest
{
ResourceNameAsAdScheduleViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad schedule view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(gagvr::AdScheduleViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdScheduleViewAsync(new GetAdScheduleViewRequest
{
ResourceNameAsAdScheduleViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad schedule view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(gagvr::AdScheduleViewName resourceName, st::CancellationToken cancellationToken) =>
GetAdScheduleViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdScheduleViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch ad schedule views.
/// </remarks>
public sealed partial class AdScheduleViewServiceClientImpl : AdScheduleViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdScheduleViewRequest, gagvr::AdScheduleView> _callGetAdScheduleView;
/// <summary>
/// Constructs a client wrapper for the AdScheduleViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AdScheduleViewServiceSettings"/> used within this client.</param>
public AdScheduleViewServiceClientImpl(AdScheduleViewService.AdScheduleViewServiceClient grpcClient, AdScheduleViewServiceSettings settings)
{
GrpcClient = grpcClient;
AdScheduleViewServiceSettings effectiveSettings = settings ?? AdScheduleViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdScheduleView = clientHelper.BuildApiCall<GetAdScheduleViewRequest, gagvr::AdScheduleView>(grpcClient.GetAdScheduleViewAsync, grpcClient.GetAdScheduleView, effectiveSettings.GetAdScheduleViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdScheduleView);
Modify_GetAdScheduleViewApiCall(ref _callGetAdScheduleView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdScheduleViewApiCall(ref gaxgrpc::ApiCall<GetAdScheduleViewRequest, gagvr::AdScheduleView> call);
partial void OnConstruction(AdScheduleViewService.AdScheduleViewServiceClient grpcClient, AdScheduleViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdScheduleViewService client</summary>
public override AdScheduleViewService.AdScheduleViewServiceClient GrpcClient { get; }
partial void Modify_GetAdScheduleViewRequest(ref GetAdScheduleViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdScheduleView GetAdScheduleView(GetAdScheduleViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdScheduleViewRequest(ref request, ref callSettings);
return _callGetAdScheduleView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad schedule view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdScheduleView> GetAdScheduleViewAsync(GetAdScheduleViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdScheduleViewRequest(ref request, ref callSettings);
return _callGetAdScheduleView.Async(request, callSettings);
}
}
}
| |
namespace Obops
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Operators
{
private Func<object, object, object>[,] AddFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] SubtractFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] MultiplyFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] DivideFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] EqualFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] NotEqualFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] GreaterFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] GreaterEqualFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] LessFunctions = new Func<object, object, object>[20, 20];
private Func<object, object, object>[,] LessEqualFunctions = new Func<object, object, object>[20, 20];
public Operators()
{
this.AddFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left + (short)right;
this.AddFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left + (int)right;
this.AddFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left + (long)right;
this.AddFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left + (float)right;
this.AddFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left + (double)right;
this.AddFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left + (short)right;
this.AddFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left + (int)right;
this.AddFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left + (long)right;
this.AddFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left + (float)right;
this.AddFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left + (double)right;
this.AddFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left + (short)right;
this.AddFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left + (int)right;
this.AddFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left + (long)right;
this.AddFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left + (float)right;
this.AddFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left + (double)right;
this.AddFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left + (short)right;
this.AddFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left + (int)right;
this.AddFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left + (long)right;
this.AddFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left + (float)right;
this.AddFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left + (double)right;
this.AddFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left + (short)right;
this.AddFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left + (int)right;
this.AddFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left + (long)right;
this.AddFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left + (float)right;
this.AddFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left + (double)right;
this.SubtractFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left - (short)right;
this.SubtractFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left - (int)right;
this.SubtractFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left - (long)right;
this.SubtractFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left - (float)right;
this.SubtractFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left - (double)right;
this.SubtractFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left - (short)right;
this.SubtractFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left - (int)right;
this.SubtractFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left - (long)right;
this.SubtractFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left - (float)right;
this.SubtractFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left - (double)right;
this.SubtractFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left - (short)right;
this.SubtractFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left - (int)right;
this.SubtractFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left - (long)right;
this.SubtractFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left - (float)right;
this.SubtractFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left - (double)right;
this.SubtractFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left - (short)right;
this.SubtractFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left - (int)right;
this.SubtractFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left - (long)right;
this.SubtractFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left - (float)right;
this.SubtractFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left - (double)right;
this.SubtractFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left - (short)right;
this.SubtractFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left - (int)right;
this.SubtractFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left - (long)right;
this.SubtractFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left - (float)right;
this.SubtractFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left - (double)right;
this.MultiplyFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left * (short)right;
this.MultiplyFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left * (int)right;
this.MultiplyFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left * (long)right;
this.MultiplyFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left * (float)right;
this.MultiplyFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left * (double)right;
this.MultiplyFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left * (short)right;
this.MultiplyFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left * (int)right;
this.MultiplyFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left * (long)right;
this.MultiplyFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left * (float)right;
this.MultiplyFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left * (double)right;
this.MultiplyFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left * (short)right;
this.MultiplyFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left * (int)right;
this.MultiplyFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left * (long)right;
this.MultiplyFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left * (float)right;
this.MultiplyFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left * (double)right;
this.MultiplyFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left * (short)right;
this.MultiplyFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left * (int)right;
this.MultiplyFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left * (long)right;
this.MultiplyFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left * (float)right;
this.MultiplyFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left * (double)right;
this.MultiplyFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left * (short)right;
this.MultiplyFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left * (int)right;
this.MultiplyFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left * (long)right;
this.MultiplyFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left * (float)right;
this.MultiplyFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left * (double)right;
this.DivideFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left / (short)right;
this.DivideFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left / (int)right;
this.DivideFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left / (long)right;
this.DivideFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left / (float)right;
this.DivideFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left / (double)right;
this.DivideFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left / (short)right;
this.DivideFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left / (int)right;
this.DivideFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left / (long)right;
this.DivideFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left / (float)right;
this.DivideFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left / (double)right;
this.DivideFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left / (short)right;
this.DivideFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left / (int)right;
this.DivideFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left / (long)right;
this.DivideFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left / (float)right;
this.DivideFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left / (double)right;
this.DivideFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left / (short)right;
this.DivideFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left / (int)right;
this.DivideFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left / (long)right;
this.DivideFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left / (float)right;
this.DivideFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left / (double)right;
this.DivideFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left / (short)right;
this.DivideFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left / (int)right;
this.DivideFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left / (long)right;
this.DivideFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left / (float)right;
this.DivideFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left / (double)right;
this.EqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left == (short)right;
this.EqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left == (int)right;
this.EqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left == (long)right;
this.EqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left == (float)right;
this.EqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left == (double)right;
this.EqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left == (short)right;
this.EqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left == (int)right;
this.EqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left == (long)right;
this.EqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left == (float)right;
this.EqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left == (double)right;
this.EqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left == (short)right;
this.EqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left == (int)right;
this.EqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left == (long)right;
this.EqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left == (float)right;
this.EqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left == (double)right;
this.EqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left == (short)right;
this.EqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left == (int)right;
this.EqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left == (long)right;
this.EqualFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left == (float)right;
this.EqualFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left == (double)right;
this.EqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left == (short)right;
this.EqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left == (int)right;
this.EqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left == (long)right;
this.EqualFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left == (float)right;
this.EqualFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left == (double)right;
this.NotEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left != (short)right;
this.NotEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left != (int)right;
this.NotEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left != (long)right;
this.NotEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left != (float)right;
this.NotEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left != (double)right;
this.NotEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left != (short)right;
this.NotEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left != (int)right;
this.NotEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left != (long)right;
this.NotEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left != (float)right;
this.NotEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left != (double)right;
this.NotEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left != (short)right;
this.NotEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left != (int)right;
this.NotEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left != (long)right;
this.NotEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left != (float)right;
this.NotEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left != (double)right;
this.NotEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left != (short)right;
this.NotEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left != (int)right;
this.NotEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left != (long)right;
this.NotEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left != (float)right;
this.NotEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left != (double)right;
this.NotEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left != (short)right;
this.NotEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left != (int)right;
this.NotEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left != (long)right;
this.NotEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left != (float)right;
this.NotEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left != (double)right;
this.GreaterFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left > (short)right;
this.GreaterFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left > (int)right;
this.GreaterFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left > (long)right;
this.GreaterFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left > (float)right;
this.GreaterFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left > (double)right;
this.GreaterFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left > (short)right;
this.GreaterFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left > (int)right;
this.GreaterFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left > (long)right;
this.GreaterFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left > (float)right;
this.GreaterFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left > (double)right;
this.GreaterFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left > (short)right;
this.GreaterFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left > (int)right;
this.GreaterFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left > (long)right;
this.GreaterFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left > (float)right;
this.GreaterFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left > (double)right;
this.GreaterFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left > (short)right;
this.GreaterFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left > (int)right;
this.GreaterFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left > (long)right;
this.GreaterFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left > (float)right;
this.GreaterFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left > (double)right;
this.GreaterFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left > (short)right;
this.GreaterFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left > (int)right;
this.GreaterFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left > (long)right;
this.GreaterFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left > (float)right;
this.GreaterFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left > (double)right;
this.GreaterEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left >= (short)right;
this.GreaterEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left >= (int)right;
this.GreaterEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left >= (long)right;
this.GreaterEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left >= (float)right;
this.GreaterEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left >= (double)right;
this.GreaterEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left >= (short)right;
this.GreaterEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left >= (int)right;
this.GreaterEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left >= (long)right;
this.GreaterEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left >= (float)right;
this.GreaterEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left >= (double)right;
this.GreaterEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left >= (short)right;
this.GreaterEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left >= (int)right;
this.GreaterEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left >= (long)right;
this.GreaterEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left >= (float)right;
this.GreaterEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left >= (double)right;
this.GreaterEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left >= (short)right;
this.GreaterEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left >= (int)right;
this.GreaterEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left >= (long)right;
this.GreaterEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left >= (float)right;
this.GreaterEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left >= (double)right;
this.GreaterEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left >= (short)right;
this.GreaterEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left >= (int)right;
this.GreaterEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left >= (long)right;
this.GreaterEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left >= (float)right;
this.GreaterEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left >= (double)right;
this.LessFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left < (short)right;
this.LessFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left < (int)right;
this.LessFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left < (long)right;
this.LessFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left < (float)right;
this.LessFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left < (double)right;
this.LessFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left < (short)right;
this.LessFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left < (int)right;
this.LessFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left < (long)right;
this.LessFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left < (float)right;
this.LessFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left < (double)right;
this.LessFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left < (short)right;
this.LessFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left < (int)right;
this.LessFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left < (long)right;
this.LessFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left < (float)right;
this.LessFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left < (double)right;
this.LessFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left < (short)right;
this.LessFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left < (int)right;
this.LessFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left < (long)right;
this.LessFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left < (float)right;
this.LessFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left < (double)right;
this.LessFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left < (short)right;
this.LessFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left < (int)right;
this.LessFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left < (long)right;
this.LessFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left < (float)right;
this.LessFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left < (double)right;
this.LessEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int16] = (left, right) => (short)left <= (short)right;
this.LessEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int32] = (left, right) => (short)left <= (int)right;
this.LessEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Int64] = (left, right) => (short)left <= (long)right;
this.LessEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Single] = (left, right) => (short)left <= (float)right;
this.LessEqualFunctions[(int)TypeCode.Int16, (int)TypeCode.Double] = (left, right) => (short)left <= (double)right;
this.LessEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int16] = (left, right) => (int)left <= (short)right;
this.LessEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int32] = (left, right) => (int)left <= (int)right;
this.LessEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Int64] = (left, right) => (int)left <= (long)right;
this.LessEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Single] = (left, right) => (int)left <= (float)right;
this.LessEqualFunctions[(int)TypeCode.Int32, (int)TypeCode.Double] = (left, right) => (int)left <= (double)right;
this.LessEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int16] = (left, right) => (long)left <= (short)right;
this.LessEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int32] = (left, right) => (long)left <= (int)right;
this.LessEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Int64] = (left, right) => (long)left <= (long)right;
this.LessEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Single] = (left, right) => (long)left <= (float)right;
this.LessEqualFunctions[(int)TypeCode.Int64, (int)TypeCode.Double] = (left, right) => (long)left <= (double)right;
this.LessEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int16] = (left, right) => (float)left <= (short)right;
this.LessEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int32] = (left, right) => (float)left <= (int)right;
this.LessEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Int64] = (left, right) => (float)left <= (long)right;
this.LessEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Single] = (left, right) => (float)left <= (float)right;
this.LessEqualFunctions[(int)TypeCode.Single, (int)TypeCode.Double] = (left, right) => (float)left <= (double)right;
this.LessEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int16] = (left, right) => (double)left <= (short)right;
this.LessEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int32] = (left, right) => (double)left <= (int)right;
this.LessEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Int64] = (left, right) => (double)left <= (long)right;
this.LessEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Single] = (left, right) => (double)left <= (float)right;
this.LessEqualFunctions[(int)TypeCode.Double, (int)TypeCode.Double] = (left, right) => (double)left <= (double)right;
}
public object AddObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.AddFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object SubtractObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.SubtractFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object MultiplyObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.MultiplyFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object DivideObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.DivideFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object EqualObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.EqualFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object NotEqualObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.NotEqualFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object GreaterObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.GreaterFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object GreaterEqualObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.GreaterEqualFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object LessObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.LessFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
public object LessEqualObject(object left, object right)
{
if (left is IConvertible && right is IConvertible)
{
return this.LessEqualFunctions[(int)((IConvertible)left).GetTypeCode(), (int)((IConvertible)right).GetTypeCode()](left, right);
}
throw new NotImplementedException();
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using static Microsoft.AspNetCore.HttpSys.Internal.UnsafeNclNativeMethods;
namespace Microsoft.AspNetCore.Server.HttpSys
{
internal sealed class Response
{
// Support is assumed until we get an error and turn it off.
private static bool SupportsGoAway = true;
private ResponseState _responseState;
private bool _aborted;
private string? _reasonPhrase;
private ResponseBody? _nativeStream;
private AuthenticationSchemes _authChallenges;
private TimeSpan? _cacheTtl;
private long _expectedBodyLength;
private BoundaryType _boundaryType;
private HttpApiTypes.HTTP_RESPONSE_V2 _nativeResponse;
private HeaderCollection? _trailers;
internal Response(RequestContext requestContext)
{
// TODO: Verbose log
RequestContext = requestContext;
Headers = new HeaderCollection();
// We haven't started yet, or we're just buffered, we can clear any data, headers, and state so
// that we can start over (e.g. to write an error message).
_nativeResponse = new HttpApiTypes.HTTP_RESPONSE_V2();
Headers.IsReadOnly = false;
Headers.Clear();
_reasonPhrase = null;
_boundaryType = BoundaryType.None;
_nativeResponse.Response_V1.StatusCode = (ushort)StatusCodes.Status200OK;
_nativeResponse.Response_V1.Version.MajorVersion = 1;
_nativeResponse.Response_V1.Version.MinorVersion = 1;
_responseState = ResponseState.Created;
_expectedBodyLength = 0;
_nativeStream = null;
_cacheTtl = null;
_authChallenges = RequestContext.Server.Options.Authentication.Schemes;
}
private enum ResponseState
{
Created,
ComputedHeaders,
Started,
Closed,
}
private RequestContext RequestContext { get; }
private Request Request => RequestContext.Request;
public int StatusCode
{
get { return _nativeResponse.Response_V1.StatusCode; }
set
{
// Http.Sys automatically sends 100 Continue responses when you read from the request body.
if (value <= 100 || 999 < value)
{
throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(CultureInfo.CurrentCulture, Resources.Exception_InvalidStatusCode, value));
}
CheckResponseStarted();
_nativeResponse.Response_V1.StatusCode = (ushort)value;
}
}
public string? ReasonPhrase
{
get { return _reasonPhrase; }
set
{
// TODO: Validate user input for illegal chars, length limit, etc.?
CheckResponseStarted();
_reasonPhrase = value;
}
}
public Stream Body
{
get
{
EnsureResponseStream();
return _nativeStream;
}
}
internal bool BodyIsFinished => _nativeStream?.IsDisposed ?? _responseState >= ResponseState.Closed;
/// <summary>
/// The authentication challenges that will be added to the response if the status code is 401.
/// This must be a subset of the AuthenticationSchemes enabled on the server.
/// </summary>
public AuthenticationSchemes AuthenticationChallenges
{
get { return _authChallenges; }
set
{
CheckResponseStarted();
_authChallenges = value;
}
}
private string GetReasonPhrase(int statusCode)
{
string? reasonPhrase = ReasonPhrase;
if (string.IsNullOrWhiteSpace(reasonPhrase))
{
// If the user hasn't set this then it is generated on the fly if possible.
reasonPhrase = HttpReasonPhrase.Get(statusCode) ?? string.Empty;
}
return reasonPhrase;
}
// We MUST NOT send message-body when we send responses with these Status codes
private static readonly int[] StatusWithNoResponseBody = { 100, 101, 204, 205, 304 };
private static bool CanSendResponseBody(int responseCode)
{
for (int i = 0; i < StatusWithNoResponseBody.Length; i++)
{
if (responseCode == StatusWithNoResponseBody[i])
{
return false;
}
}
return true;
}
public HeaderCollection Headers { get; }
public HeaderCollection Trailers => _trailers ??= new HeaderCollection(checkTrailers: true) { IsReadOnly = BodyIsFinished };
internal bool HasTrailers => _trailers?.Count > 0;
// Trailers are supported on this OS, it's HTTP/2, and the app added a Trailer response header to announce trailers were intended.
// Needed to delay the completion of Content-Length responses.
internal bool TrailersExpected => HasTrailers
|| (HttpApi.SupportsTrailers && Request.ProtocolVersion >= HttpVersion.Version20
&& Headers.ContainsKey(HeaderNames.Trailer));
internal long ExpectedBodyLength
{
get { return _expectedBodyLength; }
}
// Header accessors
public long? ContentLength
{
get { return Headers.ContentLength; }
set { Headers.ContentLength = value; }
}
/// <summary>
/// Enable kernel caching for the response with the given timeout. Http.Sys determines if the response
/// can be cached.
/// </summary>
public TimeSpan? CacheTtl
{
get { return _cacheTtl; }
set
{
CheckResponseStarted();
_cacheTtl = value;
}
}
// The response is being finished with or without trailers. Mark them as readonly to inform
// callers if they try to add them too late. E.g. after Content-Length or CompleteAsync().
internal void MakeTrailersReadOnly()
{
if (_trailers != null)
{
_trailers.IsReadOnly = true;
}
}
internal void Abort()
{
// Do not attempt a graceful Dispose.
// _responseState is not modified because that refers to app state like modifying
// status and headers. See https://github.com/dotnet/aspnetcore/issues/12194.
_aborted = true;
}
// should only be called from RequestContext
internal void Dispose()
{
if (_aborted || _responseState >= ResponseState.Closed)
{
return;
}
// TODO: Verbose log
EnsureResponseStream();
_nativeStream.Dispose();
_responseState = ResponseState.Closed;
}
internal BoundaryType BoundaryType
{
get { return _boundaryType; }
}
internal bool HasComputedHeaders
{
get { return _responseState >= ResponseState.ComputedHeaders; }
}
/// <summary>
/// Indicates if the response status, reason, and headers are prepared to send and can
/// no longer be modified. This is caused by the first write or flush to the response body.
/// </summary>
public bool HasStarted
{
get { return _responseState >= ResponseState.Started; }
}
private void CheckResponseStarted()
{
if (HasStarted)
{
throw new InvalidOperationException("Headers already sent.");
}
}
[MemberNotNull(nameof(_nativeStream))]
private void EnsureResponseStream()
{
if (_nativeStream == null)
{
_nativeStream = new ResponseBody(RequestContext);
}
}
/*
12.3
HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:
#define HTTP_SEND_RESPONSE_FLAG_DISCONNECT 0x00000001
#define HTTP_SEND_RESPONSE_FLAG_MORE_DATA 0x00000002
#define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER 0x00000004
#define HTTP_SEND_RESPONSE_FLAG_VALID 0x00000007
HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
specifies that the network connection should be disconnected immediately after
sending the response, overriding the HTTP protocol's persistent connection features.
HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
specifies that additional entity body data will be sent by the caller. Thus,
the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
HTTP_SEND_RESPONSE_RAW_HEADER:
specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
a call to HttpSendHttpResponse() in order to bypass normal header processing. The
actual HTTP header will be generated by the application and sent as entity body.
This flag should be passed on the first call to HttpSendResponseEntityBody, and
not after. Thus, flag is not applicable to HttpSendHttpResponse.
*/
// TODO: Consider using HTTP_SEND_RESPONSE_RAW_HEADER with HttpSendResponseEntityBody instead of calling HttpSendHttpResponse.
// This will give us more control of the bytes that hit the wire, including encodings, HTTP 1.0, etc..
// It may also be faster to do this work in managed code and then pass down only one buffer.
// What would we loose by bypassing HttpSendHttpResponse?
//
// TODO: Consider using the HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA flag for most/all responses rather than just Opaque.
internal unsafe uint SendHeaders(HttpApiTypes.HTTP_DATA_CHUNK[]? dataChunks,
ResponseStreamAsyncResult? asyncResult,
HttpApiTypes.HTTP_FLAGS flags,
bool isOpaqueUpgrade)
{
Debug.Assert(!HasStarted, "HttpListenerResponse::SendHeaders()|SentHeaders is true.");
_responseState = ResponseState.Started;
var reasonPhrase = GetReasonPhrase(StatusCode);
uint statusCode;
uint bytesSent;
List<GCHandle>? pinnedHeaders = SerializeHeaders(isOpaqueUpgrade);
try
{
if (dataChunks != null)
{
if (pinnedHeaders == null)
{
pinnedHeaders = new List<GCHandle>();
}
var handle = GCHandle.Alloc(dataChunks, GCHandleType.Pinned);
pinnedHeaders.Add(handle);
_nativeResponse.Response_V1.EntityChunkCount = (ushort)dataChunks.Length;
_nativeResponse.Response_V1.pEntityChunks = (HttpApiTypes.HTTP_DATA_CHUNK*)handle.AddrOfPinnedObject();
}
else if (asyncResult != null && asyncResult.DataChunks != null)
{
_nativeResponse.Response_V1.EntityChunkCount = asyncResult.DataChunkCount;
_nativeResponse.Response_V1.pEntityChunks = asyncResult.DataChunks;
}
else
{
_nativeResponse.Response_V1.EntityChunkCount = 0;
_nativeResponse.Response_V1.pEntityChunks = null;
}
var cachePolicy = new HttpApiTypes.HTTP_CACHE_POLICY();
if (_cacheTtl.HasValue && _cacheTtl.Value > TimeSpan.Zero)
{
cachePolicy.Policy = HttpApiTypes.HTTP_CACHE_POLICY_TYPE.HttpCachePolicyTimeToLive;
cachePolicy.SecondsToLive = (uint)Math.Min(_cacheTtl.Value.Ticks / TimeSpan.TicksPerSecond, Int32.MaxValue);
}
byte[] reasonPhraseBytes = HeaderEncoding.GetBytes(reasonPhrase);
fixed (byte* pReasonPhrase = reasonPhraseBytes)
{
_nativeResponse.Response_V1.ReasonLength = (ushort)reasonPhraseBytes.Length;
_nativeResponse.Response_V1.pReason = (byte*)pReasonPhrase;
fixed (HttpApiTypes.HTTP_RESPONSE_V2* pResponse = &_nativeResponse)
{
statusCode =
HttpApi.HttpSendHttpResponse(
RequestContext.Server.RequestQueue.Handle,
Request.RequestId,
(uint)flags,
pResponse,
&cachePolicy,
&bytesSent,
IntPtr.Zero,
0,
asyncResult == null ? SafeNativeOverlapped.Zero : asyncResult.NativeOverlapped!,
IntPtr.Zero);
// GoAway is only supported on later versions. Retry.
if (statusCode == ErrorCodes.ERROR_INVALID_PARAMETER
&& (flags & HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_GOAWAY) != 0)
{
flags &= ~HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_GOAWAY;
statusCode =
HttpApi.HttpSendHttpResponse(
RequestContext.Server.RequestQueue.Handle,
Request.RequestId,
(uint)flags,
pResponse,
&cachePolicy,
&bytesSent,
IntPtr.Zero,
0,
asyncResult == null ? SafeNativeOverlapped.Zero : asyncResult.NativeOverlapped!,
IntPtr.Zero);
// Succeeded without GoAway, disable them.
if (statusCode != ErrorCodes.ERROR_INVALID_PARAMETER)
{
SupportsGoAway = false;
}
}
if (asyncResult != null &&
statusCode == ErrorCodes.ERROR_SUCCESS &&
HttpSysListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.BytesSent = bytesSent;
// The caller will invoke IOCompleted
}
}
}
}
finally
{
FreePinnedHeaders(pinnedHeaders);
}
return statusCode;
}
internal HttpApiTypes.HTTP_FLAGS ComputeHeaders(long writeCount, bool endOfRequest = false)
{
Headers.IsReadOnly = false; // Temporarily unlock
if (StatusCode == (ushort)StatusCodes.Status401Unauthorized)
{
RequestContext.Server.Options.Authentication.SetAuthenticationChallenge(RequestContext);
}
var flags = HttpApiTypes.HTTP_FLAGS.NONE;
Debug.Assert(!HasComputedHeaders, nameof(HasComputedHeaders) + " is true.");
_responseState = ResponseState.ComputedHeaders;
// Gather everything from the request that affects the response:
var requestVersion = Request.ProtocolVersion;
var requestConnectionString = Request.Headers[HeaderNames.Connection];
var isHeadRequest = Request.IsHeadMethod;
var requestCloseSet = Matches(Constants.Close, requestConnectionString);
// Gather everything the app may have set on the response:
// Http.Sys does not allow us to specify the response protocol version, assume this is a HTTP/1.1 response when making decisions.
var responseConnectionString = Headers[HeaderNames.Connection];
var transferEncodingString = Headers[HeaderNames.TransferEncoding];
var responseContentLength = ContentLength;
var responseCloseSet = Matches(Constants.Close, responseConnectionString);
var responseChunkedSet = Matches(Constants.Chunked, transferEncodingString);
var statusCanHaveBody = CanSendResponseBody(RequestContext.Response.StatusCode);
// Determine if the connection will be kept alive or closed.
var keepConnectionAlive = true;
if (requestVersion <= Constants.V1_0 // Http.Sys does not support "Keep-Alive: true" or "Connection: Keep-Alive"
|| (requestVersion == Constants.V1_1 && requestCloseSet)
|| responseCloseSet)
{
keepConnectionAlive = false;
}
// Determine the body format. If the user asks to do something, let them, otherwise choose a good default for the scenario.
if (responseContentLength.HasValue)
{
_boundaryType = BoundaryType.ContentLength;
// ComputeLeftToWrite checks for HEAD requests when setting _leftToWrite
_expectedBodyLength = responseContentLength.Value;
if (_expectedBodyLength == writeCount && !isHeadRequest && !TrailersExpected)
{
// A single write with the whole content-length. Http.Sys will set the content-length for us in this scenario.
// If we don't remove it then range requests served from cache will have two.
// https://github.com/aspnet/HttpSysServer/issues/167
ContentLength = null;
}
}
else if (responseChunkedSet)
{
// The application is performing it's own chunking.
_boundaryType = BoundaryType.PassThrough;
}
else if (endOfRequest)
{
if (!isHeadRequest && statusCanHaveBody)
{
Headers[HeaderNames.ContentLength] = Constants.Zero;
}
_boundaryType = BoundaryType.ContentLength;
_expectedBodyLength = 0;
}
else if (requestVersion == Constants.V1_1)
{
_boundaryType = BoundaryType.Chunked;
Headers[HeaderNames.TransferEncoding] = Constants.Chunked;
}
else
{
// v1.0 and the length cannot be determined, so we must close the connection after writing data
// Or v2.0 and chunking isn't required.
keepConnectionAlive = false;
_boundaryType = BoundaryType.Close;
}
// Managed connection lifetime
if (!keepConnectionAlive)
{
// All Http.Sys responses are v1.1, so use 1.1 response headers
// Note that if we don't add this header, Http.Sys will often do it for us.
if (!responseCloseSet)
{
Headers.Append(HeaderNames.Connection, Constants.Close);
}
flags = HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
if (responseCloseSet && requestVersion >= Constants.V2 && SupportsGoAway)
{
flags |= HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_GOAWAY;
}
}
Headers.IsReadOnly = true;
return flags;
}
private static bool Matches(string knownValue, StringValues input)
{
return string.Equals(knownValue, input.ToString().Trim(), StringComparison.OrdinalIgnoreCase);
}
private unsafe List<GCHandle>? SerializeHeaders(bool isOpaqueUpgrade)
{
Headers.IsReadOnly = true; // Prohibit further modifications.
HttpApiTypes.HTTP_UNKNOWN_HEADER[]? unknownHeaders = null;
HttpApiTypes.HTTP_RESPONSE_INFO[]? knownHeaderInfo = null;
List<GCHandle> pinnedHeaders;
GCHandle gcHandle;
if (Headers.Count == 0)
{
return null;
}
string headerName;
string headerValue;
int lookup;
byte[]? bytes = null;
pinnedHeaders = new List<GCHandle>();
int numUnknownHeaders = 0;
int numKnownMultiHeaders = 0;
foreach (var headerPair in Headers)
{
if (headerPair.Value.Count == 0)
{
continue;
}
// See if this is an unknown header
lookup = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerPair.Key);
// Http.Sys doesn't let us send the Connection: Upgrade header as a Known header.
if (lookup == -1 ||
(isOpaqueUpgrade && lookup == (int)HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderConnection))
{
numUnknownHeaders += headerPair.Value.Count;
}
else if (headerPair.Value.Count > 1)
{
numKnownMultiHeaders++;
}
// else known single-value header.
}
try
{
fixed (HttpApiTypes.HTTP_KNOWN_HEADER* pKnownHeaders = &_nativeResponse.Response_V1.Headers.KnownHeaders)
{
foreach (var headerPair in Headers)
{
if (headerPair.Value.Count == 0)
{
continue;
}
headerName = headerPair.Key;
StringValues headerValues = headerPair.Value;
lookup = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName);
// Http.Sys doesn't let us send the Connection: Upgrade header as a Known header.
if (lookup == -1 ||
(isOpaqueUpgrade && lookup == (int)HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderConnection))
{
if (unknownHeaders == null)
{
unknownHeaders = new HttpApiTypes.HTTP_UNKNOWN_HEADER[numUnknownHeaders];
gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
_nativeResponse.Response_V1.Headers.pUnknownHeaders = (HttpApiTypes.HTTP_UNKNOWN_HEADER*)gcHandle.AddrOfPinnedObject();
}
for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++)
{
// Add Name
bytes = HeaderEncoding.GetBytes(headerName);
unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].NameLength = (ushort)bytes.Length;
gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].pName = (byte*)gcHandle.AddrOfPinnedObject();
// Add Value
headerValue = headerValues[headerValueIndex] ?? string.Empty;
bytes = HeaderEncoding.GetBytes(headerValue);
unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].RawValueLength = (ushort)bytes.Length;
gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].pRawValue = (byte*)gcHandle.AddrOfPinnedObject();
_nativeResponse.Response_V1.Headers.UnknownHeaderCount++;
}
}
else if (headerPair.Value.Count == 1)
{
headerValue = headerValues[0] ?? string.Empty;
bytes = HeaderEncoding.GetBytes(headerValue);
pKnownHeaders[lookup].RawValueLength = (ushort)bytes.Length;
gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
pKnownHeaders[lookup].pRawValue = (byte*)gcHandle.AddrOfPinnedObject();
}
else
{
if (knownHeaderInfo == null)
{
knownHeaderInfo = new HttpApiTypes.HTTP_RESPONSE_INFO[numKnownMultiHeaders];
gcHandle = GCHandle.Alloc(knownHeaderInfo, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
_nativeResponse.pResponseInfo = (HttpApiTypes.HTTP_RESPONSE_INFO*)gcHandle.AddrOfPinnedObject();
}
knownHeaderInfo[_nativeResponse.ResponseInfoCount].Type = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders;
knownHeaderInfo[_nativeResponse.ResponseInfoCount].Length = (uint)Marshal.SizeOf<HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS>();
HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS header = new HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS();
header.HeaderId = (HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum)lookup;
header.Flags = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // TODO: The docs say this is for www-auth only.
HttpApiTypes.HTTP_KNOWN_HEADER[] nativeHeaderValues = new HttpApiTypes.HTTP_KNOWN_HEADER[headerValues.Count];
gcHandle = GCHandle.Alloc(nativeHeaderValues, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
header.KnownHeaders = (HttpApiTypes.HTTP_KNOWN_HEADER*)gcHandle.AddrOfPinnedObject();
for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++)
{
// Add Value
headerValue = headerValues[headerValueIndex] ?? string.Empty;
bytes = HeaderEncoding.GetBytes(headerValue);
nativeHeaderValues[header.KnownHeaderCount].RawValueLength = (ushort)bytes.Length;
gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
nativeHeaderValues[header.KnownHeaderCount].pRawValue = (byte*)gcHandle.AddrOfPinnedObject();
header.KnownHeaderCount++;
}
// This type is a struct, not an object, so pinning it causes a boxed copy to be created. We can't do that until after all the fields are set.
gcHandle = GCHandle.Alloc(header, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
knownHeaderInfo[_nativeResponse.ResponseInfoCount].pInfo = (HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS*)gcHandle.AddrOfPinnedObject();
_nativeResponse.ResponseInfoCount++;
}
}
}
}
catch
{
FreePinnedHeaders(pinnedHeaders);
throw;
}
return pinnedHeaders;
}
private static void FreePinnedHeaders(List<GCHandle>? pinnedHeaders)
{
if (pinnedHeaders != null)
{
foreach (GCHandle gcHandle in pinnedHeaders)
{
if (gcHandle.IsAllocated)
{
gcHandle.Free();
}
}
}
}
internal unsafe void SerializeTrailers(HttpApiTypes.HTTP_DATA_CHUNK[] dataChunks, int currentChunk, List<GCHandle> pins)
{
Debug.Assert(currentChunk == dataChunks.Length - 1);
Debug.Assert(HasTrailers);
MakeTrailersReadOnly();
var trailerCount = 0;
foreach (var trailerPair in Trailers)
{
trailerCount += trailerPair.Value.Count;
}
var pinnedHeaders = new List<GCHandle>();
var unknownHeaders = new HttpApiTypes.HTTP_UNKNOWN_HEADER[trailerCount];
var gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
dataChunks[currentChunk].DataChunkType = HttpApiTypes.HTTP_DATA_CHUNK_TYPE.HttpDataChunkTrailers;
dataChunks[currentChunk].trailers.trailerCount = (ushort)trailerCount;
dataChunks[currentChunk].trailers.pTrailers = gcHandle.AddrOfPinnedObject();
try
{
var unknownHeadersOffset = 0;
foreach (var headerPair in Trailers)
{
if (headerPair.Value.Count == 0)
{
continue;
}
var headerName = headerPair.Key;
var headerValues = headerPair.Value;
for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++)
{
// Add Name
var bytes = HeaderEncoding.GetBytes(headerName);
unknownHeaders[unknownHeadersOffset].NameLength = (ushort)bytes.Length;
gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
unknownHeaders[unknownHeadersOffset].pName = (byte*)gcHandle.AddrOfPinnedObject();
// Add Value
var headerValue = headerValues[headerValueIndex] ?? string.Empty;
bytes = HeaderEncoding.GetBytes(headerValue);
unknownHeaders[unknownHeadersOffset].RawValueLength = (ushort)bytes.Length;
gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pinnedHeaders.Add(gcHandle);
unknownHeaders[unknownHeadersOffset].pRawValue = (byte*)gcHandle.AddrOfPinnedObject();
unknownHeadersOffset++;
}
}
Debug.Assert(unknownHeadersOffset == trailerCount);
}
catch
{
FreePinnedHeaders(pinnedHeaders);
throw;
}
// Success, keep the pins.
pins.AddRange(pinnedHeaders);
}
// Subset of ComputeHeaders
internal void SendOpaqueUpgrade()
{
_boundaryType = BoundaryType.Close;
// TODO: Send headers async?
ulong errorCode = SendHeaders(null, null,
HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_OPAQUE |
HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA |
HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA,
true);
if (errorCode != ErrorCodes.ERROR_SUCCESS)
{
throw new HttpSysException((int)errorCode);
}
}
internal void MarkDelegated()
{
Abort();
_nativeStream?.MarkDelegated();
}
internal void CancelLastWrite()
{
_nativeStream?.CancelLastWrite();
}
public Task SendFileAsync(string path, long offset, long? count, CancellationToken cancel)
{
EnsureResponseStream();
return _nativeStream.SendFileAsync(path, offset, count, cancel);
}
internal void SwitchToOpaqueMode()
{
EnsureResponseStream();
_nativeStream.SwitchToOpaqueMode();
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// Container for the parameters to the CreateDeployment operation.
/// <para>Deploys a stack or app.</para>
/// <ul>
/// <li>App deployment generates a <c>deploy</c> event, which runs the associated recipes and passes them a JSON stack configuration object
/// that includes information about the app. </li>
/// <li>Stack deployment runs the <c>deploy</c> recipes but does not raise an event.</li>
///
/// </ul>
/// <para>For more information, see Deploying Apps and Run Stack Commands.</para>
/// </summary>
/// <seealso cref="Amazon.OpsWorks.AmazonOpsWorks.CreateDeployment"/>
public class CreateDeploymentRequest : AmazonWebServiceRequest
{
private string stackId;
private string appId;
private List<string> instanceIds = new List<string>();
private DeploymentCommand command;
private string comment;
private string customJson;
/// <summary>
/// The stack ID.
///
/// </summary>
public string StackId
{
get { return this.stackId; }
set { this.stackId = value; }
}
/// <summary>
/// Sets the StackId property
/// </summary>
/// <param name="stackId">The value to set for the StackId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithStackId(string stackId)
{
this.stackId = stackId;
return this;
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this.stackId != null;
}
/// <summary>
/// The app ID. This parameter is required for app deployments, but not for other deployment commands.
///
/// </summary>
public string AppId
{
get { return this.appId; }
set { this.appId = value; }
}
/// <summary>
/// Sets the AppId property
/// </summary>
/// <param name="appId">The value to set for the AppId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithAppId(string appId)
{
this.appId = appId;
return this;
}
// Check to see if AppId property is set
internal bool IsSetAppId()
{
return this.appId != null;
}
/// <summary>
/// The instance IDs for the deployment targets.
///
/// </summary>
public List<string> InstanceIds
{
get { return this.instanceIds; }
set { this.instanceIds = value; }
}
/// <summary>
/// Adds elements to the InstanceIds collection
/// </summary>
/// <param name="instanceIds">The values to add to the InstanceIds collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithInstanceIds(params string[] instanceIds)
{
foreach (string element in instanceIds)
{
this.instanceIds.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the InstanceIds collection
/// </summary>
/// <param name="instanceIds">The values to add to the InstanceIds collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithInstanceIds(IEnumerable<string> instanceIds)
{
foreach (string element in instanceIds)
{
this.instanceIds.Add(element);
}
return this;
}
// Check to see if InstanceIds property is set
internal bool IsSetInstanceIds()
{
return this.instanceIds.Count > 0;
}
/// <summary>
/// A <c>DeploymentCommand</c> object that specifies the deployment command and any associated arguments.
///
/// </summary>
public DeploymentCommand Command
{
get { return this.command; }
set { this.command = value; }
}
/// <summary>
/// Sets the Command property
/// </summary>
/// <param name="command">The value to set for the Command property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithCommand(DeploymentCommand command)
{
this.command = command;
return this;
}
// Check to see if Command property is set
internal bool IsSetCommand()
{
return this.command != null;
}
/// <summary>
/// A user-defined comment.
///
/// </summary>
public string Comment
{
get { return this.comment; }
set { this.comment = value; }
}
/// <summary>
/// Sets the Comment property
/// </summary>
/// <param name="comment">The value to set for the Comment property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithComment(string comment)
{
this.comment = comment;
return this;
}
// Check to see if Comment property is set
internal bool IsSetComment()
{
return this.comment != null;
}
/// <summary>
/// A string that contains user-defined, custom JSON. It is used to override the corresponding default stack configuration JSON values. The
/// string should be in the following format and must escape characters such as '"'.: <c>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</c>
/// For more information on custom JSON, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html">Use Custom
/// JSON to Modify the Stack Configuration JSON</a>.
///
/// </summary>
public string CustomJson
{
get { return this.customJson; }
set { this.customJson = value; }
}
/// <summary>
/// Sets the CustomJson property
/// </summary>
/// <param name="customJson">The value to set for the CustomJson property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDeploymentRequest WithCustomJson(string customJson)
{
this.customJson = customJson;
return this;
}
// Check to see if CustomJson property is set
internal bool IsSetCustomJson()
{
return this.customJson != null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BI.Interface.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class HttpRetryExtensions
{
/// <summary>
/// Return 408 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head408(this IHttpRetry operations)
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Head408Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 408 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head408Async( this IHttpRetry operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head408WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put500(this IHttpRetry operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Put500Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Put500Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Put500WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch500(this IHttpRetry operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Patch500Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Patch500Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Patch500WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 502 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Get502(this IHttpRetry operations)
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Get502Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 502 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Get502Async( this IHttpRetry operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Get502WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post503(this IHttpRetry operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Post503Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Post503Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Post503WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete503(this IHttpRetry operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Delete503Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Delete503Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Delete503WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put504(this IHttpRetry operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Put504Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Put504Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Put504WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch504(this IHttpRetry operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpRetry)s).Patch504Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Patch504Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Patch504WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
/*
* 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;
namespace Lucene.Net.Store
{
/// <summary> <p/>Implements {@link LockFactory} using native OS file
/// locks. Note that because this LockFactory relies on
/// java.nio.* APIs for locking, any problems with those APIs
/// will cause locking to fail. Specifically, on certain NFS
/// environments the java.nio.* locks will fail (the lock can
/// incorrectly be double acquired) whereas {@link
/// SimpleFSLockFactory} worked perfectly in those same
/// environments. For NFS based access to an index, it's
/// recommended that you try {@link SimpleFSLockFactory}
/// first and work around the one limitation that a lock file
/// could be left when the JVM exits abnormally.<p/>
///
/// <p/>The primary benefit of {@link NativeFSLockFactory} is
/// that lock files will be properly removed (by the OS) if
/// the JVM has an abnormal exit.<p/>
///
/// <p/>Note that, unlike {@link SimpleFSLockFactory}, the existence of
/// leftover lock files in the filesystem on exiting the JVM
/// is fine because the OS will free the locks held against
/// these files even though the files still remain.<p/>
///
/// <p/>If you suspect that this or any other LockFactory is
/// not working properly in your environment, you can easily
/// test it by using {@link VerifyingLockFactory}, {@link
/// LockVerifyServer} and {@link LockStressTest}.<p/>
///
/// </summary>
/// <seealso cref="LockFactory">
/// </seealso>
public class NativeFSLockFactory:FSLockFactory
{
/// <summary> Create a NativeFSLockFactory instance, with null (unset)
/// lock directory. When you pass this factory to a {@link FSDirectory}
/// subclass, the lock directory is automatically set to the
/// directory itsself. Be sure to create one instance for each directory
/// your create!
/// </summary>
public NativeFSLockFactory():this((System.IO.DirectoryInfo) null)
{
}
/// <summary> Create a NativeFSLockFactory instance, storing lock
/// files into the specified lockDirName:
///
/// </summary>
/// <param name="lockDirName">where lock files are created.
/// </param>
public NativeFSLockFactory(System.String lockDirName):this(new System.IO.DirectoryInfo(lockDirName))
{
}
/// <summary> Create a NativeFSLockFactory instance, storing lock
/// files into the specified lockDir:
///
/// </summary>
/// <param name="lockDir">where lock files are created.
/// </param>
[System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public NativeFSLockFactory(System.IO.FileInfo lockDir) : this(new System.IO.DirectoryInfo(lockDir.FullName))
{
}
/// <summary> Create a NativeFSLockFactory instance, storing lock
/// files into the specified lockDir:
///
/// </summary>
/// <param name="lockDir">where lock files are created.
/// </param>
public NativeFSLockFactory(System.IO.DirectoryInfo lockDir)
{
SetLockDir(lockDir);
}
public override Lock MakeLock(System.String lockName)
{
lock (this)
{
if (lockPrefix != null)
lockName = lockPrefix + "-" + lockName;
return new NativeFSLock(lockDir, lockName);
}
}
public override void ClearLock(System.String lockName)
{
// Note that this isn't strictly required anymore
// because the existence of these files does not mean
// they are locked, but, still do this in case people
// really want to see the files go away:
bool tmpBool;
if (System.IO.File.Exists(lockDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockDir.FullName);
if (tmpBool)
{
if (lockPrefix != null)
{
lockName = lockPrefix + "-" + lockName;
}
System.IO.FileInfo lockFile = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockName));
bool tmpBool2;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool2 = true;
else
tmpBool2 = System.IO.Directory.Exists(lockFile.FullName);
bool tmpBool3;
if (System.IO.File.Exists(lockFile.FullName))
{
System.IO.File.Delete(lockFile.FullName);
tmpBool3 = true;
}
else if (System.IO.Directory.Exists(lockFile.FullName))
{
System.IO.Directory.Delete(lockFile.FullName);
tmpBool3 = true;
}
else
tmpBool3 = false;
if (tmpBool2 && !tmpBool3)
{
throw new System.IO.IOException("Cannot delete " + lockFile);
}
}
}
}
class NativeFSLock:Lock
{
private System.IO.FileStream f;
private System.IO.FileStream channel;
private bool lock_Renamed;
private System.IO.FileInfo path;
private System.IO.DirectoryInfo lockDir;
/*
* The javadocs for FileChannel state that you should have
* a single instance of a FileChannel (per JVM) for all
* locking against a given file. To ensure this, we have
* a single (static) HashSet that contains the file paths
* of all currently locked locks. This protects against
* possible cases where different Directory instances in
* one JVM (each with their own NativeFSLockFactory
* instance) have set the same lock dir and lock prefix.
*/
private static System.Collections.Hashtable LOCK_HELD = new System.Collections.Hashtable();
[System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public NativeFSLock(System.IO.FileInfo lockDir, System.String lockFileName):this(new System.IO.DirectoryInfo(lockDir.FullName), lockFileName)
{
}
public NativeFSLock(System.IO.DirectoryInfo lockDir, System.String lockFileName)
{
this.lockDir = lockDir;
path = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockFileName));
}
private bool LockExists()
{
lock (this)
{
return lock_Renamed != false;
}
}
public override bool Obtain()
{
lock (this)
{
if (LockExists())
{
// Our instance is already locked:
return false;
}
// Ensure that lockDir exists and is a directory.
bool tmpBool;
if (System.IO.File.Exists(lockDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockDir.FullName);
if (!tmpBool)
{
try
{
System.IO.Directory.CreateDirectory(lockDir.FullName);
}
catch
{
throw new System.IO.IOException("Cannot create directory: " + lockDir.FullName);
}
}
else if (!System.IO.Directory.Exists(lockDir.FullName))
{
throw new System.IO.IOException("Found regular file where directory expected: " + lockDir.FullName);
}
System.String canonicalPath = path.FullName;
bool markedHeld = false;
try
{
// Make sure nobody else in-process has this lock held
// already, and, mark it held if not:
lock (LOCK_HELD)
{
if (LOCK_HELD.Contains(canonicalPath))
{
// Someone else in this JVM already has the lock:
return false;
}
else
{
// This "reserves" the fact that we are the one
// thread trying to obtain this lock, so we own
// the only instance of a channel against this
// file:
LOCK_HELD.Add(canonicalPath, canonicalPath);
markedHeld = true;
}
}
try
{
f = new System.IO.FileStream(path.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
}
catch (System.IO.IOException e)
{
// On Windows, we can get intermittent "Access
// Denied" here. So, we treat this as failure to
// acquire the lock, but, store the reason in case
// there is in fact a real error case.
failureReason = e;
f = null;
}
if (f != null)
{
try
{
channel = f;
lock_Renamed = false;
try
{
channel.Lock(0, channel.Length);
lock_Renamed = true;
}
catch (System.IO.IOException e)
{
// At least on OS X, we will sometimes get an
// intermittent "Permission Denied" IOException,
// which seems to simply mean "you failed to get
// the lock". But other IOExceptions could be
// "permanent" (eg, locking is not supported via
// the filesystem). So, we record the failure
// reason here; the timeout obtain (usually the
// one calling us) will use this as "root cause"
// if it fails to get the lock.
failureReason = e;
}
finally
{
if (lock_Renamed == false)
{
try
{
channel.Close();
}
finally
{
channel = null;
}
}
}
}
finally
{
if (channel == null)
{
try
{
f.Close();
}
finally
{
f = null;
}
}
}
}
}
finally
{
if (markedHeld && !LockExists())
{
lock (LOCK_HELD)
{
if (LOCK_HELD.Contains(canonicalPath))
{
LOCK_HELD.Remove(canonicalPath);
}
}
}
}
return LockExists();
}
}
public override void Release()
{
lock (this)
{
if (LockExists())
{
try
{
channel.Unlock(0, channel.Length);
}
finally
{
lock_Renamed = false;
try
{
channel.Close();
}
finally
{
channel = null;
try
{
f.Close();
}
finally
{
f = null;
lock (LOCK_HELD)
{
LOCK_HELD.Remove(path.FullName);
}
}
}
}
bool tmpBool;
if (System.IO.File.Exists(path.FullName))
{
System.IO.File.Delete(path.FullName);
tmpBool = true;
}
else if (System.IO.Directory.Exists(path.FullName))
{
System.IO.Directory.Delete(path.FullName);
tmpBool = true;
}
else
tmpBool = false;
if (!tmpBool)
throw new LockReleaseFailedException("failed to delete " + path);
}
}
}
public override bool IsLocked()
{
lock (this)
{
// The test for is isLocked is not directly possible with native file locks:
// First a shortcut, if a lock reference in this instance is available
if (LockExists())
return true;
// Look if lock file is present; if not, there can definitely be no lock!
bool tmpBool;
if (System.IO.File.Exists(path.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(path.FullName);
if (!tmpBool)
return false;
// Try to obtain and release (if was locked) the lock
try
{
bool obtained = Obtain();
if (obtained)
Release();
return !obtained;
}
catch (System.IO.IOException ioe)
{
return false;
}
}
}
public override System.String ToString()
{
return "NativeFSLock@" + path;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 OfficeOAuth.Areas.HelpPage.ModelDescriptions;
using OfficeOAuth.Areas.HelpPage.Models;
namespace OfficeOAuth.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;
}
if (complexTypeDescription != null)
{
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 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);
}
}
}
}
| |
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Defines known values for the <see cref="HostSystemID"/> property.
/// </summary>
public enum HostSystemID
{
/// <summary>
/// Host system = MSDOS
/// </summary>
Msdos = 0,
/// <summary>
/// Host system = Amiga
/// </summary>
Amiga = 1,
/// <summary>
/// Host system = Open VMS
/// </summary>
OpenVms = 2,
/// <summary>
/// Host system = Unix
/// </summary>
Unix = 3,
/// <summary>
/// Host system = VMCms
/// </summary>
VMCms = 4,
/// <summary>
/// Host system = Atari ST
/// </summary>
AtariST = 5,
/// <summary>
/// Host system = OS2
/// </summary>
OS2 = 6,
/// <summary>
/// Host system = Macintosh
/// </summary>
Macintosh = 7,
/// <summary>
/// Host system = ZSystem
/// </summary>
ZSystem = 8,
/// <summary>
/// Host system = Cpm
/// </summary>
Cpm = 9,
/// <summary>
/// Host system = Windows NT
/// </summary>
WindowsNT = 10,
/// <summary>
/// Host system = MVS
/// </summary>
MVS = 11,
/// <summary>
/// Host system = VSE
/// </summary>
Vse = 12,
/// <summary>
/// Host system = Acorn RISC
/// </summary>
AcornRisc = 13,
/// <summary>
/// Host system = VFAT
/// </summary>
Vfat = 14,
/// <summary>
/// Host system = Alternate MVS
/// </summary>
AlternateMvs = 15,
/// <summary>
/// Host system = BEOS
/// </summary>
BeOS = 16,
/// <summary>
/// Host system = Tandem
/// </summary>
Tandem = 17,
/// <summary>
/// Host system = OS400
/// </summary>
OS400 = 18,
/// <summary>
/// Host system = OSX
/// </summary>
OSX = 19,
/// <summary>
/// Host system = WinZIP AES
/// </summary>
WinZipAES = 99,
}
/// <summary>
/// This class represents an entry in a zip archive. This can be a file
/// or a directory
/// ZipFile and ZipInputStream will give you instances of this class as
/// information about the members in an archive. ZipOutputStream
/// uses an instance of this class when creating an entry in a Zip file.
/// <br/>
/// <br/>Author of the original java version : Jochen Hoenicke
/// </summary>
public class ZipEntry
{
[Flags]
enum Known : byte
{
None = 0,
Size = 0x01,
CompressedSize = 0x02,
Crc = 0x04,
Time = 0x08,
ExternalAttributes = 0x10,
}
#region Constructors
/// <summary>
/// Creates a zip entry with the given name.
/// </summary>
/// <param name="name">
/// The name for this entry. Can include directory components.
/// The convention for names is 'unix' style paths with relative names only.
/// There are with no device names and path elements are separated by '/' characters.
/// </param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
public ZipEntry(string name)
: this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated)
{
}
/// <summary>
/// Creates a zip entry with the given name and version required to extract
/// </summary>
/// <param name="name">
/// The name for this entry. Can include directory components.
/// The convention for names is 'unix' style paths with no device names and
/// path elements separated by '/' characters. This is not enforced see <see cref="CleanName(string)">CleanName</see>
/// on how to ensure names are valid if this is desired.
/// </param>
/// <param name="versionRequiredToExtract">
/// The minimum 'feature version' required this entry
/// </param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
internal ZipEntry(string name, int versionRequiredToExtract)
: this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy,
CompressionMethod.Deflated)
{
}
/// <summary>
/// Initializes an entry with the given name and made by information
/// </summary>
/// <param name="name">Name for this entry</param>
/// <param name="madeByInfo">Version and HostSystem Information</param>
/// <param name="versionRequiredToExtract">Minimum required zip feature version required to extract this entry</param>
/// <param name="method">Compression method for this entry.</param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// versionRequiredToExtract should be 0 (auto-calculate) or > 10
/// </exception>
/// <remarks>
/// This constructor is used by the ZipFile class when reading from the central header
/// It is not generally useful, use the constructor specifying the name only.
/// </remarks>
internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo,
CompressionMethod method)
{
if (name == null) {
throw new ArgumentNullException(nameof(name));
}
if (name.Length > 0xffff) {
throw new ArgumentException("Name is too long", nameof(name));
}
if ((versionRequiredToExtract != 0) && (versionRequiredToExtract < 10)) {
throw new ArgumentOutOfRangeException(nameof(versionRequiredToExtract));
}
this.DateTime = DateTime.Now;
this.name = CleanName(name);
this.versionMadeBy = (ushort)madeByInfo;
this.versionToExtract = (ushort)versionRequiredToExtract;
this.method = method;
}
/// <summary>
/// Creates a deep copy of the given zip entry.
/// </summary>
/// <param name="entry">
/// The entry to copy.
/// </param>
[Obsolete("Use Clone instead")]
public ZipEntry(ZipEntry entry)
{
if (entry == null) {
throw new ArgumentNullException(nameof(entry));
}
known = entry.known;
name = entry.name;
size = entry.size;
compressedSize = entry.compressedSize;
crc = entry.crc;
dosTime = entry.dosTime;
method = entry.method;
comment = entry.comment;
versionToExtract = entry.versionToExtract;
versionMadeBy = entry.versionMadeBy;
externalFileAttributes = entry.externalFileAttributes;
flags = entry.flags;
zipFileIndex = entry.zipFileIndex;
offset = entry.offset;
forceZip64_ = entry.forceZip64_;
if (entry.extra != null) {
extra = new byte[entry.extra.Length];
Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length);
}
}
#endregion
/// <summary>
/// Get a value indicating wether the entry has a CRC value available.
/// </summary>
public bool HasCrc {
get {
return (known & Known.Crc) != 0;
}
}
/// <summary>
/// Get/Set flag indicating if entry is encrypted.
/// A simple helper routine to aid interpretation of <see cref="Flags">flags</see>
/// </summary>
/// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
public bool IsCrypted {
get {
return (flags & 1) != 0;
}
set {
if (value) {
flags |= 1;
} else {
flags &= ~1;
}
}
}
/// <summary>
/// Get / set a flag indicating wether entry name and comment text are
/// encoded in <a href="http://www.unicode.org">unicode UTF8</a>.
/// </summary>
/// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
public bool IsUnicodeText {
get {
return (flags & (int)GeneralBitFlags.UnicodeText) != 0;
}
set {
if (value) {
flags |= (int)GeneralBitFlags.UnicodeText;
} else {
flags &= ~(int)GeneralBitFlags.UnicodeText;
}
}
}
/// <summary>
/// Value used during password checking for PKZIP 2.0 / 'classic' encryption.
/// </summary>
internal byte CryptoCheckValue {
get {
return cryptoCheckValue_;
}
set {
cryptoCheckValue_ = value;
}
}
/// <summary>
/// Get/Set general purpose bit flag for entry
/// </summary>
/// <remarks>
/// General purpose bit flag<br/>
/// <br/>
/// Bit 0: If set, indicates the file is encrypted<br/>
/// Bit 1-2 Only used for compression type 6 Imploding, and 8, 9 deflating<br/>
/// Imploding:<br/>
/// Bit 1 if set indicates an 8K sliding dictionary was used. If clear a 4k dictionary was used<br/>
/// Bit 2 if set indicates 3 Shannon-Fanno trees were used to encode the sliding dictionary, 2 otherwise<br/>
/// <br/>
/// Deflating:<br/>
/// Bit 2 Bit 1<br/>
/// 0 0 Normal compression was used<br/>
/// 0 1 Maximum compression was used<br/>
/// 1 0 Fast compression was used<br/>
/// 1 1 Super fast compression was used<br/>
/// <br/>
/// Bit 3: If set, the fields crc-32, compressed size
/// and uncompressed size are were not able to be written during zip file creation
/// The correct values are held in a data descriptor immediately following the compressed data. <br/>
/// Bit 4: Reserved for use by PKZIP for enhanced deflating<br/>
/// Bit 5: If set indicates the file contains compressed patch data<br/>
/// Bit 6: If set indicates strong encryption was used.<br/>
/// Bit 7-10: Unused or reserved<br/>
/// Bit 11: If set the name and comments for this entry are in <a href="http://www.unicode.org">unicode</a>.<br/>
/// Bit 12-15: Unused or reserved<br/>
/// </remarks>
/// <seealso cref="IsUnicodeText"></seealso>
/// <seealso cref="IsCrypted"></seealso>
public int Flags {
get {
return flags;
}
set {
flags = value;
}
}
/// <summary>
/// Get/Set index of this entry in Zip file
/// </summary>
/// <remarks>This is only valid when the entry is part of a <see cref="ZipFile"></see></remarks>
public long ZipFileIndex {
get {
return zipFileIndex;
}
set {
zipFileIndex = value;
}
}
/// <summary>
/// Get/set offset for use in central header
/// </summary>
public long Offset {
get {
return offset;
}
set {
offset = value;
}
}
/// <summary>
/// Get/Set external file attributes as an integer.
/// The values of this are operating system dependant see
/// <see cref="HostSystem">HostSystem</see> for details
/// </summary>
public int ExternalFileAttributes {
get {
if ((known & Known.ExternalAttributes) == 0) {
return -1;
} else {
return externalFileAttributes;
}
}
set {
externalFileAttributes = value;
known |= Known.ExternalAttributes;
}
}
/// <summary>
/// Get the version made by for this entry or zero if unknown.
/// The value / 10 indicates the major version number, and
/// the value mod 10 is the minor version number
/// </summary>
public int VersionMadeBy {
get {
return (versionMadeBy & 0xff);
}
}
/// <summary>
/// Get a value indicating this entry is for a DOS/Windows system.
/// </summary>
public bool IsDOSEntry {
get {
return ((HostSystem == (int)HostSystemID.Msdos) ||
(HostSystem == (int)HostSystemID.WindowsNT));
}
}
/// <summary>
/// Test the external attributes for this <see cref="ZipEntry"/> to
/// see if the external attributes are Dos based (including WINNT and variants)
/// and match the values
/// </summary>
/// <param name="attributes">The attributes to test.</param>
/// <returns>Returns true if the external attributes are known to be DOS/Windows
/// based and have the same attributes set as the value passed.</returns>
bool HasDosAttributes(int attributes)
{
bool result = false;
if ((known & Known.ExternalAttributes) != 0) {
result |= (((HostSystem == (int)HostSystemID.Msdos) ||
(HostSystem == (int)HostSystemID.WindowsNT)) &&
(ExternalFileAttributes & attributes) == attributes);
}
return result;
}
/// <summary>
/// Gets the compatability information for the <see cref="ExternalFileAttributes">external file attribute</see>
/// If the external file attributes are compatible with MS-DOS and can be read
/// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value
/// will be non-zero and identify the host system on which the attributes are compatible.
/// </summary>
///
/// <remarks>
/// The values for this as defined in the Zip File format and by others are shown below. The values are somewhat
/// misleading in some cases as they are not all used as shown. You should consult the relevant documentation
/// to obtain up to date and correct information. The modified appnote by the infozip group is
/// particularly helpful as it documents a lot of peculiarities. The document is however a little dated.
/// <list type="table">
/// <item>0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)</item>
/// <item>1 - Amiga</item>
/// <item>2 - OpenVMS</item>
/// <item>3 - Unix</item>
/// <item>4 - VM/CMS</item>
/// <item>5 - Atari ST</item>
/// <item>6 - OS/2 HPFS</item>
/// <item>7 - Macintosh</item>
/// <item>8 - Z-System</item>
/// <item>9 - CP/M</item>
/// <item>10 - Windows NTFS</item>
/// <item>11 - MVS (OS/390 - Z/OS)</item>
/// <item>12 - VSE</item>
/// <item>13 - Acorn Risc</item>
/// <item>14 - VFAT</item>
/// <item>15 - Alternate MVS</item>
/// <item>16 - BeOS</item>
/// <item>17 - Tandem</item>
/// <item>18 - OS/400</item>
/// <item>19 - OS/X (Darwin)</item>
/// <item>99 - WinZip AES</item>
/// <item>remainder - unused</item>
/// </list>
/// </remarks>
public int HostSystem {
get {
return (versionMadeBy >> 8) & 0xff;
}
set {
versionMadeBy &= 0xff;
versionMadeBy |= (ushort)((value & 0xff) << 8);
}
}
/// <summary>
/// Get minimum Zip feature version required to extract this entry
/// </summary>
/// <remarks>
/// Minimum features are defined as:<br/>
/// 1.0 - Default value<br/>
/// 1.1 - File is a volume label<br/>
/// 2.0 - File is a folder/directory<br/>
/// 2.0 - File is compressed using Deflate compression<br/>
/// 2.0 - File is encrypted using traditional encryption<br/>
/// 2.1 - File is compressed using Deflate64<br/>
/// 2.5 - File is compressed using PKWARE DCL Implode<br/>
/// 2.7 - File is a patch data set<br/>
/// 4.5 - File uses Zip64 format extensions<br/>
/// 4.6 - File is compressed using BZIP2 compression<br/>
/// 5.0 - File is encrypted using DES<br/>
/// 5.0 - File is encrypted using 3DES<br/>
/// 5.0 - File is encrypted using original RC2 encryption<br/>
/// 5.0 - File is encrypted using RC4 encryption<br/>
/// 5.1 - File is encrypted using AES encryption<br/>
/// 5.1 - File is encrypted using corrected RC2 encryption<br/>
/// 5.1 - File is encrypted using corrected RC2-64 encryption<br/>
/// 6.1 - File is encrypted using non-OAEP key wrapping<br/>
/// 6.2 - Central directory encryption (not confirmed yet)<br/>
/// 6.3 - File is compressed using LZMA<br/>
/// 6.3 - File is compressed using PPMD+<br/>
/// 6.3 - File is encrypted using Blowfish<br/>
/// 6.3 - File is encrypted using Twofish<br/>
/// </remarks>
/// <seealso cref="CanDecompress"></seealso>
public int Version {
get {
// Return recorded version if known.
if (versionToExtract != 0) {
return versionToExtract & 0x00ff; // Only lower order byte. High order is O/S file system.
} else {
int result = 10;
if (AESKeySize > 0) {
result = ZipConstants.VERSION_AES; // Ver 5.1 = AES
} else if (CentralHeaderRequiresZip64) {
result = ZipConstants.VersionZip64;
} else if (CompressionMethod.Deflated == method) {
result = 20;
} else if (IsDirectory == true) {
result = 20;
} else if (IsCrypted == true) {
result = 20;
} else if (HasDosAttributes(0x08)) {
result = 11;
}
return result;
}
}
}
/// <summary>
/// Get a value indicating whether this entry can be decompressed by the library.
/// </summary>
/// <remarks>This is based on the <see cref="Version"></see> and
/// wether the <see cref="IsCompressionMethodSupported()">compression method</see> is supported.</remarks>
public bool CanDecompress {
get {
return (Version <= ZipConstants.VersionMadeBy) &&
((Version == 10) ||
(Version == 11) ||
(Version == 20) ||
(Version == 45) ||
(Version == 51)) &&
IsCompressionMethodSupported();
}
}
/// <summary>
/// Force this entry to be recorded using Zip64 extensions.
/// </summary>
public void ForceZip64()
{
forceZip64_ = true;
}
/// <summary>
/// Get a value indicating wether Zip64 extensions were forced.
/// </summary>
/// <returns>A <see cref="bool"/> value of true if Zip64 extensions have been forced on; false if not.</returns>
public bool IsZip64Forced()
{
return forceZip64_;
}
/// <summary>
/// Gets a value indicating if the entry requires Zip64 extensions
/// to store the full entry values.
/// </summary>
/// <value>A <see cref="bool"/> value of true if a local header requires Zip64 extensions; false if not.</value>
public bool LocalHeaderRequiresZip64 {
get {
bool result = forceZip64_;
if (!result) {
ulong trueCompressedSize = compressedSize;
if ((versionToExtract == 0) && IsCrypted) {
trueCompressedSize += ZipConstants.CryptoHeaderSize;
}
// TODO: A better estimation of the true limit based on compression overhead should be used
// to determine when an entry should use Zip64.
result =
((this.size >= uint.MaxValue) || (trueCompressedSize >= uint.MaxValue)) &&
((versionToExtract == 0) || (versionToExtract >= ZipConstants.VersionZip64));
}
return result;
}
}
/// <summary>
/// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored.
/// </summary>
public bool CentralHeaderRequiresZip64 {
get {
return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue);
}
}
/// <summary>
/// Get/Set DosTime value.
/// </summary>
/// <remarks>
/// The MS-DOS date format can only represent dates between 1/1/1980 and 12/31/2107.
/// </remarks>
public long DosTime {
get {
if ((known & Known.Time) == 0) {
return 0;
} else {
return dosTime;
}
}
set {
unchecked {
dosTime = (uint)value;
}
known |= Known.Time;
}
}
/// <summary>
/// Gets/Sets the time of last modification of the entry.
/// </summary>
/// <remarks>
/// The <see cref="DosTime"></see> property is updated to match this as far as possible.
/// </remarks>
public DateTime DateTime
{
get
{
uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
uint year = ((dosTime >> 25) & 0x7f) + 1980;
int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec);
}
set {
var year = (uint)value.Year;
var month = (uint)value.Month;
var day = (uint)value.Day;
var hour = (uint)value.Hour;
var minute = (uint)value.Minute;
var second = (uint)value.Second;
if (year < 1980) {
year = 1980;
month = 1;
day = 1;
hour = 0;
minute = 0;
second = 0;
} else if (year > 2107) {
year = 2107;
month = 12;
day = 31;
hour = 23;
minute = 59;
second = 59;
}
DosTime = ((year - 1980) & 0x7f) << 25 |
(month << 21) |
(day << 16) |
(hour << 11) |
(minute << 5) |
(second >> 1);
}
}
/// <summary>
/// Returns the entry name.
/// </summary>
/// <remarks>
/// The unix naming convention is followed.
/// Path components in the entry should always separated by forward slashes ('/').
/// Dos device names like C: should also be removed.
/// See the <see cref="ZipNameTransform"/> class, or <see cref="CleanName(string)"/>
///</remarks>
public string Name {
get {
return name;
}
}
/// <summary>
/// Gets/Sets the size of the uncompressed data.
/// </summary>
/// <returns>
/// The size or -1 if unknown.
/// </returns>
/// <remarks>Setting the size before adding an entry to an archive can help
/// avoid compatability problems with some archivers which dont understand Zip64 extensions.</remarks>
public long Size {
get {
return (known & Known.Size) != 0 ? (long)size : -1L;
}
set {
this.size = (ulong)value;
this.known |= Known.Size;
}
}
/// <summary>
/// Gets/Sets the size of the compressed data.
/// </summary>
/// <returns>
/// The compressed entry size or -1 if unknown.
/// </returns>
public long CompressedSize {
get {
return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L;
}
set {
this.compressedSize = (ulong)value;
this.known |= Known.CompressedSize;
}
}
/// <summary>
/// Gets/Sets the crc of the uncompressed data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Crc is not in the range 0..0xffffffffL
/// </exception>
/// <returns>
/// The crc value or -1 if unknown.
/// </returns>
public long Crc {
get {
return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L;
}
set {
if (((ulong)crc & 0xffffffff00000000L) != 0) {
throw new ArgumentOutOfRangeException(nameof(value));
}
this.crc = (uint)value;
this.known |= Known.Crc;
}
}
/// <summary>
/// Gets/Sets the compression method. Only Deflated and Stored are supported.
/// </summary>
/// <returns>
/// The compression method for this entry
/// </returns>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated"/>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored"/>
public CompressionMethod CompressionMethod {
get {
return method;
}
set {
if (!IsCompressionMethodSupported(value)) {
throw new NotSupportedException("Compression method not supported");
}
this.method = value;
}
}
/// <summary>
/// Gets the compression method for outputting to the local or central header.
/// Returns same value as CompressionMethod except when AES encrypting, which
/// places 99 in the method and places the real method in the extra data.
/// </summary>
internal CompressionMethod CompressionMethodForHeader {
get {
return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method;
}
}
/// <summary>
/// Gets/Sets the extra data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Extra data is longer than 64KB (0xffff) bytes.
/// </exception>
/// <returns>
/// Extra data or null if not set.
/// </returns>
public byte[] ExtraData {
get {
// TODO: This is slightly safer but less efficient. Think about wether it should change.
// return (byte[]) extra.Clone();
return extra;
}
set {
if (value == null) {
extra = null;
} else {
if (value.Length > 0xffff) {
throw new System.ArgumentOutOfRangeException(nameof(value));
}
extra = new byte[value.Length];
Array.Copy(value, 0, extra, 0, value.Length);
}
}
}
/// <summary>
/// For AES encrypted files returns or sets the number of bits of encryption (128, 192 or 256).
/// When setting, only 0 (off), 128 or 256 is supported.
/// </summary>
public int AESKeySize {
get {
// the strength (1 or 3) is in the entry header
switch (_aesEncryptionStrength) {
case 0:
return 0; // Not AES
case 1:
return 128;
case 2:
return 192; // Not used by WinZip
case 3:
return 256;
default:
throw new ZipException("Invalid AESEncryptionStrength " + _aesEncryptionStrength);
}
}
set {
switch (value) {
case 0:
_aesEncryptionStrength = 0;
break;
case 128:
_aesEncryptionStrength = 1;
break;
case 256:
_aesEncryptionStrength = 3;
break;
default:
throw new ZipException("AESKeySize must be 0, 128 or 256: " + value);
}
}
}
/// <summary>
/// AES Encryption strength for storage in extra data in entry header.
/// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit.
/// </summary>
internal byte AESEncryptionStrength {
get {
return (byte)_aesEncryptionStrength;
}
}
/// <summary>
/// Returns the length of the salt, in bytes
/// </summary>
internal int AESSaltLen {
get {
// Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes.
return AESKeySize / 16;
}
}
/// <summary>
/// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode)
/// </summary>
internal int AESOverheadSize {
get {
// File format:
// Bytes Content
// Variable Salt value
// 2 Password verification value
// Variable Encrypted file data
// 10 Authentication code
return 12 + AESSaltLen;
}
}
/// <summary>
/// Process extra data fields updating the entry based on the contents.
/// </summary>
/// <param name="localHeader">True if the extra data fields should be handled
/// for a local header, rather than for a central header.
/// </param>
internal void ProcessExtraData(bool localHeader)
{
var extraData = new ZipExtraData(this.extra);
if (extraData.Find(0x0001)) {
// Version required to extract is ignored here as some archivers dont set it correctly
// in theory it should be version 45 or higher
// The recorded size will change but remember that this is zip64.
forceZip64_ = true;
if (extraData.ValueLength < 4) {
throw new ZipException("Extra data extended Zip64 information length is invalid");
}
// (localHeader ||) was deleted, because actually there is no specific difference with reading sizes between local header & central directory
// https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
// ...
// 4.4 Explanation of fields
// ...
// 4.4.8 compressed size: (4 bytes)
// 4.4.9 uncompressed size: (4 bytes)
//
// The size of the file compressed (4.4.8) and uncompressed,
// (4.4.9) respectively. When a decryption header is present it
// will be placed in front of the file data and the value of the
// compressed file size will include the bytes of the decryption
// header. If bit 3 of the general purpose bit flag is set,
// these fields are set to zero in the local header and the
// correct values are put in the data descriptor and
// in the central directory. If an archive is in ZIP64 format
// and the value in this field is 0xFFFFFFFF, the size will be
// in the corresponding 8 byte ZIP64 extended information
// extra field. When encrypting the central directory, if the
// local header is not in ZIP64 format and general purpose bit
// flag 13 is set indicating masking, the value stored for the
// uncompressed size in the Local Header will be zero.
//
// Othewise there is problem with minizip implementation
if (size == uint.MaxValue) {
size = (ulong)extraData.ReadLong();
}
if (compressedSize == uint.MaxValue) {
compressedSize = (ulong)extraData.ReadLong();
}
if (!localHeader && (offset == uint.MaxValue)) {
offset = extraData.ReadLong();
}
// Disk number on which file starts is ignored
} else {
if (
((versionToExtract & 0xff) >= ZipConstants.VersionZip64) &&
((size == uint.MaxValue) || (compressedSize == uint.MaxValue))
) {
throw new ZipException("Zip64 Extended information required but is missing.");
}
}
DateTime = GetDateTime(extraData);
if (method == CompressionMethod.WinZipAES) {
ProcessAESExtraData(extraData);
}
}
private DateTime GetDateTime(ZipExtraData extraData) {
// Check for NT timestamp
// NOTE: Disable by default to match behavior of InfoZIP
#if RESPECT_NT_TIMESTAMP
NTTaggedData ntData = extraData.GetData<NTTaggedData>();
if (ntData != null)
return ntData.LastModificationTime;
#endif
// Check for Unix timestamp
ExtendedUnixData unixData = extraData.GetData<ExtendedUnixData>();
if (unixData != null &&
// Only apply modification time, but require all other values to be present
// This is done to match InfoZIP's behaviour
((unixData.Include & ExtendedUnixData.Flags.ModificationTime) != 0) &&
((unixData.Include & ExtendedUnixData.Flags.AccessTime) != 0) &&
((unixData.Include & ExtendedUnixData.Flags.CreateTime) != 0))
return unixData.ModificationTime;
// Fall back to DOS time
uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
uint year = ((dosTime >> 25) & 0x7f) + 1980;
int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
return new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc);
}
// For AES the method in the entry is 99, and the real compression method is in the extradata
//
private void ProcessAESExtraData(ZipExtraData extraData)
{
if (extraData.Find(0x9901)) {
// Set version and flag for Zipfile.CreateAndInitDecryptionStream
versionToExtract = ZipConstants.VERSION_AES; // Ver 5.1 = AES see "Version" getter
// Set StrongEncryption flag for ZipFile.CreateAndInitDecryptionStream
Flags = Flags | (int)GeneralBitFlags.StrongEncryption;
//
// Unpack AES extra data field see http://www.winzip.com/aes_info.htm
int length = extraData.ValueLength; // Data size currently 7
if (length < 7)
throw new ZipException("AES Extra Data Length " + length + " invalid.");
int ver = extraData.ReadShort(); // Version number (1=AE-1 2=AE-2)
int vendorId = extraData.ReadShort(); // 2-character vendor ID 0x4541 = "AE"
int encrStrength = extraData.ReadByte(); // encryption strength 1 = 128 2 = 192 3 = 256
int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file
_aesVer = ver;
_aesEncryptionStrength = encrStrength;
method = (CompressionMethod)actualCompress;
} else
throw new ZipException("AES Extra Data missing");
}
/// <summary>
/// Gets/Sets the entry comment.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If comment is longer than 0xffff.
/// </exception>
/// <returns>
/// The comment or null if not set.
/// </returns>
/// <remarks>
/// A comment is only available for entries when read via the <see cref="ZipFile"/> class.
/// The <see cref="ZipInputStream"/> class doesnt have the comment data available.
/// </remarks>
public string Comment {
get {
return comment;
}
set {
// This test is strictly incorrect as the length is in characters
// while the storage limit is in bytes.
// While the test is partially correct in that a comment of this length or greater
// is definitely invalid, shorter comments may also have an invalid length
// where there are multi-byte characters
// The full test is not possible here however as the code page to apply conversions with
// isnt available.
if ((value != null) && (value.Length > 0xffff)) {
throw new ArgumentOutOfRangeException(nameof(value), "cannot exceed 65535");
}
comment = value;
}
}
/// <summary>
/// Gets a value indicating if the entry is a directory.
/// however.
/// </summary>
/// <remarks>
/// A directory is determined by an entry name with a trailing slash '/'.
/// The external file attributes can also indicate an entry is for a directory.
/// Currently only dos/windows attributes are tested in this manner.
/// The trailing slash convention should always be followed.
/// </remarks>
public bool IsDirectory {
get {
int nameLength = name.Length;
bool result =
((nameLength > 0) &&
((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) ||
HasDosAttributes(16)
;
return result;
}
}
/// <summary>
/// Get a value of true if the entry appears to be a file; false otherwise
/// </summary>
/// <remarks>
/// This only takes account of DOS/Windows attributes. Other operating systems are ignored.
/// For linux and others the result may be incorrect.
/// </remarks>
public bool IsFile {
get {
return !IsDirectory && !HasDosAttributes(8);
}
}
/// <summary>
/// Test entry to see if data can be extracted.
/// </summary>
/// <returns>Returns true if data can be extracted for this entry; false otherwise.</returns>
public bool IsCompressionMethodSupported()
{
return IsCompressionMethodSupported(CompressionMethod);
}
#region ICloneable Members
/// <summary>
/// Creates a copy of this zip entry.
/// </summary>
/// <returns>An <see cref="Object"/> that is a copy of the current instance.</returns>
public object Clone()
{
var result = (ZipEntry)this.MemberwiseClone();
// Ensure extra data is unique if it exists.
if (extra != null) {
result.extra = new byte[extra.Length];
Array.Copy(extra, 0, result.extra, 0, extra.Length);
}
return result;
}
#endregion
/// <summary>
/// Gets a string representation of this ZipEntry.
/// </summary>
/// <returns>A readable textual representation of this <see cref="ZipEntry"/></returns>
public override string ToString()
{
return name;
}
/// <summary>
/// Test a <see cref="CompressionMethod">compression method</see> to see if this library
/// supports extracting data compressed with that method
/// </summary>
/// <param name="method">The compression method to test.</param>
/// <returns>Returns true if the compression method is supported; false otherwise</returns>
public static bool IsCompressionMethodSupported(CompressionMethod method)
{
return
(method == CompressionMethod.Deflated) ||
(method == CompressionMethod.Stored);
}
/// <summary>
/// Cleans a name making it conform to Zip file conventions.
/// Devices names ('c:\') and UNC share names ('\\server\share') are removed
/// and forward slashes ('\') are converted to back slashes ('/').
/// Names are made relative by trimming leading slashes which is compatible
/// with the ZIP naming convention.
/// </summary>
/// <param name="name">The name to clean</param>
/// <returns>The 'cleaned' name.</returns>
/// <remarks>
/// The <seealso cref="ZipNameTransform">Zip name transform</seealso> class is more flexible.
/// </remarks>
public static string CleanName(string name)
{
if (name == null) {
return string.Empty;
}
if (Path.IsPathRooted(name)) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
}
name = name.Replace(@"\", "/");
while ((name.Length > 0) && (name[0] == '/')) {
name = name.Remove(0, 1);
}
return name;
}
#region Instance Fields
Known known;
int externalFileAttributes = -1; // contains external attributes (O/S dependant)
ushort versionMadeBy; // Contains host system and version information
// only relevant for central header entries
string name;
ulong size;
ulong compressedSize;
ushort versionToExtract; // Version required to extract (library handles <= 2.0)
uint crc;
uint dosTime;
CompressionMethod method = CompressionMethod.Deflated;
byte[] extra;
string comment;
int flags; // general purpose bit flags
long zipFileIndex = -1; // used by ZipFile
long offset; // used by ZipFile and ZipOutputStream
bool forceZip64_;
byte cryptoCheckValue_;
int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used.
int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//------------------------------------------------------------------------------
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
// To get up to date fundamental definition files for your hedgefund contact [email protected]
using System;
using Newtonsoft.Json;
namespace QuantConnect.Data.Fundamental
{
/// <summary>
/// Definition of the CompanyReference class
/// </summary>
public class CompanyReference
{
/// <summary>
/// 10-digit unique and unchanging Morningstar identifier assigned to every company.
/// </summary>
/// <remarks>
/// Morningstar DataId: 1
/// </remarks>
[JsonProperty("1")]
public string CompanyId { get; set; }
/// <summary>
/// 25-character max abbreviated name of the firm. In most cases, the short name will simply be the Legal Name less the
/// "Corporation", "Corp.", "Inc.", "Incorporated", etc...
/// </summary>
/// <remarks>
/// Morningstar DataId: 2
/// </remarks>
[JsonProperty("2")]
public string ShortName { get; set; }
/// <summary>
/// The English translation of the foreign legal name if/when applicable.
/// </summary>
/// <remarks>
/// Morningstar DataId: 3
/// </remarks>
[JsonProperty("3")]
public string StandardName { get; set; }
/// <summary>
/// The full name of the registrant as specified in its charter, and most often found on the front cover of the 10K/10Q/20F filing.
/// </summary>
/// <remarks>
/// Morningstar DataId: 4
/// </remarks>
[JsonProperty("4")]
public string LegalName { get; set; }
/// <summary>
/// 3 Character ISO code of the country where the firm is domiciled. See separate reference document for Country Mappings.
/// </summary>
/// <remarks>
/// Morningstar DataId: 5
/// </remarks>
[JsonProperty("5")]
public string CountryId { get; set; }
/// <summary>
/// The Central Index Key; a corporate identifier assigned by the Securities and Exchange Commission (SEC).
/// </summary>
/// <remarks>
/// Morningstar DataId: 6
/// </remarks>
[JsonProperty("6")]
public string CIK { get; set; }
/// <summary>
/// At the Company level; each company is assigned to 1 of 3 possible status classifications; (U) Public, (V) Private, or (O) Obsolete:
/// - Public-Firm is operating and currently has at least one common share class that is currently trading on a public exchange.
/// - Private-Firm is operating but does not have any common share classes currently trading on a public exchange.
/// - Obsolete-Firm is no longer operating because it closed its business, or was acquired.
/// </summary>
/// <remarks>
/// Morningstar DataId: 9
/// </remarks>
[JsonProperty("9")]
public string CompanyStatus { get; set; }
/// <summary>
/// The Month of the company's latest fiscal year.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10
/// </remarks>
[JsonProperty("10")]
public int FiscalYearEnd { get; set; }
/// <summary>
/// This indicator will denote which one of the six industry data collection templates applies to the company. Each industry data
/// collection template includes data elements that are commonly reported by companies in that industry. N=Normal
/// (Manufacturing), M=Mining, U=Utility, T=Transportation, B=Bank, I=Insurance
/// </summary>
/// <remarks>
/// Morningstar DataId: 11
/// </remarks>
[JsonProperty("11")]
public string IndustryTemplateCode { get; set; }
/// <summary>
/// The 10-digit unique and unchanging Morningstar identifier assigned to the Primary Share class of a company. The primary share of a
/// company is defined as the first share that was traded publicly and is still actively trading. If this share is no longer trading, the
/// primary share will be the share with the highest volume.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12
/// </remarks>
[JsonProperty("12")]
public string PrimaryShareClassID { get; set; }
/// <summary>
/// The symbol of the Primary Share of the company, composed of an arrangement of characters (often letters) representing a
/// particular security listed on an exchange or otherwise traded publicly. The primary share of a company is defined as the first share
/// that was traded publicly and is still actively trading. If this share is no longer trading, the primary share will be the share with the
/// highest volume. Note: Morningstar's multi-share class symbols will often contain a "period" within the symbol; e.g. BRK.B for
/// Berkshire Hathaway Class B.
/// </summary>
/// <remarks>
/// Morningstar DataId: 13
/// </remarks>
[JsonProperty("13")]
public string PrimarySymbol { get; set; }
/// <summary>
/// The Id representing the stock exchange of the Primary Share of the company. See separate reference document for Exchange
/// Mappings. The primary share of a company is defined as the first share that was traded publicly with and is still actively trading. If
/// this share is no longer trading, the primary share will be the share with the highest volume.
/// </summary>
/// <remarks>
/// Morningstar DataId: 14
/// </remarks>
[JsonProperty("14")]
public string PrimaryExchangeID { get; set; }
/// <summary>
/// In some cases, different from the country of domicile (CountryId; DataID 5). This element is a three (3) Character ISO code of the
/// business country of the security. It is determined by a few factors, including:
/// </summary>
/// <remarks>
/// Morningstar DataId: 15
/// </remarks>
[JsonProperty("15")]
public string BusinessCountryID { get; set; }
/// <summary>
/// The language code for the foreign legal name if/when applicable. Related to DataID 4 (LegalName).
/// </summary>
/// <remarks>
/// Morningstar DataId: 16
/// </remarks>
[JsonProperty("16")]
public string LegalNameLanguageCode { get; set; }
/// <summary>
/// The legal (registered) name of the company's current auditor. Distinct from DataID 28000 Period Auditor that identifies the Auditor
/// related to that period's financial statements.
/// </summary>
/// <remarks>
/// Morningstar DataId: 17
/// </remarks>
[JsonProperty("17")]
public string Auditor { get; set; }
/// <summary>
/// The ISO code denoting the language text for Auditor's name and contact information.
/// </summary>
/// <remarks>
/// Morningstar DataId: 18
/// </remarks>
[JsonProperty("18")]
public string AuditorLanguageCode { get; set; }
/// <summary>
/// The legal (registered) name of the current legal Advisor of the company.
/// </summary>
/// <remarks>
/// Morningstar DataId: 19
/// </remarks>
[JsonProperty("19")]
public string Advisor { get; set; }
/// <summary>
/// The ISO code denoting the language text for Advisor's name and contact information.
/// </summary>
/// <remarks>
/// Morningstar DataId: 20
/// </remarks>
[JsonProperty("20")]
public string AdvisorLanguageCode { get; set; }
/// <summary>
/// Indicator to denote if the company is a limited partnership, which is a form of business structure comprised of a general partner and
/// limited partners. 1 denotes it is a LP; otherwise 0.
/// </summary>
/// <remarks>
/// Morningstar DataId: 21
/// </remarks>
[JsonProperty("21")]
public bool IsLimitedPartnership { get; set; }
/// <summary>
/// Indicator to denote if the company is a real estate investment trust (REIT). 1 denotes it is a REIT; otherwise 0.
/// </summary>
/// <remarks>
/// Morningstar DataId: 22
/// </remarks>
[JsonProperty("22")]
public bool IsREIT { get; set; }
/// <summary>
/// The MIC (market identifier code) of the PrimarySymbol of the company. See Data Appendix A for the relevant MIC to exchange
/// name mapping.
/// </summary>
/// <remarks>
/// Morningstar DataId: 23
/// </remarks>
[JsonProperty("23")]
public string PrimaryMIC { get; set; }
/// <summary>
/// This refers to the financial template used to collect the company's financial statements. There are two report styles representing
/// two different financial template structures. Report style "1" is most commonly used by US and Canadian companies, and Report
/// style "3" is most commonly used by the rest of the universe. Contact your client manager for access to the respective templates.
/// </summary>
/// <remarks>
/// Morningstar DataId: 24
/// </remarks>
[JsonProperty("24")]
public int ReportStyle { get; set; }
/// <summary>
/// The year a company was founded.
/// </summary>
/// <remarks>
/// Morningstar DataId: 25
/// </remarks>
[JsonProperty("25")]
public string YearofEstablishment { get; set; }
/// <summary>
/// Indicator to denote if the company is a limited liability company. 1 denotes it is a LLC; otherwise 0.
/// </summary>
/// <remarks>
/// Morningstar DataId: 26
/// </remarks>
[JsonProperty("26")]
public bool IsLimitedLiabilityCompany { get; set; }
/// <summary>
/// The upcoming expected year end for the company. It is calculated based on current year end (from latest available annual report)
/// + 1 year.
/// </summary>
/// <remarks>
/// Morningstar DataId: 27
/// </remarks>
[JsonProperty("27")]
public DateTime ExpectedFiscalYearEnd { get; set; }
/// <summary>
/// Creates an instance of the CompanyReference class
/// </summary>
public CompanyReference()
{
}
/// <summary>
/// Applies updated values from <paramref name="update"/> to this instance
/// </summary>
/// <remarks>Used to apply data updates to the current instance. This WILL overwrite existing values. Default update values are ignored.</remarks>
/// <param name="update">The next data update for this instance</param>
public void UpdateValues(CompanyReference update)
{
if (update == null) return;
if (!string.IsNullOrWhiteSpace(update.CompanyId)) CompanyId = update.CompanyId;
if (!string.IsNullOrWhiteSpace(update.ShortName)) ShortName = update.ShortName;
if (!string.IsNullOrWhiteSpace(update.StandardName)) StandardName = update.StandardName;
if (!string.IsNullOrWhiteSpace(update.LegalName)) LegalName = update.LegalName;
if (!string.IsNullOrWhiteSpace(update.CountryId)) CountryId = update.CountryId;
if (!string.IsNullOrWhiteSpace(update.CIK)) CIK = update.CIK;
if (!string.IsNullOrWhiteSpace(update.CompanyStatus)) CompanyStatus = update.CompanyStatus;
if (update.FiscalYearEnd != default(int)) FiscalYearEnd = update.FiscalYearEnd;
if (!string.IsNullOrWhiteSpace(update.IndustryTemplateCode)) IndustryTemplateCode = update.IndustryTemplateCode;
if (!string.IsNullOrWhiteSpace(update.PrimaryShareClassID)) PrimaryShareClassID = update.PrimaryShareClassID;
if (!string.IsNullOrWhiteSpace(update.PrimarySymbol)) PrimarySymbol = update.PrimarySymbol;
if (!string.IsNullOrWhiteSpace(update.PrimaryExchangeID)) PrimaryExchangeID = update.PrimaryExchangeID;
if (!string.IsNullOrWhiteSpace(update.BusinessCountryID)) BusinessCountryID = update.BusinessCountryID;
if (!string.IsNullOrWhiteSpace(update.LegalNameLanguageCode)) LegalNameLanguageCode = update.LegalNameLanguageCode;
if (!string.IsNullOrWhiteSpace(update.Auditor)) Auditor = update.Auditor;
if (!string.IsNullOrWhiteSpace(update.AuditorLanguageCode)) AuditorLanguageCode = update.AuditorLanguageCode;
if (!string.IsNullOrWhiteSpace(update.Advisor)) Advisor = update.Advisor;
if (!string.IsNullOrWhiteSpace(update.AdvisorLanguageCode)) AdvisorLanguageCode = update.AdvisorLanguageCode;
if (update.IsLimitedPartnership != default(bool)) IsLimitedPartnership = update.IsLimitedPartnership;
if (update.IsREIT != default(bool)) IsREIT = update.IsREIT;
if (!string.IsNullOrWhiteSpace(update.PrimaryMIC)) PrimaryMIC = update.PrimaryMIC;
if (update.ReportStyle != default(int)) ReportStyle = update.ReportStyle;
if (!string.IsNullOrWhiteSpace(update.YearofEstablishment)) YearofEstablishment = update.YearofEstablishment;
if (update.IsLimitedLiabilityCompany != default(bool)) IsLimitedLiabilityCompany = update.IsLimitedLiabilityCompany;
if (update.ExpectedFiscalYearEnd != default(DateTime)) ExpectedFiscalYearEnd = update.ExpectedFiscalYearEnd;
}
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
using Alachisoft.NosDB.Common.Communication;
using Alachisoft.NosDB.Common.Configuration.Services;
using Alachisoft.NosDB.Common.Protobuf.ManagementCommands;
using Alachisoft.NosDB.Common.RPCFramework;
using Alachisoft.NosDB.Common.RPCFramework.DotNetRPC;
using Alachisoft.NosDB.Common.Util;
using Alachisoft.NosDB.Core.Configuration.Services;
using Alachisoft.NosDB.Serialization.Formatters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Alachisoft.NosDB.Core.Monitoring.Configuration
{
public class ConfigrationMonitorSession : IConfigurationMonitor, IRequestListener
{
#region /* Fields */
ConfigurationServer configServer;
DateTime _sessionStartTime;
string _sessionid;
private Common.RPCFramework.RPCService<ConfigrationMonitorSession> _rpcService = null;
private IDualChannel _channel;
private Dictionary<string, Membership> _membershipPerShard = new Dictionary<string, Membership>();
private Dictionary<string, List<ServerInfo>> _configuredNodesPerShard;
private Dictionary<string, List<ServerInfo>> _runningNodesPerShard;
private ShardInfo[] _configuredShards;
#endregion
public IDualChannel Channel
{
get { return _channel; }
set
{
_channel = value;
//if (configServer != null) configServer.AddClientChannel((DualChannel)_channel);
}
}
public ConfigrationMonitorSession(ConfigurationServer server, UserCredentials credentials)
{
this.configServer = server;
//ConfigurationProvider.Provider = this;
this._sessionStartTime = DateTime.Now;
_sessionid = Guid.NewGuid().ToString();
_rpcService = new Common.RPCFramework.RPCService<ConfigrationMonitorSession>(new TargetObject<ConfigrationMonitorSession>(this));
}
#region /* IRequestListener Methods */
public object OnRequest(IRequest request)
{
if (request.Message is ManagementCommand)
{
ManagementCommand command = request.Message as ManagementCommand;
if (command == null)
return null;
ManagementResponse response = new ManagementResponse();
response.MethodName = command.MethodName;
response.Version = command.CommandVersion;
response.RequestId = command.RequestId;
byte[] arguments= CompactBinaryFormatter.ToByteBuffer(command.Parameters, null);
try
{
response.ResponseMessage = _rpcService.InvokeMethodOnTarget(command.MethodName,
command.Overload,
GetTargetMethodParameters(arguments)
);
_channel.GetType();
}
catch (System.Exception ex)
{
response.Exception = ex;
}
return response;
}
else
return null;
}
protected object[] GetTargetMethodParameters(byte[] graph)
{
TargetMethodParameter parameters = CompactBinaryFormatter.FromByteBuffer(graph, "ok") as TargetMethodParameter;
return parameters.ParameterList.ToArray();
}
public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
{
//if (configServer != null && channel.PeerAddress != null)
// configServer.RemoveClientChannel(channel.PeerAddress);
}
#endregion
#region /* IConfigurationMonitor Methods */
[TargetMethod(ConfigurationCommandUtil.MethodName.GetConfiguredClusters, 1)]
public ClusterInfo[] GetConfiguredClusters()
{
return configServer.GetConfiguredClusters();
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetDatabaseClusterInfo, 1)]
public ClusterInfo GetConfiguredClusters(string cluster)
{
return configServer.GetDatabaseClusterInfo(cluster);
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetMembershipInfo, 1)]
public Membership GetMembershipInfo(string cluster, string shard)
{
Membership membership = configServer.GetMembershipInfo(cluster, shard).Clone() as Membership;
if (!_membershipPerShard.ContainsKey(shard))
_membershipPerShard.Add(shard, membership);
else
_membershipPerShard[shard] = membership;
return membership;
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetUpdatedMembershipInfo, 1)]
public Membership GetUpdatedMembershipInfo(string cluster, string shard)
{
if (!_membershipPerShard.ContainsKey(shard))
return GetMembershipInfo(cluster,shard);
Membership newMembership = configServer.GetMembershipInfo(cluster, shard).Clone() as Membership;
if (newMembership == null && _membershipPerShard[shard] != null)
{
Membership unKnownMembership = new Membership();
unKnownMembership.Cluster = cluster;
unKnownMembership.Shard = shard;
unKnownMembership.Primary = null;
_membershipPerShard[shard] = null;
return unKnownMembership;
}
else if (newMembership != null && _membershipPerShard[shard] == null)
{
_membershipPerShard[shard] = newMembership;
return newMembership;
}
else if (newMembership != null && _membershipPerShard[shard] != null)
{
if (newMembership.Primary == null)
{
if (_membershipPerShard[shard].Primary != null)
{
_membershipPerShard[shard] = newMembership;
return newMembership;
}
}
else if (!newMembership.Primary.Equals(_membershipPerShard[shard].Primary))
{
_membershipPerShard[shard] = newMembership;
return newMembership;
}
}
return null;
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetConfiguredShards, 1)]
public ShardInfo[] GetConfiguredShards(string cluster)
{
return _configuredShards = configServer.GetDatabaseClusterInfo(cluster).ShardInfo.Values.ToArray();
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetUpdatedConfiguredShards, 1)]
public ShardInfo[] GetUpdatedConfiguredShards(string cluster)
{
ShardInfo[] newConfiguredShards = configServer.GetDatabaseClusterInfo(cluster).ShardInfo.Values.ToArray();
if (_configuredShards == null)
return _configuredShards = newConfiguredShards;
if(_configuredShards.Length == newConfiguredShards.Length)
{
foreach (ShardInfo shard in newConfiguredShards)
{
if (!_configuredShards.Any(x => x.Name == shard.Name))
return _configuredShards = newConfiguredShards;
}
return null;
}
return _configuredShards = newConfiguredShards;
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetConfigureServerNodes, 1)]
public Dictionary<string, List<ServerInfo>> GetConfigureServerNodes(string cluster)
{
Dictionary<string, List<ServerInfo>> configuredServersPerShard = new Dictionary<string, List<ServerInfo>>();
foreach (ShardInfo shard in configServer.GetDatabaseClusterInfo(cluster).ShardInfo.Values)
{
List<ServerInfo> serverNodes = new List<ServerInfo>();
if (shard.RunningNodes != null)
foreach (ServerInfo server in shard.ConfigureNodes.Values)
{
serverNodes.Add(server);
}
configuredServersPerShard.Add(shard.Name, serverNodes);
}
return _configuredNodesPerShard = configuredServersPerShard;
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetUpdatedConfigureServerNodes, 1)]
public Dictionary<string, List<ServerInfo>> GetUpdatedConfigureServerNodes(string cluster)
{
if (_configuredNodesPerShard == null)
return GetConfigureServerNodes(cluster);
Dictionary<string, List<ServerInfo>> newConfiguredServersPerShard = new Dictionary<string, List<ServerInfo>>();
foreach (ShardInfo shard in configServer.GetDatabaseClusterInfo(cluster).ShardInfo.Values)
{
List<ServerInfo> serverNodes = new List<ServerInfo>();
if (shard.RunningNodes != null)
foreach (ServerInfo server in shard.ConfigureNodes.Values)
{
serverNodes.Add(server);
}
newConfiguredServersPerShard.Add(shard.Name, serverNodes);
}
if (_configuredNodesPerShard.Keys.Count != newConfiguredServersPerShard.Keys.Count)
return _configuredNodesPerShard = newConfiguredServersPerShard;
else
{
foreach (string shardKey in newConfiguredServersPerShard.Keys)
{
if (!newConfiguredServersPerShard.ContainsKey(shardKey))
return _configuredNodesPerShard = newConfiguredServersPerShard;
if (newConfiguredServersPerShard[shardKey].Count != _configuredNodesPerShard[shardKey].Count)
return _configuredNodesPerShard = newConfiguredServersPerShard;
foreach (ServerInfo server in newConfiguredServersPerShard[shardKey])
{
if (!_configuredNodesPerShard[shardKey].Contains(server))
return _configuredNodesPerShard = newConfiguredServersPerShard;
}
}
}
return null;
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetRunningServerNodes, 1)]
public Dictionary<string, List<ServerInfo>> GetRunningServerNodes(string cluster)
{
Dictionary<string, List<ServerInfo>> runningServersPerShard = new Dictionary<string, List<ServerInfo>>();
foreach (ShardInfo shard in configServer.GetDatabaseClusterInfo(cluster).ShardInfo.Values)
{
List<ServerInfo> serverNodes = new List<ServerInfo>();
if(shard.RunningNodes != null)
foreach (ServerInfo server in shard.RunningNodes.Values)
{
serverNodes.Add(server);
}
runningServersPerShard.Add(shard.Name, serverNodes);
}
return _runningNodesPerShard = runningServersPerShard;
}
[TargetMethod(ConfigurationCommandUtil.MethodName.GetUpdatedRunningServerNodes, 1)]
public Dictionary<string, List<ServerInfo>> GetUpdatedRunningServerNodes(string cluster)
{
if (_runningNodesPerShard == null)
return GetRunningServerNodes(cluster);
Dictionary<string, List<ServerInfo>> newRunningServersPerShard = new Dictionary<string, List<ServerInfo>>();
foreach (ShardInfo shard in configServer.GetDatabaseClusterInfo(cluster).ShardInfo.Values)
{
List<ServerInfo> serverNodes = new List<ServerInfo>();
if (shard.RunningNodes != null)
foreach (ServerInfo server in shard.RunningNodes.Values)
{
serverNodes.Add(server);
}
newRunningServersPerShard.Add(shard.Name, serverNodes);
}
if (_runningNodesPerShard.Keys.Count != newRunningServersPerShard.Keys.Count)
return _runningNodesPerShard = newRunningServersPerShard;
else
{
foreach (string shardKey in newRunningServersPerShard.Keys)
{
if(!newRunningServersPerShard.ContainsKey(shardKey))
return _runningNodesPerShard = newRunningServersPerShard;
if(newRunningServersPerShard[shardKey].Count != _runningNodesPerShard[shardKey].Count)
return _runningNodesPerShard = newRunningServersPerShard;
foreach (ServerInfo server in newRunningServersPerShard[shardKey])
{
if (!_runningNodesPerShard[shardKey].Contains(server))
return _runningNodesPerShard = newRunningServersPerShard;
}
}
}
return null;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Net.Http;
using System.Net.Quic;
using System.Text;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Internal;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Tests
{
public class QuicConnectionContextTests : TestApplicationErrorLoggerLoggedTest
{
private static readonly byte[] TestData = Encoding.UTF8.GetBytes("Hello world");
[ConditionalFact]
[MsQuicSupported]
public async Task AcceptAsync_CancellationThenAccept_AcceptStreamAfterCancellation()
{
// Arrange
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
// Act
var acceptTask = connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await acceptTask.DefaultTimeout();
// Wait for stream and then cancel
var cts = new CancellationTokenSource();
var acceptStreamTask = serverConnection.AcceptAsync(cts.Token);
cts.Cancel();
var serverStream = await acceptStreamTask.DefaultTimeout();
Assert.Null(serverStream);
// Wait for stream after cancellation
acceptStreamTask = serverConnection.AcceptAsync();
await using var clientStream = clientConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData);
// Assert
serverStream = await acceptStreamTask.DefaultTimeout();
Assert.NotNull(serverStream);
var read = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
Assert.Equal(TestData, read.Buffer.ToArray());
serverStream.Transport.Input.AdvanceTo(read.Buffer.End);
}
[ConditionalFact]
[MsQuicSupported]
public async Task AcceptAsync_ClientClosesConnection_ServerNotified()
{
// Arrange
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
// Act
var acceptTask = connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await acceptTask.DefaultTimeout();
serverConnection.ConnectionClosed.Register(() => connectionClosedTcs.SetResult());
var acceptStreamTask = serverConnection.AcceptAsync();
await clientConnection.CloseAsync(256);
// Assert
var ex = await Assert.ThrowsAsync<ConnectionResetException>(() => acceptStreamTask.AsTask()).DefaultTimeout();
var innerEx = Assert.IsType<QuicConnectionAbortedException>(ex.InnerException);
Assert.Equal(256, innerEx.ErrorCode);
await connectionClosedTcs.Task.DefaultTimeout();
}
[ConditionalFact]
[MsQuicSupported]
public async Task AcceptAsync_ClientStartsAndStopsUnidirectionStream_ServerAccepts()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var quicConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await quicConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
// Act
var acceptTask = serverConnection.AcceptAsync();
await using var clientStream = quicConnection.OpenUnidirectionalStream();
await clientStream.WriteAsync(TestData);
await using var serverStream = await acceptTask.DefaultTimeout();
// Assert
Assert.NotNull(serverStream);
Assert.False(serverStream.ConnectionClosed.IsCancellationRequested);
var closedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
serverStream.ConnectionClosed.Register(() => closedTcs.SetResult());
// Read data from client.
var read = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
Assert.Equal(TestData, read.Buffer.ToArray());
serverStream.Transport.Input.AdvanceTo(read.Buffer.End);
// Shutdown client.
clientStream.Shutdown();
// Receive shutdown on server.
read = await serverStream.Transport.Input.ReadAsync().DefaultTimeout();
Assert.True(read.IsCompleted);
await closedTcs.Task.DefaultTimeout();
}
[ConditionalFact]
[MsQuicSupported]
public async Task AcceptAsync_ClientStartsAndStopsBidirectionStream_ServerAccepts()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var quicConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await quicConnection.ConnectAsync().DefaultTimeout();
var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
// Act
var acceptTask = serverConnection.AcceptAsync();
await using var clientStream = quicConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData);
await using var serverStream = await acceptTask.DefaultTimeout();
await serverStream.Transport.Output.WriteAsync(TestData);
// Assert
Assert.NotNull(serverStream);
Assert.False(serverStream.ConnectionClosed.IsCancellationRequested);
var closedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
serverStream.ConnectionClosed.Register(() => closedTcs.SetResult());
// Read data from client.
var read = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
Assert.Equal(TestData, read.Buffer.ToArray());
serverStream.Transport.Input.AdvanceTo(read.Buffer.End);
// Read data from server.
var data = await clientStream.ReadAtLeastLengthAsync(TestData.Length).DefaultTimeout();
Assert.Equal(TestData, data);
// Shutdown from client.
clientStream.Shutdown();
// Get shutdown from client.
read = await serverStream.Transport.Input.ReadAsync().DefaultTimeout();
Assert.True(read.IsCompleted);
await serverStream.Transport.Output.CompleteAsync();
await closedTcs.Task.DefaultTimeout();
}
[ConditionalFact]
[MsQuicSupported]
public async Task AcceptAsync_ServerStartsAndStopsUnidirectionStream_ClientAccepts()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var quicConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await quicConnection.ConnectAsync().DefaultTimeout();
var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
// Act
var acceptTask = quicConnection.AcceptStreamAsync();
await using var serverStream = await serverConnection.ConnectAsync();
await serverStream.Transport.Output.WriteAsync(TestData).DefaultTimeout();
await using var clientStream = await acceptTask.DefaultTimeout();
// Assert
Assert.NotNull(clientStream);
// Read data from server.
var data = new List<byte>();
var buffer = new byte[1024];
var readCount = 0;
while ((readCount = await clientStream.ReadAsync(buffer).DefaultTimeout()) != -1)
{
data.AddRange(buffer.AsMemory(0, readCount).ToArray());
if (data.Count == TestData.Length)
{
break;
}
}
Assert.Equal(TestData, data);
// Complete server.
await serverStream.Transport.Output.CompleteAsync().DefaultTimeout();
// Receive complete in client.
readCount = await clientStream.ReadAsync(buffer).DefaultTimeout();
Assert.Equal(0, readCount);
}
[ConditionalFact]
[MsQuicSupported]
public async Task AcceptAsync_ClientClosesConnection_ExceptionThrown()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var quicConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await quicConnection.ConnectAsync().DefaultTimeout();
var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
// Act
var acceptTask = serverConnection.AcceptAsync().AsTask();
await quicConnection.CloseAsync((long)Http3ErrorCode.NoError).DefaultTimeout();
// Assert
var ex = await Assert.ThrowsAsync<ConnectionResetException>(() => acceptTask).DefaultTimeout();
var innerEx = Assert.IsType<QuicConnectionAbortedException>(ex.InnerException);
Assert.Equal((long)Http3ErrorCode.NoError, innerEx.ErrorCode);
Assert.Equal((long)Http3ErrorCode.NoError, serverConnection.Features.Get<IProtocolErrorCodeFeature>().Error);
}
[ConditionalFact]
[MsQuicSupported]
public async Task StreamPool_StreamAbortedOnServer_NotPooled()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var testHeartbeatFeature = new TestHeartbeatFeature();
serverConnection.Features.Set<IConnectionHeartbeatFeature>(testHeartbeatFeature);
// Act & Assert
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
var clientStream = clientConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData, endStream: true).DefaultTimeout();
var serverStream = await serverConnection.AcceptAsync().DefaultTimeout();
var readResult = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream.Transport.Input.AdvanceTo(readResult.Buffer.End);
// Input should be completed.
readResult = await serverStream.Transport.Input.ReadAsync();
Assert.True(readResult.IsCompleted);
// Complete reading and then abort.
await serverStream.Transport.Input.CompleteAsync();
serverStream.Abort(new ConnectionAbortedException("Test message"));
var quicStreamContext = Assert.IsType<QuicStreamContext>(serverStream);
// Both send and receive loops have exited.
await quicStreamContext._processingTask.DefaultTimeout();
await quicStreamContext.DisposeAsync();
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
}
[ConditionalFact]
[MsQuicSupported]
public async Task StreamPool_StreamAbortedOnServerAfterComplete_NotPooled()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var testHeartbeatFeature = new TestHeartbeatFeature();
serverConnection.Features.Set<IConnectionHeartbeatFeature>(testHeartbeatFeature);
// Act & Assert
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
var clientStream = clientConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData, endStream: true).DefaultTimeout();
var serverStream = await serverConnection.AcceptAsync().DefaultTimeout();
var readResult = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream.Transport.Input.AdvanceTo(readResult.Buffer.End);
// Input should be completed.
readResult = await serverStream.Transport.Input.ReadAsync();
Assert.True(readResult.IsCompleted);
// Complete reading and writing.
await serverStream.Transport.Input.CompleteAsync();
await serverStream.Transport.Output.CompleteAsync();
var quicStreamContext = Assert.IsType<QuicStreamContext>(serverStream);
// Both send and receive loops have exited.
await quicStreamContext._processingTask.DefaultTimeout();
serverStream.Abort(new ConnectionAbortedException("Test message"));
await quicStreamContext.DisposeAsync();
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
}
[ConditionalFact]
[MsQuicSupported]
public async Task StreamPool_StreamAbortedOnClient_NotPooled()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var testHeartbeatFeature = new TestHeartbeatFeature();
serverConnection.Features.Set<IConnectionHeartbeatFeature>(testHeartbeatFeature);
// Act & Assert
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
var clientStream = clientConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData).DefaultTimeout();
var serverStream = await serverConnection.AcceptAsync().DefaultTimeout();
var readResult = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream.Transport.Input.AdvanceTo(readResult.Buffer.End);
clientStream.AbortWrite((long)Http3ErrorCode.InternalError);
// Receive abort form client.
var ex = await Assert.ThrowsAsync<ConnectionResetException>(() => serverStream.Transport.Input.ReadAsync().AsTask()).DefaultTimeout();
Assert.Equal("Stream aborted by peer (258).", ex.Message);
Assert.Equal((long)Http3ErrorCode.InternalError, ((QuicStreamAbortedException)ex.InnerException).ErrorCode);
// Complete reading and then abort.
await serverStream.Transport.Input.CompleteAsync();
await serverStream.Transport.Output.CompleteAsync();
var quicStreamContext = Assert.IsType<QuicStreamContext>(serverStream);
// Both send and receive loops have exited.
await quicStreamContext._processingTask.DefaultTimeout();
await quicStreamContext.DisposeAsync();
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
}
[ConditionalFact]
[MsQuicSupported]
public async Task StreamPool_StreamAbortedOnClientAndServer_NotPooled()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var testHeartbeatFeature = new TestHeartbeatFeature();
serverConnection.Features.Set<IConnectionHeartbeatFeature>(testHeartbeatFeature);
// Act & Assert
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
var clientStream = clientConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData).DefaultTimeout();
var serverStream = await serverConnection.AcceptAsync().DefaultTimeout();
var readResult = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream.Transport.Input.AdvanceTo(readResult.Buffer.End);
clientStream.AbortWrite((long)Http3ErrorCode.InternalError);
// Receive abort form client.
var serverEx = await Assert.ThrowsAsync<ConnectionResetException>(() => serverStream.Transport.Input.ReadAsync().AsTask()).DefaultTimeout();
Assert.Equal("Stream aborted by peer (258).", serverEx.Message);
Assert.Equal((long)Http3ErrorCode.InternalError, ((QuicStreamAbortedException)serverEx.InnerException).ErrorCode);
serverStream.Features.Get<IProtocolErrorCodeFeature>().Error = (long)Http3ErrorCode.RequestRejected;
serverStream.Abort(new ConnectionAbortedException("Test message."));
// Complete server.
await serverStream.Transport.Input.CompleteAsync();
await serverStream.Transport.Output.CompleteAsync();
var buffer = new byte[1024];
var clientEx = await Assert.ThrowsAsync<QuicStreamAbortedException>(() => clientStream.ReadAsync(buffer).AsTask()).DefaultTimeout();
Assert.Equal((long)Http3ErrorCode.RequestRejected, clientEx.ErrorCode);
var quicStreamContext = Assert.IsType<QuicStreamContext>(serverStream);
// Both send and receive loops have exited.
await quicStreamContext._processingTask.DefaultTimeout();
await quicStreamContext.DisposeAsync();
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
}
[ConditionalFact]
[MsQuicSupported]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/37862")]
public async Task StreamPool_Heartbeat_ExpiredStreamRemoved()
{
// Arrange
var now = new DateTimeOffset(2021, 7, 6, 12, 0, 0, TimeSpan.Zero);
var testSystemClock = new TestSystemClock { UtcNow = now };
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory, testSystemClock);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var testHeartbeatFeature = new TestHeartbeatFeature();
serverConnection.Features.Set<IConnectionHeartbeatFeature>(testHeartbeatFeature);
// Act & Assert
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
var stream1 = await QuicTestHelpers.CreateAndCompleteBidirectionalStreamGracefully(clientConnection, serverConnection);
Assert.Equal(1, quicConnectionContext.StreamPool.Count);
QuicStreamContext pooledStream = quicConnectionContext.StreamPool._array[0];
Assert.Same(stream1, pooledStream);
Assert.Equal(now.Ticks + QuicConnectionContext.StreamPoolExpiryTicks, pooledStream.PoolExpirationTicks);
now = now.AddMilliseconds(100);
testSystemClock.UtcNow = now;
testHeartbeatFeature.RaiseHeartbeat();
// Not removed.
Assert.Equal(1, quicConnectionContext.StreamPool.Count);
var stream2 = await QuicTestHelpers.CreateAndCompleteBidirectionalStreamGracefully(clientConnection, serverConnection);
Assert.Equal(1, quicConnectionContext.StreamPool.Count);
pooledStream = quicConnectionContext.StreamPool._array[0];
Assert.Same(stream1, pooledStream);
Assert.Equal(now.Ticks + QuicConnectionContext.StreamPoolExpiryTicks, pooledStream.PoolExpirationTicks);
Assert.Same(stream1, stream2);
now = now.AddTicks(QuicConnectionContext.StreamPoolExpiryTicks);
testSystemClock.UtcNow = now;
testHeartbeatFeature.RaiseHeartbeat();
// Not removed.
Assert.Equal(1, quicConnectionContext.StreamPool.Count);
now = now.AddTicks(1);
testSystemClock.UtcNow = now;
testHeartbeatFeature.RaiseHeartbeat();
// Removed.
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
}
[ConditionalFact]
[MsQuicSupported]
public async Task StreamPool_ManyConcurrentStreams_StreamPoolFull()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
var testHeartbeatFeature = new TestHeartbeatFeature();
serverConnection.Features.Set<IConnectionHeartbeatFeature>(testHeartbeatFeature);
// Act
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(0, quicConnectionContext.StreamPool.Count);
var pauseCompleteTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var allConnectionsOnServerTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var streamTasks = new List<Task>();
var requestState = new RequestState(clientConnection, serverConnection, allConnectionsOnServerTcs, pauseCompleteTcs.Task);
const int StreamsSent = 101;
for (var i = 0; i < StreamsSent; i++)
{
streamTasks.Add(SendStream(requestState));
}
await allConnectionsOnServerTcs.Task.DefaultTimeout();
pauseCompleteTcs.SetResult();
await Task.WhenAll(streamTasks).DefaultTimeout();
// Assert
// Up to 100 streams are pooled.
Assert.Equal(100, quicConnectionContext.StreamPool.Count);
static async Task SendStream(RequestState requestState)
{
var clientStream = requestState.QuicConnection.OpenBidirectionalStream();
await clientStream.WriteAsync(TestData, endStream: true).DefaultTimeout();
var serverStream = await requestState.ServerConnection.AcceptAsync().DefaultTimeout();
var readResult = await serverStream.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream.Transport.Input.AdvanceTo(readResult.Buffer.End);
// Input should be completed.
readResult = await serverStream.Transport.Input.ReadAsync();
Assert.True(readResult.IsCompleted);
lock (requestState)
{
requestState.ActiveConcurrentConnections++;
if (requestState.ActiveConcurrentConnections == StreamsSent)
{
requestState.AllConnectionsOnServerTcs.SetResult();
}
}
await requestState.PauseCompleteTask;
// Complete reading and writing.
await serverStream.Transport.Input.CompleteAsync();
await serverStream.Transport.Output.CompleteAsync();
var quicStreamContext = Assert.IsType<QuicStreamContext>(serverStream);
// Both send and receive loops have exited.
await quicStreamContext._processingTask.DefaultTimeout();
await quicStreamContext.DisposeAsync();
quicStreamContext.Dispose();
}
}
[ConditionalFact]
[MsQuicSupported]
public async Task PersistentState_StreamsReused_StatePersisted()
{
// Arrange
await using var connectionListener = await QuicTestHelpers.CreateConnectionListenerFactory(LoggerFactory);
var options = QuicTestHelpers.CreateClientConnectionOptions(connectionListener.EndPoint);
using var clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
await clientConnection.ConnectAsync().DefaultTimeout();
await using var serverConnection = await connectionListener.AcceptAndAddFeatureAsync().DefaultTimeout();
// Act
var clientStream1 = clientConnection.OpenBidirectionalStream();
await clientStream1.WriteAsync(TestData, endStream: true).DefaultTimeout();
var serverStream1 = await serverConnection.AcceptAsync().DefaultTimeout();
var readResult1 = await serverStream1.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream1.Transport.Input.AdvanceTo(readResult1.Buffer.End);
serverStream1.Features.Get<IPersistentStateFeature>().State["test"] = true;
// Input should be completed.
readResult1 = await serverStream1.Transport.Input.ReadAsync();
Assert.True(readResult1.IsCompleted);
// Complete reading and writing.
await serverStream1.Transport.Input.CompleteAsync();
await serverStream1.Transport.Output.CompleteAsync();
var quicStreamContext1 = Assert.IsType<QuicStreamContext>(serverStream1);
await quicStreamContext1._processingTask.DefaultTimeout();
await quicStreamContext1.DisposeAsync();
quicStreamContext1.Dispose();
var clientStream2 = clientConnection.OpenBidirectionalStream();
await clientStream2.WriteAsync(TestData, endStream: true).DefaultTimeout();
var serverStream2 = await serverConnection.AcceptAsync().DefaultTimeout();
var readResult2 = await serverStream2.Transport.Input.ReadAtLeastAsync(TestData.Length).DefaultTimeout();
serverStream2.Transport.Input.AdvanceTo(readResult2.Buffer.End);
object state = serverStream2.Features.Get<IPersistentStateFeature>().State["test"];
// Input should be completed.
readResult2 = await serverStream2.Transport.Input.ReadAsync();
Assert.True(readResult2.IsCompleted);
// Complete reading and writing.
await serverStream2.Transport.Input.CompleteAsync();
await serverStream2.Transport.Output.CompleteAsync();
var quicStreamContext2 = Assert.IsType<QuicStreamContext>(serverStream2);
await quicStreamContext2._processingTask.DefaultTimeout();
await quicStreamContext2.DisposeAsync();
quicStreamContext2.Dispose();
Assert.Same(quicStreamContext1, quicStreamContext2);
var quicConnectionContext = Assert.IsType<QuicConnectionContext>(serverConnection);
Assert.Equal(1, quicConnectionContext.StreamPool.Count);
Assert.Equal(true, state);
}
private record RequestState(
QuicConnection QuicConnection,
MultiplexedConnectionContext ServerConnection,
TaskCompletionSource AllConnectionsOnServerTcs,
Task PauseCompleteTask)
{
public int ActiveConcurrentConnections { get; set; }
};
private class TestSystemClock : ISystemClock
{
public DateTimeOffset UtcNow { get; set; }
}
private class TestHeartbeatFeature : IConnectionHeartbeatFeature
{
private readonly List<(Action<object> Action, object State)> _actions = new List<(Action<object>, object)>();
public void OnHeartbeat(Action<object> action, object state)
{
_actions.Add((action, state));
}
public void RaiseHeartbeat()
{
foreach (var a in _actions)
{
a.Action(a.State);
}
}
}
}
}
| |
/* ****************************************************************************
*
* 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
* [email protected]. 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.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using IServiceProvider = System.IServiceProvider;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
namespace Microsoft.VisualStudioTools.Project
{
internal abstract class SolutionListener : IVsSolutionEvents3, IVsSolutionEvents4, IDisposable
{
#region fields
private uint eventsCookie;
private IVsSolution solution;
private IServiceProvider serviceProvider;
private bool isDisposed;
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
#endregion
#region ctors
protected SolutionListener(IServiceProvider serviceProviderParameter)
{
if (serviceProviderParameter == null)
{
throw new ArgumentNullException("serviceProviderParameter");
}
this.serviceProvider = serviceProviderParameter;
this.solution = this.serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
if (this.solution == null)
{
throw new InvalidOperationException("Could not get the IVsSolution object from the services exposed by this project");
}
}
#endregion
#region properties
protected uint EventsCookie
{
get
{
return this.eventsCookie;
}
}
protected IVsSolution Solution
{
get
{
return this.solution;
}
}
protected IServiceProvider ServiceProvider
{
get
{
return this.serviceProvider;
}
}
#endregion
#region IVsSolutionEvents3, IVsSolutionEvents2, IVsSolutionEvents methods
public virtual int OnAfterCloseSolution(object reserved)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterClosingChildren(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterLoadProject(IVsHierarchy stubHierarchy, IVsHierarchy realHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterMergeSolution(object pUnkReserved)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterOpenProject(IVsHierarchy hierarchy, int added)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterOpeningChildren(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnBeforeCloseProject(IVsHierarchy hierarchy, int removed)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnBeforeCloseSolution(object pUnkReserved)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnBeforeClosingChildren(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnBeforeOpeningChildren(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnBeforeUnloadProject(IVsHierarchy realHierarchy, IVsHierarchy rtubHierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnQueryCloseProject(IVsHierarchy hierarchy, int removing, ref int cancel)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnQueryCloseSolution(object pUnkReserved, ref int cancel)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int cancel)
{
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsSolutionEvents4 methods
public virtual int OnAfterAsynchOpenProject(IVsHierarchy hierarchy, int added)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterChangeProjectParent(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
public virtual int OnAfterRenameProject(IVsHierarchy hierarchy)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Fired before a project is moved from one parent to another in the solution explorer
/// </summary>
public virtual int OnQueryChangeProjectParent(IVsHierarchy hierarchy, IVsHierarchy newParentHier, ref int cancel)
{
return VSConstants.E_NOTIMPL;
}
#endregion
#region Dispose
/// <summary>
/// The IDispose interface Dispose method for disposing the object determinastically.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region methods
public void Init()
{
if (this.solution != null)
{
ErrorHandler.ThrowOnFailure(this.solution.AdviseSolutionEvents(this, out this.eventsCookie));
}
}
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsSolution.UnadviseSolutionEvents(System.UInt32)")]
protected virtual void Dispose(bool disposing)
{
// Everybody can go here.
if (!this.isDisposed)
{
// Synchronize calls to the Dispose simulteniously.
lock (Mutex)
{
if (disposing && this.eventsCookie != (uint)ShellConstants.VSCOOKIE_NIL && this.solution != null)
{
this.solution.UnadviseSolutionEvents((uint)this.eventsCookie);
this.eventsCookie = (uint)ShellConstants.VSCOOKIE_NIL;
}
this.isDisposed = true;
}
}
}
#endregion
}
}
| |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using IDE.Win32;
namespace IDE.Common
{
internal class DrawHelper
{
internal enum CommandState
{
Normal,
HotTrack,
Pushed
}
protected static IntPtr _halfToneBrush = IntPtr.Zero;
public static void DrawReverseString(Graphics g,
String drawText,
Font drawFont,
Rectangle drawRect,
Brush drawBrush,
StringFormat drawFormat)
{
GraphicsContainer container = g.BeginContainer();
// The text will be rotated around the origin (0,0) and so needs moving
// back into position by using a transform
g.TranslateTransform(drawRect.Left * 2 + drawRect.Width,
drawRect.Top * 2 + drawRect.Height);
// Rotate the text by 180 degress to reverse the direction
g.RotateTransform(180);
// Draw the string as normal and let then transforms do the work
g.DrawString(drawText, drawFont, drawBrush, drawRect, drawFormat);
g.EndContainer(container);
}
public static void DrawPlainRaised(Graphics g,
Rectangle boxRect,
Color baseColor)
{
using(Pen lighlight = new Pen(ControlPaint.LightLight(baseColor)),
dark = new Pen(ControlPaint.DarkDark(baseColor)))
{
g.DrawLine(lighlight, boxRect.Left, boxRect.Bottom, boxRect.Left, boxRect.Top);
g.DrawLine(lighlight, boxRect.Left, boxRect.Top, boxRect.Right, boxRect.Top);
g.DrawLine(dark, boxRect.Right, boxRect.Top, boxRect.Right, boxRect.Bottom);
g.DrawLine(dark, boxRect.Right, boxRect.Bottom, boxRect.Left, boxRect.Bottom);
}
}
public static void DrawPlainSunken(Graphics g,
Rectangle boxRect,
Color baseColor)
{
using(Pen lighlight = new Pen(ControlPaint.LightLight(baseColor)),
dark = new Pen(ControlPaint.DarkDark(baseColor)))
{
g.DrawLine(dark, boxRect.Left, boxRect.Bottom, boxRect.Left, boxRect.Top);
g.DrawLine(dark, boxRect.Left, boxRect.Top, boxRect.Right, boxRect.Top);
g.DrawLine(lighlight, boxRect.Right, boxRect.Top, boxRect.Right, boxRect.Bottom);
g.DrawLine(lighlight, boxRect.Right, boxRect.Bottom, boxRect.Left, boxRect.Bottom);
}
}
public static void DrawPlainRaisedBorder(Graphics g,
Rectangle rect,
Color lightLight,
Color baseColor,
Color dark,
Color darkDark)
{
if ((rect.Width > 2) && (rect.Height > 2))
{
using(Pen ll = new Pen(lightLight),
b = new Pen(baseColor),
d = new Pen(dark),
dd = new Pen(darkDark))
{
int left = rect.Left;
int top = rect.Top;
int right = rect.Right;
int bottom = rect.Bottom;
// Draw the top border
g.DrawLine(b, right-1, top, left, top);
g.DrawLine(ll, right-2, top+1, left+1, top+1);
g.DrawLine(b, right-3, top+2, left+2, top+2);
// Draw the left border
g.DrawLine(b, left, top, left, bottom-1);
g.DrawLine(ll, left+1, top+1, left+1, bottom-2);
g.DrawLine(b, left+2, top+2, left+2, bottom-3);
// Draw the right
g.DrawLine(dd, right-1, top+1, right-1, bottom-1);
g.DrawLine(d, right-2, top+2, right-2, bottom-2);
g.DrawLine(b, right-3, top+3, right-3, bottom-3);
// Draw the bottom
g.DrawLine(dd, right-1, bottom-1, left, bottom-1);
g.DrawLine(d, right-2, bottom-2, left+1, bottom-2);
g.DrawLine(b, right-3, bottom-3, left+2, bottom-3);
}
}
}
public static void DrawPlainRaisedBorderTopOrBottom(Graphics g,
Rectangle rect,
Color lightLight,
Color baseColor,
Color dark,
Color darkDark,
bool drawTop)
{
if ((rect.Width > 2) && (rect.Height > 2))
{
using(Pen ll = new Pen(lightLight),
b = new Pen(baseColor),
d = new Pen(dark),
dd = new Pen(darkDark))
{
int left = rect.Left;
int top = rect.Top;
int right = rect.Right;
int bottom = rect.Bottom;
if (drawTop)
{
// Draw the top border
g.DrawLine(b, right-1, top, left, top);
g.DrawLine(ll, right-1, top+1, left, top+1);
g.DrawLine(b, right-1, top+2, left, top+2);
}
else
{
// Draw the bottom
g.DrawLine(dd, right-1, bottom-1, left, bottom-1);
g.DrawLine(d, right-1, bottom-2, left, bottom-2);
g.DrawLine(b, right-1, bottom-3, left, bottom-3);
}
}
}
}
public static void DrawPlainSunkenBorder(Graphics g,
Rectangle rect,
Color lightLight,
Color baseColor,
Color dark,
Color darkDark)
{
if ((rect.Width > 2) && (rect.Height > 2))
{
using(Pen ll = new Pen(lightLight),
b = new Pen(baseColor),
d = new Pen(dark),
dd = new Pen(darkDark))
{
int left = rect.Left;
int top = rect.Top;
int right = rect.Right;
int bottom = rect.Bottom;
// Draw the top border
g.DrawLine(d, right-1, top, left, top);
g.DrawLine(dd, right-2, top+1, left+1, top+1);
g.DrawLine(b, right-3, top+2, left+2, top+2);
// Draw the left border
g.DrawLine(d, left, top, left, bottom-1);
g.DrawLine(dd, left+1, top+1, left+1, bottom-2);
g.DrawLine(b, left+2, top+2, left+2, bottom-3);
// Draw the right
g.DrawLine(ll, right-1, top+1, right-1, bottom-1);
g.DrawLine(b, right-2, top+2, right-2, bottom-2);
g.DrawLine(b, right-3, top+3, right-3, bottom-3);
// Draw the bottom
g.DrawLine(ll, right-1, bottom-1, left, bottom-1);
g.DrawLine(b, right-2, bottom-2, left+1, bottom-2);
g.DrawLine(b, right-3, bottom-3, left+2, bottom-3);
}
}
}
public static void DrawPlainSunkenBorderTopOrBottom(Graphics g,
Rectangle rect,
Color lightLight,
Color baseColor,
Color dark,
Color darkDark,
bool drawTop)
{
if ((rect.Width > 2) && (rect.Height > 2))
{
using(Pen ll = new Pen(lightLight),
b = new Pen(baseColor),
d = new Pen(dark),
dd = new Pen(darkDark))
{
int left = rect.Left;
int top = rect.Top;
int right = rect.Right;
int bottom = rect.Bottom;
if (drawTop)
{
// Draw the top border
g.DrawLine(d, right-1, top, left, top);
g.DrawLine(dd, right-1, top+1, left, top+1);
g.DrawLine(b, right-1, top+2, left, top+2);
}
else
{
// Draw the bottom
g.DrawLine(ll, right-1, bottom-1, left, bottom-1);
g.DrawLine(b, right-1, bottom-2, left, bottom-2);
g.DrawLine(b, right-1, bottom-3, left, bottom-3);
}
}
}
}
public static void DrawButtonCommand(Graphics g,
VisualStyle style,
Direction direction,
Rectangle drawRect,
CommandState state,
Color baseColor,
Color trackLight,
Color trackBorder)
{
Rectangle rect = new Rectangle(drawRect.Left, drawRect.Top, drawRect.Width - 1, drawRect.Height - 1);
// Draw background according to style
switch(style)
{
case VisualStyle.Plain:
// Draw background with back color
using(SolidBrush backBrush = new SolidBrush(baseColor))
g.FillRectangle(backBrush, rect);
// Modify according to state
switch(state)
{
case CommandState.HotTrack:
DrawPlainRaised(g, rect, baseColor);
break;
case CommandState.Pushed:
DrawPlainSunken(g, rect, baseColor);
break;
}
break;
case VisualStyle.IDE:
// Draw according to state
switch(state)
{
case CommandState.Normal:
// Draw background with back color
using(SolidBrush backBrush = new SolidBrush(baseColor))
g.FillRectangle(backBrush, rect);
break;
case CommandState.HotTrack:
g.FillRectangle(Brushes.White, rect);
using(SolidBrush trackBrush = new SolidBrush(trackLight))
g.FillRectangle(trackBrush, rect);
using(Pen trackPen = new Pen(trackBorder))
g.DrawRectangle(trackPen, rect);
break;
case CommandState.Pushed:
//TODO: draw in a darker background color
break;
}
break;
}
}
public static void DrawSeparatorCommand(Graphics g,
VisualStyle style,
Direction direction,
Rectangle drawRect,
Color baseColor)
{
// Drawing depends on the visual style required
if (style == VisualStyle.IDE)
{
// Draw a single separating line
using(Pen dPen = new Pen(ControlPaint.Dark(baseColor)))
{
if (direction == Direction.Horizontal)
g.DrawLine(dPen, drawRect.Left, drawRect.Top,
drawRect.Left, drawRect.Bottom - 1);
else
g.DrawLine(dPen, drawRect.Left, drawRect.Top,
drawRect.Right - 1, drawRect.Top);
}
}
else
{
// Draw a dark/light combination of lines to give an indent
using(Pen lPen = new Pen(ControlPaint.Dark(baseColor)),
llPen = new Pen(ControlPaint.LightLight(baseColor)))
{
if (direction == Direction.Horizontal)
{
g.DrawLine(lPen, drawRect.Left, drawRect.Top, drawRect.Left, drawRect.Bottom - 1);
g.DrawLine(llPen, drawRect.Left + 1, drawRect.Top, drawRect.Left + 1, drawRect.Bottom - 1);
}
else
{
g.DrawLine(lPen, drawRect.Left, drawRect.Top, drawRect.Right - 1, drawRect.Top);
g.DrawLine(llPen, drawRect.Left, drawRect.Top + 1, drawRect.Right - 1, drawRect.Top + 1);
}
}
}
}
public static void DrawDragRectangle(Rectangle newRect, int indent)
{
DrawDragRectangles(new Rectangle[]{newRect}, indent);
}
public static void DrawDragRectangles(Rectangle[] newRects, int indent)
{
if (newRects.Length > 0)
{
// Create the first region
IntPtr newRegion = CreateRectangleRegion(newRects[0], indent);
for(int index=1; index<newRects.Length; index++)
{
// Create the extra region
IntPtr extraRegion = CreateRectangleRegion(newRects[index], indent);
// Remove the intersection of the existing and extra regions
Gdi32.CombineRgn(newRegion, newRegion, extraRegion, (int)Win32.CombineFlags.RGN_XOR);
// Remove unwanted intermediate objects
Gdi32.DeleteObject(extraRegion);
}
// Get hold of the DC for the desktop
IntPtr hDC = User32.GetDC(IntPtr.Zero);
// Define the area we are allowed to draw into
Gdi32.SelectClipRgn(hDC, newRegion);
Win32.RECT rectBox = new Win32.RECT();
// Get the smallest rectangle that encloses region
Gdi32.GetClipBox(hDC, ref rectBox);
IntPtr brushHandler = GetHalfToneBrush();
// Select brush into the device context
IntPtr oldHandle = Gdi32.SelectObject(hDC, brushHandler);
// Blit to screen using provided pattern brush and invert with existing screen contents
Gdi32.PatBlt(hDC,
rectBox.left,
rectBox.top,
rectBox.right - rectBox.left,
rectBox.bottom - rectBox.top,
(uint)RasterOperations.PATINVERT);
// Put old handle back again
Gdi32.SelectObject(hDC, oldHandle);
// Reset the clipping region
Gdi32.SelectClipRgn(hDC, IntPtr.Zero);
// Remove unwanted region object
Gdi32.DeleteObject(newRegion);
// Must remember to release the HDC resource!
User32.ReleaseDC(IntPtr.Zero, hDC);
}
}
protected static IntPtr CreateRectangleRegion(Rectangle rect, int indent)
{
Win32.RECT newWinRect = new Win32.RECT();
newWinRect.left = rect.Left;
newWinRect.top = rect.Top;
newWinRect.right = rect.Right;
newWinRect.bottom = rect.Bottom;
// Create region for whole of the new rectangle
IntPtr newOuter = Gdi32.CreateRectRgnIndirect(ref newWinRect);
// If the rectangle is to small to make an inner object from, then just use the outer
if ((indent <= 0) || (rect.Width <= indent) || (rect.Height <= indent))
return newOuter;
newWinRect.left += indent;
newWinRect.top += indent;
newWinRect.right -= indent;
newWinRect.bottom -= indent;
// Create region for the unwanted inside of the new rectangle
IntPtr newInner = Gdi32.CreateRectRgnIndirect(ref newWinRect);
Win32.RECT emptyWinRect = new Win32.RECT();
emptyWinRect.left = 0;
emptyWinRect.top = 0;
emptyWinRect.right = 0;
emptyWinRect.bottom = 0;
// Create a destination region
IntPtr newRegion = Gdi32.CreateRectRgnIndirect(ref emptyWinRect);
// Remove the intersection of the outer and inner
Gdi32.CombineRgn(newRegion, newOuter, newInner, (int)Win32.CombineFlags.RGN_XOR);
// Remove unwanted intermediate objects
Gdi32.DeleteObject(newOuter);
Gdi32.DeleteObject(newInner);
// Return the resultant region object
return newRegion;
}
protected static IntPtr GetHalfToneBrush()
{
if (_halfToneBrush == IntPtr.Zero)
{
Bitmap bitmap = new Bitmap(8,8,PixelFormat.Format32bppArgb);
Color white = Color.FromArgb(255,255,255,255);
Color black = Color.FromArgb(255,0,0,0);
bool flag=true;
// Alternate black and white pixels across all lines
for(int x=0; x<8; x++, flag = !flag)
for(int y=0; y<8; y++, flag = !flag)
bitmap.SetPixel(x, y, (flag ? white : black));
IntPtr hBitmap = bitmap.GetHbitmap();
Win32.LOGBRUSH brush = new Win32.LOGBRUSH();
brush.lbStyle = (uint)Win32.BrushStyles.BS_PATTERN;
brush.lbHatch = (uint)hBitmap;
_halfToneBrush = Gdi32.CreateBrushIndirect(ref brush);
}
return _halfToneBrush;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using RdlEngine.Resources;
namespace fyiReporting.RDL
{
///<summary>
/// Represents all the pages of a report. Needed when you need
/// render based on pages. e.g. PDF
///</summary>
public class Pages : IEnumerable
{
Bitmap _bm; // bitmap to build graphics object
Graphics _g; // graphics object
Report _report; // owner report
List<Page> _pages; // array of pages
Page _currentPage; // the current page; 1st page if null
float _BottomOfPage; // the bottom of the page
float _PageHeight; // default height for all pages
float _PageWidth; // default width for all pages
public Pages(Report r)
{
_report = r;
_pages = new List<Page>(); // array of Page objects
_bm = new Bitmap(10, 10); // create a small bitmap to base our graphics
_g = Graphics.FromImage(_bm);
}
internal Report Report
{
get { return _report;}
}
public Page this[int index]
{
get {return _pages[index];}
}
public int Count
{
get {return _pages.Count;}
}
public void AddPage(Page p)
{
_pages.Add(p);
_currentPage = p;
}
public void NextOrNew()
{
if (_currentPage == this.LastPage)
AddPage(new Page(PageCount+1));
else
{
_currentPage = _pages[_currentPage.PageNumber];
_currentPage.SetEmpty();
}
}
/// <summary>
/// CleanUp should be called after every render to reduce resource utilization.
/// </summary>
public void CleanUp()
{
if (_g != null)
{
_g.Dispose();
_g = null;
}
if (_bm != null)
{
_bm.Dispose();
_bm = null;
}
}
public void SortPageItems()
{
foreach (Page p in this)
{
p.SortPageItems();
}
}
public float BottomOfPage
{
get { return _BottomOfPage; }
set { _BottomOfPage = value; }
}
public Page CurrentPage
{
get
{
if (_currentPage != null)
return _currentPage;
if (_pages.Count >= 1)
{
_currentPage = _pages[0];
return _currentPage;
}
return null;
}
set
{
_currentPage = value;
#if DEBUG
if (value == null)
return;
foreach (Page p in _pages)
{
if (p == value)
return;
}
throw new Exception(Strings.Pages_Error_CurrentPageMustInList);
#endif
}
}
public Page FirstPage
{
get
{
if (_pages.Count <= 0)
return null;
else
return _pages[0];
}
}
public Page LastPage
{
get
{
if (_pages.Count <= 0)
return null;
else
return _pages[_pages.Count-1];
}
}
public float PageHeight
{
get {return _PageHeight;}
set {_PageHeight = value;}
}
public float PageWidth
{
get {return _PageWidth;}
set {_PageWidth = value;}
}
public void RemoveLastPage()
{
Page lp = LastPage;
if (lp == null) // if no last page nothing to do
return;
_pages.RemoveAt(_pages.Count-1); // remove the page
if (this.CurrentPage == lp) // reset the current if necessary
{
if (_pages.Count <= 0)
CurrentPage = null;
else
CurrentPage = _pages[_pages.Count-1];
}
return;
}
public Graphics G
{
get
{
if (_g == null)
{
_bm = new Bitmap(10, 10); // create a small bitmap to base our graphics
_g = Graphics.FromImage(_bm);
}
return _g;
}
}
public int PageCount
{
get { return _pages.Count; }
}
#region IEnumerable Members
public IEnumerator GetEnumerator() // just loop thru the pages
{
return _pages.GetEnumerator();
}
#endregion
}
public class Page : IEnumerable
{
// note: all sizes are in points
int _pageno;
List<PageItem> _items; // array of items on the page
float _yOffset; // current y offset; top margin, page header, other details, ...
float _xOffset; // current x offset; margin, body taken into account?
int _emptyItems; // # of items which constitute empty
bool _needSort; // need sort
int _lastZIndex; // last ZIndex
System.Collections.Generic.Dictionary<string, Rows> _PageExprReferences; // needed to save page header/footer expressions
public Page(int page)
{
_pageno = page;
_items = new List<PageItem>();
_emptyItems = 0;
_needSort = false;
}
public PageItem this[int index]
{
get { return _items[index]; }
}
public int Count
{
get { return _items.Count; }
}
public void InsertObject(PageItem pi)
{
AddObjectInternal(pi);
_items.Insert(0, pi);
}
public void AddObject(PageItem pi)
{
AddObjectInternal(pi);
_items.Add(pi);
}
private void AddObjectInternal(PageItem pi)
{
pi.Page = this;
pi.ItemNumber = _items.Count;
if (_items.Count == 0)
_lastZIndex = pi.ZIndex;
else if (_lastZIndex != pi.ZIndex)
_needSort = true;
// adjust the page item locations
pi.X += _xOffset;
pi.Y += _yOffset;
if (pi is PageLine)
{
PageLine pl = pi as PageLine;
pl.X2 += _xOffset;
pl.Y2 += _yOffset;
}
else if (pi is PagePolygon)
{
PagePolygon pp = pi as PagePolygon;
for (int i = 0; i < pp.Points.Length; i++ )
{
pp.Points[i].X += _xOffset;
pp.Points[i].Y += _yOffset;
}
}
else if (pi is PageCurve)
{
PageCurve pc = pi as PageCurve;
for (int i = 0; i < pc.Points.Length; i++)
{
pc.Points[i].X += _xOffset;
pc.Points[i].Y += _yOffset;
}
}
}
public bool IsEmpty()
{
return _items.Count > _emptyItems? false: true;
}
public void SortPageItems()
{
if (!_needSort)
return;
_items.Sort();
}
public void ResetEmpty()
{
_emptyItems = 0;
}
public void SetEmpty()
{
_emptyItems = _items.Count;
}
public int PageNumber
{
get { return _pageno;}
}
public float XOffset
{
get { return _xOffset; }
set { _xOffset = value; }
}
public float YOffset
{
get { return _yOffset; }
set { _yOffset = value; }
}
internal void AddPageExpressionRow(Report rpt, string exprname, Row r)
{
if (exprname == null || r == null)
return;
if (_PageExprReferences == null)
_PageExprReferences = new Dictionary<string, Rows>();
Rows rows=null;
_PageExprReferences.TryGetValue(exprname, out rows);
if (rows == null)
{
rows = new Rows(rpt);
rows.Data = new List<Row>();
_PageExprReferences.Add(exprname, rows);
}
Row row = new Row(rows, r); // have to make a new copy
row.RowNumber = rows.Data.Count;
rows.Data.Add(row); // add row to rows
return;
}
internal Rows GetPageExpressionRows(string exprname)
{
if (_PageExprReferences == null)
return null;
Rows rows=null;
_PageExprReferences.TryGetValue(exprname, out rows);
return rows;
}
internal void ResetPageExpressions()
{
_PageExprReferences = null; // clear it out; not needed once page header/footer are processed
}
#region IEnumerable Members
public IEnumerator GetEnumerator() // just loop thru the pages
{
return _items.GetEnumerator();
}
#endregion
}
public class PageItem : ICloneable, IComparable
{
Page parent; // parent page
float x; // x coordinate
float y; // y coordinate
float h; // height --- line redefines as Y2
float w; // width --- line redefines as X2
string hyperlink; // a hyperlink the object should link to
string bookmarklink; // a hyperlink within the report object should link to
string bookmark; // bookmark text for this pageItem
string tooltip; // a message to display when user hovers with mouse
int zindex; // zindex; items will be sorted by this
int itemNumber; // original number of item
StyleInfo si; // all the style information evaluated
bool allowselect = true; // allow selection of this item
public Page Page
{
get { return parent; }
set { parent = value; }
}
public bool AllowSelect
{
get { return allowselect; }
set { allowselect = value; }
}
public float X
{
get { return x;}
set { x = value;}
}
public float Y
{
get { return y;}
set { y = value;}
}
public int ZIndex
{
get { return zindex; }
set { zindex = value; }
}
public int ItemNumber
{
get { return itemNumber; }
set { itemNumber = value; }
}
public float H
{
get { return h;}
set { h = value;}
}
public float W
{
get { return w;}
set { w = value;}
}
public string HyperLink
{
get { return hyperlink;}
set { hyperlink = value;}
}
public string BookmarkLink
{
get { return bookmarklink;}
set { bookmarklink = value;}
}
public string Bookmark
{
get { return bookmark; }
set { bookmark = value; }
}
public string Tooltip
{
get { return tooltip;}
set { tooltip = value;}
}
public StyleInfo SI
{
get { return si;}
set { si = value;}
}
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
#endregion
#region IComparable Members
// Sort items based on zindex, then on order items were added to array
public int CompareTo(object obj)
{
PageItem pi = obj as PageItem;
int rc = this.zindex - pi.zindex;
if (rc == 0)
rc = this.itemNumber - pi.itemNumber;
return rc;
}
#endregion
}
public class PageImage : PageItem, ICloneable
{
string name; // name of object if constant image
ImageFormat imf; // type of image; png, jpeg are supported
byte[] imageData;
int samplesW;
int samplesH;
ImageRepeat repeat;
ImageSizingEnum sizing;
public PageImage(ImageFormat im, byte[] image, int w, int h)
{
Debug.Assert(im == ImageFormat.Jpeg || im == ImageFormat.Png || im == ImageFormat.Gif || im == ImageFormat.Wmf,
"PageImage only supports Jpeg, Gif and Png and WMF image formats (Thanks HYNE!).");
imf = im;
imageData = image;
samplesW = w;
samplesH = h;
repeat = ImageRepeat.NoRepeat;
sizing = ImageSizingEnum.AutoSize;
}
public byte[] ImageData
{
get {return imageData;}
}
public ImageFormat ImgFormat
{
get {return imf;}
}
public string Name
{
get {return name;}
set {name = value;}
}
public ImageRepeat Repeat
{
get {return repeat;}
set {repeat = value;}
}
public ImageSizingEnum Sizing
{
get {return sizing;}
set {sizing = value;}
}
public int SamplesW
{
get {return samplesW;}
}
public int SamplesH
{
get {return samplesH;}
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public enum ImageRepeat
{
Repeat, // repeat image in both x and y directions
NoRepeat, // don't repeat
RepeatX, // repeat image in x direction
RepeatY // repeat image in y direction
}
public class PageEllipse : PageItem, ICloneable
{
public PageEllipse()
{
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageLine : PageItem, ICloneable
{
public PageLine()
{
}
public float X2
{
get {return W;}
set {W = value;}
}
public float Y2
{
get {return H;}
set {H = value;}
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageCurve : PageItem, ICloneable
{
PointF[] _pointsF;
int _offset;
float _Tension;
public PageCurve()
{
}
public PointF[] Points
{
get { return _pointsF; }
set { _pointsF = value; }
}
public int Offset
{
get { return _offset; }
set { _offset = value; }
}
public float Tension
{
get { return _Tension; }
set { _Tension = value; }
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PagePolygon : PageItem, ICloneable
{
PointF[] Ps;
public PagePolygon()
{
}
public PointF[] Points
{
get {return Ps;}
set {Ps = value;}
}
}
public class PagePie : PageItem, ICloneable
{
Single SA;
Single SW;
public PagePie()
{
}
public Single StartAngle
{
get { return SA; }
set { SA = value; }
}
public Single SweepAngle
{
get { return SW; }
set { SW = value; }
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageRectangle : PageItem, ICloneable
{
public PageRectangle()
{
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
public class PageText : PageItem, ICloneable
{
string text; // the text
float descent; // in some cases the Font descent will be recorded; 0 otherwise
bool bGrow;
bool _NoClip=false; // on drawing disallow clipping
PageTextHtml _HtmlParent=null;
public PageText(string t)
{
text = t;
descent=0;
bGrow=false;
}
public PageTextHtml HtmlParent
{
get { return _HtmlParent; }
set { _HtmlParent = value; }
}
public string Text
{
get {return text;}
set {text = value;}
}
public float Descent
{
get {return descent;}
set {descent = value;}
}
public bool NoClip
{
get {return _NoClip;}
set {_NoClip = value;}
}
public bool CanGrow
{
get {return bGrow;}
set {bGrow = value;}
}
#region ICloneable Members
new public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Rotate
{
internal class App
{
public static int s_weightCount = 1;
private class BaseNode
{
public BaseNode()
{
}
public virtual void VerifyValid()
{
}
}
private class Node : BaseNode
{
private ulong _PREPAD_0;
private char _PREPAD_1;
private byte _PREPAD_2;
private char _PREPAD_3;
private uint _PREPAD_4;
private int _PREPAD_5;
private ulong _PREPAD_6;
private ulong _PREPAD_7;
private ulong _PREPAD_8;
private uint _PREPAD_9;
private ushort _PREPAD_10;
private byte _PREPAD_11;
private String _PREPAD_12;
private char _PREPAD_13;
private ushort _PREPAD_14;
public Node m_leftChild;
private int _MID1PAD_0;
private ulong _MID1PAD_1;
private String _MID1PAD_2;
private ulong _MID1PAD_3;
private String _MID1PAD_4;
private char _MID1PAD_5;
private String _MID1PAD_6;
private uint _MID1PAD_7;
private uint _MID1PAD_8;
private uint _MID1PAD_9;
private uint _MID1PAD_10;
private ushort _MID1PAD_11;
public int m_weight;
private ushort _MID2PAD_0;
private ulong _MID2PAD_1;
private ushort _MID2PAD_2;
private ulong _MID2PAD_3;
private char _MID2PAD_4;
public Node m_rightChild;
private int _AFTERPAD_0;
private ushort _AFTERPAD_1;
private byte _AFTERPAD_2;
private ushort _AFTERPAD_3;
private int _AFTERPAD_4;
private String _AFTERPAD_5;
private uint _AFTERPAD_6;
private char _AFTERPAD_7;
private char _AFTERPAD_8;
private ushort _AFTERPAD_9;
public Node()
{
m_weight = s_weightCount++;
_PREPAD_0 = 49;
_PREPAD_1 = 'R';
_PREPAD_2 = 202;
_PREPAD_3 = '_';
_PREPAD_4 = 133;
_PREPAD_5 = 51;
_PREPAD_6 = 80;
_PREPAD_7 = 250;
_PREPAD_8 = 38;
_PREPAD_9 = 20;
_PREPAD_10 = 41;
_PREPAD_11 = 202;
_PREPAD_12 = "10482";
_PREPAD_13 = '9';
_PREPAD_14 = 37;
_MID1PAD_0 = 81;
_MID1PAD_1 = 28;
_MID1PAD_2 = "13921";
_MID1PAD_3 = 128;
_MID1PAD_4 = "14428";
_MID1PAD_5 = 'Z';
_MID1PAD_6 = "702";
_MID1PAD_7 = 94;
_MID1PAD_8 = 198;
_MID1PAD_9 = 179;
_MID1PAD_10 = 31;
_MID1PAD_11 = 47;
_MID2PAD_0 = 141;
_MID2PAD_1 = 22;
_MID2PAD_2 = 214;
_MID2PAD_3 = 135;
_MID2PAD_4 = '$';
_AFTERPAD_0 = 47;
_AFTERPAD_1 = 237;
_AFTERPAD_2 = 202;
_AFTERPAD_3 = 177;
_AFTERPAD_4 = 177;
_AFTERPAD_5 = "28735";
_AFTERPAD_6 = 97;
_AFTERPAD_7 = '5';
_AFTERPAD_8 = '=';
_AFTERPAD_9 = 76;
}
public override void VerifyValid()
{
base.VerifyValid();
if (_PREPAD_0 != 49) throw new Exception("m_PREPAD_0");
if (_PREPAD_1 != 'R') throw new Exception("m_PREPAD_1");
if (_PREPAD_2 != 202) throw new Exception("m_PREPAD_2");
if (_PREPAD_3 != '_') throw new Exception("m_PREPAD_3");
if (_PREPAD_4 != 133) throw new Exception("m_PREPAD_4");
if (_PREPAD_5 != 51) throw new Exception("m_PREPAD_5");
if (_PREPAD_6 != 80) throw new Exception("m_PREPAD_6");
if (_PREPAD_7 != 250) throw new Exception("m_PREPAD_7");
if (_PREPAD_8 != 38) throw new Exception("m_PREPAD_8");
if (_PREPAD_9 != 20) throw new Exception("m_PREPAD_9");
if (_PREPAD_10 != 41) throw new Exception("m_PREPAD_10");
if (_PREPAD_11 != 202) throw new Exception("m_PREPAD_11");
if (_PREPAD_12 != "10482") throw new Exception("m_PREPAD_12");
if (_PREPAD_13 != '9') throw new Exception("m_PREPAD_13");
if (_PREPAD_14 != 37) throw new Exception("m_PREPAD_14");
if (_MID1PAD_0 != 81) throw new Exception("m_MID1PAD_0");
if (_MID1PAD_1 != 28) throw new Exception("m_MID1PAD_1");
if (_MID1PAD_2 != "13921") throw new Exception("m_MID1PAD_2");
if (_MID1PAD_3 != 128) throw new Exception("m_MID1PAD_3");
if (_MID1PAD_4 != "14428") throw new Exception("m_MID1PAD_4");
if (_MID1PAD_5 != 'Z') throw new Exception("m_MID1PAD_5");
if (_MID1PAD_6 != "702") throw new Exception("m_MID1PAD_6");
if (_MID1PAD_7 != 94) throw new Exception("m_MID1PAD_7");
if (_MID1PAD_8 != 198) throw new Exception("m_MID1PAD_8");
if (_MID1PAD_9 != 179) throw new Exception("m_MID1PAD_9");
if (_MID1PAD_10 != 31) throw new Exception("m_MID1PAD_10");
if (_MID1PAD_11 != 47) throw new Exception("m_MID1PAD_11");
if (_MID2PAD_0 != 141) throw new Exception("m_MID2PAD_0");
if (_MID2PAD_1 != 22) throw new Exception("m_MID2PAD_1");
if (_MID2PAD_2 != 214) throw new Exception("m_MID2PAD_2");
if (_MID2PAD_3 != 135) throw new Exception("m_MID2PAD_3");
if (_MID2PAD_4 != '$') throw new Exception("m_MID2PAD_4");
if (_AFTERPAD_0 != 47) throw new Exception("m_AFTERPAD_0");
if (_AFTERPAD_1 != 237) throw new Exception("m_AFTERPAD_1");
if (_AFTERPAD_2 != 202) throw new Exception("m_AFTERPAD_2");
if (_AFTERPAD_3 != 177) throw new Exception("m_AFTERPAD_3");
if (_AFTERPAD_4 != 177) throw new Exception("m_AFTERPAD_4");
if (_AFTERPAD_5 != "28735") throw new Exception("m_AFTERPAD_5");
if (_AFTERPAD_6 != 97) throw new Exception("m_AFTERPAD_6");
if (_AFTERPAD_7 != '5') throw new Exception("m_AFTERPAD_7");
if (_AFTERPAD_8 != '=') throw new Exception("m_AFTERPAD_8");
if (_AFTERPAD_9 != 76) throw new Exception("m_AFTERPAD_9");
}
public virtual Node growTree(int maxHeight, String indent)
{
//Console.WriteLine(indent + m_weight.ToString());
if (maxHeight > 0)
{
m_leftChild = new Node();
m_leftChild.growTree(maxHeight - 1, indent + " ");
m_rightChild = new Node();
m_rightChild.growTree(maxHeight - 1, indent + " ");
}
else
m_leftChild = m_rightChild = null;
return this;
}
public virtual void rotateTree(ref int leftWeight, ref int rightWeight)
{
//Console.WriteLine("rotateTree(" + m_weight.ToString() + ")");
VerifyValid();
// create node objects for children
Node newLeftChild = null, newRightChild = null;
if (m_leftChild != null)
{
newRightChild = new Node();
newRightChild.m_leftChild = m_leftChild.m_leftChild;
newRightChild.m_rightChild = m_leftChild.m_rightChild;
newRightChild.m_weight = m_leftChild.m_weight;
}
if (m_rightChild != null)
{
newLeftChild = new Node();
newLeftChild.m_leftChild = m_rightChild.m_leftChild;
newLeftChild.m_rightChild = m_rightChild.m_rightChild;
newLeftChild.m_weight = m_rightChild.m_weight;
}
// replace children
m_leftChild = newLeftChild;
m_rightChild = newRightChild;
for (int I = 0; I < 32; I++) { int[] u = new int[1024]; }
// verify all valid
if (m_rightChild != null)
{
if (m_rightChild.m_leftChild != null &&
m_rightChild.m_rightChild != null)
{
m_rightChild.m_leftChild.VerifyValid();
m_rightChild.m_rightChild.VerifyValid();
m_rightChild.rotateTree(
ref m_rightChild.m_leftChild.m_weight,
ref m_rightChild.m_rightChild.m_weight);
}
else
{
int minus1 = -1;
m_rightChild.rotateTree(ref minus1, ref minus1);
}
if (leftWeight != m_rightChild.m_weight)
{
Console.WriteLine("left weight do not match.");
throw new Exception();
}
}
if (m_leftChild != null)
{
if (m_leftChild.m_leftChild != null &&
m_leftChild.m_rightChild != null)
{
m_leftChild.m_leftChild.VerifyValid();
m_leftChild.m_rightChild.VerifyValid();
m_leftChild.rotateTree(
ref m_leftChild.m_leftChild.m_weight,
ref m_leftChild.m_rightChild.m_weight);
}
else
{
int minus1 = -1;
m_leftChild.rotateTree(ref minus1, ref minus1);
}
if (rightWeight != m_leftChild.m_weight)
{
Console.WriteLine("right weight do not match.");
throw new Exception();
}
}
}
}
private static int Main()
{
try
{
Node root = new Node();
root.growTree(6, "").rotateTree(
ref root.m_leftChild.m_weight,
ref root.m_rightChild.m_weight);
}
catch (Exception)
{
Console.WriteLine("*** FAILED ***");
return 1;
}
Console.WriteLine("*** PASSED ***");
return 100;
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
namespace MakeFileBuilder
{
/// <summary>
/// Metadata for the builder class
/// </summary>
sealed class MakeFileMeta :
Bam.Core.IBuildModeMetaData
{
private static Bam.Core.Array<MakeFileMeta> allMeta = new Bam.Core.Array<MakeFileMeta>();
private static void
AddMeta(
MakeFileMeta meta)
{
lock (allMeta)
{
allMeta.Add(meta);
}
}
// only for the BuildModeMetaData
public MakeFileMeta()
{}
/// <summary>
/// Create an instance of the meta data
/// </summary>
/// <param name="module">for this module</param>
public MakeFileMeta(
Bam.Core.Module module)
{
this.Module = module;
module.MetaData = this;
this.CommonMetaData = Bam.Core.Graph.Instance.MetaData as MakeFileCommonMetaData;
this.Rules = new Bam.Core.Array<Rule>();
AddMeta(this);
}
/// <summary>
/// Get the common meta data for this builder
/// </summary>
public MakeFileCommonMetaData CommonMetaData { get; private set; }
/// <summary>
/// Add a rule to this meta data
/// </summary>
/// <returns>The new rule</returns>
public Rule
AddRule()
{
var rule = new Rule(this.Module, this.Rules.Count);
this.Rules.Add(rule);
return rule;
}
/// <summary>
/// Get the rules associated with this metadata
/// </summary>
public Bam.Core.Array<Rule> Rules { get; private set; }
/// <summary>
/// Get the module associated with this metadata
/// </summary>
private Bam.Core.Module Module { get; set; }
/// <summary>
/// Pre-execution commands to run for this builder
/// </summary>
public static void PreExecution()
{
var graph = Bam.Core.Graph.Instance;
graph.MetaData = new MakeFileCommonMetaData();
}
/// <summary>
/// Post executable commands to run for this builder
/// </summary>
public static void PostExecution()
{
var graph = Bam.Core.Graph.Instance;
var commonMeta = graph.MetaData as MakeFileCommonMetaData;
var makeEnvironment = new System.Text.StringBuilder();
var makeVariables = new System.Text.StringBuilder();
var makeRules = new System.Text.StringBuilder();
// delete suffix rules
makeEnvironment.AppendLine(".SUFFIXES:");
// variables for package directories
var packageMap = new System.Collections.Generic.Dictionary<string, string>();
foreach (var metadata in allMeta)
{
var module = metadata.Module;
if (!Bam.Core.Graph.Instance.IsReferencedModule(module))
{
continue;
}
var package = module.GetType().Namespace;
if (packageMap.ContainsKey(package))
{
continue;
}
var packageDir = module.Macros[Bam.Core.ModuleMacroNames.PackageDirectory].ToString();
packageMap.Add(package, packageDir);
}
commonMeta.ExportPackageDirectories(
makeVariables,
packageMap
);
if (MakeFileCommonMetaData.IsNMAKE)
{
// macros in NMAKE do not export as environment variables to commands
}
else
{
commonMeta.ExportEnvironment(makeEnvironment);
}
var has_dirs = commonMeta.ExportDirectories(
makeVariables,
explicitlyCreateHierarchy: MakeFileCommonMetaData.IsNMAKE
);
// all rule
var prerequisitesOfTargetAll = new Bam.Core.StringArray();
// loop over all metadata, until the top-most modules with Make metadata are added to 'all'
// this allows skipping over any upper modules without Make policies
foreach (var metadata in allMeta)
{
foreach (var rule in metadata.Rules)
{
rule.AppendAllPrerequisiteTargetNames(prerequisitesOfTargetAll);
}
}
makeRules.Append("all:");
if (MakeFileCommonMetaData.IsNMAKE)
{
if (has_dirs)
{
// as NMAKE does not support order only dependencies
makeRules.Append(" $(DIRS) ");
}
// as NMAKE does not support defining macros to be exposed as environment variables for commands
makeRules.Append("nmakesetenv ");
}
makeRules.AppendLine(prerequisitesOfTargetAll.ToString(' '));
if (MakeFileCommonMetaData.IsNMAKE)
{
commonMeta.ExportEnvironmentAsPhonyTarget(makeRules);
}
if (has_dirs)
{
// directory direction rule
makeRules.AppendLine("$(DIRS):");
if (Bam.Core.OSUtilities.IsWindowsHosting)
{
makeRules.AppendLine("\tmkdir $@");
}
else
{
makeRules.AppendLine("\tmkdir -pv $@");
}
}
// clean rule
makeRules.AppendLine(".PHONY: clean");
makeRules.AppendLine("clean:");
if (has_dirs)
{
if (Bam.Core.OSUtilities.IsWindowsHosting)
{
makeRules.AppendLine("\t-cmd.exe /C RMDIR /S /Q $(DIRS)");
}
else
{
makeRules.AppendLine("\t@rm -frv $(DIRS)");
}
}
// write all variables and rules
foreach (var metadata in allMeta)
{
foreach (var rule in metadata.Rules)
{
rule.WriteVariables(makeVariables, commonMeta);
rule.WriteRules(makeRules, commonMeta);
}
}
Bam.Core.Log.DebugMessage("MAKEFILE CONTENTS: BEGIN");
Bam.Core.Log.DebugMessage(makeEnvironment.ToString());
Bam.Core.Log.DebugMessage(makeVariables.ToString());
Bam.Core.Log.DebugMessage(makeRules.ToString());
Bam.Core.Log.DebugMessage("MAKEFILE CONTENTS: END");
var makeFilePath = Bam.Core.TokenizedString.Create("$(buildroot)/Makefile", null);
makeFilePath.Parse();
using (var writer = new System.IO.StreamWriter(makeFilePath.ToString()))
{
writer.Write(makeEnvironment.ToString());
writer.Write(makeVariables.ToString());
writer.Write(makeRules.ToString());
}
Bam.Core.Log.Info($"Successfully created MakeFile for package '{graph.MasterPackage.Name}'\n\t{makeFilePath}");
}
Bam.Core.TokenizedString
Bam.Core.IBuildModeMetaData.ModuleOutputDirectory(
Bam.Core.Module currentModule,
Bam.Core.Module encapsulatingModule)
{
var outputDir = System.IO.Path.Combine(encapsulatingModule.GetType().Name, currentModule.BuildEnvironment.Configuration.ToString());
var moduleSubDir = currentModule.CustomOutputSubDirectory;
if (null != moduleSubDir)
{
outputDir = System.IO.Path.Combine(outputDir, moduleSubDir);
}
return Bam.Core.TokenizedString.CreateVerbatim(outputDir);
}
bool Bam.Core.IBuildModeMetaData.PublishBesideExecutable => false;
bool Bam.Core.IBuildModeMetaData.CanCreatePrebuiltProjectForAssociatedFiles => false;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace ICSimulator
{
public class Router_Node : Router
{
Flit m_injectSlot_CW;
Flit m_injectSlot_CCW;
Queue<Flit>[] ejectBuffer;
int starveCounter;
public Router_Node(Coord myCoord)
: base(myCoord)
{
// the node Router is just a Rong node. A Flit gets ejected or moves straight forward
linkOut = new Link[2];
linkIn = new Link[2];
m_injectSlot_CW = null;
m_injectSlot_CCW = null;
throttle[ID] = false;
starved[ID] = false;
starveCounter = 0;
}
public Router_Node(RC_Coord RC_c, Coord c) : base(c)
{
linkOut = new Link[2];
linkIn = new Link[2];
m_injectSlot_CW = null;
m_injectSlot_CCW = null;
ejectBuffer = new Queue<Flit> [2];
for (int i = 0; i < 2; i++)
ejectBuffer[i] = new Queue<Flit>();
throttle[ID] = false;
starved[ID] = false;
starveCounter = 0;
}
protected void acceptFlit(Flit f)
{
statsEjectFlit(f);
if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits)
statsEjectPacket(f.packet);
m_n.receiveFlit(f);
}
Flit ejectLocal()
{
// eject locally-destined flit (highest-ranked, if multiple)
Flit ret = null;
int flitsTryToEject = 0;
int bestDir = -1;
for (int dir = 0; dir < 2; dir++)
if (linkIn[dir] != null && linkIn[dir].Out != null &&
linkIn[dir].Out.state != Flit.State.Placeholder &&
linkIn[dir].Out.dest.ID == ID)
{
ret = linkIn[dir].Out;
bestDir = dir;
flitsTryToEject ++;
}
if (bestDir != -1) linkIn[bestDir].Out = null;
Simulator.stats.flitsTryToEject[flitsTryToEject].Add();
#if DEBUG
if (ret != null)
Console.WriteLine("ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound);
#endif
return ret;
}
// Only one inject Slot now.
//TODO: Create 2 injuct Slots, one for clockwise network, one for counter-clockwise network
public override bool canInjectFlit(Flit f)
{
if (throttle[ID])
return false;
bool can;
if (f.parity == 0)
{
if (m_injectSlot_CW != null)
f.timeWaitToInject ++;
can = m_injectSlot_CW == null;
}
else if (f.parity == 1)
{
if (m_injectSlot_CCW != null)
f.timeWaitToInject ++;
can = m_injectSlot_CCW == null;
}
else if (f.parity == -1)
{
if (m_injectSlot_CW != null && m_injectSlot_CCW != null)
f.timeWaitToInject ++;
can = (m_injectSlot_CW == null || m_injectSlot_CCW == null);
}
else throw new Exception("Unkown parity value!");
if (!can)
{
starveCounter ++;
Simulator.stats.injStarvation.Add();
}
if (starveCounter == Config.starveThreshold)
starved[ID] = true;
return can;
}
public override void InjectFlit(Flit f)
{
if (Config.topology != Topology.Mesh && Config.topology != Topology.MeshOfRings && f.parity != -1)
throw new Exception("In Ring based topologies, the parity must be -1");
starveCounter = 0;
starved[ID] = false;
if (f.parity == 0)
{
if (m_injectSlot_CW == null)
m_injectSlot_CW = f;
else
throw new Exception("The slot is empty!");
}
else if (f.parity == 1)
{
if (m_injectSlot_CCW == null)
m_injectSlot_CCW = f;
else
throw new Exception("The slot is empty!");
}
else
{
int preference = -1;
int dest = f.packet.dest.ID;
int src = f.packet.src.ID;
if (Config.topology == Topology.SingleRing)
{
if ((dest - src + Config.N) % Config.N < Config.N / 2)
preference = 0;
else
preference = 1;
}
else if (dest / 4 == src / 4)
{
if ((dest - src + 4) % 4 < 2)
preference = 0;
else if ((dest - src + 4) % 4 > 2)
preference = 1;
}
else if (Config.topology == Topology.HR_4drop)
{
if (ID == 1 || ID == 2 || ID == 5 || ID == 6 || ID == 8 || ID == 11 || ID == 12 || ID == 15 )
preference = 0;
else
preference = 1;
}
else if (Config.topology == Topology.HR_8drop || Config.topology == Topology.HR_8_8drop)
{
if (ID % 2 == 0)
preference = 0;
else
preference = 1;
}
else if (Config.topology == Topology.HR_8_16drop)
{
if (dest / 8 == src / 8)
{
if ((dest - src + 8) % 8 < 4)
preference = 0;
else
preference = 1;
}
else
{
if (ID % 2 == 0)
preference = 1;
else
preference = 0;
}
}
if (Config.NoPreference)
preference = -1;
if (preference == -1)
preference = Simulator.rand.Next(2);
if (preference == 0)
{
if (m_injectSlot_CW == null)
m_injectSlot_CW = f;
else if (m_injectSlot_CCW == null)
m_injectSlot_CCW = f;
}
else if (preference == 1)
{
if (m_injectSlot_CCW == null)
m_injectSlot_CCW = f;
else if (m_injectSlot_CW == null)
m_injectSlot_CW = f;
}
else
throw new Exception("Unknown preference!");
}
}
protected override void _doStep()
{
for (int i = 0; i < 2; i++) //by Xiyue: run output link first
{
if (linkIn[i].Out != null && Config.N == 16)
{
Flit f = linkIn[i].Out;
if (f.packet.src.ID / 4 == ID / 4)
f.timeInTheSourceRing+=1;
else if (f.packet.dest.ID / 4 == ID / 4)
f.timeInTheDestRing +=1;
else
f.timeInTheTransitionRing += 1;
}
}
Flit f1 = null,f2 = null;
if (Config.EjectBufferSize != -1 && Config.RingEjectTrial == -1)
{
for (int dir =0; dir < 2; dir ++)
{
if (linkIn[dir].Out != null && linkIn[dir].Out.packet.dest.ID == ID && ejectBuffer[dir].Count < Config.EjectBufferSize)
{
ejectBuffer[dir].Enqueue(linkIn[dir].Out);
linkIn[dir].Out = null;
}
}
int bestdir = -1;
for (int dir = 0; dir < 2; dir ++)
// if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Peek().injectionTime < ejectBuffer[bestdir].Peek().injectionTime))
if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Count > ejectBuffer[bestdir].Count))
// if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || Simulator.rand.Next(2) == 1))
bestdir = dir;
if (bestdir != -1)
acceptFlit(ejectBuffer[bestdir].Dequeue());
}
else
{
for (int i = 0; i < Config.RingEjectTrial; i++)
{
Flit eject = ejectLocal();
if (i == 0) f1 = eject;
else if (i == 1) f2 = eject;
if (eject != null)
acceptFlit(eject);
}
if (f1 != null && f2 != null && f1.packet == f2.packet)
Simulator.stats.ejectsFromSamePacket.Add(1);
else if (f1 != null && f2 != null)
Simulator.stats.ejectsFromSamePacket.Add(0);
}
for (int dir = 0; dir < 2; dir++)
{
if (linkIn[dir].Out != null)
{
Simulator.stats.flitsPassBy.Add(1);
linkOut[dir].In = linkIn[dir].Out;
linkIn[dir].Out = null;
}
}
if (m_injectSlot_CW != null && linkOut[0].In == null) //inject a flit into network
{
linkOut[0].In = m_injectSlot_CW;
statsInjectFlit(m_injectSlot_CW);
m_injectSlot_CW = null;
}
if (m_injectSlot_CCW != null && linkOut[1].In == null)
{
linkOut[1].In = m_injectSlot_CCW;
statsInjectFlit(m_injectSlot_CCW);
m_injectSlot_CCW = null;
}
}
}
public class Router_Switch : Router
{
int bufferDepth = 1;
public static int[,] bufferCurD = new int[Config.N,4];
Flit[,] buffers;// = new Flit[4,32];
public Router_Switch(int ID) : base()
{
coord.ID = ID;
enable = true;
m_n = null;
buffers = new Flit[4,32]; // actual buffer depth is decided by bufferDepth
for (int i = 0; i < 4; i++)
for (int n = 0; n < bufferDepth; n++)
buffers[i, n] = null;
}
int Local_CW = 0;
int Local_CCW = 1;
int GL_CW = 2;
int GL_CCW = 3;
// different routing algorithms can be implemented by changing this function
private bool productiveRouter(Flit f, int port)
{
// Console.WriteLine("Net/RouterRing.cs");
int RingID = ID / 4;
if (Config.HR_NoBias)
{
if ((port == Local_CW || port == Local_CCW) && RingID == f.packet.dest.ID / 4)
return false;
else if ((port == Local_CW || port == Local_CCW) && RingID != f.packet.dest.ID / 4)
return true;
else if ((port == GL_CW || port == GL_CCW) && RingID == f.packet.dest.ID / 4)
return true;
else if ((port == GL_CW || port == GL_CCW) && RingID != f.packet.dest.ID / 4)
return false;
else
throw new Exception("Unknown port of switchRouter");
}
else if (Config.HR_SimpleBias)
{
if ((port == Local_CW || port == Local_CCW) && RingID == f.packet.dest.ID / 4)
return false;
else if ((port == Local_CW || port == Local_CCW) && RingID != f.packet.dest.ID / 4)
// if (RingID + f.packet.dest.ID / 4 == 3) //diagonal. can always inject
return true;
/* else if (RingID == 0 && destID == 1) return ID == 2 || ID == 1;
else if (RingID == 0 && destID == 2) return ID == 3 || ID == 0;
else if (RingID == 1 && destID == 0) return ID == 4 || ID == 5;
else if (RingID == 1 && destID == 3) return ID == 6 || ID == 7;
else if (RingID == 2 && destID == 0) return ID == 8 || ID == 9;
else if (RingID == 2 && destID == 3) return ID == 10 || ID == 11;
else if (RingID == 3 && destID == 1) return ID == 13 || ID == 14;
else if (RingID == 3 && destID == 2) return ID == 12 || ID == 15;
else
throw new Exception("Unknown src and dest in Hierarchical Ring");*/
else if ((port == GL_CW || port == GL_CCW) && RingID == f.packet.dest.ID / 4)
return true;
else if ((port == GL_CW || port == GL_CCW) && RingID != f.packet.dest.ID / 4)
return false;
else
throw new Exception("Unknown port of switchRouter");
}
else
throw new Exception("Unknow Routing Algorithm for Hierarchical Ring");
}
protected override void _doStep()
{
switchRouterStats();
// consider 4 input ports seperately. If not productive, keep circling
if (!enable) return;
/* if (ID == 3)
{
if (linkIn[0].Out != null && linkIn[0].Out.packet.dest.ID == 11)
Console.WriteLine("parity : {0}, src:{1}", linkIn[0].Out.parity, linkIn[0].Out.packet.src.ID);
}*/
for (int dir = 0; dir < 4; dir ++)
{
int i;
for (i = 0; i < bufferDepth; i++)
if (buffers[dir, i] == null)
break;
//Console.WriteLine("linkIn[dir] == null:{0},ID:{1}, dir:{2}", linkIn[dir] == null, ID, dir);
bool productive = (linkIn[dir].Out != null)? productiveRouter(linkIn[dir].Out, dir) : false;
//Console.WriteLine("productive: {0}", productive);
if (linkIn[dir].Out != null && !productive || i == bufferDepth) // nonproductive or the buffer is full : bypass the router
{
linkOut[dir].In = linkIn[dir].Out;
linkIn[dir].Out = null;
}
else if (linkIn[dir].Out != null) //productive direction and the buffer has empty space, add into buffer
{
int k;
for (k = 0; k < bufferDepth; k++)
{
if (buffers[dir, k] == null)
{
buffers[dir, k] = linkIn[dir].Out;
linkIn[dir].Out = null;
break;
}
//Console.WriteLine("{0}", k);
}
if (k == bufferDepth)
throw new Exception("The buffer is full!!");
}
}
// if there're extra slots in the same direction network, inject from the buffer
for (int dir = 0; dir < 4; dir ++)
{
if (linkOut[dir].In == null) // extra slot available
{
int posdir = (dir+2) % 4;
if (buffers[posdir, 0] != null)
{
linkOut[dir].In = buffers[posdir, 0];
buffers[posdir, 0] = null;
}
}
}
// if the productive direction with the same parity is not available. The direction with the other parity is also fine
for (int dir = 0; dir < 4; dir ++)
{
int crossdir = 3 - dir;
if (linkOut[dir].In == null) // extra slot available
{
if (buffers[crossdir, 0] != null)
{
// for HR_SimpleBias is the dir is not a local ring, can't change rotating direction
if (Config.HR_SimpleBias && (dir == GL_CW || dir == GL_CCW))
continue;
linkOut[dir].In = buffers[crossdir, 0];
buffers[crossdir, 0] = null;
}
}
}
if (Config.HR_NoBuffer)
{
for (int dir = 0; dir < 4; dir ++)
{
if (buffers[dir, 0] != null)
{
if (linkOut[dir].In != null)
throw new Exception("The outlet of the buffer is blocked");
linkOut[dir].In = buffers[dir, 0];
buffers[dir, 0] = null;
}
}
}
// move all the flits in the buffer if the head flit is null
for (int dir = 0; dir < 4; dir ++)
{
if (buffers[dir, 0] == null)
{
for (int i = 0; i < bufferDepth - 1; i++)
buffers[dir, i] = buffers[dir, i + 1];
buffers[dir, bufferDepth-1] = null;
}
}
for (int dir = 0; dir < 4; dir ++)
{
int i;
for (i = 0; i < bufferDepth; i++)
if (buffers[dir, i] == null)
break;
bufferCurD[ID,dir] = i;
}
}
void switchRouterStats()
{
for (int dir = 0; dir < 4; dir ++)
{
Flit f = linkIn[dir].Out;
if (f != null && (dir == Local_CW || dir == Local_CCW))
{
if (f.packet.src.ID / 4 == ID / 4)
f.timeInTheSourceRing ++;
else if (f.packet.dest.ID / 4 == ID / 4)
f.timeInTheDestRing ++;
}
else if (f != null && (dir == GL_CW || dir == GL_CCW))
f.timeInGR += 2;
}
return;
}
public override bool canInjectFlit(Flit f)
{
return false;
}
public override void InjectFlit(Flit f)
{
return;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
namespace SubsetNetworkEvaluators
{
/// <summary>
/// The filter subset network evaluator is a custom network evaluator for modeling dynamic restriction attributes
/// where the subset of elements to restrict can be quickly switched at run-time without having to update the network
/// dataset schema in ArcCatalog. In this example the subset of network elements that are restricted is determined
/// based on the selected network features in ArcMap, but it does not matter how the element subset is determined.
/// The selected features can be interpreted as the only restricted features or as the only traversable features based
/// on a parameter flag value, and the subset of elements is also specified as a network attribute parameter value.
/// </summary>
[ClassInterface(ClassInterfaceType.None)]
[Guid("e2a9fbbf-8950-48cb-b487-0ee3f43dccca")]
[ProgId("SubsetNetworkEvaluators.FilterSubsetEvaluator")]
public class FilterSubsetEvaluator : INetworkEvaluator2, INetworkEvaluatorSetup
{
#region Member Variables
private INetworkDataset m_networkDataset;
private INetworkSource m_networkSource;
private INetworkAttribute m_networkAttribute;
// Indicates if filter values should be restricted (otherwise NON filter values are restricted)
// SPECIAL CASE: if NO elements are in the filter, then no elements for THIS SOURCE will be restricted.
// number of EIDs to filter for this source
// the EIDs to override values for, by scaling, for this source
private bool m_restrictFilterElements = true;
private int m_countSourceEIDs = 0;
private Dictionary<int, int> m_sourceEIDHashTable;
#endregion
#region INetworkEvaluator Members
public bool CacheAttribute
{
// CacheAttribute returns whether or not we want the network dataset to cache our evaluated attribute values during the network dataset build
// Since this is a dynamic evaluator, we will return false, so that our attribute values are dynamically queried at runtime
get { return false; }
}
public string DisplayName
{
get { return "FilterSubset"; }
}
public string Name
{
get { return "SubsetNetworkEvaluators.FilterSubset"; }
}
#endregion
#region INetworkEvaluator2 Members
public void Refresh()
{
// This method is called internally during a solve operation immediately prior to performing the actual solve
// This gives us an opportunity to update our evaluator's internal state based on parameter values
m_restrictFilterElements = true;
m_countSourceEIDs = 0;
m_sourceEIDHashTable = new Dictionary<int, int>();
INetworkAttribute2 netAttribute2 = m_networkAttribute as INetworkAttribute2;
IArray netAttributeParams = netAttribute2.Parameters;
// Parameters: "FilterSubset_Restrict", "FilterSubset_EID_<SourceName>"
string prefix = BaseParameterName + "_";
string paramRestrictFilterName = prefix + "Restrict";
string paramEIDsName = prefix + "EIDs_" + m_networkSource.Name;
int nParamRestrictFilter = SubsetHelper.FindParameter(netAttributeParams, paramRestrictFilterName);
int nParamEIDs = SubsetHelper.FindParameter(netAttributeParams, paramEIDsName);
object value;
INetworkAttributeParameter paramRestrictFilter;
INetworkAttributeParameter paramEIDs;
if (nParamRestrictFilter >= 0)
{
paramRestrictFilter = netAttributeParams.get_Element(nParamRestrictFilter) as INetworkAttributeParameter;
value = paramRestrictFilter.Value;
if (value != null)
m_restrictFilterElements = (bool)value;
}
if (nParamEIDs >= 0)
{
paramEIDs = netAttributeParams.get_Element(nParamEIDs) as INetworkAttributeParameter;
value = paramEIDs.Value as int[];
if (value != null)
{
int eid;
int[] rgEIDs;
rgEIDs = (int[])value;
int lb = rgEIDs.GetLowerBound(0);
int ub = rgEIDs.GetUpperBound(0);
for (int i = lb; i <= ub; ++i)
{
++m_countSourceEIDs;
eid = rgEIDs[i];
m_sourceEIDHashTable.Add(eid, eid);
}
}
}
}
public IStringArray RequiredFieldNames
{
// This custom evaluator does not require any field names
get { return null; }
}
#endregion
#region INetworkEvaluatorSetup Members
public UID CLSID
{
get
{
UID uid = new UIDClass();
uid.Value = "{e2a9fbbf-8950-48cb-b487-0ee3f43dccca}";
return uid;
}
}
public IPropertySet Data
{
// The Data property is intended to make use of property sets to get/set the custom evaluator's properties using only one call to the evaluator object
// This custom evaluator does not make use of this property
get { return null; }
set { }
}
public bool DataHasEdits
{
// Since this custom evaluator does not make any data edits, return false
get { return false; }
}
public void Initialize(INetworkDataset networkDataset, IDENetworkDataset DataElement, INetworkSource netSource, IEvaluatedNetworkAttribute netAttribute)
{
// Initialize is called once per session (ArcMap session, ArcCatalog session, etc.) to initialize the evaluator for an associated network dataset
m_networkDataset = networkDataset;
m_networkSource = netSource;
m_networkAttribute = netAttribute;
Refresh();
}
public object QueryValue(INetworkElement Element, IRow Row)
{
if (m_countSourceEIDs <= 0)
return false;
bool restrict = !m_restrictFilterElements;
int eid = -1;
if (m_sourceEIDHashTable.TryGetValue(Element.EID, out eid))
restrict = m_restrictFilterElements;
return restrict;
}
public bool SupportsDefault(esriNetworkElementType ElementType, IEvaluatedNetworkAttribute netAttribute)
{
return false;
}
public bool SupportsSource(INetworkSource Source, IEvaluatedNetworkAttribute netAttribute)
{
// This custom evaluator supports restriction attributes for all sources
return netAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTRestriction;
}
public bool ValidateDefault(esriNetworkElementType ElementType, IEvaluatedNetworkAttribute netAttribute, ref int ErrorCode, ref string ErrorDescription, ref string errorAppendInfo)
{
if (SupportsDefault(ElementType, netAttribute))
{
ErrorCode = 0;
ErrorDescription = errorAppendInfo = string.Empty;
return true;
}
else
{
ErrorCode = -1;
ErrorDescription = errorAppendInfo = string.Empty;
return false;
}
}
public bool ValidateSource(IDatasetContainer2 datasetContainer, INetworkSource netSource, IEvaluatedNetworkAttribute netAttribute, ref int ErrorCode, ref string ErrorDescription, ref string errorAppendInfo)
{
if (SupportsSource(netSource, netAttribute))
{
ErrorCode = 0;
ErrorDescription = errorAppendInfo = string.Empty;
return true;
}
else
{
ErrorCode = -1;
ErrorDescription = errorAppendInfo = string.Empty;
return false;
}
}
#endregion
#region Static Members
public static string BaseParameterName
{
get
{
return "FilterSubset";
}
}
public static void RemoveFilterSubsetAttribute(IDENetworkDataset deNet)
{
IArray netAttributes = SubsetHelper.RemoveAttributesByPrefix(deNet.Attributes, "Filter");
deNet.Attributes = netAttributes;
}
public static IEvaluatedNetworkAttribute AddFilterSubsetAttribute(IDENetworkDataset deNet)
{
IArray netAttributes = deNet.Attributes;
IEvaluatedNetworkAttribute netAttribute = new EvaluatedNetworkAttributeClass() as IEvaluatedNetworkAttribute;
netAttribute.Name = BaseParameterName;
netAttribute.UsageType = esriNetworkAttributeUsageType.esriNAUTRestriction;
netAttribute.DataType = esriNetworkAttributeDataType.esriNADTBoolean;
netAttribute.Units = esriNetworkAttributeUnits.esriNAUUnknown;
INetworkAttribute2 netAttribute2 = netAttribute as INetworkAttribute2;
netAttribute2.UseByDefault = true;
List<INetworkSource> allNetSources = SubsetHelper.GetSourceList(deNet.Sources);
List<INetworkSource> netSources = SubsetHelper.GetSourceList(allNetSources, esriNetworkElementType.esriNETEdge);
List<string> netSourceNames = SubsetHelper.GetSourceNames(netSources);
ResetFilterSubsetParameters((INetworkAttribute2)netAttribute, netSourceNames);
bool supportTurns = deNet.SupportsTurns;
//default evaluators
SubsetHelper.SetDefaultEvaluator(netAttribute, false, esriNetworkElementType.esriNETEdge);
SubsetHelper.SetDefaultEvaluator(netAttribute, false, esriNetworkElementType.esriNETJunction);
if (supportTurns)
SubsetHelper.SetDefaultEvaluator(netAttribute, false, esriNetworkElementType.esriNETTurn);
//sourced evaluators
foreach (INetworkSource netSource in netSources)
SubsetHelper.SetEvaluators(netAttribute, netSource, typeof(FilterSubsetEvaluator));
netAttributes.Add(netAttribute);
deNet.Attributes = netAttributes;
return netAttribute;
}
public static void ResetFilterSubsetParameters(INetworkAttribute2 netAttribute, List<string> netSourceNames)
{
IArray netParams = new ESRI.ArcGIS.esriSystem.ArrayClass();
INetworkAttributeParameter netParam = null;
object paramValue = null;
netParam = new NetworkAttributeParameterClass();
paramValue = true;
string paramName = "";
paramName = BaseParameterName;
paramName += "_Restrict";
netParam.Name = paramName;
netParam.VarType = (int)VarType.Bool;
netParam.Value = paramValue;
netParam.DefaultValue = paramValue;
netParams.Add(netParam);
netParam = new NetworkAttributeParameterClass();
paramValue = 1;
foreach (string netSourceName in netSourceNames)
{
netParam = new NetworkAttributeParameterClass();
paramValue = null;
paramName = BaseParameterName;
paramName += "_EIDs_";
paramName += netSourceName;
netParam.Name = paramName;
netParam.VarType = (int)(VarType.Array | VarType.Integer);
netParam.Value = paramValue;
netParam.DefaultValue = paramValue;
netParams.Add(netParam);
}
//does not preserve existing parameters if any
netAttribute.Parameters = netParams;
}
#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.TrafficManager.Fluent
{
using System.Collections.Generic;
using ResourceManager.Fluent.Core;
using System;
using System.Linq;
using Models;
/// <summary>
/// Represents an endpoint collection associated with a traffic manager profile.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnRyYWZmaWNtYW5hZ2VyLmltcGxlbWVudGF0aW9uLlRyYWZmaWNNYW5hZ2VyRW5kcG9pbnRzSW1wbA==
internal partial class TrafficManagerEndpointsImpl :
ExternalChildResourcesCached<TrafficManagerEndpointImpl, ITrafficManagerEndpoint, EndpointInner, ITrafficManagerProfile, TrafficManagerProfileImpl>
{
/// <summary>
/// Creates new EndpointsImpl.
/// </summary>
/// <param name="parent">The parent traffic manager profile of the endpoints.</param>
///GENMHASH:4D0E5B9E7FAF82899EC6E6B3762A42CE:86647EE6A7C92249B46A6C7B4A2F9A64
internal TrafficManagerEndpointsImpl(TrafficManagerProfileImpl parent) : base(parent, "Endpoint")
{
CacheCollection();
}
internal IList<EndpointInner> AllEndpointsInners()
{
return this.Collection.Values.Select(e => e.Inner).ToList();
}
///GENMHASH:8CB67A1B3CF8E6894B88F02B1AE365EC:31C08CE442572994D91AB64D5DB46CB3
public void AddEndpoint(TrafficManagerEndpointImpl endpoint)
{
this.AddChildResource(endpoint);
}
/// <return>The nested profile endpoints as a map indexed by name.</return>
///GENMHASH:B49B27ECF031E10A22023E6336E734E5:CE6855352C0CC1F5B88859811F7E2029
internal IReadOnlyDictionary<string, ITrafficManagerNestedProfileEndpoint> NestedProfileEndpointsAsMap()
{
Dictionary<string, ITrafficManagerNestedProfileEndpoint> result = new Dictionary<string, ITrafficManagerNestedProfileEndpoint>();
foreach (var entry in this.Collection)
{
TrafficManagerEndpointImpl endpoint = entry.Value;
if (endpoint.EndpointType() == EndpointType.NestedProfile)
{
ITrafficManagerNestedProfileEndpoint nestedProfileEndpoint = new TrafficManagerNestedProfileEndpointImpl(
entry.Key,
Parent,
endpoint.Inner);
result.Add(entry.Key, nestedProfileEndpoint);
}
}
return result;
}
/// <summary>
/// Mark the endpoint with given name as to be removed.
/// </summary>
/// <param name="name">The name of the endpoint to be removed.</param>
///GENMHASH:FC8ECF797E9AF86E82C3899A3D5C00BB:97028F0C4A32755497D72429D22C1125
public void Remove(string name)
{
base.PrepareRemove(name);
}
/// <return>The external endpoints as a map indexed by name.</return>
///GENMHASH:9E9CCBF47923D34FC60535C1BF252975:241C2E97F7493232FD204964162A4C4D
internal IReadOnlyDictionary<string, ITrafficManagerExternalEndpoint> ExternalEndpointsAsMap()
{
Dictionary<string, ITrafficManagerExternalEndpoint> result = new Dictionary<string, ITrafficManagerExternalEndpoint>();
foreach (var entry in this.Collection)
{
TrafficManagerEndpointImpl endpoint = entry.Value;
if (endpoint.EndpointType() == EndpointType.External)
{
ITrafficManagerExternalEndpoint externalEndpoint = new TrafficManagerExternalEndpointImpl(
entry.Key,
Parent,
endpoint.Inner);
result.Add(entry.Key, externalEndpoint);
}
}
return result;
}
///GENMHASH:6A122C62EB559D6E6E53725061B422FB:E362A504788CC2639B19EB2A280DC22C
protected override IList<TrafficManagerEndpointImpl> ListChildResources()
{
List<TrafficManagerEndpointImpl> childResources = new List<TrafficManagerEndpointImpl>();
if (Parent.Inner.Endpoints != null)
{
foreach (var inner in Parent.Inner.Endpoints)
{
childResources.Add(new TrafficManagerEndpointImpl(
inner.Name,
Parent,
inner));
}
}
return childResources;
}
/// <return>The azure endpoints as a map indexed by name.</return>
///GENMHASH:6ADF0039F06A892E8F3B1C405F538F3C:9442957E47473D025199992BF235E603
internal IReadOnlyDictionary<string, ITrafficManagerAzureEndpoint> AzureEndpointsAsMap()
{
Dictionary<string, ITrafficManagerAzureEndpoint> result = new Dictionary<string, ITrafficManagerAzureEndpoint>();
foreach (var entry in this.Collection)
{
TrafficManagerEndpointImpl endpoint = entry.Value;
if (endpoint.EndpointType() == EndpointType.Azure)
{
ITrafficManagerAzureEndpoint azureEndpoint = new TrafficManagerAzureEndpointImpl(
entry.Key,
Parent,
endpoint.Inner);
result.Add(entry.Key, azureEndpoint);
}
}
return result;
}
/// <summary>
/// Starts an external endpoint update chain.
/// </summary>
/// <param name="name">The name of the endpoint to be updated.</param>
/// <return>The endpoint.</return>
///GENMHASH:DCEFD84C43018F459854BC29B1935412:461635A9A465B4AC37C1544F187F8CCB
public TrafficManagerEndpointImpl UpdateExternalEndpoint(string name)
{
TrafficManagerEndpointImpl endpoint = base.PrepareUpdate(name);
if (endpoint.EndpointType() != EndpointType.External)
{
throw new ArgumentException($"An external endpoint with name {name} not found in the profile");
}
return endpoint;
}
/// <summary>
/// Starts an nested profile endpoint definition chain.
/// </summary>
/// <param name="name">The name of the endpoint to be added.</param>
/// <return>The endpoint.</return>
///GENMHASH:E299B5EC44792111DF66BBF20E5DD793:3D2F0EDDDDF7C14C2BD25AD76310C6D0
public TrafficManagerEndpointImpl DefineNestedProfileTargetEndpoint(string name)
{
TrafficManagerEndpointImpl endpoint = base.PrepareDefine(name);
endpoint.Inner.Type = EndpointType.NestedProfile.ToString();
return endpoint;
}
/// <summary>
/// Starts an external endpoint definition chain.
/// </summary>
/// <param name="name">The name of the endpoint to be added.</param>
/// <return>The endpoint.</return>
///GENMHASH:92CB7AA7AD787F0DF94966625C981BF2:21E3F1E2671256798F0DEB88891E678D
public TrafficManagerEndpointImpl DefineExteralTargetEndpoint(string name)
{
TrafficManagerEndpointImpl endpoint = base.PrepareDefine(name);
endpoint.Inner.Type = EndpointType.External.ToString();
return endpoint;
}
/// <summary>
/// Starts an azure endpoint update chain.
/// </summary>
/// <param name="name">The name of the endpoint to be updated.</param>
/// <return>The endpoint.</return>
///GENMHASH:24E62EC73B5276BE1A4C9512125E5F24:567851E04A4537D499D352E5C6B37E4D
public TrafficManagerEndpointImpl UpdateAzureEndpoint(string name)
{
TrafficManagerEndpointImpl endpoint = base.PrepareUpdate(name);
if (endpoint.EndpointType() != EndpointType.Azure)
{
throw new ArgumentException($"An azure endpoint with name { name } not found in the profile");
}
return endpoint;
}
///GENMHASH:8E8DA5B84731A2D412247D25A544C502:37DC546F8DB33DF63F6C1EF339D32991
protected override TrafficManagerEndpointImpl NewChildResource(string name)
{
TrafficManagerEndpointImpl endpoint = new TrafficManagerEndpointImpl(
name,
Parent, new EndpointInner { Name = name });
return endpoint
.WithRoutingWeight(1)
.WithTrafficEnabled();
}
/// <summary>
/// Starts an Azure endpoint definition chain.
/// </summary>
/// <param name="name">The name of the endpoint to be added.</param>
/// <return>The endpoint.</return>
///GENMHASH:A912B64DAA5D27988A4E605BC2374EEA:7E23814F3155E7732156E4EB5E17C0BC
public TrafficManagerEndpointImpl DefineAzureTargetEndpoint(string name)
{
TrafficManagerEndpointImpl endpoint = base.PrepareDefine(name);
endpoint.Inner.Type = EndpointType.Azure.ToString();
return endpoint;
}
/// <summary>
/// Starts a nested profile endpoint update chain.
/// </summary>
/// <param name="name">The name of the endpoint to be updated.</param>
/// <return>The endpoint.</return>
///GENMHASH:7D642A8E2F1E22246EC9157C176A5B30:C705D303B24BFD0020C12D616A005882
public TrafficManagerEndpointImpl UpdateNestedProfileEndpoint(string name)
{
TrafficManagerEndpointImpl endpoint = base.PrepareUpdate(name);
if (endpoint.EndpointType() != EndpointType.NestedProfile)
{
throw new ArgumentException($"A nested profile endpoint with name { name } not found in the profile");
}
return endpoint;
}
}
}
| |
/*
* 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 ParquetSharp.Column;
using ParquetSharp.Column.Statistics;
using ParquetSharp.Filter2.Predicate;
using ParquetSharp.Hadoop.Metadata;
using Xunit;
using static ParquetSharp.Filter2.Predicate.FilterApi;
using static ParquetSharp.Filter2.Predicate.Operators;
using static ParquetSharp.Filter2.StatisticsLevel.StatisticsFilter;
using static ParquetSharp.Schema.PrimitiveType;
namespace ParquetHadoopTests.Filter2.StatisticsLevel
{
public class TestStatisticsFilter
{
private static ColumnChunkMetaData getIntColumnMeta(IntStatistics stats, long valueCount)
{
return ColumnChunkMetaData.get(ColumnPath.get("int", "column"),
PrimitiveTypeName.INT32,
CompressionCodecName.GZIP,
new HashSet<Encoding>(new[] { Encoding.PLAIN }),
stats,
0L, 0L, valueCount, 0L, 0L);
}
private static ColumnChunkMetaData getDoubleColumnMeta(DoubleStatistics stats, long valueCount)
{
return ColumnChunkMetaData.get(ColumnPath.get("double", "column"),
PrimitiveTypeName.DOUBLE,
CompressionCodecName.GZIP,
new HashSet<Encoding>(new[] { Encoding.PLAIN }),
stats,
0L, 0L, valueCount, 0L, 0L);
}
private static readonly IntColumn intColumn = intColumn("int.column");
private static readonly DoubleColumn doubleColumn = doubleColumn("double.column");
private static readonly IntStatistics intStats = new IntStatistics();
private static readonly IntStatistics nullIntStats = new IntStatistics();
private static readonly DoubleStatistics doubleStats = new DoubleStatistics();
static TestStatisticsFilter()
{
intStats.setMinMax(10, 100);
doubleStats.setMinMax(10, 100);
nullIntStats.setMinMax(0, 0);
nullIntStats.setNumNulls(177);
}
private static readonly List<ColumnChunkMetaData> columnMetas = new List<ColumnChunkMetaData> {
getIntColumnMeta(intStats, 177L),
getDoubleColumnMeta(doubleStats, 177L) };
private static readonly List<ColumnChunkMetaData> nullColumnMetas = new List<ColumnChunkMetaData> {
getIntColumnMeta(nullIntStats, 177L), // column of all nulls
getDoubleColumnMeta(doubleStats, 177L) };
[Fact]
public void testEqNonNull()
{
Assert.True(canDrop(eq(intColumn, 9), columnMetas));
Assert.False(canDrop(eq(intColumn, 10), columnMetas));
Assert.False(canDrop(eq(intColumn, 100), columnMetas));
Assert.True(canDrop(eq(intColumn, 101), columnMetas));
// drop columns of all nulls when looking for non-null value
Assert.True(canDrop(eq(intColumn, 0), nullColumnMetas));
}
[Fact]
public void testEqNull()
{
IntStatistics statsNoNulls = new IntStatistics();
statsNoNulls.setMinMax(10, 100);
statsNoNulls.setNumNulls(0);
IntStatistics statsSomeNulls = new IntStatistics();
statsSomeNulls.setMinMax(10, 100);
statsSomeNulls.setNumNulls(3);
Assert.True(canDrop(eq(intColumn, null), new List<ColumnChunkMetaData> {
getIntColumnMeta(statsNoNulls, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.False(canDrop(eq(intColumn, null), new List<ColumnChunkMetaData> {
getIntColumnMeta(statsSomeNulls, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
}
[Fact]
public void testNotEqNonNull()
{
Assert.False(canDrop(notEq(intColumn, 9), columnMetas));
Assert.False(canDrop(notEq(intColumn, 10), columnMetas));
Assert.False(canDrop(notEq(intColumn, 100), columnMetas));
Assert.False(canDrop(notEq(intColumn, 101), columnMetas));
IntStatistics allSevens = new IntStatistics();
allSevens.setMinMax(7, 7);
Assert.True(canDrop(notEq(intColumn, 7), new List<ColumnChunkMetaData> {
getIntColumnMeta(allSevens, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
}
[Fact]
public void testNotEqNull()
{
IntStatistics statsNoNulls = new IntStatistics();
statsNoNulls.setMinMax(10, 100);
statsNoNulls.setNumNulls(0);
IntStatistics statsSomeNulls = new IntStatistics();
statsSomeNulls.setMinMax(10, 100);
statsSomeNulls.setNumNulls(3);
IntStatistics statsAllNulls = new IntStatistics();
statsAllNulls.setMinMax(0, 0);
statsAllNulls.setNumNulls(177);
Assert.False(canDrop(notEq(intColumn, null), new List<ColumnChunkMetaData> {
getIntColumnMeta(statsNoNulls, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.False(canDrop(notEq(intColumn, null), new List<ColumnChunkMetaData> {
getIntColumnMeta(statsSomeNulls, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.True(canDrop(notEq(intColumn, null), new List<ColumnChunkMetaData> {
getIntColumnMeta(statsAllNulls, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
}
[Fact]
public void testLt()
{
Assert.True(canDrop(lt(intColumn, 9), columnMetas));
Assert.True(canDrop(lt(intColumn, 10), columnMetas));
Assert.False(canDrop(lt(intColumn, 100), columnMetas));
Assert.False(canDrop(lt(intColumn, 101), columnMetas));
Assert.True(canDrop(lt(intColumn, 0), nullColumnMetas));
Assert.True(canDrop(lt(intColumn, 7), nullColumnMetas));
}
[Fact]
public void testLtEq()
{
Assert.True(canDrop(ltEq(intColumn, 9), columnMetas));
Assert.False(canDrop(ltEq(intColumn, 10), columnMetas));
Assert.False(canDrop(ltEq(intColumn, 100), columnMetas));
Assert.False(canDrop(ltEq(intColumn, 101), columnMetas));
Assert.True(canDrop(ltEq(intColumn, 0), nullColumnMetas));
Assert.True(canDrop(ltEq(intColumn, 7), nullColumnMetas));
}
[Fact]
public void testGt()
{
Assert.False(canDrop(gt(intColumn, 9), columnMetas));
Assert.False(canDrop(gt(intColumn, 10), columnMetas));
Assert.True(canDrop(gt(intColumn, 100), columnMetas));
Assert.True(canDrop(gt(intColumn, 101), columnMetas));
Assert.True(canDrop(gt(intColumn, 0), nullColumnMetas));
Assert.True(canDrop(gt(intColumn, 7), nullColumnMetas));
}
[Fact]
public void testGtEq()
{
Assert.False(canDrop(gtEq(intColumn, 9), columnMetas));
Assert.False(canDrop(gtEq(intColumn, 10), columnMetas));
Assert.False(canDrop(gtEq(intColumn, 100), columnMetas));
Assert.True(canDrop(gtEq(intColumn, 101), columnMetas));
Assert.True(canDrop(gtEq(intColumn, 0), nullColumnMetas));
Assert.True(canDrop(gtEq(intColumn, 7), nullColumnMetas));
}
[Fact]
public void testAnd()
{
FilterPredicate yes = eq(intColumn, 9);
FilterPredicate no = eq(doubleColumn, 50D);
Assert.True(canDrop(and(yes, yes), columnMetas));
Assert.True(canDrop(and(yes, no), columnMetas));
Assert.True(canDrop(and(no, yes), columnMetas));
Assert.False(canDrop(and(no, no), columnMetas));
}
[Fact]
public void testOr()
{
FilterPredicate yes = eq(intColumn, 9);
FilterPredicate no = eq(doubleColumn, 50D);
Assert.True(canDrop(or(yes, yes), columnMetas));
Assert.False(canDrop(or(yes, no), columnMetas));
Assert.False(canDrop(or(no, yes), columnMetas));
Assert.False(canDrop(or(no, no), columnMetas));
}
public class SevensAndEightsUdp : UserDefinedPredicate<int>
{
public override bool keep(int value)
{
throw new InvalidOperationException("this method should not be called");
}
public override bool canDrop(ParquetSharp.Filter2.Predicate.Statistics<int> statistics)
{
return statistics.getMin() == 7 && statistics.getMax() == 7;
}
public override bool inverseCanDrop(ParquetSharp.Filter2.Predicate.Statistics<int> statistics)
{
return statistics.getMin() == 8 && statistics.getMax() == 8;
}
}
[Fact]
public void testUdp()
{
FilterPredicate pred = userDefined<int, SevensAndEightsUdp>(intColumn);
FilterPredicate invPred = LogicalInverseRewriter.rewrite(not(userDefined<int, SevensAndEightsUdp>(intColumn)));
IntStatistics seven = new IntStatistics();
seven.setMinMax(7, 7);
IntStatistics eight = new IntStatistics();
eight.setMinMax(8, 8);
IntStatistics neither = new IntStatistics();
neither.setMinMax(1, 2);
Assert.True(canDrop(pred, new List<ColumnChunkMetaData> {
getIntColumnMeta(seven, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.False(canDrop(pred, new List<ColumnChunkMetaData> {
getIntColumnMeta(eight, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.False(canDrop(pred, new List<ColumnChunkMetaData> {
getIntColumnMeta(neither, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.False(canDrop(invPred, new List<ColumnChunkMetaData> {
getIntColumnMeta(seven, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.True(canDrop(invPred, new List<ColumnChunkMetaData> {
getIntColumnMeta(eight, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
Assert.False(canDrop(invPred, new List<ColumnChunkMetaData> {
getIntColumnMeta(neither, 177L),
getDoubleColumnMeta(doubleStats, 177L) }));
}
[Fact]
public void testClearExceptionForNots()
{
List<ColumnChunkMetaData> columnMetas = new List<ColumnChunkMetaData> {
getDoubleColumnMeta(new DoubleStatistics(), 0L),
getIntColumnMeta(new IntStatistics(), 0L) };
FilterPredicate pred = and(not(eq(doubleColumn, 12.0)), eq(intColumn, 17));
try
{
canDrop(pred, columnMetas);
Assert.True(false, "This should throw");
}
catch (ArgumentException e)
{
Assert.Equal("This predicate contains a not! Did you forget to run this predicate through LogicalInverseRewriter?"
+ " not(eq(double.column, 12.0))", e.Message);
}
}
[Fact]
public void testMissingColumn()
{
List<ColumnChunkMetaData> columnMetas = new List<ColumnChunkMetaData> {
getIntColumnMeta(new IntStatistics(), 0L) };
try
{
canDrop(and(eq(doubleColumn, 12.0), eq(intColumn, 17)), columnMetas);
Assert.True(false, "This should throw");
}
catch (ArgumentException e)
{
Assert.Equal("Column double.column not found in schema!", e.Message);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 ProstateBioBank.Areas.HelpPage.ModelDescriptions;
using ProstateBioBank.Areas.HelpPage.Models;
namespace ProstateBioBank.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;
}
if (complexTypeDescription != null)
{
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 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);
}
}
}
}
| |
using System;
using System.Collections;
using System.Xml.Serialization;
namespace Data.Scans
{
/// <summary>
/// A scan point is a single point in a scan. It might have
/// more than one Shot (perhaps because several shots are being
/// taken per shot to improve S:N. The shots are stored in two
/// groups to facilitate switched scans. A scan point also has some
/// analog channel readings associated with it. The scan point keeps
/// a record of the scan parameter.
/// </summary>
[Serializable]
public class ScanPoint : MarshalByRefObject
{
private double scanParameter;
private ArrayList onShots = new ArrayList();
private ArrayList offShots = new ArrayList();
private ArrayList analogs = new ArrayList();
public Shot AverageOnShot
{
get { return AverageShots(onShots); }
}
public Shot AverageOffShot
{
get { return AverageShots(offShots); }
}
private Shot AverageShots(ArrayList shots)
{
if (shots.Count == 1) return (Shot)shots[0];
Shot temp = new Shot();
foreach (Shot s in shots) temp += s;
return temp/shots.Count;
}
public double IntegrateOn(int index, double startTime, double endTime)
{
return Integrate(onShots, index, startTime, endTime);
}
public double IntegrateOff(int index, double startTime, double endTime)
{
return Integrate(offShots, index, startTime, endTime);
}
public double VarianceOn(int index, double startTime, double endTime)
{
return Variance(onShots, index, startTime, endTime);
}
public double FractionOfShotNoiseOn(int index, double startTime, double endTime)
{
return FractionOfShotNoise(onShots, index, startTime, endTime);
}
public double FractionOfShotNoiseNormedOn(int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
return FractionOfShotNoiseNormed(onShots, index, startTime0, endTime0,startTime1,endTime1);
}
private double Integrate(ArrayList shots, int index, double startTime, double endTime)
{
double temp = 0;
foreach (Shot s in shots) temp += s.Integrate(index, startTime, endTime);
return temp/shots.Count;
}
private double IntegrateNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
double temp = 0;
foreach (Shot s in shots) temp += s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1);
return temp / shots.Count;
}
private double Variance(ArrayList shots, int index, double startTime, double endTime)
{
double tempMn = 0;
double tempx2 = 0;
double vari = 0;
double n = shots.Count;
if (n==1)
{
return vari;
}
else
{
foreach (Shot s in shots) tempMn += s.Integrate(index, startTime, endTime);
foreach (Shot s in shots) tempx2 += Math.Pow(s.Integrate(index, startTime, endTime),2);
return vari = (n / (n - 1)) * ((tempx2 / n) - Math.Pow((tempMn / n), 2));
}
}
private double VarianceNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
double tempMn = 0;
double tempx2 = 0;
double vari = 0;
double n = shots.Count;
if (n == 1)
{
return vari;
}
else
{
foreach (Shot s in shots) tempMn += s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1);
foreach (Shot s in shots) tempx2 += Math.Pow(s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1), 2);
return vari = (n / (n - 1)) * ((tempx2 / n) - Math.Pow((tempMn / n), 2));
}
}
private double Calibration(ArrayList shots, int index)
{
Shot s = (Shot)shots[0];
return s.Calibration(index);
}
private double FractionOfShotNoise(ArrayList shots, int index, double startTime, double endTime)
{
return Math.Pow(Variance(shots, index, startTime, endTime)/(Integrate(shots, index, startTime, endTime)*Calibration(shots, index)),0.5);
}
private double FractionOfShotNoiseNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
double fracNoiseTN = Math.Pow(VarianceNormed(shots, index, startTime0, endTime0, startTime1, endTime1),0.5) / IntegrateNormed(shots, index, startTime0, endTime0, startTime1, endTime1);
double fracNoiseT2 = Calibration(shots, index[0]) / Integrate(shots, index[0], startTime0, endTime0);
double fracNoiseN2 = Calibration(shots, index[1]) / Integrate(shots, index[1], startTime1, endTime1);
return fracNoiseTN / Math.Pow(fracNoiseT2 + fracNoiseN2, 0.5);
}
public double MeanOn(int index)
{
return Mean(onShots, index);
}
public double MeanOff(int index)
{
return Mean(offShots, index);
}
private double Mean(ArrayList shots, int index)
{
double temp = 0;
foreach (Shot s in shots) temp += s.Mean(index);
return temp / shots.Count;
}
public static ScanPoint operator +(ScanPoint p1, ScanPoint p2)
{
if (p1.OnShots.Count == p2.OnShots.Count
&& p1.OffShots.Count == p2.OffShots.Count
&& p1.Analogs.Count == p2.Analogs.Count)
{
ScanPoint temp = new ScanPoint();
temp.ScanParameter = p1.ScanParameter;
for (int i = 0 ; i < p1.OnShots.Count ; i++)
temp.OnShots.Add((Shot)p1.OnShots[i] + (Shot)p2.OnShots[i]);
for (int i = 0 ; i < p1.OffShots.Count ; i++)
temp.OffShots.Add((Shot)p1.OffShots[i] + (Shot)p2.OffShots[i]);
for (int i = 0 ; i < p1.Analogs.Count ; i++)
temp.Analogs.Add((double)p1.Analogs[i] + (double)p2.Analogs[i]);
return temp;
}
else
{
if (p1.OnShots.Count == 0) return p2;
if (p2.OnShots.Count == 0) return p1;
return null;
}
}
public static ScanPoint operator /(ScanPoint p, int n)
{
ScanPoint temp = new ScanPoint();
temp.ScanParameter = p.ScanParameter;
foreach (Shot s in p.OnShots) temp.OnShots.Add(s/n);
foreach (Shot s in p.OffShots) temp.OffShots.Add(s/n);
foreach (double a in p.Analogs) temp.Analogs.Add(a/n);
return temp;
}
public double ScanParameter
{
get { return scanParameter; }
set { scanParameter = value; }
}
[XmlArray]
[XmlArrayItem(Type = typeof(Shot))]
public ArrayList OnShots
{
get { return onShots; }
}
[XmlArray]
[XmlArrayItem(Type = typeof(Shot))]
public ArrayList OffShots
{
get { return offShots; }
}
[XmlArray]
[XmlArrayItem(Type = typeof(double))]
public ArrayList Analogs
{
get { return analogs; }
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Threading;
using Windows.Devices.SmartCards;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace SDKTemplate
{
public sealed partial class Scenario1_ProvisionTPM : Page
{
private MainPage rootPage = MainPage.Current;
private const int NTE_DEVICE_NOT_READY = unchecked((int)0x80090030);
private const int NTE_DEVICE_NOT_FOUND = unchecked((int)0x80090035);
private const String pinPolicyDisallowed = "Disallowed";
private const String pinPolicyAllowed = "Allowed";
private const String pinPolicyRequireOne = "Require At Least One";
private SmartCardReader reader = null;
public Scenario1_ProvisionTPM()
{
this.InitializeComponent();
}
/// <summary>
/// Click handler for the 'create' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void Create_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.IsEnabled = false;
rootPage.NotifyUser("Creating TPM virtual smart card...", NotifyType.StatusMessage);
try
{
SmartCardPinPolicy pinPolicy = ParsePinPolicy();
IBuffer adminkey = CryptographicBuffer.GenerateRandom(MainPage.ADMIN_KEY_LENGTH_IN_BYTES);
SmartCardProvisioning provisioning = await SmartCardProvisioning.RequestVirtualSmartCardCreationAsync(FriendlyName.Text, adminkey, pinPolicy);
// If card creation is cancelled by the user,
// RequestVirtualSmartCard will return null instead of a
// SmartCardProvisioning object.
if (null == provisioning)
{
rootPage.NotifyUser("TPM virtual smart card creation was canceled by the user.", NotifyType.StatusMessage);
b.IsEnabled = true;
return;
}
// The following two lines are not directly related to TPM virtual
// smart card creation, but are used to demonstrate how to handle
// CardAdded events by registering an event handler with a
// SmartCardReader object. Since we are using a TPM virtual smart
// card in this case, the card cannot actually be added to or
// removed from the reader, but a CardAdded event will fire as
// soon as the event handler is added, since the card is already
// inserted.
//
// We must retain a reference to the SmartCardReader object to
// which we are adding the event handler. Hence we assign the
// reader object associated with the SmartCardProvisioning we
// received from RequestVirtualSmartCardCreationAsync to the
// class's "reader" member. Then, we use += to add the
// HandleCardAdded method as an event handler. The function
// will be automatically boxed in a TypedEventHandler, but
// the function signature match the template arguments for
// the specific event - in this case,
// <SmartCardReader, CardAddedEventArgs>
reader = provisioning.SmartCard.Reader;
reader.CardAdded += HandleCardAdded;
// Store the reader's device ID and admin key to enable the
// following scenarios in the sample.
rootPage.SmartCardReaderDeviceId = provisioning.SmartCard.Reader.DeviceId;
rootPage.AdminKey = adminkey;
// Once RequestVirtualSmartCardCreationAsync has returned, the card
// is already provisioned and ready to use. Therefore, the steps
// in this using block are not actually necessary at this point.
// However, should you want to re-provision the card in the future,
// you would follow this sequence: acquire a challenge context,
// calculate a response, and then call ProvisionAsync on the
// challenge context with the calculated response.
using (var context = await provisioning.GetChallengeContextAsync())
{
IBuffer response = ChallengeResponseAlgorithm.CalculateResponse(context.Challenge, adminkey);
await context.ProvisionAsync(response, true);
}
rootPage.NotifyUser("TPM virtual smart card is provisioned and ready for use.", NotifyType.StatusMessage);
}
catch (Exception ex)
{
// Two potentially common error scenarios when creating a TPM
// virtual smart card are that the user's machine may not have
// a TPM, or the TPM may not be ready for use. It is important
// to explicitly check for these scenarios by checking the
// HResult of any exceptions thrown by
// RequestVirtualSmartCardCreationAsync and gracefully
// providing a suitable message to the user.
if (NTE_DEVICE_NOT_FOUND == ex.HResult)
{
rootPage.NotifyUser("We were unable to find a Trusted Platform Module on your machine. A TPM is required to use a TPM Virtual Smart Card.", NotifyType.ErrorMessage);
}
else if (NTE_DEVICE_NOT_READY == ex.HResult)
{
rootPage.NotifyUser("Your Trusted Platform Module is not ready for use. Please contact your administrator for assistance with initializing your TPM.", NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser("TPM virtual smart card creation failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
}
}
finally
{
b.IsEnabled = true;
}
}
void HandleCardAdded(SmartCardReader sender, CardAddedEventArgs args)
{
// Note that this event is raised from a background thread.
// However, the NotifyUser method is safe to call from background threads.
rootPage.NotifyUser("Card added to reader " + reader.Name + ".", NotifyType.StatusMessage);
}
private SmartCardPinPolicy ParsePinPolicy()
{
SmartCardPinPolicy pinPolicy = new SmartCardPinPolicy();
pinPolicy.MinLength = uint.Parse(PinMinLength.Text);
pinPolicy.MaxLength = uint.Parse(PinMaxLength.Text);
switch (PinUppercase.SelectedValue.ToString())
{
case pinPolicyDisallowed:
pinPolicy.UppercaseLetters = SmartCardPinCharacterPolicyOption.Disallow;
break;
case pinPolicyAllowed:
pinPolicy.UppercaseLetters = SmartCardPinCharacterPolicyOption.Allow;
break;
case pinPolicyRequireOne:
pinPolicy.UppercaseLetters = SmartCardPinCharacterPolicyOption.RequireAtLeastOne;
break;
default:
throw new InvalidOperationException();
}
switch (PinLowercase.SelectedValue.ToString())
{
case pinPolicyDisallowed:
pinPolicy.LowercaseLetters = SmartCardPinCharacterPolicyOption.Disallow;
break;
case pinPolicyAllowed:
pinPolicy.LowercaseLetters = SmartCardPinCharacterPolicyOption.Allow;
break;
case pinPolicyRequireOne:
pinPolicy.LowercaseLetters = SmartCardPinCharacterPolicyOption.RequireAtLeastOne;
break;
default:
throw new InvalidOperationException();
}
switch (PinDigits.SelectedValue.ToString())
{
case pinPolicyDisallowed:
pinPolicy.Digits = SmartCardPinCharacterPolicyOption.Disallow;
break;
case pinPolicyAllowed:
pinPolicy.Digits = SmartCardPinCharacterPolicyOption.Allow;
break;
case pinPolicyRequireOne:
pinPolicy.Digits = SmartCardPinCharacterPolicyOption.RequireAtLeastOne;
break;
default:
throw new InvalidOperationException();
}
switch (PinSpecial.SelectedValue.ToString())
{
case pinPolicyDisallowed:
pinPolicy.SpecialCharacters = SmartCardPinCharacterPolicyOption.Disallow;
break;
case pinPolicyAllowed:
pinPolicy.SpecialCharacters = SmartCardPinCharacterPolicyOption.Allow;
break;
case pinPolicyRequireOne:
pinPolicy.SpecialCharacters = SmartCardPinCharacterPolicyOption.RequireAtLeastOne;
break;
default:
throw new InvalidOperationException();
}
return pinPolicy;
}
}
}
| |
using System;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
class Script
{
const string usage = "Usage: cswscript GetOptusUsage username:password [/p[:proxyUsername[:proxyPassword]]]...\nGets Optus (www.optus.com.au) data usage. Optionally connect with proxy authentication\n";
//const string urlTemplate = "https://myaccount.optusnet.com.au/mydatamonitor/usage.txt?login={0}&passwd={1}"; //old
//https://memberservices.optusnet.com.au/myusage/usage.xml?username=<username>&password=<password> //xml format
const string urlTemplate = "https://memberservices.optusnet.com.au/myusage/usage.txt?username={0}&password={1}";
static public void Main(string[] args)
{
if (args.Length < 1 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
{
Console.WriteLine(usage);
}
else
{
try
{
string user = null, pw = null;
string userPxy = null, pwPxy = null;
//prepare http credentials
string[] credentials = args[0].Split(":".ToCharArray(), 2);
user = credentials[0];
if (credentials.Length > 1)
{
pw = credentials[1];
}
if (pw == null)
{
if (!AuthenticationForm.GetCredentials(ref user, ref pw, "Account login"))
{
return;
}
}
//prepare proxy credentials
if (args.Length > 1 && args[1].StartsWith("/p"))
{
string[] credentialsPxy = args[1].Split(":".ToCharArray(), 3);
if (credentialsPxy.Length > 1)
{
userPxy = credentialsPxy[1];
}
if (credentialsPxy.Length > 2)
{
pwPxy = credentialsPxy[2];
}
if (userPxy == null || pwPxy == null)
if (!AuthenticationForm.GetCredentials(ref userPxy, ref pwPxy, "Proxy Authentication"))
{
return;
}
}
string htmlStr = GetHTML(String.Format(urlTemplate, user, pw), userPxy, pwPxy);
string msg = "";
string title = "";
using (StringReader strReader = new StringReader(htmlStr))
{
string line;
while ((line = strReader.ReadLine()) != null)
{
if (line.StartsWith("plan_limit"))
{
msg += "Limit: " + line.Split("=".ToCharArray(), 2)[1] + "\n";
}
if (line.StartsWith("usage"))
{
msg += "Usage: " + line.Split("=".ToCharArray(), 2)[1] + "\n";
}
if (line.StartsWith("username"))
{
msg += "User: " + line.Split("=".ToCharArray(), 2)[1] + "\n";
}
if (line.StartsWith("plan_name"))
{
title = line.Split("=".ToCharArray(), 2)[1] + " Plan";
}
}
}
MessageBox.Show(msg, title);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
static string GetHTML(string url, string proxyUser, string proxyPw)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (proxyUser != null)
{
WebProxy proxyObject = (WebProxy)GlobalProxySelection.Select;
request.Proxy = proxyObject;
proxyObject.Credentials = new NetworkCredential(proxyUser, proxyPw);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
NetworkCredential test = (NetworkCredential)CredentialCache.DefaultCredentials;
string tempString = null;
int count = 0;
while (0 < (count = resStream.Read(buf, 0, buf.Length)))
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
return sb.ToString();
}
public class AuthenticationForm : System.Windows.Forms.Form
{
public string userName {get {return textBox1.Text;} set {textBox1.Text = value;}}
public string password {get {return textBox2.Text;} set {textBox2.Text = value;}}
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.ComponentModel.Container components = null;
public AuthenticationForm(string userName, string password, string title)
{
InitializeComponent();
textBox1.Text = userName;
textBox2.Text = password;
if (textBox1.Text != "")
{
textBox2.Select();
}
if (title != null)
{
this.Text = title;
}
}
static public bool GetCredentials(ref string userName, ref string password, string title)
{
using(AuthenticationForm dlg = new AuthenticationForm(userName, password, title))
{
if (DialogResult.OK == dlg.ShowDialog())
{
userName = dlg.userName;
password = dlg.password;
return true;
}
else
{
return false;
}
}
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.Location = new System.Drawing.Point(40, 80);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(72, 24);
this.button1.TabIndex = 2;
this.button1.Text = "&Ok";
//
// button2
//
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(136, 80);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(80, 24);
this.button2.TabIndex = 3;
this.button2.Text = "&Cancel";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(80, 8);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(160, 20);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(80, 40);
this.textBox2.Name = "textBox2";
this.textBox2.PasswordChar = '*';
this.textBox2.Size = new System.Drawing.Size(160, 20);
this.textBox2.TabIndex = 1;
this.textBox2.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 23);
this.label1.TabIndex = 4;
this.label1.Text = "User Name:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 40);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(72, 23);
this.label2.TabIndex = 4;
this.label2.Text = "Password:";
//
// AuthenticationForm
//
this.AcceptButton = this.button1;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.button2;
this.ClientSize = new System.Drawing.Size(250, 112);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "AuthenticationForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Authentication";
this.ResumeLayout(false);
}
#endregion
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ===========================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CoroutinesLib;
using CoroutinesLib.Shared;
using CoroutinesLib.TestHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Node.Caching;
using NodeCs.Shared.Caching;
namespace Node.Cache.Test
{
[TestClass]
public class NodeCacheTest
{
[ClassInitialize]
public static void SetUp(TestContext ctx)
{
RunnerFactory.Initialize();
_runner = new RunnerForTest();
}
// ReSharper disable ReturnValueOfPureMethodIsNotUsed
[TestMethod]
public void ShouldExistTheDefaultEmptyGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
Assert.AreEqual(1, target.Groups.Count);
var group = target.Groups[string.Empty];
Assert.IsNotNull(group);
}
#region TimeBased tests
[TestMethod]
public void WhenTimeoutIsReachedNoDataIsReturned()
{
_loadDataCalled = 0;
object result = null;
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
var waiter = (FluentResultBuilder)target.AddAndGet(new CacheDefinition
{
Id = "test",
LoadData = () => LoadDataWithWait(20, 5),
ExpireAfter = TimeSpan.FromMilliseconds(3)
}, (r) => result = r);
target.Execute().Count(); //Initialize
var task = Task.Run(() =>
{
for (int i = 0; i < 8; i++)
{
_runner.RunCycle();//Fun the getter function
}
});
Task.WaitAll(task);
target.Execute().Count(); //Initialize
target.Execute().Count(); //Initialize
Assert.IsNull(result);
Assert.AreEqual(1, _loadDataCalled);
}
[TestMethod]
public void ItShouldBePossibleToAddAndGetNotExistingItem()
{
_loadDataCalled = 0;
object result = null;
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
var cr = new NodeCacheCoroutine(target);
_runner.StartCoroutine(cr);
_runner.RunCycle();
var waiter = (FluentResultBuilder)target.AddAndGet(new CacheDefinition
{
Id = "test",
LoadData = () => LoadDataWithWait(10, 5)
}, (r) =>
{
result = r;
});
_runner.StartCoroutine(waiter.AsCoroutine());
_runner.RunCycleFor(200);
Assert.AreEqual(1, _loadDataCalled);
Assert.AreEqual("RESULT", result);
}
#endregion
#region Groups Management
[TestMethod]
public void ItShouldBePossibleToAddGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddGroup(new CacheGroupDefinition
{
Id = "test",
Capped = 1000,
ExpireAfter = TimeSpan.FromMilliseconds(500),
RollingExpiration = true
});
target.Execute().Count();
Assert.AreEqual(2, target.Groups.Count);
Assert.IsTrue(target.Groups.ContainsKey("test"));
}
[TestMethod]
public void ItShouldBePossibleToAddGroupUpdatingShouldThrow()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddGroup(new CacheGroupDefinition
{
Id = "test",
Capped = 1000,
ExpireAfter = TimeSpan.FromMilliseconds(500),
RollingExpiration = true
});
target.Execute().Count();
Exception resultEx = null;
try
{
target.AddGroup(new CacheGroupDefinition
{
Id = "test",
Capped = 100,
ExpireAfter = TimeSpan.FromMilliseconds(500),
RollingExpiration = true
});
}
catch (Exception ex)
{
resultEx = ex;
}
Assert.IsNotNull(resultEx);
}
[TestMethod]
public void ItShouldBePossibleToRemoveGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddGroup(new CacheGroupDefinition
{
Id = "test",
Capped = 1000,
ExpireAfter = TimeSpan.FromMilliseconds(500),
RollingExpiration = true
});
target.Execute().Count();
Assert.AreEqual(2, target.Groups.Count);
target.RemoveGroup("test");
target.Execute().Count();
Assert.AreEqual(1, target.Groups.Count);
Assert.IsFalse(target.Groups.ContainsKey("test"));
}
[TestMethod]
public void ItShouldBePossibleToRemoveGroupNoGroupShouldDoNothing()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.RemoveGroup("notExisting");
target.Execute().Count();
Assert.AreEqual(1, target.Groups.Count);
Assert.IsFalse(target.Groups.ContainsKey("notExisting"));
}
#endregion
#region AddItem
[TestMethod]
public void ItShouldBePossibleToAddItemToSpecificGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddGroup(new CacheGroupDefinition
{
Id = "testGroup",
Capped = 1000,
ExpireAfter = TimeSpan.FromMilliseconds(500),
RollingExpiration = true
});
target.Execute().Count();
target.AddItem("testId", "testValue", "testGroup");
target.Execute().Count();
var group = target.Groups["testGroup"];
Assert.IsTrue(target.GetItems("testGroup").ContainsKey("testId"));
var item = target.GetItems("testGroup")["testId"];
Assert.AreEqual(group.ExpireAfter, item.ExpireAfter);
Assert.AreEqual("testValue", item.Value);
}
[TestMethod]
public void ItShouldBePossibleToAddItemToDefaultGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem("testId", "testValue");
target.Execute().Count();
var group = target.Groups[string.Empty];
Assert.IsTrue(target.GetItems("").ContainsKey("testId"));
var item = target.GetItems("")["testId"];
Assert.AreEqual(group.ExpireAfter, item.ExpireAfter);
Assert.AreEqual("testValue", item.Value);
}
[TestMethod]
public void ItShouldBePossibleToAddItemDuplicateShouldDoNothing()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem("testId", "testValue");
target.Execute().Count();
target.AddItem("testId", "testValueChange");
target.Execute().Count();
var item = target.GetItems("")["testId"];
Assert.AreEqual("testValue", item.Value);
}
[TestMethod]
public void ItShouldBePossibleToAddItemWithCd()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem(new CacheDefinition
{
Value = "testValue",
Id = "testId"
});
target.Execute().Count();
var group = target.Groups[string.Empty];
Assert.IsTrue(target.GetItems("").ContainsKey("testId"));
var item = target.GetItems("")["testId"];
Assert.AreEqual(group.ExpireAfter, item.ExpireAfter);
Assert.AreEqual("testValue", item.Value);
Assert.IsFalse(target.Groups.ContainsKey("test"));
}
[TestMethod]
public void ItShouldBePossibleToAddItemDuplicateShouldDoNothingWithCd()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem(new CacheDefinition
{
Value = "testValue",
Id = "testId"
});
target.Execute().Count();
target.AddItem(new CacheDefinition
{
Value = "testValueDifferent",
Id = "testId"
});
target.Execute().Count();
var item = target.GetItems("")["testId"];
Assert.AreEqual("testValue", item.Value);
}
#endregion
#region AddOrUpdateItem
[TestMethod]
public void ItShouldBePossibleToAddUpdateItemToSpecificGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddGroup(new CacheGroupDefinition
{
Id = "testGroup",
Capped = 1000,
ExpireAfter = TimeSpan.FromMilliseconds(500),
RollingExpiration = true
});
target.Execute().Count();
target.AddOrUpdateItem("testId", "testValue", "testGroup");
target.Execute().Count();
var group = target.Groups["testGroup"];
Assert.IsTrue(target.GetItems("testGroup").ContainsKey("testId"));
var item = target.GetItems("testGroup")["testId"];
Assert.AreEqual(group.ExpireAfter, item.ExpireAfter);
Assert.AreEqual("testValue", item.Value);
}
[TestMethod]
public void ItShouldBePossibleToAddUpdateItemToDefaultGroup()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddOrUpdateItem("testId", "testValue");
target.Execute().Count();
var group = target.Groups[string.Empty];
Assert.IsTrue(target.GetItems("").ContainsKey("testId"));
var item = target.GetItems("")["testId"];
Assert.AreEqual(group.ExpireAfter, item.ExpireAfter);
Assert.AreEqual("testValue", item.Value);
}
[TestMethod]
public void ItShouldBePossibleToAddUpdateItemDuplicateShouldUpdate()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem("testId", "testValue");
target.Execute().Count();
target.AddOrUpdateItem("testId", "testValueChange");
target.Execute().Count();
var item = target.GetItems("")["testId"];
Assert.AreEqual("testValueChange", item.Value);
}
[TestMethod]
public void ItShouldBePossibleToAddUpdateItemWithCd()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddOrUpdateItem(new CacheDefinition
{
Value = "testValue",
Id = "testId"
});
target.Execute().Count();
var group = target.Groups[string.Empty];
Assert.IsTrue(target.GetItems("").ContainsKey("testId"));
var item = target.GetItems("")["testId"];
Assert.AreEqual(group.ExpireAfter, item.ExpireAfter);
Assert.AreEqual("testValue", item.Value);
Assert.IsFalse(target.Groups.ContainsKey("test"));
}
[TestMethod]
public void ItShouldBePossibleToAddUpdateItemDuplicateShouldUpdateCd()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem(new CacheDefinition
{
Value = "testValue",
Id = "testId"
});
target.Execute().Count();
target.AddOrUpdateItem(new CacheDefinition
{
Value = "testValueDifferent",
Id = "testId"
});
target.Execute().Count();
var item = target.GetItems("")["testId"];
Assert.AreEqual("testValueDifferent", item.Value);
}
#endregion
#region InvalidateItem
[TestMethod]
public void ItShouldBePossibleToInvalidateItem()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem("testId", "testValue");
target.Execute().Count();
target.InvalidateItem("testId");
target.Execute().Count();
Assert.IsFalse(target.GetItems("").ContainsKey("testId"));
}
[TestMethod]
public void ItShouldBePossibleToInvalidateItemNoItemShouldDoNothing()
{
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.InvalidateItem("testId");
target.Execute().Count();
Assert.IsFalse(target.GetItems("").ContainsKey("testId"));
}
#endregion
#region AddAndGet
private int ExecuteEnumerator(IEnumerator enumerator)
{
var result = 0;
while (enumerator.MoveNext())
{
result++;
}
return result;
}
private int _loadDataCalled = 0;
private static RunnerForTest _runner;
private IEnumerable<ICoroutineResult> LoadDataWithWait(int waitCycleMs, int times)
{
_loadDataCalled++;
while (times > 0)
{
Thread.Sleep(waitCycleMs);
yield return CoroutineResult.Wait;
times--;
}
yield return CoroutineResult.Return("RESULT");
}
private IEnumerable<ICoroutineResult> LoadData(int times, string returns = "RESULT")
{
_loadDataCalled++;
while (times > 0)
{
yield return CoroutineResult.Wait;
times--;
}
yield return CoroutineResult.Return(returns);
}
[TestMethod]
public void OverlappingRequestWillNotInvokeTwiceTheLoadDataButWillHaveTheSameResult()
{
_loadDataCalled = 0;
object result1 = null;
object result2 = null;
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
_runner.StartCoroutine(new NodeCacheCoroutine(target));
_runner.RunCycle(); //Initialize node cache coroutine
var waiter1 = (FluentResultBuilder)target.AddAndGet(new CacheDefinition
{
Id = "test",
LoadData = () => LoadData(5)
}, (r) =>
{
result1 = r;
});
_runner.StartCoroutine(waiter1.AsCoroutine());
var waiter2 = (FluentResultBuilder)target.AddAndGet(new CacheDefinition
{
Id = "test",
LoadData = () => LoadData(5, "ANOTHER THING"),
ExpireAfter = TimeSpan.FromMinutes(5)
}, (r) =>
{
result2 = r;
});
_runner.StartCoroutine(waiter2.AsCoroutine());
_runner.RunCycle(); //Load the coroutines
_runner.RunCycle(); //Start the coroutines methods
_runner.RunCycle(5); //Wait for completion
_runner.RunCycle(); //Copy the data
Assert.AreEqual(1, _loadDataCalled);
Assert.AreEqual("RESULT", result1, "Result 1 is " + result1);
Assert.AreEqual("RESULT", result2, "Result 2 is " + result1);
}
[TestMethod]
public void ItShouldBePossibleToAddAndGetAnAlreadyExistingItem()
{
_loadDataCalled = 0;
object result = null;
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
target.AddItem("test", "RESULT");
_runner.StartCoroutine(new NodeCacheCoroutine(target));
_runner.RunCycle(); //Initialize node cache coroutine
var waiter = (FluentResultBuilder)target.AddAndGet(new CacheDefinition
{
Id = "test",
LoadData = () => LoadData(5),
ExpireAfter = TimeSpan.FromMinutes(1)
}, (r) =>
{
result = r;
});
_runner.StartCoroutine(waiter.AsCoroutine());
//target.Execute().Count(); //Initialize
_runner.RunCycle();
Assert.AreEqual("RESULT", result);
Assert.AreEqual(0, _loadDataCalled);
}
[TestMethod]
public void AddAndGetNonExistingItemWithTimeoutWillNotSetTheValue()
{
_loadDataCalled = 0;
object result = null;
var target = new NodeCache(_runner,TimeSpan.FromSeconds(10));
var waiter = (FluentResultBuilder)target.AddAndGet(new CacheDefinition
{
Id = "test",
LoadData = () => LoadData(20)
}, (r) => result = r);
target.Execute().Count(); //Initialize
//Fun the getter function
_runner.RunCycle(6);
target.Execute().Count(); //Initialize
target.Execute().Count(); //Initialize
//ExecuteEnumerator(waiter.NestedEnumerator);
Assert.IsNull(result);
Assert.AreEqual(1, _loadDataCalled);
}
#endregion
/*
ItShouldBePossibleToAddAnItemWithLoadItem
ItShouldBePossibleToAddAnItemWithLoadItemOverlappingButCallingTheRequestOnlyOnce
ItShouldBePossibleToAddAndGet
ItShouldBePossibleToAddAndGetWithTimeoutThatShouldDoNothing
ItShouldBePossibleToAddAndGetNoItemShouldDoNothing
ItShouldBePossibleToAddAndGetWithCd
ItShouldBePossibleToAddAndGetWithTimeoutThatShouldDoNothingWithCd
ItShouldBePossibleToAddAndGetNoItemShouldDoNothingWithCd
ItShouldBePossibleToAddOrUpdateAndGetAdding
ItShouldBePossibleToAddOrUpdateAndGetUpdating
ItShouldBePossibleToAddOrUpdateAndGetAddingWithCd
ItShouldBePossibleToAddOrUpdateAndGetUpdatingWithCd
ItShouldBePossibleToGetAnItem
ItShouldBePossibleToGetAnItemNoItemShouldDoNothing
ItShouldBePossibleToInvalidateGroup
ItShouldBePossibleToInvalidateGroupNoGroupShouldDoNothing
ItemsWithoutValueShouldBePurged
ItemsTimeoutedShouldBePurged
ReachingTheCappedLimitItemsShouldBePurged
*/
//Should test that the correct expiration is set...
//Adding an item contextually with the group
// ReSharper restore ReturnValueOfPureMethodIsNotUsed
}
}
| |
//
// Copyright 2012-2013, Xamarin 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 Android.App;
using Android.Net.Http;
using Android.Webkit;
using Android.OS;
using System.Threading.Tasks;
using Xamarin.Utilities.Android;
namespace Xamarin.Auth
{
[Activity (Label = "Web Authenticator")]
#if XAMARIN_AUTH_INTERNAL
internal class WebAuthenticatorActivity : Activity
#else
public class WebAuthenticatorActivity : Activity
#endif
{
WebView webView;
internal class State : Java.Lang.Object
{
public WebAuthenticator Authenticator;
}
internal static readonly ActivityStateRepository<State> StateRepo = new ActivityStateRepository<State> ();
State state;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
//
// Load the state either from a configuration change or from the intent.
//
state = LastNonConfigurationInstance as State;
if (state == null && Intent.HasExtra ("StateKey")) {
var stateKey = Intent.GetStringExtra ("StateKey");
state = StateRepo.Remove (stateKey);
}
if (state == null) {
Finish ();
return;
}
Title = state.Authenticator.Title;
//
// Watch for completion
//
state.Authenticator.Completed += (s, e) => {
SetResult (e.IsAuthenticated ? Result.Ok : Result.Canceled);
Finish ();
};
state.Authenticator.Error += (s, e) => {
if (e.Exception != null) {
this.ShowError ("Authentication Error", e.Exception);
}
else {
this.ShowError ("Authentication Error", e.Message);
}
BeginLoadingInitialUrl ();
};
//
// Build the UI
//
webView = new WebView (this) {
Id = 42,
};
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient (new Client (this));
SetContentView (webView);
//
// Restore the UI state or start over
//
if (savedInstanceState != null) {
webView.RestoreState (savedInstanceState);
}
else {
if (Intent.GetBooleanExtra ("ClearCookies", true))
WebAuthenticator.ClearCookies();
BeginLoadingInitialUrl ();
}
}
void BeginLoadingInitialUrl ()
{
state.Authenticator.GetInitialUrlAsync ().ContinueWith (t => {
if (t.IsFaulted) {
this.ShowError ("Authentication Error", t.Exception);
}
else {
webView.LoadUrl (t.Result.AbsoluteUri);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
public override void OnBackPressed ()
{
if (state.Authenticator.AllowCancel)
{
state.Authenticator.OnCancelled ();
}
}
public override Java.Lang.Object OnRetainNonConfigurationInstance ()
{
return state;
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState (outState);
webView.SaveState (outState);
}
void BeginProgress (string message)
{
webView.Enabled = false;
}
void EndProgress ()
{
webView.Enabled = true;
}
class Client : WebViewClient
{
WebAuthenticatorActivity activity;
HashSet<SslCertificate> sslContinue;
Dictionary<SslCertificate, List<SslErrorHandler>> inProgress;
public Client (WebAuthenticatorActivity activity)
{
this.activity = activity;
}
public override bool ShouldOverrideUrlLoading (WebView view, string url)
{
return false;
}
public override void OnPageStarted (WebView view, string url, Android.Graphics.Bitmap favicon)
{
var uri = new Uri (url);
activity.state.Authenticator.OnPageLoading (uri);
activity.BeginProgress (uri.Authority);
}
public override void OnPageFinished (WebView view, string url)
{
var uri = new Uri (url);
activity.state.Authenticator.OnPageLoaded (uri);
activity.EndProgress ();
}
class SslCertificateEqualityComparer
: IEqualityComparer<SslCertificate>
{
public bool Equals (SslCertificate x, SslCertificate y)
{
return Equals (x.IssuedTo, y.IssuedTo) && Equals (x.IssuedBy, y.IssuedBy) && x.ValidNotBeforeDate.Equals (y.ValidNotBeforeDate) && x.ValidNotAfterDate.Equals (y.ValidNotAfterDate);
}
bool Equals (SslCertificate.DName x, SslCertificate.DName y)
{
if (ReferenceEquals (x, y))
return true;
if (ReferenceEquals (x, y) || ReferenceEquals (null, y))
return false;
return x.GetDName().Equals (y.GetDName());
}
public int GetHashCode (SslCertificate obj)
{
unchecked {
int hashCode = GetHashCode (obj.IssuedTo);
hashCode = (hashCode * 397) ^ GetHashCode (obj.IssuedBy);
hashCode = (hashCode * 397) ^ obj.ValidNotBeforeDate.GetHashCode();
hashCode = (hashCode * 397) ^ obj.ValidNotAfterDate.GetHashCode();
return hashCode;
}
}
int GetHashCode (SslCertificate.DName dname)
{
return dname.GetDName().GetHashCode();
}
}
public override void OnReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
{
if (sslContinue == null) {
var certComparer = new SslCertificateEqualityComparer();
sslContinue = new HashSet<SslCertificate> (certComparer);
inProgress = new Dictionary<SslCertificate, List<SslErrorHandler>> (certComparer);
}
List<SslErrorHandler> handlers;
if (inProgress.TryGetValue (error.Certificate, out handlers)) {
handlers.Add (handler);
return;
}
if (sslContinue.Contains (error.Certificate)) {
handler.Proceed();
return;
}
inProgress[error.Certificate] = new List<SslErrorHandler>();
AlertDialog.Builder builder = new AlertDialog.Builder (this.activity);
builder.SetTitle ("Security warning");
builder.SetIcon (Android.Resource.Drawable.IcDialogAlert);
builder.SetMessage ("There are problems with the security certificate for this site.");
builder.SetNegativeButton ("Go back", (sender, args) => {
UpdateInProgressHandlers (error.Certificate, h => h.Cancel());
handler.Cancel();
});
builder.SetPositiveButton ("Continue", (sender, args) => {
sslContinue.Add (error.Certificate);
UpdateInProgressHandlers (error.Certificate, h => h.Proceed());
handler.Proceed();
});
builder.Create().Show();
}
void UpdateInProgressHandlers (SslCertificate certificate, Action<SslErrorHandler> update)
{
List<SslErrorHandler> inProgressHandlers;
if (!this.inProgress.TryGetValue (certificate, out inProgressHandlers))
return;
foreach (SslErrorHandler sslErrorHandler in inProgressHandlers)
update (sslErrorHandler);
inProgressHandlers.Clear();
}
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) Rick Brewster, Tom Jackson, and past contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
/////////////////////////////////////////////////////////////////////////////////
using System;
using Cairo;
namespace Pinta.Core
{
/// <summary>
/// Histogram is used to calculate a histogram for a surface (in a selection,
/// if desired). This can then be used to retrieve percentile, average, peak,
/// and distribution information.
/// </summary>
public abstract class Histogram
{
protected long[][] histogram;
public long[][] HistogramValues
{
get
{
return this.histogram;
}
set
{
if (value.Length == this.histogram.Length && value[0].Length == this.histogram[0].Length)
{
this.histogram = value;
OnHistogramUpdated();
}
else
{
throw new ArgumentException("value muse be an array of arrays of matching size", "value");
}
}
}
public int Channels
{
get
{
return this.histogram.Length;
}
}
public int Entries
{
get
{
return this.histogram[0].Length;
}
}
protected internal Histogram(int channels, int entries)
{
this.histogram = new long[channels][];
for (int channel = 0; channel < channels; ++channel)
{
this.histogram[channel] = new long[entries];
}
}
public event EventHandler HistogramChanged;
protected void OnHistogramUpdated()
{
if (HistogramChanged != null)
{
HistogramChanged(this, EventArgs.Empty);
}
}
protected ColorBgra[] visualColors;
public ColorBgra GetVisualColor(int channel)
{
return visualColors[channel];
}
public long GetOccurrences(int channel, int val)
{
return histogram[channel][val];
}
public long GetMax()
{
long max = -1;
foreach (long[] channelHistogram in histogram)
{
foreach (long i in channelHistogram)
{
if (i > max)
{
max = i;
}
}
}
return max;
}
public long GetMax(int channel)
{
long max = -1;
foreach (long i in histogram[channel])
{
if (i > max)
{
max = i;
}
}
return max;
}
public float[] GetMean()
{
float[] ret = new float[Channels];
for (int channel = 0; channel < Channels; ++channel)
{
long[] channelHistogram = histogram[channel];
long avg = 0;
long sum = 0;
for (int j = 0; j < channelHistogram.Length; j++)
{
avg += j * channelHistogram[j];
sum += channelHistogram[j];
}
if (sum != 0)
{
ret[channel] = (float)avg / (float)sum;
}
else
{
ret[channel] = 0;
}
}
return ret;
}
public int[] GetPercentile(float fraction)
{
int[] ret = new int[Channels];
for (int channel = 0; channel < Channels; ++channel)
{
long[] channelHistogram = histogram[channel];
long integral = 0;
long sum = 0;
for (int j = 0; j < channelHistogram.Length; j++)
{
sum += channelHistogram[j];
}
for (int j = 0; j < channelHistogram.Length; j++)
{
integral += channelHistogram[j];
if (integral > sum * fraction)
{
ret[channel] = j;
break;
}
}
}
return ret;
}
public abstract ColorBgra GetMeanColor();
public abstract ColorBgra GetPercentileColor(float fraction);
/// <summary>
/// Sets the histogram to be all zeros.
/// </summary>
protected void Clear()
{
histogram.Initialize();
}
protected abstract void AddSurfaceRectangleToHistogram(ImageSurface surface, Gdk.Rectangle rect);
//public void UpdateHistogram(Surface surface)
//{
// Clear();
// AddSurfaceRectangleToHistogram(surface, surface.Bounds);
// OnHistogramUpdated();
//}
public void UpdateHistogram (ImageSurface surface, Gdk.Rectangle rect)
{
Clear();
AddSurfaceRectangleToHistogram(surface, rect);
OnHistogramUpdated();
}
//public void UpdateHistogram(Surface surface, PdnRegion roi)
//{
// Clear();
// foreach (Rectangle rect in roi.GetRegionScansReadOnlyInt())
// {
// AddSurfaceRectangleToHistogram(surface, rect);
// }
// OnHistogramUpdated();
//}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
{
#region Static Members
[System.Security.SecurityCritical] // auto-generated
internal static DelegateEntry GetDelegateSerializationInfo(
SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
{
// Used for MulticastDelegate
if (method == null)
throw new ArgumentNullException("method");
Contract.EndContractBlock();
if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
if (method.DeclaringType == null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
if (info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
info.AddValue("Delegate",de,typeof(DelegateEntry));
}
// target can be an object so it needs to be added to the info, or else a fixup is needed
// when deserializing, and the fixup will occur too late. If it is added directly to the
// info then the rules of deserialization will guarantee that it will be available when
// needed
if (target != null)
{
String targetName = "target" + targetIndex;
info.AddValue(targetName, de.target);
de.target = targetName;
}
// Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
// first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
// get this by serializing the target MethodInfo. We still need to send the same information as before though (the
// DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
// ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
// order of deserialization guarantee otherwise.
String methodInfoName = "method" + targetIndex;
info.AddValue(methodInfoName, method);
return de;
}
#endregion
#region Definitions
[Serializable]
internal class DelegateEntry
{
#region Internal Data Members
internal String type;
internal String assembly;
internal Object target;
internal String targetTypeAssembly;
internal String targetTypeName;
internal String methodName;
internal DelegateEntry delegateEntry;
#endregion
#region Constructor
internal DelegateEntry(
String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName)
{
this.type = type;
this.assembly = assembly;
this.target = target;
this.targetTypeAssembly = targetTypeAssembly;
this.targetTypeName = targetTypeName;
this.methodName = methodName;
}
#endregion
#region Internal Members
internal DelegateEntry Entry
{
get { return delegateEntry; }
set { delegateEntry = value; }
}
#endregion
}
#endregion
#region Private Data Members
private DelegateEntry m_delegateEntry;
private MethodInfo[] m_methods;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
bool bNewWire = true;
try
{
m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
}
catch
{
// Old wire format
m_delegateEntry = OldDelegateWireFormat(info, context);
bNewWire = false;
}
if (bNewWire)
{
// retrieve the targets
DelegateEntry deiter = m_delegateEntry;
int count = 0;
while (deiter != null)
{
if (deiter.target != null)
{
string stringTarget = deiter.target as string; //need test to pass older wire format
if (stringTarget != null)
deiter.target = info.GetValue(stringTarget, typeof(Object));
}
count++;
deiter = deiter.delegateEntry;
}
// If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
// them into an ordered array if present.
MethodInfo[] methods = new MethodInfo[count];
int i;
for (i = 0; i < count; i++)
{
String methodInfoName = "method" + i;
methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
if (methods[i] == null)
break;
}
// If we got the info then make the array available for deserialization.
if (i == count)
m_methods = methods;
}
}
#endregion
#region Private Members
private void ThrowInsufficientState(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
String delegateType = info.GetString("DelegateType");
String delegateAssembly = info.GetString("DelegateAssembly");
Object target = info.GetValue("Target", typeof(Object));
String targetTypeAssembly = info.GetString("TargetTypeAssembly");
String targetTypeName = info.GetString("TargetTypeName");
String methodName = info.GetString("MethodName");
return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
}
[System.Security.SecurityCritical]
private Delegate GetDelegate(DelegateEntry de, int index)
{
Delegate d;
try
{
if (de.methodName == null || de.methodName.Length == 0)
ThrowInsufficientState("MethodName");
if (de.assembly == null || de.assembly.Length == 0)
ThrowInsufficientState("DelegateAssembly");
if (de.targetTypeName == null || de.targetTypeName.Length == 0)
ThrowInsufficientState("TargetTypeName");
// We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
// If we received the new style delegate encoding we already have the target MethodInfo in hand.
if (m_methods != null)
{
#if FEATURE_REMOTING
Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
#else
if(!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
Object target=de.target;
#endif
d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
}
else
{
if (de.target != null)
#if FEATURE_REMOTING
d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
#else
{
if(!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
d = Delegate.CreateDelegate(type, de.target, de.methodName);
}
#endif
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
}
if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
catch (Exception e)
{
if (e is SerializationException)
throw e;
throw new SerializationException(e.Message, e);
}
return d;
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
int count = 0;
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
count++;
int maxindex = count - 1;
if (count == 1)
{
return GetDelegate(m_delegateEntry, 0);
}
else
{
object[] invocationList = new object[count];
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
{
// Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
// the order we process the entries: we're actually looking at them in reverse order.
--count;
invocationList[count] = GetDelegate(de, maxindex - count);
}
return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length);
}
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using LogShark.Shared.LogReading.Containers;
using LogShark.Shared.LogReading.Readers;
namespace LogShark.Shared.LogReading
{
public class LogTypeDetails : ILogTypeDetails
{
private readonly Dictionary<LogType, LogTypeInfo> _logFileInfoDictionary;
public LogTypeDetails(IProcessingNotificationsCollector processingNotificationsCollector)
{
_logFileInfoDictionary = LoadDetails(processingNotificationsCollector)
.ToDictionary(logTypeInfo => logTypeInfo.LogType, logTypeInfo => logTypeInfo);
}
public LogTypeInfo GetInfoForLogType(LogType logType)
{
return _logFileInfoDictionary[logType];
}
public static IEnumerable<Regex> GetAllKnownLogFileLocations()
{
return LoadDetails(null) // null is fine here, as we never call factory methods than use this parameter
.Where(logTypeInfo => logTypeInfo.LogType != LogType.CrashPackageLog &&
logTypeInfo.LogType != LogType.CrashPackageManifest)
.SelectMany(logTypeInfo => logTypeInfo.FileLocations);
}
private static IEnumerable<LogTypeInfo> LoadDetails(IProcessingNotificationsCollector processingNotificationsCollector)
{
return new List<LogTypeInfo>
{
new LogTypeInfo(
logType: LogType.Apache,
logReaderProvider: (stream, filePath) => new SimpleLinePerLineReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("httpd", "access"), // pre-TSM - httpd/access.*.log (access.2015_05_18_00_00_00.log)
TsmV0Log("httpd" , "access"), // TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\httpd\access.2018_08_08_00_00_00.log
TsmLog("gateway" , "access"), // TSM - node2\gateway_0.20182.18.0627.22308342643935754496180\logs\access.2018_08_08_00_00_00.log
}),
new LogTypeInfo(
logType: LogType.BackgrounderCpp,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
TabadminNativeLog("backgrounder"), // pre-TSM - vizqlserver\Logs\backgrounder-0_2018_07_28_00_00_00.txt
TsmV0NativeLog("backgrounder"), // TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\backgrounder\nativeapi_backgrounder_1-0_2018_08_07_00_00_00.txt
TsmNativeLog("backgrounder"), // TSM - node2\backgrounder_0.20182.18.0627.22306436150448756480580\logs\nativeapi_backgrounder_2-1_2018_08_08_00_00_00.txt
}),
new LogTypeInfo(
logType: LogType.BackgrounderJava,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("backgrounder"), // pre-TSM - backgrounder/backgrounder-*.log with optional date at the end (backgrounder-0.log.2015-05-18)
TsmV0Log("backgrounder"), // TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\backgrounder\backgrounder_node1-1.log
TsmLog("backgrounder"), // TSM - node2\backgrounder_0.20182.18.0627.22306436150448756480580\logs\backgrounder_node2-1.log.2018-08-08
}),
new LogTypeInfo(
logType: LogType.ClusterController,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("clustercontroller"), // pre-TSM - clustercontroller/clustercontroller.log.2015-05-18
TsmV0Log("clustercontroller"), // TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\clustercontroller\clustercontroller.log
TsmLog("clustercontroller"), // TSM - node2\clustercontroller_0.20182.18.0627.22301467407848617992908\logs\clustercontroller.log
}),
new LogTypeInfo(
logType: LogType.ControlLogsJava,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
// Control logs are placed in the logs folder of the component they control, so dir can be anything
TsmLog("[^/]+", "control"), // node1/tabadminagent_0.20202.20.0818.08576654979113587254208/logs/control_tabadminagent_node1-0.log.2020-09-27
}),
new LogTypeInfo(
logType: LogType.CrashPackageLog,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
Regex(@"^[^/]*\.log$"),
Regex(@"^[^/]*\.txt$")
}),
new LogTypeInfo(
logType: LogType.CrashPackageManifest,
logReaderProvider: (stream, filePath) => new SimpleLinePerLineReader(stream),
fileLocations: new List<Regex>
{
Regex(@"^[^/]*\.manifest$")
}),
new LogTypeInfo(
logType: LogType.DataserverCpp,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
TabadminNativeLog("dataserver"), // pre-TSM - vizqlserver\Logs\dataserver-0_2018_07_28_00_00_00.txt
TsmV0NativeLog("dataserver"), // TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\dataserver\nativeapi_dataserver_1-0_2018_08_07_00_00_00.txt
TsmNativeLog("dataserver"), // TSM - node2\dataserver_0.20182.18.0627.22301765668120146669553\logs\nativeapi_dataserver_2-1_2018_08_08_00_00_00.txt
}),
new LogTypeInfo(
logType: LogType.DataserverJava,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("dataserver"),
TsmV0Log("dataserver"),
TsmLog("dataserver")
}),
new LogTypeInfo(
logType: LogType.Filestore,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("filestore"), // pre-TSM - filestore/filestore.log.2018-07-31
TsmV0Log("filestore"), // TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\filestore\filestore.log
TsmLog("filestore"), // TSM - node1\filestore_0.20182.18.0627.22302895224363938766334\logs\filestore.log
}),
new LogTypeInfo(
logType: LogType.Hyper,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
TabadminLog("hyper"), // pre-TSM - hyper/hyper_2018_07_19_22_24_32.log
TsmV0Log("hyper"), // TSMv0 - localhost\tabadminagent_0.20181.18.0510.1418770265691097820228\logs\hyper\hyper_0_2018_07_30_08_08_24.log
TsmLog("hyper"), // TSM - node2\hyper_0.20182.18.0627.22308540150062437331610\logs\hyper_0_2018_08_08_15_07_26.log
}),
new LogTypeInfo(
logType: LogType.NetstatLinux,
logReaderProvider: (stream, filePath) => new SimpleLinePerLineReader(stream),
fileLocations: new List<Regex>
{
Regex(@".+/netstat-anp\.txt$") // TSMv0 and TSM - (TSMv0 example: localhost\tabadminagent_0.20181.18.0510.1418770265691097820228\sysinfo\netstat-anp.txt)
}),
new LogTypeInfo(
logType: LogType.NetstatWindows,
logReaderProvider: (stream, filePath) => new NetstatWindowsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
Regex(@"netstat-info\.txt$"), // pre-TSM - netstat-info.txt in the root
Regex(@"/netstat-info\.txt$") // TSM - node1\tabadminagent_0.20182.18.1001.21153436271280456730793\netstat-info.txt
}),
new LogTypeInfo(
logType: LogType.PostgresCsv,
logReaderProvider: (stream, filePath) => new CsvLogReader<PostgresCsvMapping>(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
TabadminLog("pgsql", "postgresql", "csv"), // pre-TSM - pgsql/postgresql-Sat.csv
TsmV0Log("pgsql", "postgresql", "csv"), // TSMv0 - localhost\tabadminagent_0.20181.18.0510.1418770265691097820228\logs\pgsql\postgresql-Mon.csv
TsmLog("pgsql", "postgresql", "csv"), // TSM - node2\pgsql_0.20182.18.0627.22303045353787439845635\logs\postgresql-Wed.csv
}),
new LogTypeInfo(
logType: LogType.ProtocolServer,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
Regex(@"^tabprotosrv.*\.txt"), // Desktop, zipped files
Regex(@"^[Ll]ogs\tabprotosrv.*\.txt"), // Desktop, zipped Logs folder
TabadminLog("vizqlserver", "tabprotosrv", "txt"), // pre-TSM - vizqlserver\tabprotosrv_vizqlserver_0-0_1.txt
TsmV0ProtocolLog("backgrounder"), // TSMv0 - Backgrounder - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\backgrounder\tabprotosrv_backgrounder_1-0.txt
TsmV0ProtocolLog("dataserver"), // TSMv0 - Dataserver
TsmV0ProtocolLog("vizportal"), // TSMv0 - Vizportal - localhost\tabadminagent_0.20181.18.0510.14183743094502915100234\logs\vizportal\tabprotosrv_vizportal_2-0.txt
TsmV0ProtocolLog("vizqlserver"), // TSMv0 - Vizqlserver - locahost\tabadminagent_0.20181.18.0510.14183743094502915100234\logs\vizqlserver\tabprotosrv_vizqlserver_2-0.txt
TsmProtocolLog("backgrounder"), // TSM - Backgrounder - node2\backgrounder_0.20182.18.0627.22306436150448756480580\logs\tabprotosrv_backgrounder_2-0.txt
TsmProtocolLog("dataserver"), // TSM - Dataserver
TsmProtocolLog("vizportal"), // TSM - Vizportal - node1\vizportal_0.20182.18.0627.22304211226147125020104\logs\tabprotosrv_vizportal_1-0.txt
TsmProtocolLog("vizqlserver"), // TSM - Vizqlserver - node1\vizqlserver_0.20182.18.0627.22305268092790927660381\logs\tabprotosrv_vizqlserver_1-1.txt
}),
new LogTypeInfo(
logType: LogType.SearchServer,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("searchserver"), // pre-TSM - searchserver/searchserver-0.log.2018-07-19
TsmV0Log("searchserver"), // TSMv0 - localhost\tabadminagent_0.20181.18.0510.1418770265691097820228\logs\searchserver\searchserver_node1-0.log.2018-07-30
TsmLog("searchserver"), // TSM - node1\searchserver_0.20182.18.0627.22308531537836253176995\logs\searchserver_node1-0.log
}),
new LogTypeInfo(
logType: LogType.Tabadmin,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
Regex(@"logs/tabadmin\.log"), // pre-TSM - logs/tabadmin.log
Regex(@"tabadmin/tabadmin.*\.log.*") // pre-TSM
}),
new LogTypeInfo(
logType: LogType.TabadminAgentJava,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TsmLog("tabadminagent", "tabadminagent_node") // node1/tabadminagent_0.20202.20.0818.08576654979113587254208/logs/tabadminagent_node1-0.log.2020-09-26
}),
new LogTypeInfo(
logType: LogType.TabadminControllerJava,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TsmLog("tabadmincontroller") // node1/tabadmincontroller_0.20201.20.0913.21097164108816806990865/logs/tabadmincontroller_node1-0.log
}),
new LogTypeInfo(
logType: LogType.TabsvcYml,
logReaderProvider: (stream, filePath) => new YamlConfigLogReader(stream),
fileLocations: new List<Regex>
{
Regex(@"^tabsvc\.yml$"), // pre-TSM - tabsvc.yml in the root of the archive
// TSMv0 doesn't include config info
Regex(@"config/tabadminagent[^/]+/tabsvc\.yml$") // TSM - node1\tabadminagent_0.20182.18.1001.21153436271280456730793\config\tabadminagent_0.20182.18.1001.2115\tabsvc.yml
}),
new LogTypeInfo(
logType: LogType.VizportalCpp,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
TabadminNativeLog("vizportal"), // pre-TSM - vizqlserver\Logs\vizportal_0-0_2018_08_01_00_00_00.txt
TsmV0NativeLog("vizportal"), // TSMv0 - localhost\tabadminagent_0.20181.18.0510.14183743094502915100234\logs\vizportal\nativeapi_vizportal_2-0_2018_07_31_00_00_00.txt
TsmNativeLog("vizportal"), // TSM - node1\vizportal_0.20182.18.0627.22304211226147125020104\logs\nativeapi_vizportal_1-0_2018_08_08_00_00_00.txt
}),
new LogTypeInfo(
logType: LogType.VizportalJava,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("vizportal"), // pre-TSM - vizportal/vizportal-0.log.2018-07-22
TsmV0Log("vizportal"), // TSMv0 - localhost\tabadminagent_0.20181.18.0510.14183743094502915100234\logs\vizportal\vizportal_node2-0.log.2018-07-30
TsmLog("vizportal"), // TSM - node1\vizportal_0.20182.18.0627.22304211226147125020104\logs\vizportal_node1-0.log
}),
new LogTypeInfo(
logType: LogType.VizqlserverCpp,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
TabadminNativeLog("vizqlserver"), // pre-TSM
TsmV0NativeLog("vizqlserver"), // TSMv0 - locahost\tabadminagent_0.20181.18.0510.14183743094502915100234\logs\vizqlserver\nativeapi_vizqlserver_2-1_2018_07_30_00_00_00.txt
TsmNativeLog("vizqlserver"), // TSM - node2\vizqlserver_0.20182.18.0627.22306727828712986214311\logs\nativeapi_vizqlserver_2-0_2018_08_08_00_00_00.txt
}),
new LogTypeInfo(
logType: LogType.VizqlDesktop,
logReaderProvider: (stream, filePath) => new NativeJsonLogsReader(stream, filePath, processingNotificationsCollector),
fileLocations: new List<Regex>
{
Regex(@"^log[^/]*\.txt"), // If somebody zipped files, log files are in root
Regex(@"^[Ll]ogs/log.*\.txt"), // If somebody zipped whole Logs folder
}),
new LogTypeInfo(
logType: LogType.WorkgroupYml,
logReaderProvider: (stream, filePath) => new YamlConfigLogReader(stream),
fileLocations: new List<Regex>
{
Regex(@"config/workgroup\.yml$"), // pre-TSM & TSM. Pre TSM - config folder is at the root. TSM - node1\tabadminagent_0.20182.18.1001.21153436271280456730793\config\tabadminagent_0.20182.18.1001.2115\workgroup.yml
// TSMv0 doesn't include config info
Regex(@"config/tabadminagent[^/]+/workgroup\.yml$") // TSM - node1\tabadminagent_0.20182.18.1001.21153436271280456730793\config\tabadminagent_0.20182.18.1001.2115\workgroup.yml
}),
new LogTypeInfo(
logType: LogType.Zookeeper,
logReaderProvider: (stream, _) => new MultilineJavaLogReader(stream),
fileLocations: new List<Regex>
{
TabadminLog("zookeeper"), // pre-TSM - zookeeper/zookeeper-0.log.2018-07-19
TsmV0Log("appzookeeper"),// TSMv0 - localhost\tabadminagent_0.20181.18.0404.16052600117725665315795\logs\appzookeeper\appzookeeper_node1-0.log
TsmLog("appzookeeper"), // TSM - node1\appzookeeper_1.20182.18.0627.22308155521326766729002\logs\appzookeeper_node1-0.log.2018-08-08
}),
};
}
private static Regex Regex(string pattern)
{
return new Regex(pattern, RegexOptions.Compiled);
}
private static Regex TabadminLog(string dir, string fileName = null, string extension = "log")
{
const string pattern = @"{0}/{1}.*\.{2}";
return Regex(string.Format(pattern, dir, fileName ?? dir, extension));
}
private static Regex TabadminNativeLog(string name)
{
return TabadminLog("vizqlserver/Logs", name, "txt");
}
private static Regex TsmV0Log(string dir, string fileName = null, string extension = "log")
{
const string pattern = @"[^/]+/tabadminagent[^/]*/logs/{0}/{1}.*\.{2}";
return Regex(string.Format(pattern, dir, fileName ?? dir, extension));
}
private static Regex TsmV0NativeLog(string name)
{
return TsmV0Log(name, "nativeapi_" + name, "txt");
}
private static Regex TsmV0ProtocolLog(string name)
{
return TsmV0Log(name, "tabprotosrv_" + name, "txt");
}
private static Regex TsmLog(string dir, string fileName = null, string extension = "log")
{
const string pattern = @"/{0}[^/]*/logs/{1}.*\.{2}";
return Regex(string.Format(pattern, dir, fileName ?? dir, extension));
}
private static Regex TsmNativeLog(string name)
{
return TsmLog(name, "nativeapi_" + name, "txt");
}
private static Regex TsmProtocolLog(string name)
{
return TsmLog(name, "tabprotosrv_" + name, "txt");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.MirrorSequences
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// A sample API that uses a petstore as an example to demonstrate
/// features in the swagger-2.0 specification
/// </summary>
public partial class SequenceRequestResponseTest : ServiceClient<SequenceRequestResponseTest>, ISequenceRequestResponseTest
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
public SequenceRequestResponseTest() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://petstore.swagger.wordnik.com/api");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
}
/// <summary>
/// Creates a new pet in the store. Duplicates are allowed
/// </summary>
/// <param name='pets'>
/// Pets to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<Pet>>> AddPetWithHttpMessagesAsync(IList<Pet> pets, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (pets == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pets");
}
if (pets != null)
{
foreach (var element in pets)
{
if (element != null)
{
element.Validate();
}
}
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("pets", pets);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "AddPet", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
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 = JsonConvert.SerializeObject(pets, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel errorBody = JsonConvert.DeserializeObject<ErrorModel>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<Pet>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<Pet>>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Adds new pet stylesin the store. Duplicates are allowed
/// </summary>
/// <param name='petStyle'>
/// Pet style to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<int?>>> AddPetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (petStyle == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "petStyle");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petStyle", petStyle);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "AddPetStyles", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
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 = JsonConvert.SerializeObject(petStyle, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
IList<ErrorModel> errorBody = JsonConvert.DeserializeObject<IList<ErrorModel>>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<int?>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<int?>>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Updates new pet stylesin the store. Duplicates are allowed
/// </summary>
/// <param name='petStyle'>
/// Pet style to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<int?>>> UpdatePetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (petStyle == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "petStyle");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petStyle", petStyle);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "UpdatePetStyles", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
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 = JsonConvert.SerializeObject(petStyle, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
IList<ErrorModel> errorBody = JsonConvert.DeserializeObject<IList<ErrorModel>>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<int?>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<int?>>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing.Printing;
using System.Reflection;
using C1.Win.C1Preview;
using C1.C1Report;
using PCSUtils.Framework.ReportFrame;
using PCSUtils.Utils;
using C1PrintPreviewDialog = PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog;
namespace SaleByCustomerReport
{
public class SaleByCustomerReport : MarshalByRefObject, IDynamicReport
{
#region IDynamicReport Members
private string mConnectionString;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
private ReportBuilder mReportBuilder;
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
private C1PrintPreviewControl mViewer;
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mViewer; }
set { mViewer = value; }
}
private object mResult;
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
private bool mUseEngine;
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport
/// or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseEngine; }
set { mUseEngine = value; }
}
private string mReportFolder;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mReportFolder; }
set { mReportFolder = value; }
}
private string mLayoutFile;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get { return mLayoutFile; }
set { mLayoutFile = value; }
}
/// <summary>
///
/// </summary>
/// <param name="pstrMethod">name of the method to call (which declare in the DynamicReport C# file)</param>
/// <param name="pobjParameters">Array of parameters provide to call the Method with method name = pstrMethod</param>
/// <returns></returns>
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
#endregion
public DataTable ExecuteReport(string pstrCCNID, string pstrFromDate, string pstrToDate, string pstrTypeCode, string pstrCustomerID, string pstrMakeItem)
{
int intMakeItem = -1;
if (pstrMakeItem != null && pstrMakeItem != string.Empty)
intMakeItem = Convert.ToInt32(Convert.ToBoolean(pstrMakeItem));
DateTime dtmFromDate = Convert.ToDateTime(pstrFromDate);
DateTime dtmToDate = Convert.ToDateTime(pstrToDate);
#region report table
DataTable dtbData = new DataTable();
dtbData.Columns.Add(new DataColumn("Type", typeof (string)));
dtbData.Columns.Add(new DataColumn("Customer", typeof (string)));
dtbData.Columns.Add(new DataColumn("Model", typeof (string)));
dtbData.Columns.Add(new DataColumn("PartNo", typeof (string)));
dtbData.Columns.Add(new DataColumn("PartName", typeof (string)));
dtbData.Columns.Add(new DataColumn("Quantity", typeof (decimal)));
dtbData.Columns.Add(new DataColumn("Amount", typeof (decimal)));
dtbData.Columns.Add(new DataColumn("CostOfGoodsSold", typeof (decimal)));
#endregion
#region build report data
DataTable dtbReportData = GetReportData(pstrCCNID, dtmFromDate, dtmToDate, pstrTypeCode, pstrCustomerID, intMakeItem);
DataTable dtbActualCost = GetActualCost(pstrCCNID);
DataTable dtbStdCost = GetStdCost();
DataTable dtbChargeAllocation = GetChargeAllocation(pstrCCNID);
string strLastProductID = string.Empty;
string strLastPartyID = string.Empty;
string strLastType = string.Empty;
foreach (DataRow drowData in dtbReportData.Rows)
{
// party id
string strPartyID = drowData["PartyID"].ToString();
// product id
string strProductID = drowData["ProductID"].ToString();
// type
string strTypeCode = drowData["TypeCode"].ToString();
if (strLastType == strTypeCode && strLastProductID == strProductID && strLastPartyID == strPartyID)
continue;
strLastType = strTypeCode;
strLastProductID = strProductID;
strLastPartyID = strPartyID;
DataRow drowReport = dtbData.NewRow();
drowReport["Type"] = drowData["Type"];
drowReport["Customer"] = drowData["Customer"];
drowReport["Model"] = drowData["Model"];
drowReport["PartNo"] = drowData["PartNo"];
drowReport["PartName"] = drowData["PartName"];
string strFilter = "TypeCode = '" + strTypeCode
+ "' AND PartyID = '" + strPartyID
+ "' AND ProductID = '" + strProductID + "'";
decimal decQuantity = 0, decAmount = 0, decDSAmount = 0;
decimal decRecycleAmount = 0, decAdjustAmount = 0;
decimal decOHDSAmount = 0, decOHRecAmount = 0, decOHAdjAmount = 0;
decimal decSumQuantity = 0;
try
{
decQuantity = Convert.ToDecimal(dtbReportData.Compute("SUM(Quantity)", strFilter));
}
catch{}
try
{
decSumQuantity = Convert.ToDecimal(dtbReportData.Compute("SUM(Quantity)", "ProductID = " + strProductID));
}
catch{}
try
{
decAmount = Convert.ToDecimal(dtbReportData.Compute("SUM(Amount)", strFilter));
}
catch{}
drowReport["Quantity"] = decQuantity;
drowReport["Amount"] = decAmount;
#region calculate cost of goods sold for each item
// shipped date to determine which cost period will take effect here
DateTime dtmShippedDate = (DateTime) drowData["ShippedDate"];
dtmShippedDate = new DateTime(dtmShippedDate.Year, dtmShippedDate.Month, dtmShippedDate.Day);
// filter condition
string strFilterCondition = "ProductID = '" + strProductID + "'"
+ " AND FromDate <= '" + dtmShippedDate.ToString("G") + "'"
+ " AND ToDate >= '" + dtmShippedDate.ToString("G") + "'";
#region DS Amount
try
{
decDSAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(DSAmount)", strFilterCondition));
}
catch
{
decDSAmount = 0;
}
#endregion
#region Recycle Amount
try
{
decRecycleAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(RecycleAmount)", strFilterCondition));
}
catch
{
decRecycleAmount = 0;
}
#endregion
#region Adjust Amount
try
{
decAdjustAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(AdjustAmount)", strFilterCondition));
}
catch
{
decAdjustAmount = 0;
}
#endregion
#region OH DS Amount
try
{
decOHDSAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(OH_DSAmount)", strFilterCondition));
}
catch
{
decOHDSAmount = 0;
}
#endregion
#region OH Recycle Amount
try
{
decOHRecAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(OH_RecycleAmount)", strFilterCondition));
}
catch
{
decOHRecAmount = 0;
}
#endregion
#region OH Adjust Amount
try
{
decOHAdjAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(OH_AdjustAmount)", strFilterCondition));
}
catch
{
decOHAdjAmount = 0;
}
#endregion
decimal decCharge = (decDSAmount - decRecycleAmount - decAdjustAmount)
+ (decOHDSAmount - decOHRecAmount - decOHAdjAmount);
decimal decRate = decQuantity / decSumQuantity;
// try to get actual cost of item
DataRow[] drowActualCost = dtbActualCost.Select(strFilterCondition);
if (drowActualCost.Length > 0)
{
decimal decActualCost = 0;
try
{
decActualCost = Convert.ToDecimal(dtbActualCost.Compute("SUM(ActualCost)", strFilterCondition));
drowReport["CostOfGoodsSold"] = decRate * decCharge + decQuantity * decActualCost;
}
catch{}
}
else
{
// if item not yet rollup actual cost, try to get standard cost
DataRow[] drowStdCost = dtbStdCost.Select("ProductID = '" + strProductID + "'");
if (drowStdCost.Length > 0)
{
decimal decStdCost = 0;
try
{
decStdCost = Convert.ToDecimal(dtbStdCost.Compute("SUM(Cost)", "ProductID = '" + strProductID + "'"));
drowReport["CostOfGoodsSold"] = decRate * decCharge + decQuantity * decStdCost;
}
catch{}
}
else // if item dot have any cost
drowReport["CostOfGoodsSold"] = decimal.Zero;
}
#endregion
dtbData.Rows.Add(drowReport);
}
#endregion
#region report
C1Report rptReport = new C1Report();
mLayoutFile = "SaleByCustomer.xml";
rptReport.Load(mReportFolder + "\\" + mLayoutFile, rptReport.GetReportInfo(mReportFolder + "\\" + mLayoutFile)[0]);
rptReport.Layout.PaperSize = PaperKind.A4;
#region report parameter
try
{
rptReport.Fields["fldCCN"].Text = GetCCN(pstrCCNID);
}
catch{}
try
{
rptReport.Fields["fldFromDate"].Text = dtmFromDate.ToString("dd-MM-yyyy HH:mm");
}
catch{}
try
{
rptReport.Fields["fldToDate"].Text = dtmToDate.ToString("dd-MM-yyyy HH:mm");
}
catch{}
try
{
if (pstrTypeCode.Split(",".ToCharArray()).Length > 1)
rptReport.Fields["fldReg"].Text = "Multi-Selection";
else if (pstrTypeCode.Length > 0)
rptReport.Fields["fldReg"].Text = GetTypeDescription(pstrTypeCode);
}
catch{}
try
{
if (pstrCustomerID.Split(",".ToCharArray()).Length > 1)
rptReport.Fields["fldCust"].Text = "Multi-Selection";
else if (pstrCustomerID.Length > 0)
rptReport.Fields["fldCust"].Text = GetCustomerInfo(pstrCustomerID);
}
catch{}
#endregion
// set datasource object that provides data to report.
rptReport.DataSource.Recordset = dtbData;
// render report
rptReport.Render();
// render the report into the PrintPreviewControl
C1PrintPreviewDialog ppvViewer = new C1PrintPreviewDialog();
ppvViewer.FormTitle = "Sale Amount Report (Classified By Customers)";
ppvViewer.ReportViewer.Document = rptReport.Document;
ppvViewer.Show();
#endregion
return dtbData;
}
private DataTable GetReportData(string pstrCCNID, DateTime pdtmFromDate, DateTime pdtmToDate, string pstrTypeCode, string pstrCustomerID, int pintMakeItem)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SO_ConfirmShipDetail.InvoiceQty AS Quantity, SO_ConfirmShipDetail.InvoiceQty * ISNULL(SO_ConfirmShipDetail.Price,0) * SO_ConfirmShipMaster.ExchangeRate AS Amount,"
+ " ITM_Product.Code AS PartNo, ITM_Product.Description AS PartName, ITM_Product.Revision AS Model,"
+ " MST_Party.Code AS Customer, SO_Type.Code AS TypeCode, SO_Type.Description AS Type, SO_ConfirmShipDetail.ProductID,"
+ " ShippedDate, SO_SaleOrderMaster.PartyID"
+ " FROM SO_ConfirmShipMaster JOIN SO_ConfirmShipDetail"
+ " ON SO_ConfirmShipMaster.ConfirmShipMasterID = SO_ConfirmShipDetail.ConfirmShipMasterID"
+ " JOIN ITM_Product"
+ " ON SO_ConfirmShipDetail.ProductID = ITM_Product.ProductID"
+ " JOIN SO_SaleOrderMaster"
+ " ON SO_ConfirmShipMaster.SaleOrderMasterID = SO_SaleOrderMaster.SaleOrderMasterID"
+ " JOIN SO_SaleOrderDetail"
+ " ON SO_ConfirmShipDetail.SaleOrderDetailID = SO_SaleOrderDetail.SaleOrderDetailID"
+ " JOIN MST_Party"
+ " ON SO_SaleOrderMaster.PartyID = MST_Party.PartyID"
+ " JOIN SO_Type"
+ " ON SO_SaleOrderMaster.TypeID = SO_Type.TypeID"
+ " WHERE ShippedDate >= ?"
+ " AND ShippedDate <= ?"
+ " AND SO_ConfirmShipDetail.InvoiceQty > 0"
+ " AND SO_SaleOrderMaster.CCNID = " + pstrCCNID;
if (pstrTypeCode.Length > 0)
strSql += " AND SO_Type.Code IN (" + pstrTypeCode + ")";
if (pstrCustomerID.Length > 0)
strSql += " AND SO_SaleOrderMaster.PartyID IN (" + pstrCustomerID + ")";
if (pintMakeItem >= 0)
strSql += " AND ITM_Product.MakeItem = " + pintMakeItem;
//hacked by duongna, select return goods receipt
strSql += " UNION ALL " +
" SELECT " +
" -SO_ReturnedGoodsDetail.ReceiveQuantity AS Quantity, " +
" -SO_ReturnedGoodsDetail.ReceiveQuantity * ISNULL(SO_ReturnedGoodsDetail.UnitPrice,0) * SO_ReturnedGoodsMaster.ExchangeRate AS Amount, " +
" ITM_Product.Code AS PartNo, " +
" ITM_Product.Description AS PartName, " +
" ITM_Product.Revision AS Model, " +
" MST_Party.Code AS Customer, " +
" SO_Type.Code AS TypeCode, " +
" SO_Type.Description AS Type, " +
" SO_ReturnedGoodsDetail.ProductID, " +
" PostDate ShippedDate, " +
" SO_ReturnedGoodsMaster.PartyID " +
" FROM " +
" SO_ReturnedGoodsMaster " +
" JOIN SO_ReturnedGoodsDetail " +
" ON SO_ReturnedGoodsMaster.ReturnedGoodsMasterID = SO_ReturnedGoodsDetail.ReturnedGoodsMasterID " +
" JOIN ITM_Product " +
" ON SO_ReturnedGoodsDetail.ProductID = ITM_Product.ProductID " +
" JOIN MST_Party " +
" ON SO_ReturnedGoodsMaster.PartyID = MST_Party.PartyID " +
" JOIN SO_ConfirmShipMaster " +
" ON SO_ReturnedGoodsDetail.ConfirmShipMasterID = SO_ConfirmShipMaster.ConfirmShipMasterID " +
" JOIN SO_SaleOrderMaster " +
" ON SO_ConfirmShipMaster.SaleOrderMasterID = SO_SaleOrderMaster.SaleOrderMasterID " +
" JOIN SO_Type " +
" ON SO_SaleOrderMaster.TypeID = SO_Type.TypeID " +
" WHERE PostDate >= ?" +
" AND PostDate <= ?" +
" AND SO_ReturnedGoodsDetail.ReceiveQuantity > 0" +
" AND SO_SaleOrderMaster.CCNID = " + pstrCCNID;
if (pstrTypeCode.Length > 0)
strSql += " AND SO_Type.Code IN (" + pstrTypeCode + ")";
if (pstrCustomerID.Length > 0)
strSql += " AND SO_ReturnedGoodsMaster.PartyID IN (" + pstrCustomerID + ")";
if (pintMakeItem >= 0)
strSql += " AND ITM_Product.MakeItem = " + pintMakeItem;
strSql += " ORDER BY SO_Type.Description, MST_Party.Code, ITM_Product.Revision, ITM_Product.Code, ITM_Product.Description";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate;
ocmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate;
ocmdPCS.Parameters.Add(new OleDbParameter("FromDateReturn", OleDbType.Date)).Value = pdtmFromDate;
ocmdPCS.Parameters.Add(new OleDbParameter("ToDateReturn", OleDbType.Date)).Value = pdtmToDate;
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetActualCost(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SUM(CST_ActualCostHistory.ActualCost) AS ActualCost, CST_ActualCostHistory.ProductID,"
+ " CST_ActualCostHistory.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate"
+ " FROM CST_ActualCostHistory JOIN CST_ActCostAllocationMaster"
+ " ON CST_ActualCostHistory.ActCostAllocationMasterID = CST_ActCostAllocationMaster.ActCostAllocationMasterID"
+ " WHERE CST_ActCostAllocationMaster.CCNID = " + pstrCCNID
+ " GROUP BY CST_ActualCostHistory.ProductID, CST_ActualCostHistory.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate"
+ " ORDER BY CST_ActCostAllocationMaster.FromDate";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetStdCost()
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SUM(Cost) AS Cost, ProductID"
+ " FROM CST_STDItemCost GROUP BY ProductID ORDER BY ProductID";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCCN(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT Code + ' (' + Description + ')' FROM MST_CCN WHERE CCNID = " + pstrCCNID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetTypeDescription(string pstrTypeCode)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT Description FROM SO_Type WHERE Code = " + pstrTypeCode;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCustomerInfo(string pstrCustomerID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT Code + ' (' + Name + ')' FROM MST_Party WHERE PartyID = " + pstrCustomerID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetChargeAllocation(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SUM(CST_DSAndRecycleAllocation.DSAmount) AS DSAmount,"
+ " SUM(CST_DSAndRecycleAllocation.RecycleAmount) AS RecycleAmount,"
+ " SUM(CST_DSAndRecycleAllocation.AdjustAmount) AS AdjustAmount,"
+ " SUM(CST_DSAndRecycleAllocation.OH_RecycleAmount) AS OH_RecycleAmount,"
+ " SUM(CST_DSAndRecycleAllocation.OH_DSAmount) AS OH_DSAmount,"
+ " SUM(CST_DSAndRecycleAllocation.OH_AdjustAmount) AS OH_AdjustAmount,"
+ " CST_DSAndRecycleAllocation.ProductID,"
+ " CST_DSAndRecycleAllocation.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate, STD_CostElementType.Code AS CostElementType"
+ " FROM CST_DSAndRecycleAllocation JOIN CST_ActCostAllocationMaster"
+ " ON CST_DSAndRecycleAllocation.ActCostAllocationMasterID = CST_ActCostAllocationMaster.ActCostAllocationMasterID"
+ " JOIN STD_CostElement"
+ " ON CST_DSAndRecycleAllocation.CostElementID = STD_CostElement.CostElementID"
+ " JOIN STD_CostElementType"
+ " ON STD_CostElement.CostElementTypeID = STD_CostElementType.CostElementTypeID"
+ " WHERE CST_ActCostAllocationMaster.CCNID = " + pstrCCNID
+ " GROUP BY CST_DSAndRecycleAllocation.ProductID, CST_DSAndRecycleAllocation.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate, STD_CostElementType.Code"
+ " ORDER BY CST_ActCostAllocationMaster.FromDate";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
}
}
| |
// 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.Runtime.CompilerServices;
class C
{
public static int Main(string[] args)
{
int error = Test1();
error += Test2();
error += Test3();
error += Test3b();
error += Test4();
error += Test5();
error += Test6();
Console.WriteLine(error == 0 ? "Pass" : "Fail");
return 100 + error;
}
static int Test1()
{
try {
return Test1Inner();
}
catch {
return 1;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test1Inner()
{
int i = 3;
do
{
try
{
throw new Exception();
}
// we should be decrementing i here, it does not happen
catch (Exception) when (--i < 0)
{
Console.Write("e");
break;
}
catch (Exception)
{
// just printing constant 3 here
//000000b5 mov ecx,3
//000000ba call 000000005B3CBAF0
Print1(i);
}
} while (true);
return 0;
}
static int limit = 10;
[MethodImpl(MethodImplOptions.NoInlining)]
static void Print1(int i)
{
if (limit > 0) {
Console.Write(i.ToString());
--limit;
}
else {
throw new Exception();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test2()
{
int x = 1, y = 5;
try {
throw new Exception();
} catch when (Print2(Print2(0, --x), ++x) == 1) {
} catch {
// Need a PHI here for x that includes the decremented
// value; doesn't happen if we don't realize that exceptions
// at the first call to Print2 can reach here.
// Without it, we might const-prop a 1 here which is
// incorrect when the first Print2 call throws.
y = Print2(1, x);
}
return y;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Print2(int i, int j)
{
if (i == 0)
throw new Exception();
Console.WriteLine(j.ToString());
return j;
}
static int Test3()
{
return Test3(0, 50);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test3(int x, int y) // must pass 50 for y
{
try {
throw new Exception();
}
// Need to make sure the increment to y is not
// hoisted to before the call to Throw(x). If
// the importer doesn't realize that an exception
// from Throw(x) can be caught in this method, it
// won't separate Throw(x) out from the Ignore(..)
// tree, but will still separate out ++y, creating
// the bad reordering
catch when (Ignore(Throw(x), ++y)) { }
catch { Print3(y); }
return y - 50; // Caller should pass '50'
}
static int Test3b()
{
return Test3b(new int[5], 50);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test3b(int[] x, int y)
{
try {
throw new Exception();
}
// Same as Test3 except that the tree which raises
// an exception is the array access x[100] instead
// of a call.
catch when (Ignore(x[100], ++y)) { }
catch { Print3(y); }
return y - 50; // Caller should pass '50'
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool Ignore(int a, int b) { return false; }
[MethodImpl(MethodImplOptions.NoInlining)]
static int Throw(int n) { throw new Exception(); }
[MethodImpl(MethodImplOptions.NoInlining)]
static int Print3(int i)
{
Console.WriteLine(i.ToString());
return i;
}
class BoxedBool
{
public bool Field;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test4()
{
return Test4(new BoxedBool(), new Exception());
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test4(BoxedBool box, Exception e)
{
bool b = box.Field;
try {
throw e;
}
// This filter side-effects the heap and then throws an
// exception which is caught by the outer catch; make
// sure we recognize the heap modification and don't think
// we can value-number the load here the same as the load
// on entry to the function.
catch when ((box.Field = true) && ((BoxedBool)null).Field) {
}
catch {
b = box.Field;
}
if (b) {
Console.WriteLine("true");
}
else {
Console.WriteLine("false");
}
return (b ? 0 : 1);
}
static int Test5()
{
int n = int.MaxValue - 1;
int m = Test5(n);
return (m == n ? 0 : 1);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test5(int n)
{
try {
throw new Exception();
}
catch when (Filter5(ref n)) { }
catch { }
return n;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool Filter5(ref int n)
{
// Codegen'ing this as
// add [addr_of_n], 2
// jo throw_ovf
// would incorrectly modify n on the path where
// the exception occurs.
n = checked(n + 2);
return (n != 0);
}
static int Test6()
{
int n = int.MaxValue - 3;
int m = Test6(n);
return (m == n + 2 ? 0 : 1);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int Test6(int n)
{
try {
throw new Exception();
}
catch when (Filter6(ref n)) { }
catch { }
return n;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool Filter6(ref int n)
{
// Codegen'ing this as
// add [addr_of_n], 4
// jo throw_ovf
// would incorrectly increment n by 4 rather than 2
// on the path where the exception occurs.
checked {
n += 2;
n += 2;
}
return (n != 0);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReportsOperations operations.
/// </summary>
public partial interface IReportsOperations
{
/// <summary>
/// Lists report records.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByApiWithHttpMessagesAsync(ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by User.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByUserWithHttpMessagesAsync(ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by API Operations.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByOperationWithHttpMessagesAsync(ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by Product.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByProductWithHttpMessagesAsync(ODataQuery<ReportRecordContract> odataQuery, string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by GeoGraphy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByGeoWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by subscription.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListBySubscriptionWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by Time.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='interval'>
/// By time interval. Interval must be multiple of 15 minutes and may
/// not be zero. The value should be in ISO 8601 format
/// (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be
/// used to convert TimeSpan to a valid interval string:
/// XmlConvert.ToString(new TimeSpan(hours, minutes, secconds))
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByTimeWithHttpMessagesAsync(string resourceGroupName, string serviceName, System.TimeSpan interval, ODataQuery<ReportRecordContract> odataQuery = default(ODataQuery<ReportRecordContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by Request.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<RequestReportRecordContract>>> ListByRequestWithHttpMessagesAsync(ODataQuery<RequestReportRecordContract> odataQuery, string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByApiNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by User.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByUserNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by API Operations.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByOperationNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by Product.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByProductNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by GeoGraphy.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByGeoNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists report records by Time.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ReportRecordContract>>> ListByTimeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Describes a launch configuration.
/// </summary>
public partial class LaunchConfiguration
{
private bool? _associatePublicIpAddress;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private string _classicLinkVPCId;
private List<string> _classicLinkVPCSecurityGroups = new List<string>();
private DateTime? _createdTime;
private bool? _ebsOptimized;
private string _iamInstanceProfile;
private string _imageId;
private InstanceMonitoring _instanceMonitoring;
private string _instanceType;
private string _kernelId;
private string _keyName;
private string _launchConfigurationARN;
private string _launchConfigurationName;
private string _placementTenancy;
private string _ramdiskId;
private List<string> _securityGroups = new List<string>();
private string _spotPrice;
private string _userData;
/// <summary>
/// Gets and sets the property AssociatePublicIpAddress.
/// <para>
/// [EC2-VPC] Indicates whether to assign a public IP address to each instance.
/// </para>
/// </summary>
public bool AssociatePublicIpAddress
{
get { return this._associatePublicIpAddress.GetValueOrDefault(); }
set { this._associatePublicIpAddress = value; }
}
// Check to see if AssociatePublicIpAddress property is set
internal bool IsSetAssociatePublicIpAddress()
{
return this._associatePublicIpAddress.HasValue;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// A block device mapping, which specifies the block devices for the instance.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property ClassicLinkVPCId.
/// <para>
/// The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. This parameter
/// can only be used if you are launching EC2-Classic instances. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a>
/// in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string ClassicLinkVPCId
{
get { return this._classicLinkVPCId; }
set { this._classicLinkVPCId = value; }
}
// Check to see if ClassicLinkVPCId property is set
internal bool IsSetClassicLinkVPCId()
{
return this._classicLinkVPCId != null;
}
/// <summary>
/// Gets and sets the property ClassicLinkVPCSecurityGroups.
/// <para>
/// The IDs of one or more security groups for the VPC specified in <code>ClassicLinkVPCId</code>.
/// This parameter is required if <code>ClassicLinkVPCId</code> is specified, and cannot
/// be used otherwise. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a>
/// in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public List<string> ClassicLinkVPCSecurityGroups
{
get { return this._classicLinkVPCSecurityGroups; }
set { this._classicLinkVPCSecurityGroups = value; }
}
// Check to see if ClassicLinkVPCSecurityGroups property is set
internal bool IsSetClassicLinkVPCSecurityGroups()
{
return this._classicLinkVPCSecurityGroups != null && this._classicLinkVPCSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property CreatedTime.
/// <para>
/// The creation date and time for the launch configuration.
/// </para>
/// </summary>
public DateTime CreatedTime
{
get { return this._createdTime.GetValueOrDefault(); }
set { this._createdTime = value; }
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this._createdTime.HasValue;
}
/// <summary>
/// Gets and sets the property EbsOptimized.
/// <para>
/// Controls whether the instance is optimized for EBS I/O (<code>true</code>) or not
/// (<code>false</code>).
/// </para>
/// </summary>
public bool EbsOptimized
{
get { return this._ebsOptimized.GetValueOrDefault(); }
set { this._ebsOptimized = value; }
}
// Check to see if EbsOptimized property is set
internal bool IsSetEbsOptimized()
{
return this._ebsOptimized.HasValue;
}
/// <summary>
/// Gets and sets the property IamInstanceProfile.
/// <para>
/// The name or Amazon Resource Name (ARN) of the instance profile associated with the
/// IAM role for the instance.
/// </para>
/// </summary>
public string IamInstanceProfile
{
get { return this._iamInstanceProfile; }
set { this._iamInstanceProfile = value; }
}
// Check to see if IamInstanceProfile property is set
internal bool IsSetIamInstanceProfile()
{
return this._iamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the Amazon Machine Image (AMI).
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property InstanceMonitoring.
/// <para>
/// Controls whether instances in this group are launched with detailed monitoring.
/// </para>
/// </summary>
public InstanceMonitoring InstanceMonitoring
{
get { return this._instanceMonitoring; }
set { this._instanceMonitoring = value; }
}
// Check to see if InstanceMonitoring property is set
internal bool IsSetInstanceMonitoring()
{
return this._instanceMonitoring != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type for the instances.
/// </para>
/// </summary>
public string InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel associated with the AMI.
/// </para>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property KeyName.
/// <para>
/// The name of the key pair.
/// </para>
/// </summary>
public string KeyName
{
get { return this._keyName; }
set { this._keyName = value; }
}
// Check to see if KeyName property is set
internal bool IsSetKeyName()
{
return this._keyName != null;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationARN.
/// <para>
/// The Amazon Resource Name (ARN) of the launch configuration.
/// </para>
/// </summary>
public string LaunchConfigurationARN
{
get { return this._launchConfigurationARN; }
set { this._launchConfigurationARN = value; }
}
// Check to see if LaunchConfigurationARN property is set
internal bool IsSetLaunchConfigurationARN()
{
return this._launchConfigurationARN != null;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationName.
/// <para>
/// The name of the launch configuration.
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this._launchConfigurationName; }
set { this._launchConfigurationName = value; }
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this._launchConfigurationName != null;
}
/// <summary>
/// Gets and sets the property PlacementTenancy.
/// <para>
/// The tenancy of the instance, either <code>default</code> or <code>dedicated</code>.
/// An instance with <code>dedicated</code> tenancy runs in an isolated, single-tenant
/// hardware and can only be launched into a VPC.
/// </para>
/// </summary>
public string PlacementTenancy
{
get { return this._placementTenancy; }
set { this._placementTenancy = value; }
}
// Check to see if PlacementTenancy property is set
internal bool IsSetPlacementTenancy()
{
return this._placementTenancy != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk associated with the AMI.
/// </para>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// The security groups to associate with the instances.
/// </para>
/// </summary>
public List<string> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The price to bid when launching Spot Instances.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// The user data available to the instances.
/// </para>
/// </summary>
public string UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
}
}
| |
/*
* NumericUpDown.cs - Implementation of the
* "System.Windows.Forms.NumericUpDown" class.
*
* Copyright (C) 2003 Free Software Foundation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System.Drawing;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms.Themes;
namespace System.Windows.Forms
{
[DefaultEventAttribute("ValueChanged")]
[DefaultPropertyAttribute("Value")]
public class NumericUpDown : UpDownBase, ISupportInitialize
{
private const int DefaultDecimalPlaces = 0;
private const bool DefaultHexadecimal = false;
private const bool DefaultThousandsSeparator = false;
private decimal currentValue;
private int decimalPlaces;
private bool hexadecimal;
private decimal increment;
private bool initializing;
private decimal maximum;
private decimal minimum;
private bool thousandsSeparator;
private static int DefaultIncrement
{
get
{
return 1;
}
}
private static decimal DefaultMaximum
{
get
{
return 100;
}
}
private static decimal DefaultMinimum
{
get
{
return 0;
}
}
private static decimal DefaultValue
{
get
{
return DefaultMinimum;
}
}
public NumericUpDown(): base()
{
decimalPlaces = DefaultDecimalPlaces;
hexadecimal = DefaultHexadecimal;
increment = DefaultIncrement;
maximum = DefaultMaximum;
minimum = DefaultMinimum;
initializing = false;
currentValue = DefaultValue;
thousandsSeparator = DefaultThousandsSeparator;
UpdateEditText();
}
[TODO]
public void BeginInit()
{
initializing = true;
}
[DefaultValue(0)]
public int DecimalPlaces
{
get
{
return decimalPlaces;
}
set
{
if ((value < 0) || (value > 99))
{
throw new ArgumentException();
}
if (decimalPlaces != value)
{
decimalPlaces = value;
UpdateEditText();
}
}
}
[TODO]
public void EndInit()
{
initializing = false;
}
public decimal Increment
{
get
{
return increment;
}
set
{
increment = value;
}
}
[RefreshProperties(RefreshProperties.All)]
public decimal Maximum
{
get
{
return maximum;
}
set
{
maximum = Constrain(value);
if (maximum < currentValue)
{
currentValue = maximum;
UpdateEditText();
}
}
}
[RefreshProperties(RefreshProperties.All)]
public decimal Minimum
{
get
{
return minimum;
}
set
{
minimum = Constrain(value);
if (minimum > currentValue)
{
currentValue = minimum;
UpdateEditText();
}
}
}
public decimal Value
{
get
{
return currentValue;
}
set
{
if ((value < minimum) || (value > maximum))
{
throw new ArgumentException();
}
currentValue = Constrain(value);
UpdateEditText();
}
}
[TODO]
private decimal Constrain(decimal value)
{
return value;
}
public override void UpButton()
{
if (currentValue < maximum)
{
currentValue += increment;
if (currentValue > maximum)
{
currentValue = maximum;
}
UpdateEditText();
}
}
public override void DownButton()
{
if (currentValue > minimum)
{
currentValue -= increment;
if (currentValue < minimum)
{
currentValue = minimum;
}
UpdateEditText();
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
[Bindable(false)]
public override string Text
{
get
{
return base.Text;
}
set
{
// FIXME
base.Text = value;
}
}
[Localizable(true)]
[DefaultValue(false)]
public bool ThousandsSeparator
{
get
{
return thousandsSeparator;
}
set
{
if (thousandsSeparator != value)
{
thousandsSeparator = value;
UpdateEditText();
}
}
}
protected override void UpdateEditText()
{
if (hexadecimal)
{
base.Text = currentValue.ToString("X");
}
else
{
if (thousandsSeparator)
{
base.Text = currentValue.ToString("N" + decimalPlaces.ToString());
}
else
{
base.Text = currentValue.ToString("F" + decimalPlaces.ToString());
}
}
}
[TODO]
protected virtual void ValidateEditText()
{
}
[TODO]
protected override void OnChanged(object source, EventArgs e)
{
throw new NotImplementedException("OnChanged");
}
public override string ToString()
{
return "System.Windows.Forms.NumericUpDown, Minimum = " + minimum.ToString() +
", Maximun = " + maximum.ToString();
}
public event EventHandler ValueChanged;
}; // class DomainUpDown
}; // namespace System.Windows.Forms
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.Mount;
using Microsoft.TemplateEngine.Cli.CommandParsing;
using Microsoft.TemplateEngine.Cli.PostActionProcessors;
using Microsoft.TemplateEngine.Edge;
using Microsoft.TemplateEngine.Edge.Settings;
using Microsoft.TemplateEngine.Edge.Template;
using Microsoft.TemplateEngine.Utils;
namespace Microsoft.TemplateEngine.Cli
{
public class New3Command
{
private readonly ITelemetryLogger _telemetryLogger;
private readonly TemplateCreator _templateCreator;
private readonly SettingsLoader _settingsLoader;
private readonly AliasRegistry _aliasRegistry;
private readonly Paths _paths;
private readonly INewCommandInput _commandInput;
private readonly IHostSpecificDataLoader _hostDataLoader;
private readonly string _defaultLanguage;
private static readonly Regex LocaleFormatRegex = new Regex(@"
^
[a-z]{2}
(?:-[A-Z]{2})?
$"
, RegexOptions.IgnorePatternWhitespace);
private readonly Action<IEngineEnvironmentSettings, IInstaller> _onFirstRun;
public New3Command(string commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, Action<IEngineEnvironmentSettings, IInstaller> onFirstRun, INewCommandInput commandInput)
: this(commandName, host, telemetryLogger, onFirstRun, commandInput, null)
{
}
public New3Command(string commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, Action<IEngineEnvironmentSettings, IInstaller> onFirstRun, INewCommandInput commandInput, string hivePath)
{
_telemetryLogger = telemetryLogger;
host = new ExtendedTemplateEngineHost(host, this);
EnvironmentSettings = new EngineEnvironmentSettings(host, x => new SettingsLoader(x), hivePath);
_settingsLoader = (SettingsLoader)EnvironmentSettings.SettingsLoader;
Installer = new Installer(EnvironmentSettings);
_templateCreator = new TemplateCreator(EnvironmentSettings);
_aliasRegistry = new AliasRegistry(EnvironmentSettings);
CommandName = commandName;
_paths = new Paths(EnvironmentSettings);
_onFirstRun = onFirstRun;
_hostDataLoader = new HostSpecificDataLoader(EnvironmentSettings.SettingsLoader);
_commandInput = commandInput;
if (!EnvironmentSettings.Host.TryGetHostParamDefault("prefs:language", out _defaultLanguage))
{
_defaultLanguage = null;
}
}
public static IInstaller Installer { get; set; }
public string CommandName { get; }
public string TemplateName => _commandInput.TemplateName;
public string OutputPath => _commandInput.OutputPath;
public EngineEnvironmentSettings EnvironmentSettings { get; private set; }
public static int Run(string commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, Action<IEngineEnvironmentSettings, IInstaller> onFirstRun, string[] args)
{
return Run(commandName, host, telemetryLogger, onFirstRun, args, null);
}
public static int Run(string commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, Action<IEngineEnvironmentSettings, IInstaller> onFirstRun, string[] args, string hivePath)
{
if (args.Any(x => string.Equals(x, "--debug:attach", StringComparison.Ordinal)))
{
Console.ReadLine();
}
if (args.Length == 0)
{
telemetryLogger.TrackEvent(commandName + TelemetryConstants.CalledWithNoArgsEventSuffix);
}
INewCommandInput commandInput = new NewCommandInputCli(commandName);
New3Command instance = new New3Command(commandName, host, telemetryLogger, onFirstRun, commandInput, hivePath);
commandInput.OnExecute(instance.ExecuteAsync);
int result;
try
{
using (Timing.Over(host, "Execute"))
{
result = commandInput.Execute(args);
}
}
catch (Exception ex)
{
AggregateException ax = ex as AggregateException;
while (ax != null && ax.InnerExceptions.Count == 1)
{
ex = ax.InnerException;
ax = ex as AggregateException;
}
Reporter.Error.WriteLine(ex.Message.Bold().Red());
while (ex.InnerException != null)
{
ex = ex.InnerException;
ax = ex as AggregateException;
while (ax != null && ax.InnerExceptions.Count == 1)
{
ex = ax.InnerException;
ax = ex as AggregateException;
}
Reporter.Error.WriteLine(ex.Message.Bold().Red());
}
Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
result = 1;
}
return result;
}
private void ConfigureEnvironment()
{
_onFirstRun?.Invoke(EnvironmentSettings, Installer);
foreach (Type type in typeof(New3Command).GetTypeInfo().Assembly.GetTypes())
{
EnvironmentSettings.SettingsLoader.Components.Register(type);
}
}
private async Task<CreationResultStatus> CreateTemplateAsync(ITemplateInfo template)
{
string fallbackName = new DirectoryInfo(_commandInput.OutputPath ?? Directory.GetCurrentDirectory()).Name;
if (string.IsNullOrEmpty(fallbackName) || string.Equals(fallbackName, "/", StringComparison.Ordinal))
{ // DirectoryInfo("/").Name on *nix returns "/", as opposed to null or "".
fallbackName = null;
}
TemplateCreationResult instantiateResult;
try
{
instantiateResult = await _templateCreator.InstantiateAsync(template, _commandInput.Name, fallbackName, _commandInput.OutputPath, _commandInput.AllTemplateParams, _commandInput.SkipUpdateCheck, _commandInput.IsForceFlagSpecified, _commandInput.BaselineName).ConfigureAwait(false);
}
catch (ContentGenerationException cx)
{
Reporter.Error.WriteLine(cx.Message.Bold().Red());
if(cx.InnerException != null)
{
Reporter.Error.WriteLine(cx.InnerException.Message.Bold().Red());
}
return CreationResultStatus.CreateFailed;
}
catch (TemplateAuthoringException tae)
{
Reporter.Error.WriteLine(tae.Message.Bold().Red());
return CreationResultStatus.CreateFailed;
}
string resultTemplateName = string.IsNullOrEmpty(instantiateResult.TemplateFullName) ? TemplateName : instantiateResult.TemplateFullName;
switch (instantiateResult.Status)
{
case CreationResultStatus.Success:
Reporter.Output.WriteLine(string.Format(LocalizableStrings.CreateSuccessful, resultTemplateName));
if(!string.IsNullOrEmpty(template.ThirdPartyNotices))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.ThirdPartyNotices, template.ThirdPartyNotices));
}
HandlePostActions(instantiateResult);
break;
case CreationResultStatus.CreateFailed:
Reporter.Error.WriteLine(string.Format(LocalizableStrings.CreateFailed, resultTemplateName, instantiateResult.Message).Bold().Red());
break;
case CreationResultStatus.MissingMandatoryParam:
if (string.Equals(instantiateResult.Message, "--name", StringComparison.Ordinal))
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.MissingRequiredParameter, instantiateResult.Message, resultTemplateName).Bold().Red());
}
else
{
IReadOnlyList<string> missingParamNamesCanonical = instantiateResult.Message.Split(new[] { ',' })
.Select(x => _commandInput.VariantsForCanonical(x.Trim())
.DefaultIfEmpty(x.Trim()).First())
.ToList();
string fixedMessage = string.Join(", ", missingParamNamesCanonical);
Reporter.Error.WriteLine(string.Format(LocalizableStrings.MissingRequiredParameter, fixedMessage, resultTemplateName).Bold().Red());
}
break;
case CreationResultStatus.OperationNotSpecified:
break;
case CreationResultStatus.InvalidParamValues:
IReadOnlyList<InvalidParameterInfo> invalidParameterList = GetTemplateUsageInformation(template, out IParameterSet ps, out IReadOnlyList<string> userParamsWithInvalidValues, out IReadOnlyDictionary<string, IReadOnlyList<string>> variantsForCanonicals, out HashSet<string> userParamsWithDefaultValues, out bool hasPostActionScriptRunner);
string invalidParamsError = InvalidParameterInfo.InvalidParameterListToString(invalidParameterList);
Reporter.Error.WriteLine(invalidParamsError.Bold().Red());
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, $"{CommandName} {TemplateName}").Bold().Red());
break;
default:
break;
}
return instantiateResult.Status;
}
private IReadOnlyList<InvalidParameterInfo> GetTemplateUsageInformation(ITemplateInfo templateInfo, out IParameterSet allParams, out IReadOnlyList<string> userParamsWithInvalidValues,
out IReadOnlyDictionary<string, IReadOnlyList<string>> variantsForCanonicals, out HashSet<string> userParamsWithDefaultValues, out bool hasPostActionScriptRunner)
{
ITemplate template = EnvironmentSettings.SettingsLoader.LoadTemplate(templateInfo, _commandInput.BaselineName);
ParseTemplateArgs(templateInfo);
allParams = _templateCreator.SetupDefaultParamValuesFromTemplateAndHost(template, template.DefaultName ?? "testName", out IReadOnlyList<string> defaultParamsWithInvalidValues);
_templateCreator.ResolveUserParameters(template, allParams, _commandInput.AllTemplateParams, out userParamsWithInvalidValues);
hasPostActionScriptRunner = CheckIfTemplateHasScriptRunningPostActions(template);
_templateCreator.ReleaseMountPoints(template);
List<InvalidParameterInfo> invalidParameters = new List<InvalidParameterInfo>();
if (userParamsWithInvalidValues.Any())
{
// Lookup the input param formats - userParamsWithInvalidValues has canonical.
foreach (string canonical in userParamsWithInvalidValues)
{
_commandInput.AllTemplateParams.TryGetValue(canonical, out string specifiedValue);
string inputFormat = _commandInput.TemplateParamInputFormat(canonical);
InvalidParameterInfo invalidParam = new InvalidParameterInfo(inputFormat, specifiedValue, canonical);
invalidParameters.Add(invalidParam);
}
}
if (_templateCreator.AnyParametersWithInvalidDefaultsUnresolved(defaultParamsWithInvalidValues, userParamsWithInvalidValues, _commandInput.AllTemplateParams, out IReadOnlyList<string> defaultsWithUnresolvedInvalidValues))
{
IParameterSet templateParams = template.Generator.GetParametersForTemplate(EnvironmentSettings, template);
foreach (string defaultParamName in defaultsWithUnresolvedInvalidValues)
{
ITemplateParameter param = templateParams.ParameterDefinitions.FirstOrDefault(x => string.Equals(x.Name, defaultParamName, StringComparison.Ordinal));
if (param != null)
{
// Get the best input format available.
IReadOnlyList<string> inputVariants = _commandInput.VariantsForCanonical(param.Name);
string displayName = inputVariants.FirstOrDefault(x => x.Contains(param.Name))
?? inputVariants.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur)
?? param.Name;
InvalidParameterInfo invalidParam = new InvalidParameterInfo(displayName, param.DefaultValue, displayName, true);
invalidParameters.Add(invalidParam);
}
}
}
// get all the flags
// get all the user input params that have the default value
Dictionary<string, IReadOnlyList<string>> inputFlagVariants = new Dictionary<string, IReadOnlyList<string>>();
userParamsWithDefaultValues = new HashSet<string>();
foreach (string paramName in allParams.ParameterDefinitions.Select(x => x.Name))
{
inputFlagVariants[paramName] = _commandInput.VariantsForCanonical(paramName);
if (_commandInput.TemplateParamHasValue(paramName) && string.IsNullOrEmpty(_commandInput.TemplateParamValue(paramName)))
{
userParamsWithDefaultValues.Add(paramName);
}
}
variantsForCanonicals = inputFlagVariants;
return invalidParameters;
}
private bool CheckIfTemplateHasScriptRunningPostActions(ITemplate template)
{
// use a throwaway set of params for getting the creation effects - it makes changes to them.
string targetDir = _commandInput.OutputPath ?? EnvironmentSettings.Host.FileSystem.GetCurrentDirectory();
IParameterSet paramsForCreationEffects = _templateCreator.SetupDefaultParamValuesFromTemplateAndHost(template, template.DefaultName ?? "testName", out IReadOnlyList<string> throwaway);
_templateCreator.ResolveUserParameters(template, paramsForCreationEffects, _commandInput.AllTemplateParams, out IReadOnlyList<string> userParamsWithInvalidValues);
ICreationEffects creationEffects = template.Generator.GetCreationEffects(EnvironmentSettings, template, paramsForCreationEffects, EnvironmentSettings.SettingsLoader.Components, targetDir);
return creationEffects.CreationResult.PostActions.Any(x => x.ActionId == ProcessStartPostActionProcessor.ActionProcessorId);
}
private string GetLanguageMismatchErrorMessage(string inputLanguage)
{
string inputFlagForm;
if (_commandInput.Tokens.Contains("-lang"))
{
inputFlagForm = "-lang";
}
else
{
inputFlagForm = "--language";
}
string invalidLanguageErrorText = LocalizableStrings.InvalidTemplateParameterValues;
invalidLanguageErrorText += Environment.NewLine + string.Format(LocalizableStrings.InvalidParameterDetail, inputFlagForm, inputLanguage, "language");
return invalidLanguageErrorText;
}
private void HandlePostActions(TemplateCreationResult creationResult)
{
if (creationResult.Status != CreationResultStatus.Success)
{
return;
}
AllowPostActionsSetting scriptRunSettings;
if (string.IsNullOrEmpty(_commandInput.AllowScriptsToRun) || string.Equals(_commandInput.AllowScriptsToRun, "prompt", StringComparison.OrdinalIgnoreCase))
{
scriptRunSettings = AllowPostActionsSetting.Prompt;
}
else if (string.Equals(_commandInput.AllowScriptsToRun, "yes", StringComparison.OrdinalIgnoreCase))
{
scriptRunSettings = AllowPostActionsSetting.Yes;
}
else if (string.Equals(_commandInput.AllowScriptsToRun, "no", StringComparison.OrdinalIgnoreCase))
{
scriptRunSettings = AllowPostActionsSetting.No;
}
else
{
scriptRunSettings = AllowPostActionsSetting.Prompt;
}
PostActionDispatcher postActionDispatcher = new PostActionDispatcher(EnvironmentSettings, creationResult, scriptRunSettings);
postActionDispatcher.Process(() => Console.ReadLine());
}
// Checks the result of TemplatesToDisplayInfoAbout()
// If they all have the same group identity, return them.
// Otherwise retun an empty list.
private IEnumerable<ITemplateInfo> GetTemplatesToShowDetailedHelpAbout(TemplateListResolutionResult templateResolutionResult)
{
IReadOnlyList<ITemplateInfo> candidateTemplates = GetTemplatesToDisplayInfoAbout(templateResolutionResult);
Func<ITemplateInfo, string> groupIdentitySelector = (x) => x.GroupIdentity;
if (candidateTemplates.AllAreTheSame(groupIdentitySelector, StringComparer.OrdinalIgnoreCase))
{
return candidateTemplates;
}
return new List<ITemplateInfo>();
}
// If there are secondary matches, return them
// Else if there are primary matches, return them
// Otherwise return all templates in the current context
private IReadOnlyList<ITemplateInfo> GetTemplatesToDisplayInfoAbout(TemplateListResolutionResult templateResolutionResult)
{
IEnumerable<ITemplateInfo> templateList;
if (templateResolutionResult.HasUnambiguousTemplateGroupToUse)
{
templateList = templateResolutionResult.UnambiguousTemplateGroupToUse.Select(x => x.Info);
}
else if (!string.IsNullOrEmpty(TemplateName) && templateResolutionResult.HasMatchedTemplatesWithSecondaryMatchInfo)
{ // without template name, it's not reasonable to do secondary matching
templateList = templateResolutionResult.MatchedTemplatesWithSecondaryMatchInfo.Select(x => x.Info);
}
else if (templateResolutionResult.HasCoreMatchedTemplatesWithDisposition(x => x.IsMatch))
{
templateList = templateResolutionResult.CoreMatchedTemplates.Where(x => x.IsMatch).Select(x => x.Info);
}
else if (templateResolutionResult.HasCoreMatchedTemplatesWithDisposition(x => x.IsPartialMatch))
{
templateList = templateResolutionResult.CoreMatchedTemplates.Where(x => x.IsPartialMatch).Select(x => x.Info);
}
else
{
templateList = TemplateListResolver.PerformAllTemplatesInContextQuery(_settingsLoader.UserTemplateCache.TemplateInfo, _hostDataLoader, _commandInput.TypeFilter?.ToLowerInvariant())
.Where(x => x.IsMatch).Select(x => x.Info);
}
return templateList.ToList();
}
private void DisplayTemplateList(TemplateListResolutionResult templateResolutionResult)
{
IReadOnlyList<ITemplateInfo> results = GetTemplatesToDisplayInfoAbout(templateResolutionResult);
IEnumerable<IGrouping<string, ITemplateInfo>> grouped = results.GroupBy(x => x.GroupIdentity, x => !string.IsNullOrEmpty(x.GroupIdentity));
Dictionary<ITemplateInfo, string> templatesVersusLanguages = new Dictionary<ITemplateInfo, string>();
foreach (IGrouping<string, ITemplateInfo> grouping in grouped)
{
List<string> languageForDisplay = new List<string>();
HashSet<string> uniqueLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string defaultLanguageDisplay = string.Empty;
foreach (ITemplateInfo info in grouping)
{
if (info.Tags != null && info.Tags.TryGetValue("language", out ICacheTag languageTag))
{
foreach (string lang in languageTag.ChoicesAndDescriptions.Keys)
{
if (uniqueLanguages.Add(lang))
{
if (string.IsNullOrEmpty(_commandInput.Language) && string.Equals(_defaultLanguage, lang, StringComparison.OrdinalIgnoreCase))
{
defaultLanguageDisplay = $"[{lang}]";
}
else
{
languageForDisplay.Add(lang);
}
}
}
}
}
languageForDisplay.Sort(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(defaultLanguageDisplay))
{
languageForDisplay.Insert(0, defaultLanguageDisplay);
}
templatesVersusLanguages[grouping.First()] = string.Join(", ", languageForDisplay);
}
HelpFormatter<KeyValuePair<ITemplateInfo, string>> formatter = HelpFormatter.For(EnvironmentSettings, templatesVersusLanguages, 6, '-', false)
.DefineColumn(t => t.Key.Name, LocalizableStrings.Templates)
.DefineColumn(t => t.Key.ShortName, LocalizableStrings.ShortName)
.DefineColumn(t => t.Value, out object languageColumn, LocalizableStrings.Language)
.DefineColumn(t => t.Key.Classifications != null ? string.Join("/", t.Key.Classifications) : null, out object tagsColumn, LocalizableStrings.Tags)
.OrderByDescending(languageColumn, new NullOrEmptyIsLastStringComparer())
.OrderBy(tagsColumn);
Reporter.Output.WriteLine(formatter.Layout());
if (!_commandInput.IsListFlagSpecified)
{
Reporter.Output.WriteLine();
ShowInvocationExamples(templateResolutionResult);
IList<ITemplateInfo> templatesToShow = GetTemplatesToShowDetailedHelpAbout(templateResolutionResult).ToList();
ShowTemplateGroupHelp(templatesToShow);
}
}
private CreationResultStatus EnterAmbiguousTemplateManipulationFlow(TemplateListResolutionResult templateResolutionResult)
{
if (!string.IsNullOrEmpty(TemplateName)
&& templateResolutionResult.CoreMatchedTemplates.Count > 0
&& templateResolutionResult.CoreMatchedTemplates.All(x => x.MatchDisposition.Any(d => d.Location == MatchLocation.Language && d.Kind == MatchKind.Mismatch)))
{
string errorMessage = GetLanguageMismatchErrorMessage(_commandInput.Language);
Reporter.Error.WriteLine(errorMessage.Bold().Red());
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, $"{CommandName} {TemplateName}").Bold().Red());
return CreationResultStatus.NotFound;
}
if (!TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList<string> invalidParams) || (!_commandInput.IsListFlagSpecified && !string.IsNullOrEmpty(TemplateName)))
{
DisplayInvalidParameters(invalidParams);
bool anyPartialMatchesDisplayed = ShowTemplateNameMismatchHelp(templateResolutionResult);
DisplayTemplateList(templateResolutionResult);
return CreationResultStatus.NotFound;
}
if (!string.IsNullOrWhiteSpace(_commandInput.Alias))
{
Reporter.Error.WriteLine(LocalizableStrings.InvalidInputSwitch.Bold().Red());
Reporter.Error.WriteLine(" " + _commandInput.TemplateParamInputFormat("--alias").Bold().Red());
return CreationResultStatus.NotFound;
}
if (_commandInput.IsHelpFlagSpecified)
{
ShowUsageHelp();
DisplayTemplateList(templateResolutionResult);
return CreationResultStatus.Success;
}
else
{
DisplayTemplateList(templateResolutionResult);
//If we're showing the list because we were asked to, exit with success, otherwise, exit with failure
if (_commandInput.IsListFlagSpecified)
{
return CreationResultStatus.Success;
}
else
{
return CreationResultStatus.OperationNotSpecified;
}
}
}
private CreationResultStatus EnterInstallFlow()
{
_telemetryLogger.TrackEvent(CommandName + TelemetryConstants.InstallEventSuffix, new Dictionary<string, string> { { TelemetryConstants.ToInstallCount, _commandInput.ToInstallList.Count.ToString() } });
Installer.InstallPackages(_commandInput.ToInstallList);
//TODO: When an installer that directly calls into NuGet is available,
// return a more accurate representation of the outcome of the operation
return CreationResultStatus.Success;
}
private CreationResultStatus EnterMaintenanceFlow()
{
if (!TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList<string> invalidParams))
{
DisplayInvalidParameters(invalidParams);
if (_commandInput.IsHelpFlagSpecified)
{
ShowUsageHelp();
}
else
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, CommandName).Bold().Red());
}
return CreationResultStatus.InvalidParamValues;
}
if (_commandInput.ToInstallList != null && _commandInput.ToInstallList.Count > 0 && _commandInput.ToInstallList[0] != null)
{
Installer.Uninstall(_commandInput.ToInstallList.Select(x => x.Split(new[] { "::" }, StringSplitOptions.None)[0]));
}
if (_commandInput.ToUninstallList != null && _commandInput.ToUninstallList.Count > 0 && _commandInput.ToUninstallList[0] != null)
{
IEnumerable<string> failures = Installer.Uninstall(_commandInput.ToUninstallList);
foreach (string failure in failures)
{
Console.WriteLine(LocalizableStrings.CouldntUninstall, failure);
}
}
if (_commandInput.ToInstallList != null && _commandInput.ToInstallList.Count > 0 && _commandInput.ToInstallList[0] != null)
{
CreationResultStatus installResult = EnterInstallFlow();
if (installResult == CreationResultStatus.Success)
{
_settingsLoader.Reload();
TemplateListResolutionResult resolutionResult = QueryForTemplateMatches();
DisplayTemplateList(resolutionResult);
}
return installResult;
}
//No other cases specified, we've fallen through to "Usage help + List"
ShowUsageHelp();
TemplateListResolutionResult templateResolutionResult = QueryForTemplateMatches();
DisplayTemplateList(templateResolutionResult);
return CreationResultStatus.Success;
}
private CreationResultStatus SingularGroupDisplayTemplateListIfAnyAreValid(TemplateListResolutionResult templateResolutionResult)
{
bool anyValid = false;
foreach (IFilteredTemplateInfo templateInfo in templateResolutionResult.UnambiguousTemplateGroupToUse)
{
ParseTemplateArgs(templateInfo.Info);
if (!TemplateListResolver.AnyRemainingParameters(_commandInput))
{
anyValid = true;
break;
}
}
if (!anyValid)
{
IFilteredTemplateInfo highestPrecedenceTemplate = TemplateListResolver.FindHighestPrecedenceTemplateIfAllSameGroupIdentity(templateResolutionResult.UnambiguousTemplateGroupToUse);
if (highestPrecedenceTemplate != null)
{
ParseTemplateArgs(highestPrecedenceTemplate.Info);
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, CommandName).Bold().Red());
return CreationResultStatus.InvalidParamValues;
}
}
DisplayTemplateList(templateResolutionResult);
return CreationResultStatus.Success;
}
private CreationResultStatus DisplayTemplateHelpForSingularGroup(TemplateListResolutionResult templateResolutionResult)
{
bool anyArgsErrors = false;
ShowUsageHelp();
bool showImplicitlyHiddenParams = templateResolutionResult.UnambiguousTemplateGroupToUse.Count > 1;
IList<ITemplateInfo> templatesToShowHelpOn = new List<ITemplateInfo>();
HashSet<string> argsInvalidForAllTemplatesInGroup = new HashSet<string>();
bool firstTemplate = true;
foreach (IFilteredTemplateInfo templateInfo in templateResolutionResult.UnambiguousTemplateGroupToUse.OrderByDescending(x => x.Info.Precedence))
{
bool argsError = false;
string commandParseFailureMessage = null;
try
{
ParseTemplateArgs(templateInfo.Info);
}
catch (CommandParserException ex)
{
commandParseFailureMessage = ex.Message;
argsError = true;
}
if (!argsError)
{
argsError = !TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList<string> invalidParamsForTemplate);
if (argsError)
{
if (firstTemplate)
{
argsInvalidForAllTemplatesInGroup.UnionWith(invalidParamsForTemplate);
}
else
{
argsInvalidForAllTemplatesInGroup.IntersectWith(invalidParamsForTemplate);
}
}
}
if (commandParseFailureMessage != null)
{
Reporter.Error.WriteLine(commandParseFailureMessage.Bold().Red());
}
templatesToShowHelpOn.Add(templateInfo.Info);
anyArgsErrors |= argsError;
firstTemplate = false;
}
if (argsInvalidForAllTemplatesInGroup.Count > 0)
{
DisplayInvalidParameters(argsInvalidForAllTemplatesInGroup.ToList());
}
ShowTemplateGroupHelp(templatesToShowHelpOn, showImplicitlyHiddenParams);
return anyArgsErrors ? CreationResultStatus.InvalidParamValues : CreationResultStatus.Success;
}
private async Task<CreationResultStatus> EnterSingularTemplateManipulationFlowAsync(TemplateListResolutionResult templateResolutionResult)
{
if (_commandInput.IsListFlagSpecified)
{
return SingularGroupDisplayTemplateListIfAnyAreValid(templateResolutionResult);
}
else if (_commandInput.IsHelpFlagSpecified)
{
return DisplayTemplateHelpForSingularGroup(templateResolutionResult);
}
bool argsError = false;
string commandParseFailureMessage = null;
IFilteredTemplateInfo highestPrecedenceTemplate = TemplateListResolver.FindHighestPrecedenceTemplateIfAllSameGroupIdentity(templateResolutionResult.UnambiguousTemplateGroupToUse);
try
{
ParseTemplateArgs(highestPrecedenceTemplate.Info);
}
catch (CommandParserException ex)
{
commandParseFailureMessage = ex.Message;
argsError = true;
}
if (!argsError)
{
if (!TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList<string> invalidParams))
{
DisplayInvalidParameters(invalidParams);
argsError = true;
}
else
{
argsError = false;
}
}
highestPrecedenceTemplate.Info.Tags.TryGetValue("language", out ICacheTag language);
bool isMicrosoftAuthored = string.Equals(highestPrecedenceTemplate.Info.Author, "Microsoft", StringComparison.OrdinalIgnoreCase);
string framework = null;
string auth = null;
string templateName = null;
if (isMicrosoftAuthored)
{
templateName = highestPrecedenceTemplate.Info.Identity;
_commandInput.AllTemplateParams.TryGetValue("Framework", out string inputFrameworkValue);
framework = TelemetryHelper.HashWithNormalizedCasing(TelemetryHelper.GetCanonicalValueForChoiceParamOrDefault(highestPrecedenceTemplate.Info, "Framework", inputFrameworkValue));
_commandInput.AllTemplateParams.TryGetValue("auth", out string inputAuthValue);
auth = TelemetryHelper.HashWithNormalizedCasing(TelemetryHelper.GetCanonicalValueForChoiceParamOrDefault(highestPrecedenceTemplate.Info, "auth", inputAuthValue));
}
else
{
templateName = TelemetryHelper.HashWithNormalizedCasing(highestPrecedenceTemplate.Info.Identity);
}
if (argsError)
{
_telemetryLogger.TrackEvent(CommandName + TelemetryConstants.CreateEventSuffix, new Dictionary<string, string>
{
{ TelemetryConstants.Language, language?.ChoicesAndDescriptions.Keys.FirstOrDefault() },
{ TelemetryConstants.ArgError, "True" },
{ TelemetryConstants.Framework, framework },
{ TelemetryConstants.TemplateName, templateName },
{ TelemetryConstants.IsTemplateThirdParty, (!isMicrosoftAuthored).ToString() },
{ TelemetryConstants.Auth, auth }
});
if (commandParseFailureMessage != null)
{
Reporter.Error.WriteLine(commandParseFailureMessage.Bold().Red());
}
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, $"{CommandName} {TemplateName}").Bold().Red());
return CreationResultStatus.InvalidParamValues;
}
else
{
bool success = true;
try
{
return await CreateTemplateAsync(highestPrecedenceTemplate.Info).ConfigureAwait(false);
}
catch (ContentGenerationException cx)
{
success = false;
Reporter.Error.WriteLine(cx.Message.Bold().Red());
if(cx.InnerException != null)
{
Reporter.Error.WriteLine(cx.InnerException.Message.Bold().Red());
}
return CreationResultStatus.CreateFailed;
}
catch (Exception ex)
{
success = false;
Reporter.Error.WriteLine(ex.Message.Bold().Red());
}
finally
{
_telemetryLogger.TrackEvent(CommandName + TelemetryConstants.CreateEventSuffix, new Dictionary<string, string>
{
{ TelemetryConstants.Language, language?.ChoicesAndDescriptions.Keys.FirstOrDefault() },
{ TelemetryConstants.ArgError, "False" },
{ TelemetryConstants.Framework, framework },
{ TelemetryConstants.TemplateName, templateName },
{ TelemetryConstants.IsTemplateThirdParty, (!isMicrosoftAuthored).ToString() },
{ TelemetryConstants.CreationResult, success.ToString() },
{ TelemetryConstants.Auth, auth }
});
}
return CreationResultStatus.CreateFailed;
}
}
private async Task<CreationResultStatus> EnterTemplateManipulationFlowAsync()
{
TemplateListResolutionResult templateResolutionResult = QueryForTemplateMatches();
if (templateResolutionResult.HasUnambiguousTemplateGroupToUse
&& !templateResolutionResult.UnambiguousTemplateGroupToUse.Any(x => x.HasAmbiguousParameterMatch))
{
// unambiguous templates should all have the same dispositions
if (templateResolutionResult.UnambiguousTemplateGroupToUse[0].MatchDisposition.Any(x => x.Kind == MatchKind.Exact && x.Location != MatchLocation.Context && x.Location != MatchLocation.Language))
{
return await EnterSingularTemplateManipulationFlowAsync(templateResolutionResult).ConfigureAwait(false);
}
else if(EnvironmentSettings.Host.OnConfirmPartialMatch(templateResolutionResult.UnambiguousTemplateGroupToUse[0].Info.Name))
{ // unambiguous templates will all have the same name
return await EnterSingularTemplateManipulationFlowAsync(templateResolutionResult).ConfigureAwait(false);
}
else
{
return CreationResultStatus.Cancelled;
}
}
return EnterAmbiguousTemplateManipulationFlow(templateResolutionResult);
}
// Attempts to match templates against the inputs.
private TemplateListResolutionResult QueryForTemplateMatches()
{
return TemplateListResolver.PerformCoreTemplateQuery(_settingsLoader.UserTemplateCache.TemplateInfo, _hostDataLoader, _commandInput, _defaultLanguage);
}
private async Task<CreationResultStatus> ExecuteAsync()
{
// this is checking the initial parse, which is template agnostic.
if (_commandInput.HasParseError)
{
return HandleParseError();
}
if (_commandInput.IsHelpFlagSpecified)
{
_telemetryLogger.TrackEvent(CommandName + TelemetryConstants.HelpEventSuffix);
}
if (_commandInput.ShowAliasesSpecified)
{
return AliasSupport.DisplayAliasValues(EnvironmentSettings, _commandInput, _aliasRegistry, CommandName);
}
if (_commandInput.ExpandedExtraArgsFiles && string.IsNullOrEmpty(_commandInput.Alias))
{ // Only show this if there was no alias expansion.
// ExpandedExtraArgsFiles must be checked before alias expansion - it'll get reset if there's an alias.
Reporter.Output.WriteLine(string.Format(LocalizableStrings.ExtraArgsCommandAfterExpansion, string.Join(" ", _commandInput.Tokens)));
}
if (string.IsNullOrEmpty(_commandInput.Alias))
{ // The --alias param is for creating / updating / deleting aliases.
// If it's not present, try expanding aliases now.
AliasExpansionStatus aliasExpansionStatus = AliasSupport.TryExpandAliases(_commandInput, _aliasRegistry);
if (aliasExpansionStatus == AliasExpansionStatus.ExpansionError)
{
Reporter.Output.WriteLine(LocalizableStrings.AliasExpansionError);
return CreationResultStatus.InvalidParamValues;
}
else if (aliasExpansionStatus == AliasExpansionStatus.Expanded)
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.AliasCommandAfterExpansion, string.Join(" ", _commandInput.Tokens)));
if (_commandInput.HasParseError)
{
Reporter.Output.WriteLine(LocalizableStrings.AliasExpandedCommandParseError);
return HandleParseError();
}
}
// else NoChange... no special action necessary
}
if (!ConfigureLocale())
{
return CreationResultStatus.InvalidParamValues;
}
Initialize();
bool forceCacheRebuild = _commandInput.HasDebuggingFlag("--debug:rebuildcache");
_settingsLoader.RebuildCacheFromSettingsIfNotCurrent(forceCacheRebuild);
try
{
if (!string.IsNullOrEmpty(_commandInput.Alias) && !_commandInput.IsHelpFlagSpecified)
{
return AliasSupport.ManipulateAliasIfValid(_aliasRegistry, _commandInput.Alias, _commandInput.Tokens.ToList(), AllTemplateShortNames);
}
if (string.IsNullOrWhiteSpace(TemplateName))
{
return EnterMaintenanceFlow();
}
return await EnterTemplateManipulationFlowAsync().ConfigureAwait(false);
}
catch (TemplateAuthoringException tae)
{
Reporter.Error.WriteLine(tae.Message.Bold().Red());
return CreationResultStatus.CreateFailed;
}
}
private CreationResultStatus HandleParseError()
{
TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList<string> invalidParams);
DisplayInvalidParameters(invalidParams);
// TODO: get a meaningful error message from the parser
if (_commandInput.IsHelpFlagSpecified)
{
ShowUsageHelp();
}
else
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, CommandName).Bold().Red());
}
return CreationResultStatus.InvalidParamValues;
}
private bool ConfigureLocale()
{
if (!string.IsNullOrEmpty(_commandInput.Locale))
{
string newLocale = _commandInput.Locale;
if (!ValidateLocaleFormat(newLocale))
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.BadLocaleError, newLocale).Bold().Red());
return false;
}
EnvironmentSettings.Host.UpdateLocale(newLocale);
// cache the templates for the new locale
_settingsLoader.Reload();
}
return true;
}
// Note: This method explicitly filters out "type" and "language", in addition to other filtering.
private static IEnumerable<ITemplateParameter> FilterParamsForHelp(IEnumerable<ITemplateParameter> parameterDefinitions, HashSet<string> hiddenParams, bool showImplicitlyHiddenParams = false, bool hasPostActionScriptRunner = false)
{
IList<ITemplateParameter> filteredParams = parameterDefinitions
.Where(x => x.Priority != TemplateParameterPriority.Implicit
&& !hiddenParams.Contains(x.Name) && !string.Equals(x.Name, "type", StringComparison.OrdinalIgnoreCase) && !string.Equals(x.Name, "language", StringComparison.OrdinalIgnoreCase)
&& (showImplicitlyHiddenParams || x.DataType != "choice" || x.Choices.Count > 1)).ToList(); // for filtering "tags"
if (hasPostActionScriptRunner)
{
ITemplateParameter allowScriptsParam = new TemplateParameter()
{
Documentation = LocalizableStrings.WhetherToAllowScriptsToRun,
Name = "allow-scripts",
DataType = "choice",
DefaultValue = "prompt",
Choices = new Dictionary<string, string>()
{
{ "yes", LocalizableStrings.AllowScriptsYesChoice },
{ "no", LocalizableStrings.AllowScriptsNoChoice },
{ "prompt", LocalizableStrings.AllowScriptsPromptChoice }
}
};
filteredParams.Add(allowScriptsParam);
}
return filteredParams;
}
private bool GenerateUsageForTemplate(ITemplateInfo templateInfo)
{
HostSpecificTemplateData hostTemplateData = _hostDataLoader.ReadHostSpecificTemplateData(templateInfo);
if(hostTemplateData.UsageExamples != null)
{
if(hostTemplateData.UsageExamples.Count == 0)
{
return false;
}
Reporter.Output.WriteLine($" dotnet {CommandName} {templateInfo.ShortName} {hostTemplateData.UsageExamples[0]}");
return true;
}
Reporter.Output.Write($" dotnet {CommandName} {templateInfo.ShortName}");
IReadOnlyList<ITemplateParameter> allParameterDefinitions = templateInfo.Parameters;
IEnumerable<ITemplateParameter> filteredParams = FilterParamsForHelp(allParameterDefinitions, hostTemplateData.HiddenParameterNames);
foreach (ITemplateParameter parameter in filteredParams)
{
if (string.Equals(parameter.DataType, "bool", StringComparison.OrdinalIgnoreCase)
&& string.Equals(parameter.DefaultValue, "false", StringComparison.OrdinalIgnoreCase))
{
continue;
}
else if (string.Equals(parameter.DataType, "string", StringComparison.OrdinalIgnoreCase))
{
continue;
}
else if (string.Equals(parameter.DataType, "choice", StringComparison.OrdinalIgnoreCase) && parameter.Choices.Count == 1)
{
continue;
}
string displayParameter = hostTemplateData.DisplayNameForParameter(parameter.Name);
Reporter.Output.Write($" --{displayParameter}");
if (!string.IsNullOrEmpty(parameter.DefaultValue) && !string.Equals(parameter.DataType, "bool", StringComparison.OrdinalIgnoreCase))
{
Reporter.Output.Write($" {parameter.DefaultValue}");
}
}
Reporter.Output.WriteLine();
return true;
}
private bool Initialize()
{
bool ephemeralHiveFlag = _commandInput.HasDebuggingFlag("--debug:ephemeral-hive");
if (ephemeralHiveFlag)
{
EnvironmentSettings.Host.VirtualizeDirectory(_paths.User.BaseDir);
}
bool reinitFlag = _commandInput.HasDebuggingFlag("--debug:reinit");
if (reinitFlag)
{
_paths.Delete(_paths.User.BaseDir);
}
// Note: this leaves things in a weird state. Might be related to the localized caches.
// not sure, need to look into it.
if (reinitFlag || _commandInput.HasDebuggingFlag("--debug:reset-config"))
{
_paths.Delete(_paths.User.AliasesFile);
_paths.Delete(_paths.User.SettingsFile);
_settingsLoader.UserTemplateCache.DeleteAllLocaleCacheFiles();
_settingsLoader.Reload();
return false;
}
if (!_paths.Exists(_paths.User.BaseDir) || !_paths.Exists(_paths.User.FirstRunCookie))
{
if (!_commandInput.IsQuietFlagSpecified)
{
Reporter.Output.WriteLine(LocalizableStrings.GettingReady);
}
ConfigureEnvironment();
_paths.WriteAllText(_paths.User.FirstRunCookie, "");
}
if (_commandInput.HasDebuggingFlag("--debug:showconfig"))
{
ShowConfig();
return false;
}
return true;
}
private void ShowParameterHelp(IReadOnlyDictionary<string, string> inputParams, IParameterSet allParams, string additionalInfo, IReadOnlyList<string> invalidParams, HashSet<string> explicitlyHiddenParams,
IReadOnlyDictionary<string, IReadOnlyList<string>> groupVariantsForCanonicals, HashSet<string> groupUserParamsWithDefaultValues, bool showImplicitlyHiddenParams, bool hasPostActionScriptRunner)
{
if (!string.IsNullOrEmpty(additionalInfo))
{
Reporter.Error.WriteLine(additionalInfo.Bold().Red());
Reporter.Output.WriteLine();
}
IEnumerable<ITemplateParameter> filteredParams = FilterParamsForHelp(allParams.ParameterDefinitions, explicitlyHiddenParams, showImplicitlyHiddenParams, hasPostActionScriptRunner);
if (filteredParams.Any())
{
HelpFormatter<ITemplateParameter> formatter = new HelpFormatter<ITemplateParameter>(EnvironmentSettings, filteredParams, 2, null, true);
formatter.DefineColumn(
param =>
{
string options;
if (string.Equals(param.Name, "allow-scripts", StringComparison.OrdinalIgnoreCase))
{
options = "--" + param.Name;
}
else
{
// the key is guaranteed to exist
IList<string> variants = groupVariantsForCanonicals[param.Name].ToList();
options = string.Join("|", variants.Reverse());
}
return " " + options;
},
LocalizableStrings.Options
);
formatter.DefineColumn(delegate (ITemplateParameter param)
{
StringBuilder displayValue = new StringBuilder(255);
displayValue.AppendLine(param.Documentation);
if (string.Equals(param.DataType, "choice", StringComparison.OrdinalIgnoreCase))
{
int longestChoiceLength = param.Choices.Keys.Max(x => x.Length);
foreach (KeyValuePair<string, string> choiceInfo in param.Choices)
{
displayValue.Append(" " + choiceInfo.Key.PadRight(longestChoiceLength + 4));
if (!string.IsNullOrWhiteSpace(choiceInfo.Value))
{
displayValue.Append("- " + choiceInfo.Value);
}
displayValue.AppendLine();
}
}
else
{
displayValue.Append(param.DataType ?? "string");
displayValue.AppendLine(" - " + param.Priority.ToString());
}
// display the configured value if there is one
string configuredValue = null;
if (allParams.ResolvedValues.TryGetValue(param, out object resolvedValueObject))
{
string resolvedValue = resolvedValueObject as string;
if (!string.IsNullOrEmpty(resolvedValue)
&& !string.IsNullOrEmpty(param.DefaultValue)
&& !string.Equals(param.DefaultValue, resolvedValue))
{
configuredValue = resolvedValue;
}
}
if (string.IsNullOrEmpty(configuredValue))
{
// this will catch when the user inputs the default value. The above deliberately skips it on the resolved values.
if (string.Equals(param.DataType, "bool", StringComparison.OrdinalIgnoreCase)
&& groupUserParamsWithDefaultValues.Contains(param.Name))
{
configuredValue = "true";
}
else
{
inputParams.TryGetValue(param.Name, out configuredValue);
}
}
if (!string.IsNullOrEmpty(configuredValue))
{
string realValue = configuredValue;
if (invalidParams.Contains(param.Name) ||
(string.Equals(param.DataType, "choice", StringComparison.OrdinalIgnoreCase)
&& !param.Choices.ContainsKey(configuredValue)))
{
realValue = realValue.Bold().Red();
}
else if (allParams.TryGetRuntimeValue(EnvironmentSettings, param.Name, out object runtimeVal) && runtimeVal != null)
{
realValue = runtimeVal.ToString();
}
displayValue.AppendLine(string.Format(LocalizableStrings.ConfiguredValue, realValue));
}
// display the default value if there is one
if (!string.IsNullOrEmpty(param.DefaultValue))
{
displayValue.AppendLine(string.Format(LocalizableStrings.DefaultValue, param.DefaultValue));
}
return displayValue.ToString();
}, string.Empty);
Reporter.Output.WriteLine(formatter.Layout());
}
else
{
Reporter.Output.WriteLine(LocalizableStrings.NoParameters);
}
}
private void ParseTemplateArgs(ITemplateInfo templateInfo)
{
HostSpecificTemplateData hostSpecificTemplateData = _hostDataLoader.ReadHostSpecificTemplateData(templateInfo);
_commandInput.ReparseForTemplate(templateInfo, hostSpecificTemplateData);
}
private string DetermineTemplateContext()
{
return _commandInput.TypeFilter?.ToLowerInvariant();
}
private HashSet<string> AllTemplateShortNames
{
get
{
IReadOnlyCollection<IFilteredTemplateInfo> allTemplates = TemplateListResolver.PerformAllTemplatesQuery(_settingsLoader.UserTemplateCache.TemplateInfo, _hostDataLoader);
HashSet<string> allShortNames = new HashSet<string>(allTemplates.Select(x => x.Info.ShortName));
return allShortNames;
}
}
private void ShowConfig()
{
Reporter.Output.WriteLine(LocalizableStrings.CurrentConfiguration);
Reporter.Output.WriteLine(" ");
TableFormatter.Print(EnvironmentSettings.SettingsLoader.MountPoints, LocalizableStrings.NoItems, " ", '-', new Dictionary<string, Func<MountPointInfo, object>>
{
{LocalizableStrings.MountPoints, x => x.Place},
{LocalizableStrings.Id, x => x.MountPointId},
{LocalizableStrings.Parent, x => x.ParentMountPointId},
{LocalizableStrings.Factory, x => x.MountPointFactoryId}
});
TableFormatter.Print(EnvironmentSettings.SettingsLoader.Components.OfType<IMountPointFactory>(), LocalizableStrings.NoItems, " ", '-', new Dictionary<string, Func<IMountPointFactory, object>>
{
{LocalizableStrings.MountPointFactories, x => x.Id},
{LocalizableStrings.Type, x => x.GetType().FullName},
{LocalizableStrings.Assembly, x => x.GetType().GetTypeInfo().Assembly.FullName}
});
TableFormatter.Print(EnvironmentSettings.SettingsLoader.Components.OfType<IGenerator>(), LocalizableStrings.NoItems, " ", '-', new Dictionary<string, Func<IGenerator, object>>
{
{LocalizableStrings.Generators, x => x.Id},
{LocalizableStrings.Type, x => x.GetType().FullName},
{LocalizableStrings.Assembly, x => x.GetType().GetTypeInfo().Assembly.FullName}
});
}
private void ShowInvocationExamples(TemplateListResolutionResult templateResolutionResult)
{
const int ExamplesToShow = 2;
IReadOnlyList<string> preferredNameList = new List<string>() { "mvc" };
int numShown = 0;
if (templateResolutionResult.CoreMatchedTemplates.Count == 0)
{
return;
}
List<ITemplateInfo> templateList = templateResolutionResult.CoreMatchedTemplates.Select(x => x.Info).ToList();
Reporter.Output.WriteLine("Examples:");
HashSet<string> usedGroupIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string preferredName in preferredNameList)
{
ITemplateInfo template = templateList.FirstOrDefault(x => string.Equals(x.ShortName, preferredName, StringComparison.OrdinalIgnoreCase));
if (template != null)
{
string identity = string.IsNullOrWhiteSpace(template.GroupIdentity) ? string.IsNullOrWhiteSpace(template.Identity) ? string.Empty : template.Identity : template.GroupIdentity;
if (usedGroupIds.Add(identity))
{
GenerateUsageForTemplate(template);
numShown++;
}
}
templateList.Remove(template); // remove it so it won't get chosen again
}
// show up to 2 examples (total, including the above)
Random rnd = new Random();
for (int i = numShown; i < ExamplesToShow && templateList.Count > 0; i++)
{
int index = rnd.Next(0, templateList.Count - 1);
ITemplateInfo template = templateList[index];
string identity = string.IsNullOrWhiteSpace(template.GroupIdentity) ? string.IsNullOrWhiteSpace(template.Identity) ? string.Empty : template.Identity : template.GroupIdentity;
if (usedGroupIds.Add(identity) && !GenerateUsageForTemplate(template))
{
--i;
}
templateList.Remove(template); // remove it so it won't get chosen again
}
// show a help example
Reporter.Output.WriteLine($" dotnet {CommandName} --help");
}
private void ShowTemplateGroupHelp(IList<ITemplateInfo> templateGroup, bool showImplicitlyHiddenParams = false)
{
if (templateGroup.Count == 0)
{
return;
}
// Use the highest precedence template for most of the output
ITemplateInfo preferredTemplate = templateGroup.OrderByDescending(x => x.Precedence).First();
// use all templates to get the language choices
HashSet<string> languages = new HashSet<string>();
foreach (ITemplateInfo templateInfo in templateGroup)
{
if (templateInfo.Tags != null && templateInfo.Tags.TryGetValue("language", out ICacheTag languageTag))
{
languages.UnionWith(languageTag.ChoicesAndDescriptions.Keys.Where(x => !string.IsNullOrWhiteSpace(x)).ToList());
}
}
if (languages != null && languages.Any())
{
Reporter.Output.WriteLine($"{preferredTemplate.Name} ({string.Join(", ", languages)})");
}
else
{
Reporter.Output.WriteLine(preferredTemplate.Name);
}
if (!string.IsNullOrWhiteSpace(preferredTemplate.Author))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.Author, preferredTemplate.Author));
}
if (!string.IsNullOrWhiteSpace(preferredTemplate.Description))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.Description, preferredTemplate.Description));
}
if (!string.IsNullOrEmpty(preferredTemplate.ThirdPartyNotices))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.ThirdPartyNotices, preferredTemplate.ThirdPartyNotices));
}
HashSet<string> groupUserParamsWithInvalidValues = new HashSet<string>(StringComparer.Ordinal);
bool groupHasPostActionScriptRunner = false;
List<IParameterSet> parameterSetsForAllTemplatesInGroup = new List<IParameterSet>();
IDictionary<string, InvalidParameterInfo> invalidParametersForGroup = new Dictionary<string, InvalidParameterInfo>(StringComparer.Ordinal);
bool firstInList = true;
Dictionary<string, IReadOnlyList<string>> groupVariantsForCanonicals = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal);
HashSet<string> groupUserParamsWithDefaultValues = new HashSet<string>(StringComparer.Ordinal);
Dictionary<string, bool> parameterHidingDisposition = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (ITemplateInfo templateInfo in templateGroup)
{
IReadOnlyList<InvalidParameterInfo> invalidParamsForTemplate = GetTemplateUsageInformation(templateInfo, out IParameterSet allParamsForTemplate, out IReadOnlyList<string> userParamsWithInvalidValues, out IReadOnlyDictionary<string, IReadOnlyList<string>> variantsForCanonicals, out HashSet<string> userParamsWithDefaultValues, out bool hasPostActionScriptRunner);
HostSpecificTemplateData hostSpecificTemplateData = _hostDataLoader.ReadHostSpecificTemplateData(templateInfo);
HashSet<string> parametersToExplicitlyHide = hostSpecificTemplateData?.HiddenParameterNames ?? new HashSet<string>(StringComparer.Ordinal);
foreach (ITemplateParameter parameter in allParamsForTemplate.ParameterDefinitions)
{
//If the parameter has previously been encountered...
if (parameterHidingDisposition.TryGetValue(parameter.Name, out bool isCurrentlyHidden))
{
//...and it was hidden, but it's not hidden in this template in the group,
// remove its hiding, otherwise leave it as is
if (isCurrentlyHidden && !parametersToExplicitlyHide.Contains(parameter.Name))
{
parameterHidingDisposition[parameter.Name] = false;
}
}
//...otherwise, since this is the first time the parameter has been seen,
// its hiding state should be used as the current disposition
else
{
parameterHidingDisposition[parameter.Name] = parametersToExplicitlyHide.Contains(parameter.Name);
}
}
if (firstInList)
{
invalidParametersForGroup = invalidParamsForTemplate.ToDictionary(x => x.Canonical, x => x);
firstInList = false;
}
else
{
invalidParametersForGroup = InvalidParameterInfo.IntersectWithExisting(invalidParametersForGroup, invalidParamsForTemplate);
}
groupUserParamsWithInvalidValues.IntersectWith(userParamsWithInvalidValues); // intersect because if the value is valid for any version, it's valid.
groupHasPostActionScriptRunner |= hasPostActionScriptRunner;
parameterSetsForAllTemplatesInGroup.Add(allParamsForTemplate);
// take the variants from the first template that has the canonical
foreach (KeyValuePair<string, IReadOnlyList<string>> canonicalAndVariants in variantsForCanonicals)
{
if (!groupVariantsForCanonicals.ContainsKey(canonicalAndVariants.Key))
{
groupVariantsForCanonicals[canonicalAndVariants.Key] = canonicalAndVariants.Value;
}
}
// If any template says the user input value is the default, include it here.
groupUserParamsWithDefaultValues.UnionWith(userParamsWithDefaultValues);
}
IParameterSet allGroupParameters = new TemplateGroupParameterSet(parameterSetsForAllTemplatesInGroup);
string parameterErrors = InvalidParameterInfo.InvalidParameterListToString(invalidParametersForGroup.Values.ToList());
HashSet<string> parametersToHide = new HashSet<string>(parameterHidingDisposition.Where(x => x.Value).Select(x => x.Key), StringComparer.Ordinal);
ShowParameterHelp(_commandInput.AllTemplateParams, allGroupParameters, parameterErrors, groupUserParamsWithInvalidValues.ToList(), parametersToHide, groupVariantsForCanonicals, groupUserParamsWithDefaultValues, showImplicitlyHiddenParams, groupHasPostActionScriptRunner);
}
// Returns true if any partial matches were displayed, false otherwise
private bool ShowTemplateNameMismatchHelp(TemplateListResolutionResult templateResolutionResult)
{
IDictionary<string, IFilteredTemplateInfo> contextProblemMatches = new Dictionary<string, IFilteredTemplateInfo>();
IDictionary<string, IFilteredTemplateInfo> remainingPartialMatches = new Dictionary<string, IFilteredTemplateInfo>();
// this filtering / grouping ignores language differences.
foreach (IFilteredTemplateInfo template in templateResolutionResult.CoreMatchedTemplates)
{
if (contextProblemMatches.ContainsKey(template.Info.Name) || remainingPartialMatches.ContainsKey(template.Info.Name))
{
continue;
}
if (template.MatchDisposition.Any(x => x.Location == MatchLocation.Context && x.Kind != MatchKind.Exact))
{
contextProblemMatches.Add(template.Info.Name, template);
}
else if(template.MatchDisposition.Any(t => t.Location != MatchLocation.Context && t.Kind != MatchKind.Mismatch && t.Kind != MatchKind.Unspecified))
{
remainingPartialMatches.Add(template.Info.Name, template);
}
}
if (contextProblemMatches.Keys.Count + remainingPartialMatches.Keys.Count > 1)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.AmbiguousInputTemplateName, TemplateName));
}
else if (contextProblemMatches.Keys.Count + remainingPartialMatches.Keys.Count == 0)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.NoTemplatesMatchName, TemplateName));
Reporter.Error.WriteLine();
return false;
}
foreach (IFilteredTemplateInfo template in contextProblemMatches.Values)
{
if (template.Info.Tags != null && template.Info.Tags.TryGetValue("type", out ICacheTag typeTag))
{
MatchInfo? matchInfo = WellKnownSearchFilters.ContextFilter(DetermineTemplateContext())(template.Info);
if ((matchInfo?.Kind ?? MatchKind.Mismatch) == MatchKind.Mismatch)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.TemplateNotValidGivenTheSpecifiedFilter, template.Info.Name).Bold().Red());
}
}
else
{ // this really shouldn't ever happen. But better to have a generic error than quietly ignore the partial match.
Reporter.Error.WriteLine(string.Format(LocalizableStrings.GenericPlaceholderTemplateContextError, template.Info.Name).Bold().Red());
}
}
if (remainingPartialMatches.Keys.Count > 0)
{
Reporter.Error.WriteLine(LocalizableStrings.TemplateMultiplePartialNameMatches.Bold().Red());
}
Reporter.Error.WriteLine();
return true;
}
private void ShowUsageHelp()
{
Reporter.Output.WriteLine(_commandInput.HelpText);
Reporter.Output.WriteLine();
}
private void DisplayInvalidParameters(IReadOnlyList<string> invalidParams)
{
if (invalidParams.Count > 0)
{
Reporter.Error.WriteLine(LocalizableStrings.InvalidInputSwitch.Bold().Red());
foreach (string flag in invalidParams)
{
Reporter.Error.WriteLine($" {flag}".Bold().Red());
}
}
}
private static bool ValidateLocaleFormat(string localeToCheck)
{
return LocaleFormatRegex.IsMatch(localeToCheck);
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
namespace OpenTK.Math
{
/// <summary>
/// Represents a 3D vector using three double-precision floating-point numbers.
/// </summary>
[Obsolete("OpenTK.Math functions have been moved to the root OpenTK namespace (reason: XNA compatibility")]
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3d : IEquatable<Vector3d>
{
#region Fields
/// <summary>
/// The X component of the Vector3.
/// </summary>
public double X;
/// <summary>
/// The Y component of the Vector3.
/// </summary>
public double Y;
/// <summary>
/// The Z component of the Vector3.
/// </summary>
public double Z;
#endregion
#region Constructors
/// <summary>
/// Constructs a new Vector3.
/// </summary>
/// <param name="x">The x component of the Vector3.</param>
/// <param name="y">The y component of the Vector3.</param>
/// <param name="z">The z component of the Vector3.</param>
public Vector3d(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
/// <summary>
/// Constructs a new instance from the given Vector2d.
/// </summary>
/// <param name="v">The Vector2d to copy components from.</param>
public Vector3d(Vector2d v)
{
X = v.X;
Y = v.Y;
Z = 0.0f;
}
/// <summary>
/// Constructs a new instance from the given Vector3d.
/// </summary>
/// <param name="v">The Vector3d to copy components from.</param>
public Vector3d(Vector3d v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
}
/// <summary>
/// Constructs a new instance from the given Vector4d.
/// </summary>
/// <param name="v">The Vector4d to copy components from.</param>
public Vector3d(Vector4d v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
}
#endregion
#region Public Members
#region Instance
#region public void Add()
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
public void Add(Vector3d right)
{
this.X += right.X;
this.Y += right.Y;
this.Z += right.Z;
}
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
public void Add(ref Vector3d right)
{
this.X += right.X;
this.Y += right.Y;
this.Z += right.Z;
}
#endregion public void Add()
#region public void Sub()
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
public void Sub(Vector3d right)
{
this.X -= right.X;
this.Y -= right.Y;
this.Z -= right.Z;
}
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
public void Sub(ref Vector3d right)
{
this.X -= right.X;
this.Y -= right.Y;
this.Z -= right.Z;
}
#endregion public void Sub()
#region public void Mult()
/// <summary>Multiply this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
public void Mult(double f)
{
this.X *= f;
this.Y *= f;
this.Z *= f;
}
#endregion public void Mult()
#region public void Div()
/// <summary>Divide this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
public void Div(double f)
{
double mult = 1.0 / f;
this.X *= mult;
this.Y *= mult;
this.Z *= mult;
}
#endregion public void Div()
#region public double Length
/// <summary>
/// Gets the length (magnitude) of the vector.
/// </summary>
/// <see cref="LengthFast"/>
/// <seealso cref="LengthSquared"/>
public double Length
{
get
{
return (float)System.Math.Sqrt(X * X + Y * Y + Z * Z);
}
}
#endregion
#region public double LengthFast
/// <summary>
/// Gets an approximation of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property uses an approximation of the square root function to calculate vector magnitude, with
/// an upper error bound of 0.001.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthSquared"/>
public double LengthFast
{
get
{
return 1.0f / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z);
}
}
#endregion
#region public double LengthSquared
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthFast"/>
public double LengthSquared
{
get
{
return X * X + Y * Y + Z * Z;
}
}
#endregion
#region public void Normalize()
/// <summary>
/// Scales the Vector3d to unit length.
/// </summary>
public void Normalize()
{
double scale = 1.0f / this.Length;
X *= scale;
Y *= scale;
Z *= scale;
}
#endregion
#region public void NormalizeFast()
/// <summary>
/// Scales the Vector3d to approximately unit length.
/// </summary>
public void NormalizeFast()
{
double scale = Functions.InverseSqrtFast(X * X + Y * Y + Z * Z);
X *= scale;
Y *= scale;
Z *= scale;
}
#endregion
#region public void Scale()
/// <summary>
/// Scales the current Vector3d by the given amounts.
/// </summary>
/// <param name="sx">The scale of the X component.</param>
/// <param name="sy">The scale of the Y component.</param>
/// <param name="sz">The scale of the Z component.</param>
public void Scale(double sx, double sy, double sz)
{
this.X = X * sx;
this.Y = Y * sy;
this.Z = Z * sz;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
public void Scale(Vector3d scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
this.Z *= scale.Z;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
[CLSCompliant(false)]
public void Scale(ref Vector3d scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
this.Z *= scale.Z;
}
#endregion public void Scale()
#endregion
#region Static
#region Fields
/// <summary>
/// Defines a unit-length Vector3d that points towards the X-axis.
/// </summary>
public static readonly Vector3d UnitX = new Vector3d(1, 0, 0);
/// <summary>
/// Defines a unit-length Vector3d that points towards the Y-axis.
/// </summary>
public static readonly Vector3d UnitY = new Vector3d(0, 1, 0);
/// <summary>
/// /// Defines a unit-length Vector3d that points towards the Z-axis.
/// </summary>
public static readonly Vector3d UnitZ = new Vector3d(0, 0, 1);
/// <summary>
/// Defines a zero-length Vector3.
/// </summary>
public static readonly Vector3d Zero = new Vector3d(0, 0, 0);
/// <summary>
/// Defines an instance with all components set to 1.
/// </summary>
public static readonly Vector3d One = new Vector3d(1, 1, 1);
/// <summary>
/// Defines the size of the Vector3d struct in bytes.
/// </summary>
public static readonly int SizeInBytes = Marshal.SizeOf(new Vector3d());
#endregion
#region Add
/// <summary>
/// Add two Vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of addition</returns>
public static Vector3d Add(Vector3d a, Vector3d b)
{
a.X += b.X;
a.Y += b.Y;
a.Z += b.Z;
return a;
}
/// <summary>
/// Add two Vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of addition</param>
public static void Add(ref Vector3d a, ref Vector3d b, out Vector3d result)
{
result.X = a.X + b.X;
result.Y = a.Y + b.Y;
result.Z = a.Z + b.Z;
}
#endregion
#region Sub
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
public static Vector3d Sub(Vector3d a, Vector3d b)
{
a.X -= b.X;
a.Y -= b.Y;
a.Z -= b.Z;
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
public static void Sub(ref Vector3d a, ref Vector3d b, out Vector3d result)
{
result.X = a.X - b.X;
result.Y = a.Y - b.Y;
result.Z = a.Z - b.Z;
}
#endregion
#region Mult
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the multiplication</returns>
public static Vector3d Mult(Vector3d a, double f)
{
a.X *= f;
a.Y *= f;
a.Z *= f;
return a;
}
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the multiplication</param>
public static void Mult(ref Vector3d a, double f, out Vector3d result)
{
result.X = a.X * f;
result.Y = a.Y * f;
result.Z = a.Z * f;
}
#endregion
#region Div
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the division</returns>
public static Vector3d Div(Vector3d a, double f)
{
double mult = 1.0f / f;
a.X *= mult;
a.Y *= mult;
a.Z *= mult;
return a;
}
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the division</param>
public static void Div(ref Vector3d a, double f, out Vector3d result)
{
double mult = 1.0f / f;
result.X = a.X * mult;
result.Y = a.Y * mult;
result.Z = a.Z * mult;
}
#endregion
#region ComponentMin
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise minimum</returns>
public static Vector3d ComponentMin(Vector3d a, Vector3d b)
{
a.X = a.X < b.X ? a.X : b.X;
a.Y = a.Y < b.Y ? a.Y : b.Y;
a.Z = a.Z < b.Z ? a.Z : b.Z;
return a;
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise minimum</param>
public static void ComponentMin(ref Vector3d a, ref Vector3d b, out Vector3d result)
{
result.X = a.X < b.X ? a.X : b.X;
result.Y = a.Y < b.Y ? a.Y : b.Y;
result.Z = a.Z < b.Z ? a.Z : b.Z;
}
#endregion
#region ComponentMax
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise maximum</returns>
public static Vector3d ComponentMax(Vector3d a, Vector3d b)
{
a.X = a.X > b.X ? a.X : b.X;
a.Y = a.Y > b.Y ? a.Y : b.Y;
a.Z = a.Z > b.Z ? a.Z : b.Z;
return a;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise maximum</param>
public static void ComponentMax(ref Vector3d a, ref Vector3d b, out Vector3d result)
{
result.X = a.X > b.X ? a.X : b.X;
result.Y = a.Y > b.Y ? a.Y : b.Y;
result.Z = a.Z > b.Z ? a.Z : b.Z;
}
#endregion
#region Min
/// <summary>
/// Returns the Vector3d with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3</returns>
public static Vector3d Min(Vector3d left, Vector3d right)
{
return left.LengthSquared < right.LengthSquared ? left : right;
}
#endregion
#region Max
/// <summary>
/// Returns the Vector3d with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3</returns>
public static Vector3d Max(Vector3d left, Vector3d right)
{
return left.LengthSquared >= right.LengthSquared ? left : right;
}
#endregion
#region Clamp
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <returns>The clamped vector</returns>
public static Vector3d Clamp(Vector3d vec, Vector3d min, Vector3d max)
{
vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
vec.Z = vec.Z < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z;
return vec;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <param name="result">The clamped vector</param>
public static void Clamp(ref Vector3d vec, ref Vector3d min, ref Vector3d max, out Vector3d result)
{
result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
result.Z = vec.Z < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z;
}
#endregion
#region Normalize
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector3d Normalize(Vector3d vec)
{
double scale = 1.0f / vec.Length;
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
return vec;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void Normalize(ref Vector3d vec, out Vector3d result)
{
double scale = 1.0f / vec.Length;
result.X = vec.X * scale;
result.Y = vec.Y * scale;
result.Z = vec.Z * scale;
}
#endregion
#region NormalizeFast
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector3d NormalizeFast(Vector3d vec)
{
double scale = Functions.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z);
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
return vec;
}
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void NormalizeFast(ref Vector3d vec, out Vector3d result)
{
double scale = Functions.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z);
result.X = vec.X * scale;
result.Y = vec.Y * scale;
result.Z = vec.Z * scale;
}
#endregion
#region Dot
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The dot product of the two inputs</returns>
public static double Dot(Vector3d left, Vector3d right)
{
return left.X * right.X + left.Y * right.Y + left.Z * right.Z;
}
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <param name="result">The dot product of the two inputs</param>
public static void Dot(ref Vector3d left, ref Vector3d right, out double result)
{
result = left.X * right.X + left.Y * right.Y + left.Z * right.Z;
}
#endregion
#region Cross
/// <summary>
/// Caclulate the cross (vector) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The cross product of the two inputs</returns>
public static Vector3d Cross(Vector3d left, Vector3d right)
{
return new Vector3d(left.Y * right.Z - left.Z * right.Y,
left.Z * right.X - left.X * right.Z,
left.X * right.Y - left.Y * right.X);
}
/// <summary>
/// Caclulate the cross (vector) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The cross product of the two inputs</returns>
/// <param name="result">The cross product of the two inputs</param>
public static void Cross(ref Vector3d left, ref Vector3d right, out Vector3d result)
{
result.X = left.Y * right.Z - left.Z * right.Y;
result.Y = left.Z * right.X - left.X * right.Z;
result.Z = left.X * right.Y - left.Y * right.X;
}
#endregion
#region Lerp
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns>
public static Vector3d Lerp(Vector3d a, Vector3d b, double blend)
{
a.X = blend * (b.X - a.X) + a.X;
a.Y = blend * (b.Y - a.Y) + a.Y;
a.Z = blend * (b.Z - a.Z) + a.Z;
return a;
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param>
public static void Lerp(ref Vector3d a, ref Vector3d b, double blend, out Vector3d result)
{
result.X = blend * (b.X - a.X) + a.X;
result.Y = blend * (b.Y - a.Y) + a.Y;
result.Z = blend * (b.Z - a.Z) + a.Z;
}
#endregion
#region Barycentric
/// <summary>
/// Interpolate 3 Vectors using Barycentric coordinates
/// </summary>
/// <param name="a">First input Vector</param>
/// <param name="b">Second input Vector</param>
/// <param name="c">Third input Vector</param>
/// <param name="u">First Barycentric Coordinate</param>
/// <param name="v">Second Barycentric Coordinate</param>
/// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns>
public static Vector3d BaryCentric(Vector3d a, Vector3d b, Vector3d c, double u, double v)
{
return a + u * (b - a) + v * (c - a);
}
/// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary>
/// <param name="a">First input Vector.</param>
/// <param name="b">Second input Vector.</param>
/// <param name="c">Third input Vector.</param>
/// <param name="u">First Barycentric Coordinate.</param>
/// <param name="v">Second Barycentric Coordinate.</param>
/// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param>
public static void BaryCentric(ref Vector3d a, ref Vector3d b, ref Vector3d c, float u, float v, out Vector3d result)
{
result = a; // copy
Vector3d temp = b; // copy
temp.Sub(ref a);
temp.Mult(u);
result.Add(ref temp);
temp = c; // copy
temp.Sub(ref a);
temp.Mult(v);
result.Add(ref temp);
}
#endregion
#region Transform
/// <summary>Transform a direction vector by the given Matrix
/// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored.
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3d TransformVector(Vector3d vec, Matrix4d mat)
{
return new Vector3d(
Vector3d.Dot(vec, new Vector3d(mat.Column0)),
Vector3d.Dot(vec, new Vector3d(mat.Column1)),
Vector3d.Dot(vec, new Vector3d(mat.Column2)));
}
/// <summary>Transform a direction vector by the given Matrix
/// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored.
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void TransformVector(ref Vector3d vec, ref Matrix4d mat, out Vector3d result)
{
result.X = vec.X * mat.Row0.X +
vec.Y * mat.Row1.X +
vec.Z * mat.Row2.X;
result.Y = vec.X * mat.Row0.Y +
vec.Y * mat.Row1.Y +
vec.Z * mat.Row2.Y;
result.Z = vec.X * mat.Row0.Z +
vec.Y * mat.Row1.Z +
vec.Z * mat.Row2.Z;
}
/// <summary>Transform a Normal by the given Matrix</summary>
/// <remarks>
/// This calculates the inverse of the given matrix, use TransformNormalInverse if you
/// already have the inverse to avoid this extra calculation
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed normal</returns>
public static Vector3d TransformNormal(Vector3d norm, Matrix4d mat)
{
mat.Invert();
return TransformNormalInverse(norm, mat);
}
/// <summary>Transform a Normal by the given Matrix</summary>
/// <remarks>
/// This calculates the inverse of the given matrix, use TransformNormalInverse if you
/// already have the inverse to avoid this extra calculation
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed normal</param>
public static void TransformNormal(ref Vector3d norm, ref Matrix4d mat, out Vector3d result)
{
Matrix4d Inverse = Matrix4d.Invert(mat);
Vector3d.TransformNormalInverse(ref norm, ref Inverse, out result);
}
/// <summary>Transform a Normal by the (transpose of the) given Matrix</summary>
/// <remarks>
/// This version doesn't calculate the inverse matrix.
/// Use this version if you already have the inverse of the desired transform to hand
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="invMat">The inverse of the desired transformation</param>
/// <returns>The transformed normal</returns>
public static Vector3d TransformNormalInverse(Vector3d norm, Matrix4d invMat)
{
return new Vector3d(
Vector3d.Dot(norm, new Vector3d(invMat.Row0)),
Vector3d.Dot(norm, new Vector3d(invMat.Row1)),
Vector3d.Dot(norm, new Vector3d(invMat.Row2)));
}
/// <summary>Transform a Normal by the (transpose of the) given Matrix</summary>
/// <remarks>
/// This version doesn't calculate the inverse matrix.
/// Use this version if you already have the inverse of the desired transform to hand
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="invMat">The inverse of the desired transformation</param>
/// <param name="result">The transformed normal</param>
public static void TransformNormalInverse(ref Vector3d norm, ref Matrix4d invMat, out Vector3d result)
{
result.X = norm.X * invMat.Row0.X +
norm.Y * invMat.Row0.Y +
norm.Z * invMat.Row0.Z;
result.Y = norm.X * invMat.Row1.X +
norm.Y * invMat.Row1.Y +
norm.Z * invMat.Row1.Z;
result.Z = norm.X * invMat.Row2.X +
norm.Y * invMat.Row2.Y +
norm.Z * invMat.Row2.Z;
}
/// <summary>Transform a Position by the given Matrix</summary>
/// <param name="pos">The position to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed position</returns>
public static Vector3d TransformPosition(Vector3d pos, Matrix4d mat)
{
return new Vector3d(
Vector3d.Dot(pos, new Vector3d(mat.Column0)) + mat.Row3.X,
Vector3d.Dot(pos, new Vector3d(mat.Column1)) + mat.Row3.Y,
Vector3d.Dot(pos, new Vector3d(mat.Column2)) + mat.Row3.Z);
}
/// <summary>Transform a Position by the given Matrix</summary>
/// <param name="pos">The position to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed position</param>
public static void TransformPosition(ref Vector3d pos, ref Matrix4d mat, out Vector3d result)
{
result.X = pos.X * mat.Row0.X +
pos.Y * mat.Row1.X +
pos.Z * mat.Row2.X +
mat.Row3.X;
result.Y = pos.X * mat.Row0.Y +
pos.Y * mat.Row1.Y +
pos.Z * mat.Row2.Y +
mat.Row3.Y;
result.Z = pos.X * mat.Row0.Z +
pos.Y * mat.Row1.Z +
pos.Z * mat.Row2.Z +
mat.Row3.Z;
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector4d Transform(Vector3d vec, Matrix4d mat)
{
Vector4d v4 = new Vector4d(vec.X, vec.Y, vec.Z, 1.0f);
return new Vector4d(
Vector4d.Dot(v4, mat.Column0),
Vector4d.Dot(v4, mat.Column1),
Vector4d.Dot(v4, mat.Column2),
Vector4d.Dot(v4, mat.Column3));
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void Transform(ref Vector3d vec, ref Matrix4d mat, out Vector4d result)
{
Vector4d v4 = new Vector4d(vec.X, vec.Y, vec.Z, 1.0f);
Vector4d.Transform(ref v4, ref mat, out result);
}
/// <summary>
/// Transform a Vector3d by the given Matrix, and project the resulting Vector4 back to a Vector3
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3d TransformPerspective(Vector3d vec, Matrix4d mat)
{
Vector4d h = Transform(vec, mat);
return new Vector3d(h.X / h.W, h.Y / h.W, h.Z / h.W);
}
/// <summary>Transform a Vector3d by the given Matrix, and project the resulting Vector4d back to a Vector3d</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void TransformPerspective(ref Vector3d vec, ref Matrix4d mat, out Vector3d result)
{
Vector4d h;
Vector3d.Transform(ref vec, ref mat, out h);
result.X = h.X / h.W;
result.Y = h.Y / h.W;
result.Z = h.Z / h.W;
}
#endregion
#region CalculateAngle
/// <summary>
/// Calculates the angle (in radians) between two vectors.
/// </summary>
/// <param name="first">The first vector.</param>
/// <param name="second">The second vector.</param>
/// <returns>Angle (in radians) between the vectors.</returns>
/// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks>
public static double CalculateAngle(Vector3d first, Vector3d second)
{
return System.Math.Acos((Vector3d.Dot(first, second)) / (first.Length * second.Length));
}
/// <summary>Calculates the angle (in radians) between two vectors.</summary>
/// <param name="first">The first vector.</param>
/// <param name="second">The second vector.</param>
/// <param name="result">Angle (in radians) between the vectors.</param>
/// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks>
public static void CalculateAngle(ref Vector3d first, ref Vector3d second, out double result)
{
double temp;
Vector3d.Dot(ref first, ref second, out temp);
result = System.Math.Acos(temp / (first.Length * second.Length));
}
#endregion
#endregion
#region Swizzle
/// <summary>
/// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2d Xy { get { return new Vector2d(X, Y); } set { X = value.X; Y = value.Y; } }
#endregion
#region Operators
public static Vector3d operator +(Vector3d left, Vector3d right)
{
left.X += right.X;
left.Y += right.Y;
left.Z += right.Z;
return left;
}
public static Vector3d operator -(Vector3d left, Vector3d right)
{
left.X -= right.X;
left.Y -= right.Y;
left.Z -= right.Z;
return left;
}
public static Vector3d operator -(Vector3d vec)
{
vec.X = -vec.X;
vec.Y = -vec.Y;
vec.Z = -vec.Z;
return vec;
}
public static Vector3d operator *(Vector3d vec, double f)
{
vec.X *= f;
vec.Y *= f;
vec.Z *= f;
return vec;
}
public static Vector3d operator *(double f, Vector3d vec)
{
vec.X *= f;
vec.Y *= f;
vec.Z *= f;
return vec;
}
public static Vector3d operator /(Vector3d vec, double f)
{
double mult = 1.0f / f;
vec.X *= mult;
vec.Y *= mult;
vec.Z *= mult;
return vec;
}
public static bool operator ==(Vector3d left, Vector3d right)
{
return left.Equals(right);
}
public static bool operator !=(Vector3d left, Vector3d right)
{
return !left.Equals(right);
}
/// <summary>Converts OpenTK.Vector3 to OpenTK.Vector3d.</summary>
/// <param name="v3">The Vector3 to convert.</param>
/// <returns>The resulting Vector3d.</returns>
public static explicit operator Vector3d(Vector3 v3)
{
return new Vector3d(v3.X, v3.Y, v3.Z);
}
/// <summary>Converts OpenTK.Vector3d to OpenTK.Vector3.</summary>
/// <param name="v3d">The Vector3d to convert.</param>
/// <returns>The resulting Vector3.</returns>
public static explicit operator Vector3(Vector3d v3d)
{
return new Vector3((float)v3d.X, (float)v3d.Y, (float)v3d.Z);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Vector3.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("({0}, {1}, {2})", X, Y, Z);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Vector3))
return false;
return this.Equals((Vector3)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Vector3> Members
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector3d other)
{
return
X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Parse.Push.Internal;
using Parse.Core.Internal;
using Parse.Common.Internal;
namespace Parse {
/// <summary>
/// A utility class for sending and receiving push notifications.
/// </summary>
public partial class ParsePush {
private object mutex;
private IPushState state;
/// <summary>
/// Creates a push which will target every device. The Data field must be set before calling SendAsync.
/// </summary>
public ParsePush() {
mutex = new object();
// Default to everyone.
state = new MutablePushState {
Query = ParseInstallation.Query
};
}
#region Properties
/// <summary>
/// An installation query that specifies which installations should receive
/// this push.
/// This should not be used in tandem with Channels.
/// </summary>
public ParseQuery<ParseInstallation> Query {
get { return state.Query; }
set {
MutateState(s => {
if (s.Channels != null && value != null && value.GetConstraint("channels") != null) {
throw new InvalidOperationException("A push may not have both Channels and a Query with a channels constraint");
}
s.Query = value;
});
}
}
/// <summary>
/// A short-hand to set a query which only discriminates on the channels to which a device is subscribed.
/// This is shorthand for:
///
/// <code>
/// var push = new Push();
/// push.Query = ParseInstallation.Query.WhereKeyContainedIn("channels", channels);
/// </code>
///
/// This cannot be used in tandem with Query.
/// </summary>
public IEnumerable<string> Channels {
get { return state.Channels; }
set {
MutateState(s => {
if (value != null && s.Query != null && s.Query.GetConstraint("channels") != null) {
throw new InvalidOperationException("A push may not have both Channels and a Query with a channels constraint");
}
s.Channels = value;
});
}
}
/// <summary>
/// The time at which this push will expire. This should not be used in tandem with ExpirationInterval.
/// </summary>
public DateTime? Expiration {
get { return state.Expiration; }
set {
MutateState(s => {
if (s.ExpirationInterval != null) {
throw new InvalidOperationException("Cannot set Expiration after setting ExpirationInterval");
}
s.Expiration = value;
});
}
}
/// <summary>
/// The time at which this push will be sent.
/// </summary>
public DateTime? PushTime {
get { return state.PushTime; }
set {
MutateState(s => {
DateTime now = DateTime.Now;
if (value < now || value > now.AddDays(14)) {
throw new InvalidOperationException("Cannot set PushTime in the past or more than two weeks later than now");
}
s.PushTime = value;
});
}
}
/// <summary>
/// The time from initial schedul when this push will expire. This should not be used in tandem with Expiration.
/// </summary>
public TimeSpan? ExpirationInterval {
get { return state.ExpirationInterval; }
set {
MutateState(s => {
if (s.Expiration != null) {
throw new InvalidOperationException("Cannot set ExpirationInterval after setting Expiration");
}
s.ExpirationInterval = value;
});
}
}
/// <summary>
/// The contents of this push. Some keys have special meaning. A full list of pre-defined
/// keys can be found in the Parse Push Guide. The following keys affect WinRT devices.
/// Keys which do not start with x-winrt- can be prefixed with x-winrt- to specify an
/// override only sent to winrt devices.
/// alert: the body of the alert text.
/// title: The title of the text.
/// x-winrt-payload: A full XML payload to be sent to WinRT installations instead of
/// the auto-layout.
/// This should not be used in tandem with Alert.
/// </summary>
public IDictionary<string, object> Data {
get { return state.Data; }
set {
MutateState(s => {
if (s.Alert != null && value != null) {
throw new InvalidOperationException("A push may not have both an Alert and Data");
}
s.Data = value;
});
}
}
/// <summary>
/// A convenience method which sets Data to a dictionary with alert as its only field. Equivalent to
///
/// <code>
/// Data = new Dictionary<string, object> {{"alert", alert}};
/// </code>
///
/// This should not be used in tandem with Data.
/// </summary>
public string Alert {
get { return state.Alert; }
set {
MutateState(s => {
if (s.Data != null && value != null) {
throw new InvalidOperationException("A push may not have both an Alert and Data");
}
s.Alert = value;
});
}
}
#endregion
internal IDictionary<string, object> Encode() {
return ParsePushEncoder.Instance.Encode(state);
}
private void MutateState(Action<MutablePushState> func) {
lock (mutex) {
state = state.MutatedClone(func);
}
}
private static IParsePushController PushController {
get {
return ParsePushPlugins.Instance.PushController;
}
}
private static IParsePushChannelsController PushChannelsController {
get {
return ParsePushPlugins.Instance.PushChannelsController;
}
}
#region Sending Push
/// <summary>
/// Request a push to be sent. When this task completes, Parse has successfully acknowledged a request
/// to send push notifications but has not necessarily finished sending all notifications
/// requested. The current status of recent push notifications can be seen in your Push Notifications
/// console on http://parse.com
/// </summary>
/// <returns>A Task for continuation.</returns>
public Task SendAsync() {
return SendAsync(CancellationToken.None);
}
/// <summary>
/// Request a push to be sent. When this task completes, Parse has successfully acknowledged a request
/// to send push notifications but has not necessarily finished sending all notifications
/// requested. The current status of recent push notifications can be seen in your Push Notifications
/// console on http://parse.com
/// </summary>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public Task SendAsync(CancellationToken cancellationToken) {
return PushController.SendPushNotificationAsync(state, cancellationToken);
}
/// <summary>
/// Pushes a simple message to every device. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
public static Task SendAlertAsync(string alert) {
var push = new ParsePush();
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes a simple message to every device subscribed to channel. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = new List<string> { channel };
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
/// <param name="channel">An Installation must be subscribed to channel to receive this Push Notification.</param>
public static Task SendAlertAsync(string alert, string channel) {
var push = new ParsePush();
push.Channels = new List<string> { channel };
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes a simple message to every device subscribed to any of channels. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = channels;
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
/// <param name="channels">An Installation must be subscribed to any of channels to receive this Push Notification.</param>
public static Task SendAlertAsync(string alert, IEnumerable<string> channels) {
var push = new ParsePush();
push.Channels = channels;
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes a simple message to every device matching the target query. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Query = query;
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
/// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
public static Task SendAlertAsync(string alert, ParseQuery<ParseInstallation> query) {
var push = new ParsePush();
push.Query = query;
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
public static Task SendDataAsync(IDictionary<string, object> data) {
var push = new ParsePush();
push.Data = data;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device subscribed to channel. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = new List<string> { channel };
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
/// <param name="channel">An Installation must be subscribed to channel to receive this Push Notification.</param>
public static Task SendDataAsync(IDictionary<string, object> data, string channel) {
var push = new ParsePush();
push.Channels = new List<string> { channel };
push.Data = data;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device subscribed to any of channels. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = channels;
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
/// <param name="channels">An Installation must be subscribed to any of channels to receive this Push Notification.</param>
public static Task SendDataAsync(IDictionary<string, object> data, IEnumerable<string> channels) {
var push = new ParsePush();
push.Channels = channels;
push.Data = data;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device matching target. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Query = query
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
/// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
public static Task SendDataAsync(IDictionary<string, object> data, ParseQuery<ParseInstallation> query) {
var push = new ParsePush();
push.Query = query;
push.Data = data;
return push.SendAsync();
}
#endregion
#region Receiving Push
/// <summary>
/// An event fired when a push notification is received.
/// </summary>
public static event EventHandler<ParsePushNotificationEventArgs> ParsePushNotificationReceived {
add {
parsePushNotificationReceived.Add(value);
}
remove {
parsePushNotificationReceived.Remove(value);
}
}
internal static readonly SynchronizedEventHandler<ParsePushNotificationEventArgs> parsePushNotificationReceived = new SynchronizedEventHandler<ParsePushNotificationEventArgs>();
#endregion
#region Push Subscription
/// <summary>
/// Subscribe the current installation to this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddUniqueToList("channels", channel);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channel">The channel to which this installation should subscribe.</param>
public static Task SubscribeAsync(string channel) {
return SubscribeAsync(new List<string> { channel }, CancellationToken.None);
}
/// <summary>
/// Subscribe the current installation to this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddUniqueToList("channels", channel);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channel">The channel to which this installation should subscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task SubscribeAsync(string channel, CancellationToken cancellationToken) {
return SubscribeAsync(new List<string> { channel }, cancellationToken);
}
/// <summary>
/// Subscribe the current installation to these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddRangeUniqueToList("channels", channels);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channels">The channels to which this installation should subscribe.</param>
public static Task SubscribeAsync(IEnumerable<string> channels) {
return SubscribeAsync(channels, CancellationToken.None);
}
/// <summary>
/// Subscribe the current installation to these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddRangeUniqueToList("channels", channels);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channels">The channels to which this installation should subscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task SubscribeAsync(IEnumerable<string> channels, CancellationToken cancellationToken) {
return PushChannelsController.SubscribeAsync(channels, cancellationToken);
}
/// <summary>
/// Unsubscribe the current installation from this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.Remove("channels", channel);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channel">The channel from which this installation should unsubscribe.</param>
public static Task UnsubscribeAsync(string channel) {
return UnsubscribeAsync(new List<string> { channel }, CancellationToken.None);
}
/// <summary>
/// Unsubscribe the current installation from this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.Remove("channels", channel);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channel">The channel from which this installation should unsubscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task UnsubscribeAsync(string channel, CancellationToken cancellationToken) {
return UnsubscribeAsync(new List<string> { channel }, cancellationToken);
}
/// <summary>
/// Unsubscribe the current installation from these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.RemoveAllFromList("channels", channels);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channels">The channels from which this installation should unsubscribe.</param>
public static Task UnsubscribeAsync(IEnumerable<string> channels) {
return UnsubscribeAsync(channels, CancellationToken.None);
}
/// <summary>
/// Unsubscribe the current installation from these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.RemoveAllFromList("channels", channels);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channels">The channels from which this installation should unsubscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task UnsubscribeAsync(IEnumerable<string> channels, CancellationToken cancellationToken) {
return PushChannelsController.UnsubscribeAsync(channels, cancellationToken);
}
#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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.StorSimple;
using Microsoft.WindowsAzure.Management.StorSimple.Models;
namespace Microsoft.WindowsAzure.Management.StorSimple
{
/// <summary>
/// This is an RESTFul API to manage you StorSimple Objects
/// </summary>
public static partial class DataContainerOperationsExtensions
{
/// <summary>
/// The Begin Creating Volume Container operation creates a new volume
/// container.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='containerDetails'>
/// Required. Parameters supplied to the Begin Creating Volume
/// Container operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public static TaskResponse BeginCreating(this IDataContainerOperations operations, string deviceId, DataContainerRequest containerDetails, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataContainerOperations)s).BeginCreatingAsync(deviceId, containerDetails, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Creating Volume Container operation creates a new volume
/// container.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='containerDetails'>
/// Required. Parameters supplied to the Begin Creating Volume
/// Container operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public static Task<TaskResponse> BeginCreatingAsync(this IDataContainerOperations operations, string deviceId, DataContainerRequest containerDetails, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginCreatingAsync(deviceId, containerDetails, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// The Begin Deleting Volume Container operation deletes the specified
/// volume container.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='dataContainerId'>
/// Required. id of data container which needs to be deleted
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public static TaskResponse BeginDeleting(this IDataContainerOperations operations, string deviceId, string dataContainerId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataContainerOperations)s).BeginDeletingAsync(deviceId, dataContainerId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Deleting Volume Container operation deletes the specified
/// volume container.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='dataContainerId'>
/// Required. id of data container which needs to be deleted
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public static Task<TaskResponse> BeginDeletingAsync(this IDataContainerOperations operations, string deviceId, string dataContainerId, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginDeletingAsync(deviceId, dataContainerId, customRequestHeaders, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='containerDetails'>
/// Required. Parameters supplied to the Create Volume Container
/// operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public static TaskStatusInfo Create(this IDataContainerOperations operations, string deviceId, DataContainerRequest containerDetails, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataContainerOperations)s).CreateAsync(deviceId, containerDetails, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='containerDetails'>
/// Required. Parameters supplied to the Create Volume Container
/// operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public static Task<TaskStatusInfo> CreateAsync(this IDataContainerOperations operations, string deviceId, DataContainerRequest containerDetails, CustomRequestHeaders customRequestHeaders)
{
return operations.CreateAsync(deviceId, containerDetails, customRequestHeaders, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='dataContainerId'>
/// Required. id of data container which needs to be deleted
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public static TaskStatusInfo Delete(this IDataContainerOperations operations, string deviceId, string dataContainerId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataContainerOperations)s).DeleteAsync(deviceId, dataContainerId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Required. device id
/// </param>
/// <param name='dataContainerId'>
/// Required. id of data container which needs to be deleted
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public static Task<TaskStatusInfo> DeleteAsync(this IDataContainerOperations operations, string deviceId, string dataContainerId, CustomRequestHeaders customRequestHeaders)
{
return operations.DeleteAsync(deviceId, dataContainerId, customRequestHeaders, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Optional.
/// </param>
/// <param name='dataContainerName'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional.
/// </param>
/// <returns>
/// The response model for the get of data containers.
/// </returns>
public static DataContainerGetResponse Get(this IDataContainerOperations operations, string deviceId, string dataContainerName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataContainerOperations)s).GetAsync(deviceId, dataContainerName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Optional.
/// </param>
/// <param name='dataContainerName'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional.
/// </param>
/// <returns>
/// The response model for the get of data containers.
/// </returns>
public static Task<DataContainerGetResponse> GetAsync(this IDataContainerOperations operations, string deviceId, string dataContainerName, CustomRequestHeaders customRequestHeaders)
{
return operations.GetAsync(deviceId, dataContainerName, customRequestHeaders, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional.
/// </param>
/// <returns>
/// The response model for the list of data containers.
/// </returns>
public static DataContainerListResponse List(this IDataContainerOperations operations, string deviceId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataContainerOperations)s).ListAsync(deviceId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.IDataContainerOperations.
/// </param>
/// <param name='deviceId'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional.
/// </param>
/// <returns>
/// The response model for the list of data containers.
/// </returns>
public static Task<DataContainerListResponse> ListAsync(this IDataContainerOperations operations, string deviceId, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(deviceId, customRequestHeaders, CancellationToken.None);
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/backend.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/backend.proto</summary>
public static partial class BackendReflection {
#region Descriptor
/// <summary>File descriptor for google/api/backend.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static BackendReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chhnb29nbGUvYXBpL2JhY2tlbmQucHJvdG8SCmdvb2dsZS5hcGkiMQoHQmFj",
"a2VuZBImCgVydWxlcxgBIAMoCzIXLmdvb2dsZS5hcGkuQmFja2VuZFJ1bGUi",
"8gIKC0JhY2tlbmRSdWxlEhAKCHNlbGVjdG9yGAEgASgJEg8KB2FkZHJlc3MY",
"AiABKAkSEAoIZGVhZGxpbmUYAyABKAESFAoMbWluX2RlYWRsaW5lGAQgASgB",
"EhoKEm9wZXJhdGlvbl9kZWFkbGluZRgFIAEoARJBChBwYXRoX3RyYW5zbGF0",
"aW9uGAYgASgOMicuZ29vZ2xlLmFwaS5CYWNrZW5kUnVsZS5QYXRoVHJhbnNs",
"YXRpb24SFgoMand0X2F1ZGllbmNlGAcgASgJSAASFgoMZGlzYWJsZV9hdXRo",
"GAggASgISAASEAoIcHJvdG9jb2wYCSABKAkiZQoPUGF0aFRyYW5zbGF0aW9u",
"EiAKHFBBVEhfVFJBTlNMQVRJT05fVU5TUEVDSUZJRUQQABIUChBDT05TVEFO",
"VF9BRERSRVNTEAESGgoWQVBQRU5EX1BBVEhfVE9fQUREUkVTUxACQhAKDmF1",
"dGhlbnRpY2F0aW9uQm4KDmNvbS5nb29nbGUuYXBpQgxCYWNrZW5kUHJvdG9Q",
"AVpFZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkv",
"c2VydmljZWNvbmZpZztzZXJ2aWNlY29uZmlnogIER0FQSWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Backend), global::Google.Api.Backend.Parser, new[]{ "Rules" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.BackendRule), global::Google.Api.BackendRule.Parser, new[]{ "Selector", "Address", "Deadline", "MinDeadline", "OperationDeadline", "PathTranslation", "JwtAudience", "DisableAuth", "Protocol" }, new[]{ "Authentication" }, new[]{ typeof(global::Google.Api.BackendRule.Types.PathTranslation) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// `Backend` defines the backend configuration for a service.
/// </summary>
public sealed partial class Backend : pb::IMessage<Backend>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Backend> _parser = new pb::MessageParser<Backend>(() => new Backend());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Backend> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.BackendReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Backend() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Backend(Backend other) : this() {
rules_ = other.rules_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Backend Clone() {
return new Backend(this);
}
/// <summary>Field number for the "rules" field.</summary>
public const int RulesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Api.BackendRule> _repeated_rules_codec
= pb::FieldCodec.ForMessage(10, global::Google.Api.BackendRule.Parser);
private readonly pbc::RepeatedField<global::Google.Api.BackendRule> rules_ = new pbc::RepeatedField<global::Google.Api.BackendRule>();
/// <summary>
/// A list of API backend rules that apply to individual API methods.
///
/// **NOTE:** All service configuration rules follow "last one wins" order.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.BackendRule> Rules {
get { return rules_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Backend);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Backend other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!rules_.Equals(other.rules_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= rules_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
rules_.WriteTo(output, _repeated_rules_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
rules_.WriteTo(ref output, _repeated_rules_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += rules_.CalculateSize(_repeated_rules_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Backend other) {
if (other == null) {
return;
}
rules_.Add(other.rules_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
rules_.AddEntriesFrom(input, _repeated_rules_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
rules_.AddEntriesFrom(ref input, _repeated_rules_codec);
break;
}
}
}
}
#endif
}
/// <summary>
/// A backend rule provides configuration for an individual API element.
/// </summary>
public sealed partial class BackendRule : pb::IMessage<BackendRule>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<BackendRule> _parser = new pb::MessageParser<BackendRule>(() => new BackendRule());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BackendRule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.BackendReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BackendRule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BackendRule(BackendRule other) : this() {
selector_ = other.selector_;
address_ = other.address_;
deadline_ = other.deadline_;
minDeadline_ = other.minDeadline_;
operationDeadline_ = other.operationDeadline_;
pathTranslation_ = other.pathTranslation_;
protocol_ = other.protocol_;
switch (other.AuthenticationCase) {
case AuthenticationOneofCase.JwtAudience:
JwtAudience = other.JwtAudience;
break;
case AuthenticationOneofCase.DisableAuth:
DisableAuth = other.DisableAuth;
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BackendRule Clone() {
return new BackendRule(this);
}
/// <summary>Field number for the "selector" field.</summary>
public const int SelectorFieldNumber = 1;
private string selector_ = "";
/// <summary>
/// Selects the methods to which this rule applies.
///
/// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Selector {
get { return selector_; }
set {
selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "address" field.</summary>
public const int AddressFieldNumber = 2;
private string address_ = "";
/// <summary>
/// The address of the API backend.
///
/// The scheme is used to determine the backend protocol and security.
/// The following schemes are accepted:
///
/// SCHEME PROTOCOL SECURITY
/// http:// HTTP None
/// https:// HTTP TLS
/// grpc:// gRPC None
/// grpcs:// gRPC TLS
///
/// It is recommended to explicitly include a scheme. Leaving out the scheme
/// may cause constrasting behaviors across platforms.
///
/// If the port is unspecified, the default is:
/// - 80 for schemes without TLS
/// - 443 for schemes with TLS
///
/// For HTTP backends, use [protocol][google.api.BackendRule.protocol]
/// to specify the protocol version.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Address {
get { return address_; }
set {
address_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "deadline" field.</summary>
public const int DeadlineFieldNumber = 3;
private double deadline_;
/// <summary>
/// The number of seconds to wait for a response from a request. The default
/// varies based on the request protocol and deployment environment.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Deadline {
get { return deadline_; }
set {
deadline_ = value;
}
}
/// <summary>Field number for the "min_deadline" field.</summary>
public const int MinDeadlineFieldNumber = 4;
private double minDeadline_;
/// <summary>
/// Minimum deadline in seconds needed for this method. Calls having deadline
/// value lower than this will be rejected.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double MinDeadline {
get { return minDeadline_; }
set {
minDeadline_ = value;
}
}
/// <summary>Field number for the "operation_deadline" field.</summary>
public const int OperationDeadlineFieldNumber = 5;
private double operationDeadline_;
/// <summary>
/// The number of seconds to wait for the completion of a long running
/// operation. The default is no deadline.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double OperationDeadline {
get { return operationDeadline_; }
set {
operationDeadline_ = value;
}
}
/// <summary>Field number for the "path_translation" field.</summary>
public const int PathTranslationFieldNumber = 6;
private global::Google.Api.BackendRule.Types.PathTranslation pathTranslation_ = global::Google.Api.BackendRule.Types.PathTranslation.Unspecified;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.BackendRule.Types.PathTranslation PathTranslation {
get { return pathTranslation_; }
set {
pathTranslation_ = value;
}
}
/// <summary>Field number for the "jwt_audience" field.</summary>
public const int JwtAudienceFieldNumber = 7;
/// <summary>
/// The JWT audience is used when generating a JWT ID token for the backend.
/// This ID token will be added in the HTTP "authorization" header, and sent
/// to the backend.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JwtAudience {
get { return authenticationCase_ == AuthenticationOneofCase.JwtAudience ? (string) authentication_ : ""; }
set {
authentication_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
authenticationCase_ = AuthenticationOneofCase.JwtAudience;
}
}
/// <summary>Field number for the "disable_auth" field.</summary>
public const int DisableAuthFieldNumber = 8;
/// <summary>
/// When disable_auth is true, a JWT ID token won't be generated and the
/// original "Authorization" HTTP header will be preserved. If the header is
/// used to carry the original token and is expected by the backend, this
/// field must be set to true to preserve the header.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool DisableAuth {
get { return authenticationCase_ == AuthenticationOneofCase.DisableAuth ? (bool) authentication_ : false; }
set {
authentication_ = value;
authenticationCase_ = AuthenticationOneofCase.DisableAuth;
}
}
/// <summary>Field number for the "protocol" field.</summary>
public const int ProtocolFieldNumber = 9;
private string protocol_ = "";
/// <summary>
/// The protocol used for sending a request to the backend.
/// The supported values are "http/1.1" and "h2".
///
/// The default value is inferred from the scheme in the
/// [address][google.api.BackendRule.address] field:
///
/// SCHEME PROTOCOL
/// http:// http/1.1
/// https:// http/1.1
/// grpc:// h2
/// grpcs:// h2
///
/// For secure HTTP backends (https://) that support HTTP/2, set this field
/// to "h2" for improved performance.
///
/// Configuring this field to non-default values is only supported for secure
/// HTTP backends. This field will be ignored for all other backends.
///
/// See
/// https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
/// for more details on the supported values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Protocol {
get { return protocol_; }
set {
protocol_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
private object authentication_;
/// <summary>Enum of possible cases for the "authentication" oneof.</summary>
public enum AuthenticationOneofCase {
None = 0,
JwtAudience = 7,
DisableAuth = 8,
}
private AuthenticationOneofCase authenticationCase_ = AuthenticationOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationOneofCase AuthenticationCase {
get { return authenticationCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearAuthentication() {
authenticationCase_ = AuthenticationOneofCase.None;
authentication_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BackendRule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BackendRule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Selector != other.Selector) return false;
if (Address != other.Address) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(Deadline, other.Deadline)) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(MinDeadline, other.MinDeadline)) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(OperationDeadline, other.OperationDeadline)) return false;
if (PathTranslation != other.PathTranslation) return false;
if (JwtAudience != other.JwtAudience) return false;
if (DisableAuth != other.DisableAuth) return false;
if (Protocol != other.Protocol) return false;
if (AuthenticationCase != other.AuthenticationCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Selector.Length != 0) hash ^= Selector.GetHashCode();
if (Address.Length != 0) hash ^= Address.GetHashCode();
if (Deadline != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Deadline);
if (MinDeadline != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(MinDeadline);
if (OperationDeadline != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(OperationDeadline);
if (PathTranslation != global::Google.Api.BackendRule.Types.PathTranslation.Unspecified) hash ^= PathTranslation.GetHashCode();
if (authenticationCase_ == AuthenticationOneofCase.JwtAudience) hash ^= JwtAudience.GetHashCode();
if (authenticationCase_ == AuthenticationOneofCase.DisableAuth) hash ^= DisableAuth.GetHashCode();
if (Protocol.Length != 0) hash ^= Protocol.GetHashCode();
hash ^= (int) authenticationCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (Address.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Address);
}
if (Deadline != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Deadline);
}
if (MinDeadline != 0D) {
output.WriteRawTag(33);
output.WriteDouble(MinDeadline);
}
if (OperationDeadline != 0D) {
output.WriteRawTag(41);
output.WriteDouble(OperationDeadline);
}
if (PathTranslation != global::Google.Api.BackendRule.Types.PathTranslation.Unspecified) {
output.WriteRawTag(48);
output.WriteEnum((int) PathTranslation);
}
if (authenticationCase_ == AuthenticationOneofCase.JwtAudience) {
output.WriteRawTag(58);
output.WriteString(JwtAudience);
}
if (authenticationCase_ == AuthenticationOneofCase.DisableAuth) {
output.WriteRawTag(64);
output.WriteBool(DisableAuth);
}
if (Protocol.Length != 0) {
output.WriteRawTag(74);
output.WriteString(Protocol);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (Address.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Address);
}
if (Deadline != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Deadline);
}
if (MinDeadline != 0D) {
output.WriteRawTag(33);
output.WriteDouble(MinDeadline);
}
if (OperationDeadline != 0D) {
output.WriteRawTag(41);
output.WriteDouble(OperationDeadline);
}
if (PathTranslation != global::Google.Api.BackendRule.Types.PathTranslation.Unspecified) {
output.WriteRawTag(48);
output.WriteEnum((int) PathTranslation);
}
if (authenticationCase_ == AuthenticationOneofCase.JwtAudience) {
output.WriteRawTag(58);
output.WriteString(JwtAudience);
}
if (authenticationCase_ == AuthenticationOneofCase.DisableAuth) {
output.WriteRawTag(64);
output.WriteBool(DisableAuth);
}
if (Protocol.Length != 0) {
output.WriteRawTag(74);
output.WriteString(Protocol);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Selector.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector);
}
if (Address.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Address);
}
if (Deadline != 0D) {
size += 1 + 8;
}
if (MinDeadline != 0D) {
size += 1 + 8;
}
if (OperationDeadline != 0D) {
size += 1 + 8;
}
if (PathTranslation != global::Google.Api.BackendRule.Types.PathTranslation.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PathTranslation);
}
if (authenticationCase_ == AuthenticationOneofCase.JwtAudience) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JwtAudience);
}
if (authenticationCase_ == AuthenticationOneofCase.DisableAuth) {
size += 1 + 1;
}
if (Protocol.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Protocol);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BackendRule other) {
if (other == null) {
return;
}
if (other.Selector.Length != 0) {
Selector = other.Selector;
}
if (other.Address.Length != 0) {
Address = other.Address;
}
if (other.Deadline != 0D) {
Deadline = other.Deadline;
}
if (other.MinDeadline != 0D) {
MinDeadline = other.MinDeadline;
}
if (other.OperationDeadline != 0D) {
OperationDeadline = other.OperationDeadline;
}
if (other.PathTranslation != global::Google.Api.BackendRule.Types.PathTranslation.Unspecified) {
PathTranslation = other.PathTranslation;
}
if (other.Protocol.Length != 0) {
Protocol = other.Protocol;
}
switch (other.AuthenticationCase) {
case AuthenticationOneofCase.JwtAudience:
JwtAudience = other.JwtAudience;
break;
case AuthenticationOneofCase.DisableAuth:
DisableAuth = other.DisableAuth;
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Selector = input.ReadString();
break;
}
case 18: {
Address = input.ReadString();
break;
}
case 25: {
Deadline = input.ReadDouble();
break;
}
case 33: {
MinDeadline = input.ReadDouble();
break;
}
case 41: {
OperationDeadline = input.ReadDouble();
break;
}
case 48: {
PathTranslation = (global::Google.Api.BackendRule.Types.PathTranslation) input.ReadEnum();
break;
}
case 58: {
JwtAudience = input.ReadString();
break;
}
case 64: {
DisableAuth = input.ReadBool();
break;
}
case 74: {
Protocol = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Selector = input.ReadString();
break;
}
case 18: {
Address = input.ReadString();
break;
}
case 25: {
Deadline = input.ReadDouble();
break;
}
case 33: {
MinDeadline = input.ReadDouble();
break;
}
case 41: {
OperationDeadline = input.ReadDouble();
break;
}
case 48: {
PathTranslation = (global::Google.Api.BackendRule.Types.PathTranslation) input.ReadEnum();
break;
}
case 58: {
JwtAudience = input.ReadString();
break;
}
case 64: {
DisableAuth = input.ReadBool();
break;
}
case 74: {
Protocol = input.ReadString();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the BackendRule message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Path Translation specifies how to combine the backend address with the
/// request path in order to produce the appropriate forwarding URL for the
/// request.
///
/// Path Translation is applicable only to HTTP-based backends. Backends which
/// do not accept requests over HTTP/HTTPS should leave `path_translation`
/// unspecified.
/// </summary>
public enum PathTranslation {
[pbr::OriginalName("PATH_TRANSLATION_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Use the backend address as-is, with no modification to the path. If the
/// URL pattern contains variables, the variable names and values will be
/// appended to the query string. If a query string parameter and a URL
/// pattern variable have the same name, this may result in duplicate keys in
/// the query string.
///
/// # Examples
///
/// Given the following operation config:
///
/// Method path: /api/company/{cid}/user/{uid}
/// Backend address: https://example.cloudfunctions.net/getUser
///
/// Requests to the following request paths will call the backend at the
/// translated path:
///
/// Request path: /api/company/widgetworks/user/johndoe
/// Translated:
/// https://example.cloudfunctions.net/getUser?cid=widgetworks&uid=johndoe
///
/// Request path: /api/company/widgetworks/user/johndoe?timezone=EST
/// Translated:
/// https://example.cloudfunctions.net/getUser?timezone=EST&cid=widgetworks&uid=johndoe
/// </summary>
[pbr::OriginalName("CONSTANT_ADDRESS")] ConstantAddress = 1,
/// <summary>
/// The request path will be appended to the backend address.
///
/// # Examples
///
/// Given the following operation config:
///
/// Method path: /api/company/{cid}/user/{uid}
/// Backend address: https://example.appspot.com
///
/// Requests to the following request paths will call the backend at the
/// translated path:
///
/// Request path: /api/company/widgetworks/user/johndoe
/// Translated:
/// https://example.appspot.com/api/company/widgetworks/user/johndoe
///
/// Request path: /api/company/widgetworks/user/johndoe?timezone=EST
/// Translated:
/// https://example.appspot.com/api/company/widgetworks/user/johndoe?timezone=EST
/// </summary>
[pbr::OriginalName("APPEND_PATH_TO_ADDRESS")] AppendPathToAddress = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public partial class ThreadGroup : java.lang.Object, java.lang.Thread.UncaughtExceptionHandler
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ThreadGroup()
{
InitJNI();
}
protected ThreadGroup(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _uncaughtException13379;
public virtual void uncaughtException(java.lang.Thread arg0, java.lang.Throwable arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._uncaughtException13379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._uncaughtException13379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _toString13380;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ThreadGroup._toString13380)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._toString13380)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getName13381;
public virtual global::java.lang.String getName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ThreadGroup._getName13381)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._getName13381)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getParent13382;
public virtual global::java.lang.ThreadGroup getParent()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ThreadGroup._getParent13382)) as java.lang.ThreadGroup;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._getParent13382)) as java.lang.ThreadGroup;
}
internal static global::MonoJavaBridge.MethodId _setDaemon13383;
public virtual void setDaemon(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._setDaemon13383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._setDaemon13383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _stop13384;
public virtual void stop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._stop13384);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._stop13384);
}
internal static global::MonoJavaBridge.MethodId _interrupt13385;
public virtual void interrupt()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._interrupt13385);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._interrupt13385);
}
internal static global::MonoJavaBridge.MethodId _destroy13386;
public virtual void destroy()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._destroy13386);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._destroy13386);
}
internal static global::MonoJavaBridge.MethodId _suspend13387;
public virtual void suspend()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._suspend13387);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._suspend13387);
}
internal static global::MonoJavaBridge.MethodId _resume13388;
public virtual void resume()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._resume13388);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._resume13388);
}
internal static global::MonoJavaBridge.MethodId _activeCount13389;
public virtual int activeCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._activeCount13389);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._activeCount13389);
}
internal static global::MonoJavaBridge.MethodId _enumerate13390;
public virtual int enumerate(java.lang.ThreadGroup[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._enumerate13390, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._enumerate13390, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _enumerate13391;
public virtual int enumerate(java.lang.ThreadGroup[] arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._enumerate13391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._enumerate13391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _enumerate13392;
public virtual int enumerate(java.lang.Thread[] arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._enumerate13392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._enumerate13392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _enumerate13393;
public virtual int enumerate(java.lang.Thread[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._enumerate13393, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._enumerate13393, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isDaemon13394;
public virtual bool isDaemon()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup._isDaemon13394);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._isDaemon13394);
}
internal static global::MonoJavaBridge.MethodId _checkAccess13395;
public virtual void checkAccess()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._checkAccess13395);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._checkAccess13395);
}
internal static global::MonoJavaBridge.MethodId _getMaxPriority13396;
public virtual int getMaxPriority()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._getMaxPriority13396);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._getMaxPriority13396);
}
internal static global::MonoJavaBridge.MethodId _isDestroyed13397;
public virtual bool isDestroyed()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup._isDestroyed13397);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._isDestroyed13397);
}
internal static global::MonoJavaBridge.MethodId _setMaxPriority13398;
public virtual void setMaxPriority(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._setMaxPriority13398, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._setMaxPriority13398, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _parentOf13399;
public virtual bool parentOf(java.lang.ThreadGroup arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup._parentOf13399, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._parentOf13399, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _activeGroupCount13400;
public virtual int activeGroupCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.ThreadGroup._activeGroupCount13400);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._activeGroupCount13400);
}
internal static global::MonoJavaBridge.MethodId _list13401;
public virtual void list()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup._list13401);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._list13401);
}
internal static global::MonoJavaBridge.MethodId _allowThreadSuspension13402;
public virtual bool allowThreadSuspension(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup._allowThreadSuspension13402, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._allowThreadSuspension13402, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _ThreadGroup13403;
public ThreadGroup(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._ThreadGroup13403, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ThreadGroup13404;
public ThreadGroup(java.lang.ThreadGroup arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.ThreadGroup.staticClass, global::java.lang.ThreadGroup._ThreadGroup13404, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.ThreadGroup.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/ThreadGroup"));
global::java.lang.ThreadGroup._uncaughtException13379 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
global::java.lang.ThreadGroup._toString13380 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "toString", "()Ljava/lang/String;");
global::java.lang.ThreadGroup._getName13381 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "getName", "()Ljava/lang/String;");
global::java.lang.ThreadGroup._getParent13382 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "getParent", "()Ljava/lang/ThreadGroup;");
global::java.lang.ThreadGroup._setDaemon13383 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "setDaemon", "(Z)V");
global::java.lang.ThreadGroup._stop13384 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "stop", "()V");
global::java.lang.ThreadGroup._interrupt13385 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "interrupt", "()V");
global::java.lang.ThreadGroup._destroy13386 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "destroy", "()V");
global::java.lang.ThreadGroup._suspend13387 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "suspend", "()V");
global::java.lang.ThreadGroup._resume13388 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "resume", "()V");
global::java.lang.ThreadGroup._activeCount13389 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "activeCount", "()I");
global::java.lang.ThreadGroup._enumerate13390 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "enumerate", "([Ljava/lang/ThreadGroup;)I");
global::java.lang.ThreadGroup._enumerate13391 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "enumerate", "([Ljava/lang/ThreadGroup;Z)I");
global::java.lang.ThreadGroup._enumerate13392 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "enumerate", "([Ljava/lang/Thread;Z)I");
global::java.lang.ThreadGroup._enumerate13393 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "enumerate", "([Ljava/lang/Thread;)I");
global::java.lang.ThreadGroup._isDaemon13394 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "isDaemon", "()Z");
global::java.lang.ThreadGroup._checkAccess13395 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "checkAccess", "()V");
global::java.lang.ThreadGroup._getMaxPriority13396 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "getMaxPriority", "()I");
global::java.lang.ThreadGroup._isDestroyed13397 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "isDestroyed", "()Z");
global::java.lang.ThreadGroup._setMaxPriority13398 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "setMaxPriority", "(I)V");
global::java.lang.ThreadGroup._parentOf13399 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "parentOf", "(Ljava/lang/ThreadGroup;)Z");
global::java.lang.ThreadGroup._activeGroupCount13400 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "activeGroupCount", "()I");
global::java.lang.ThreadGroup._list13401 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "list", "()V");
global::java.lang.ThreadGroup._allowThreadSuspension13402 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "allowThreadSuspension", "(Z)Z");
global::java.lang.ThreadGroup._ThreadGroup13403 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "<init>", "(Ljava/lang/String;)V");
global::java.lang.ThreadGroup._ThreadGroup13404 = @__env.GetMethodIDNoThrow(global::java.lang.ThreadGroup.staticClass, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class DisposedSocket
{
private readonly static byte[] s_buffer = new byte[1];
private readonly static IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) };
private static Socket GetDisposedSocket(AddressFamily addressFamily = AddressFamily.InterNetwork)
{
using (var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp))
{
return socket;
}
}
private static void TheAsyncCallback(IAsyncResult ar)
{
}
[Fact]
public void BeginConnect_EndPoint_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddress_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(IPAddress.Loopback, 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddresses_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_Host_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect("localhost", 1, TheAsyncCallback, null));
}
[Fact]
public void EndConnect_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndConnect(null));
}
[Fact]
public void BeginDisconnect_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginDisconnect(false, TheAsyncCallback, null));
}
[Fact]
public void EndDisconnect_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndDisconnect(null));
}
[Fact]
public void BeginSend_Buffer_Throws_ObjectDisposedException()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffer_SocketError_Throws_ObjectDisposedException()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffers_Throws_ObjectDisposedException()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffers, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffers_SocketError_Throws_ObjectDisposedException()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffers, SocketFlags.None, out errorCode, TheAsyncCallback, null));
}
[Fact]
public void EndSend_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSend(null));
}
[Fact]
public void EndSend_SocketError_Throws_ObjectDisposed()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSend(null, out errorCode));
}
[Fact]
public void BeginSendTo_Throws_ObjectDisposedException()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSendTo(s_buffer, 0, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
}
[Fact]
public void EndSendTo_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSendTo(null));
}
[Fact]
public void BeginReceive_Buffer_Throws_ObjectDisposedException()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffer_SocketError_Throws_ObjectDisposedException()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffers_Throws_ObjectDisposedException()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffers, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffers_SocketError_Throws_ObjectDisposedException()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffers, SocketFlags.None, out errorCode, TheAsyncCallback, null));
}
[Fact]
public void EndReceive_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceive(null));
}
[Fact]
public void EndReceive_SocketError_Throws_ObjectDisposed()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceive(null, out errorCode));
}
[Fact]
public void BeginReceiveFrom_Throws_ObjectDisposedException()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void EndReceiveFrom_Throws_ObjectDisposed()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceiveFrom(null, ref remote));
}
[Fact]
public void BeginReceiveMessageFrom_Throws_ObjectDisposedException()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void EndReceiveMessageFrom_Throws_ObjectDisposed()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]
public void BeginAccept_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginAccept(TheAsyncCallback, null));
}
[Fact]
public void BeginAccept_Int_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginAccept(0, TheAsyncCallback, null));
}
[Fact]
public void BeginAccept_Socket_Int_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginAccept(null, 0, TheAsyncCallback, null));
}
[Fact]
public void EndAccept_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndAccept(null));
}
[Fact]
public void EndAccept_Buffer_Throws_ObjectDisposed()
{
byte[] buffer;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndAccept(out buffer, null));
}
[Fact]
public void EndAccept_Buffer_Int_Throws_ObjectDisposed()
{
byte[] buffer;
int received;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndAccept(out buffer, out received, null));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DepAnalyzer.Properties;
namespace DepAnalyzer
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SolutionTextBox.Text = Settings.Default.SolutionFile;
ConfigTextBox.Text = Settings.Default.SolutionConfig;
ShowSingleCheckBox.Checked = Settings.Default.ShowSingleNodes;
ShowChildrenCheckBox.Checked = Settings.Default.ShowChildNodes;
BuildButton.Text = "Start";
builder = new Builder(BuildList, LogCombo, LogTextBoxRich);
SolutionTextBox.TextChanged += textBox1_TextChanged;
ShowSingleCheckBox.CheckedChanged += checkBox1_CheckedChanged;
ShowChildrenCheckBox.CheckedChanged += checkBox2_CheckedChanged;
TryParse(false);
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog diag = new OpenFileDialog();
diag.CheckFileExists = true;
diag.Filter = "Solution files (*.sln)|*.sln|All files (*.*)|*.*";
string solutionSource = SolutionTextBox.Text;
if (!String.IsNullOrEmpty(solutionSource))
{
FileInfo snlFileInfo = new FileInfo(solutionSource);
if (snlFileInfo.Exists && snlFileInfo.DirectoryName != null)
{
diag.InitialDirectory = snlFileInfo.DirectoryName;
}
}
if(diag.ShowDialog() == DialogResult.OK)
{
SolutionTextBox.Text = diag.FileName;
TryParse(true);
}
}
public static bool IsSolutionValid(string path)
{
if (String.IsNullOrEmpty(path))
return false;
FileInfo snlFileInfo = new FileInfo(path);
if (!snlFileInfo.Exists)
return false;
return true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
ParseButton.Enabled = IsSolutionValid(SolutionTextBox.Text);
}
private bool TryParse(bool isUpdate)
{
if (!IsSolutionValid(SolutionTextBox.Text))
return false;
Program.form.Icon = Resources.tree;
string solutionSource = SolutionTextBox.Text;
bool update = isUpdate && (Settings.Default.SolutionFile == solutionSource);
SolutionParser.ParseSolution(solutionSource, update);
UpdateNodeList();
// Update settings
Settings.Default.SolutionFile = SolutionTextBox.Text;
Settings.Default.Save();
return true;
}
private void UpdateNodeList()
{
bool showSingleNodes = Settings.Default.ShowSingleNodes;
bool showChildNodes = Settings.Default.ShowChildNodes;
ProjectList.Items.Clear();
foreach (string rootName in SolutionParser.GetRootNames(showSingleNodes))
{
ProjectList.Items.Add(rootName);
if (showChildNodes)
{
foreach (string projName in SolutionParser.GetDepNames(rootName))
{
string item = " " + projName;
ProjectList.Items.Add(item);
}
}
}
if (ProjectList.Items.Count != 0)
{
ProjectList.SelectedIndex = 0;
}
}
private void button2_Click(object sender, EventArgs e)
{
TryParse(true);
}
private string[] GetSelectedRoots()
{
List<string> rootNames = new List<string>();
foreach (string item in ProjectList.SelectedItems)
{
string projName = item.Trim();
rootNames.Add(projName);
}
return rootNames.ToArray();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] rootNames = GetSelectedRoots();
// update dep graph
depGraph.GenerateGraphImageForRoots(rootNames);
// update matrix
depMatrix.GenerateTableForRoots(rootNames);
// update builder
builder.GenerateOrderListForRoots(rootNames);
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
// Update settings
Settings.Default.ShowSingleNodes = ShowSingleCheckBox.Checked;
Settings.Default.Save();
UpdateNodeList();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
// Update settings
Settings.Default.ShowChildNodes = ShowChildrenCheckBox.Checked;
Settings.Default.Save();
UpdateNodeList();
}
private void button3_Click(object sender, EventArgs e)
{
string solutionConfig = ConfigTextBox.Text;
Settings.Default.SolutionConfig = solutionConfig;
Settings.Default.Save();
if (BuildButton.Text == "Start")
{
string solutionSource = SolutionTextBox.Text;
//ClearBuildLog();
builder.StartBuild(SolutionParser.VSVersion, solutionSource, solutionConfig);
BuildButton.Text = "Stop";
Program.form.Icon = Resources.process;
} else
if(BuildButton.Text == "Stop")
{
builder.StopBuild();
BuildButton.Text = "Start";
Program.form.Icon = Resources.wait;
}
}
public void UpdateBuildButton(string data)
{
BuildButton.Text = "Start";
if (data == "Success")
{
Program.form.Icon = Resources.success;
MessageBox.Show("Build finished with success", "Build", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (data == "Fail")
{
Program.form.Icon = Resources.failed;
MessageBox.Show("Build failed. See log for more details.", "Build", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
builder.StopBuild();
}
private void LogCombo_SelectedIndexChanged(object sender, EventArgs e)
{
builder.SelectLogCombo();
}
private void LogCombo_DropDown(object sender, EventArgs e)
{
//builder.UpdateLogCombo();
}
private void LogCombo_DropDownClosed(object sender, EventArgs e)
{
builder.PreSelectLogCombo();
}
private void BuildList_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
ListViewItem item = BuildList.GetItemAt(e.X, e.Y);
if (item != null)
{
var proj = SolutionParser.ProjTable[item.Text];
item.Selected = true;
BuildContextMenu.Items[0].Enabled = proj.HasLog;
BuildContextMenu.Items[1].Enabled = !builder.IsBuilding && proj.IsBuilt;
BuildContextMenu.Show(BuildList, e.Location);
}
}
}
private void showLogToolStripMenuItem_Click(object sender, EventArgs e)
{
var proj = SolutionParser.ProjTable[BuildList.SelectedItems[0].Text];
LogCombo.SelectedItem = proj;
}
private void rebuildToolStripMenuItem_Click(object sender, EventArgs e)
{
var proj = SolutionParser.ProjTable[BuildList.SelectedItems[0].Text];
proj.Status = Project.BuildStatus.Wait;
}
private void BuildList_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (BuildContextMenu.Items[0].Enabled)
showLogToolStripMenuItem_Click(sender, e);
}
private Builder builder;
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Serialization.TypeSystem;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace Tester.HeterogeneousSilosTests
{
[TestCategory("Functional")]
public class HeterogeneousTests : OrleansTestingBase, IDisposable, IAsyncLifetime
{
private static readonly TimeSpan ClientRefreshDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan RefreshInterval = TimeSpan.FromMilliseconds(200);
private TestCluster cluster;
private void SetupAndDeployCluster(Type defaultPlacementStrategy, params Type[] blackListedTypes)
{
cluster?.StopAllSilos();
var builder = new TestClusterBuilder(1);
builder.Properties["DefaultPlacementStrategy"] = RuntimeTypeNameFormatter.Format(defaultPlacementStrategy);
builder.Properties["BlockedGrainTypes"] = string.Join("|", blackListedTypes.Select(t => RuntimeTypeNameFormatter.Format(t)));
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
builder.AddClientBuilderConfigurator<ClientConfigurator>();
cluster = builder.Build();
cluster.Deploy();
}
public class SiloConfigurator : ISiloConfigurator
{
public void Configure(ISiloBuilder hostBuilder)
{
hostBuilder.Configure<SiloMessagingOptions>(options => options.AssumeHomogenousSilosForTesting = false);
hostBuilder.Configure<TypeManagementOptions>(options => options.TypeMapRefreshInterval = RefreshInterval);
hostBuilder.Configure<GrainTypeOptions>(options =>
{
var cfg = hostBuilder.GetConfiguration();
var siloOptions = new TestSiloSpecificOptions();
cfg.Bind(siloOptions);
// The blacklist is only intended for the primary silo in these tests.
if (string.Equals(siloOptions.SiloName, Silo.PrimarySiloName))
{
var typeNames = cfg["BlockedGrainTypes"].Split('|').ToList();
foreach (var typeName in typeNames)
{
var type = Type.GetType(typeName);
options.Classes.Remove(type);
}
}
});
hostBuilder.ConfigureServices(services =>
{
var defaultPlacementStrategy = Type.GetType(hostBuilder.GetConfiguration()["DefaultPlacementStrategy"]);
services.AddSingleton(typeof(PlacementStrategy), defaultPlacementStrategy);
});
}
}
public class ClientConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.Configure<TypeManagementOptions>(options => options.TypeMapRefreshInterval = ClientRefreshDelay);
}
}
public void Dispose()
{
cluster?.Dispose();
cluster = null;
}
[Fact]
public void GrainExcludedTest()
{
SetupAndDeployCluster(typeof(RandomPlacement), typeof(TestGrain));
// Should fail
var exception = Assert.Throws<ArgumentException>(() => this.cluster.GrainFactory.GetGrain<ITestGrain>(0));
Assert.Contains("Could not find an implementation for interface", exception.Message);
// Should not fail
this.cluster.GrainFactory.GetGrain<ISimpleGrainWithAsyncMethods>(0);
}
[Fact]
public async Task MergeGrainResolverTests()
{
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(RandomPlacement), true, this.CallITestGrainMethod, typeof(TestGrain));
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(PreferLocalPlacement), true, this.CallITestGrainMethod, typeof(TestGrain));
// TODO Check ActivationCountBasedPlacement in tests
//await MergeGrainResolverTestsImpl("ActivationCountBasedPlacement", typeof(TestGrain));
}
[Fact]
public async Task MergeGrainResolverWithClientRefreshTests()
{
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(RandomPlacement), false, this.CallITestGrainMethod, typeof(TestGrain));
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(PreferLocalPlacement), false, this.CallITestGrainMethod, typeof(TestGrain));
// TODO Check ActivationCountBasedPlacement in tests
//await MergeGrainResolverTestsImpl("ActivationCountBasedPlacement", typeof(TestGrain));
}
[Fact]
public async Task StatelessWorkerPlacementTests()
{
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(RandomPlacement), true, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(PreferLocalPlacement), true, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
}
[Fact]
public async Task StatelessWorkerPlacementWithClientRefreshTests()
{
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(RandomPlacement), false, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(PreferLocalPlacement), false, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
}
private async Task CallITestGrainMethod(IGrain grain)
{
var g = grain.Cast<ITestGrain>();
await g.SetLabel("Hello world");
}
private async Task CallIStatelessWorkerGrainMethod(IGrain grain)
{
var g = grain.Cast<IStatelessWorkerGrain>();
await g.GetCallStats();
}
private async Task MergeGrainResolverTestsImpl<T>(Type defaultPlacementStrategy, bool restartClient, Func<IGrain, Task> func, params Type[] blackListedTypes)
where T : IGrainWithIntegerKey
{
SetupAndDeployCluster(defaultPlacementStrategy, blackListedTypes);
var delayTimeout = RefreshInterval.Add(RefreshInterval);
// Should fail
var exception = Assert.Throws<ArgumentException>(() => this.cluster.GrainFactory.GetGrain<T>(0));
Assert.Contains("Could not find an implementation for interface", exception.Message);
// Start a new silo with TestGrain
await cluster.StartAdditionalSiloAsync();
await Task.Delay(delayTimeout);
if (restartClient)
{
// Disconnect/Reconnect the client
await cluster.Client.Close();
cluster.Client.Dispose();
cluster.InitializeClient();
}
else
{
await Task.Delay(ClientRefreshDelay.Multiply(3));
}
for (var i = 0; i < 5; i++)
{
// Success
var g = this.cluster.GrainFactory.GetGrain<T>(i);
await func(g);
}
// Stop the latest silos
await cluster.StopSecondarySilosAsync();
await Task.Delay(delayTimeout);
if (restartClient)
{
// Disconnect/Reconnect the client
await cluster.Client.Close();
cluster.Client.Dispose();
cluster.InitializeClient();
}
else
{
await Task.Delay(ClientRefreshDelay.Multiply(3));
}
// Should fail
exception = Assert.Throws<ArgumentException>(() => this.cluster.GrainFactory.GetGrain<T>(0));
Assert.Contains("Could not find an implementation for interface", exception.Message);
}
public Task InitializeAsync()
{
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
try
{
if (this.cluster is TestCluster c)
{
await c.StopAllSilosAsync();
}
}
finally
{
this.cluster?.Dispose();
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Scheduler;
using Microsoft.WindowsAzure.Management.Scheduler.Models;
namespace Microsoft.WindowsAzure.Management.Scheduler
{
internal partial class JobCollectionOperations : IServiceOperations<SchedulerManagementClient>, IJobCollectionOperations
{
/// <summary>
/// Initializes a new instance of the JobCollectionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal JobCollectionOperations(SchedulerManagementClient client)
{
this._client = client;
}
private SchedulerManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.SchedulerManagementClient.
/// </summary>
public SchedulerManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service containing the job collection.
/// </param>
/// <param name='jobCollectionName'>
/// The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Job Collection operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Job Collection operation response.
/// </returns>
public async Task<JobCollectionCreateResponse> BeginCreatingAsync(string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (jobCollectionName.Length > 100)
{
throw new ArgumentOutOfRangeException("jobCollectionName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + this.Client.Credentials.SubscriptionId + "/cloudservices/" + cloudServiceName + "/resources/scheduler/JobCollections/" + jobCollectionName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
if (parameters.SchemaVersion != null)
{
XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
schemaVersionElement.Value = parameters.SchemaVersion;
resourceElement.Add(schemaVersionElement);
}
if (parameters.IntrinsicSettings != null)
{
XElement intrinsicSettingsElement = new XElement(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure"));
resourceElement.Add(intrinsicSettingsElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.IntrinsicSettings.Plan.ToString();
intrinsicSettingsElement.Add(planElement);
if (parameters.IntrinsicSettings.Quota != null)
{
XElement quotaElement = new XElement(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure"));
intrinsicSettingsElement.Add(quotaElement);
if (parameters.IntrinsicSettings.Quota.MaxJobCount != null)
{
XElement maxJobCountElement = new XElement(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure"));
maxJobCountElement.Value = parameters.IntrinsicSettings.Quota.MaxJobCount.ToString();
quotaElement.Add(maxJobCountElement);
}
if (parameters.IntrinsicSettings.Quota.MaxJobOccurrence != null)
{
XElement maxJobOccurrenceElement = new XElement(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure"));
maxJobOccurrenceElement.Value = parameters.IntrinsicSettings.Quota.MaxJobOccurrence.ToString();
quotaElement.Add(maxJobOccurrenceElement);
}
if (parameters.IntrinsicSettings.Quota.MaxRecurrence != null)
{
XElement maxRecurrenceElement = new XElement(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure"));
quotaElement.Add(maxRecurrenceElement);
XElement frequencyElement = new XElement(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure"));
frequencyElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString();
maxRecurrenceElement.Add(frequencyElement);
XElement intervalElement = new XElement(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure"));
intervalElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString();
maxRecurrenceElement.Add(intervalElement);
}
}
}
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = TypeConversion.ToBase64String(parameters.Label);
resourceElement.Add(labelElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionCreateResponse result = null;
result = new JobCollectionCreateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// The name of the job collection to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> BeginDeletingAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + this.Client.Credentials.SubscriptionId + "/cloudservices/" + cloudServiceName + "/resources/scheduler/JobCollections/" + jobCollectionName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service containing the job collection.
/// </param>
/// <param name='jobCollectionName'>
/// The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Job Collection operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Update Job Collection operation response.
/// </returns>
public async Task<JobCollectionUpdateResponse> BeginUpdatingAsync(string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (jobCollectionName.Length > 100)
{
throw new ArgumentOutOfRangeException("jobCollectionName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ETag == null)
{
throw new ArgumentNullException("parameters.ETag");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + this.Client.Credentials.SubscriptionId + "/cloudservices/" + cloudServiceName + "/resources/scheduler/JobCollections/" + jobCollectionName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", parameters.ETag);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
if (parameters.SchemaVersion != null)
{
XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
schemaVersionElement.Value = parameters.SchemaVersion;
resourceElement.Add(schemaVersionElement);
}
XElement eTagElement = new XElement(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
resourceElement.Add(eTagElement);
if (parameters.IntrinsicSettings != null)
{
XElement intrinsicSettingsElement = new XElement(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure"));
resourceElement.Add(intrinsicSettingsElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.IntrinsicSettings.Plan.ToString();
intrinsicSettingsElement.Add(planElement);
if (parameters.IntrinsicSettings.Quota != null)
{
XElement quotaElement = new XElement(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure"));
intrinsicSettingsElement.Add(quotaElement);
if (parameters.IntrinsicSettings.Quota.MaxJobCount != null)
{
XElement maxJobCountElement = new XElement(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure"));
maxJobCountElement.Value = parameters.IntrinsicSettings.Quota.MaxJobCount.ToString();
quotaElement.Add(maxJobCountElement);
}
if (parameters.IntrinsicSettings.Quota.MaxJobOccurrence != null)
{
XElement maxJobOccurrenceElement = new XElement(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure"));
maxJobOccurrenceElement.Value = parameters.IntrinsicSettings.Quota.MaxJobOccurrence.ToString();
quotaElement.Add(maxJobOccurrenceElement);
}
if (parameters.IntrinsicSettings.Quota.MaxRecurrence != null)
{
XElement maxRecurrenceElement = new XElement(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure"));
quotaElement.Add(maxRecurrenceElement);
XElement frequencyElement = new XElement(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure"));
frequencyElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString();
maxRecurrenceElement.Add(frequencyElement);
XElement intervalElement = new XElement(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure"));
intervalElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString();
maxRecurrenceElement.Add(intervalElement);
}
}
}
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = TypeConversion.ToBase64String(parameters.Label);
resourceElement.Add(labelElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionUpdateResponse result = null;
result = new JobCollectionUpdateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Determine if the JobCollection name is available to be used.
/// JobCollection names must be unique within a cloud-service.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// A name for the JobCollection. The name must be unique as scoped
/// within the CloudService. The name can be up to 100 characters in
/// length.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Check Name Availability operation response.
/// </returns>
public async Task<JobCollectionCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (jobCollectionName.Length > 100)
{
throw new ArgumentOutOfRangeException("jobCollectionName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "CheckNameAvailabilityAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + this.Client.Credentials.SubscriptionId + "/cloudservices/" + cloudServiceName + "/resources/scheduler/JobCollections/?op=checknameavailability&resourceName=" + jobCollectionName;
// 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)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionCheckNameAvailabilityResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobCollectionCheckNameAvailabilityResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement resourceNameAvailabilityResponseElement = responseDoc.Element(XName.Get("ResourceNameAvailabilityResponse", "http://schemas.microsoft.com/windowsazure"));
if (resourceNameAvailabilityResponseElement != null)
{
XElement isAvailableElement = resourceNameAvailabilityResponseElement.Element(XName.Get("IsAvailable", "http://schemas.microsoft.com/windowsazure"));
if (isAvailableElement != null)
{
bool isAvailableInstance = bool.Parse(isAvailableElement.Value);
result.IsAvailable = isAvailableInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service containing the job collection.
/// </param>
/// <param name='jobCollectionName'>
/// The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Job Collection operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<SchedulerOperationStatusResponse> CreateAsync(string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters, CancellationToken cancellationToken)
{
SchedulerManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
JobCollectionCreateResponse response = await client.JobCollections.BeginCreatingAsync(cloudServiceName, jobCollectionName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
while ((result.Status != SchedulerOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != SchedulerOperationStatus.Succeeded)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
result.ETag = response.ETag;
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// The name of the job collection to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<SchedulerOperationStatusResponse> DeleteAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
SchedulerManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
OperationResponse response = await client.JobCollections.BeginDeletingAsync(cloudServiceName, jobCollectionName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
while ((result.Status != SchedulerOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != SchedulerOperationStatus.Succeeded)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// Retreive a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Name of the job collection.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Job Collection operation response.
/// </returns>
public async Task<JobCollectionGetResponse> GetAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + this.Client.Credentials.SubscriptionId + "/cloudservices/" + cloudServiceName + "/resources/scheduler/~/JobCollections/" + jobCollectionName;
// 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)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobCollectionGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement resourceElement = responseDoc.Element(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
if (resourceElement != null)
{
XElement nameElement = resourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
result.Name = nameInstance;
}
XElement eTagElement = resourceElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
if (eTagElement != null)
{
string eTagInstance = eTagElement.Value;
result.ETag = eTagInstance;
}
XElement stateElement = resourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
JobCollectionState stateInstance = (JobCollectionState)Enum.Parse(typeof(JobCollectionState), stateElement.Value, false);
result.State = stateInstance;
}
XElement schemaVersionElement = resourceElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
if (schemaVersionElement != null)
{
string schemaVersionInstance = schemaVersionElement.Value;
result.SchemaVersion = schemaVersionInstance;
}
XElement planElement = resourceElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
if (planElement != null)
{
string planInstance = planElement.Value;
result.Plan = planInstance;
}
XElement promotionCodeElement = resourceElement.Element(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure"));
if (promotionCodeElement != null)
{
string promotionCodeInstance = promotionCodeElement.Value;
result.PromotionCode = promotionCodeInstance;
}
XElement intrinsicSettingsElement = resourceElement.Element(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure"));
if (intrinsicSettingsElement != null)
{
JobCollectionIntrinsicSettings intrinsicSettingsInstance = new JobCollectionIntrinsicSettings();
result.IntrinsicSettings = intrinsicSettingsInstance;
XElement planElement2 = intrinsicSettingsElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
if (planElement2 != null)
{
JobCollectionPlan planInstance2 = (JobCollectionPlan)Enum.Parse(typeof(JobCollectionPlan), planElement2.Value, false);
intrinsicSettingsInstance.Plan = planInstance2;
}
XElement quotaElement = intrinsicSettingsElement.Element(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure"));
if (quotaElement != null)
{
JobCollectionQuota quotaInstance = new JobCollectionQuota();
intrinsicSettingsInstance.Quota = quotaInstance;
XElement maxJobCountElement = quotaElement.Element(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure"));
if (maxJobCountElement != null && string.IsNullOrEmpty(maxJobCountElement.Value) == false)
{
int maxJobCountInstance = int.Parse(maxJobCountElement.Value, CultureInfo.InvariantCulture);
quotaInstance.MaxJobCount = maxJobCountInstance;
}
XElement maxJobOccurrenceElement = quotaElement.Element(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure"));
if (maxJobOccurrenceElement != null && string.IsNullOrEmpty(maxJobOccurrenceElement.Value) == false)
{
int maxJobOccurrenceInstance = int.Parse(maxJobOccurrenceElement.Value, CultureInfo.InvariantCulture);
quotaInstance.MaxJobOccurrence = maxJobOccurrenceInstance;
}
XElement maxRecurrenceElement = quotaElement.Element(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure"));
if (maxRecurrenceElement != null)
{
JobCollectionMaxRecurrence maxRecurrenceInstance = new JobCollectionMaxRecurrence();
quotaInstance.MaxRecurrence = maxRecurrenceInstance;
XElement frequencyElement = maxRecurrenceElement.Element(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure"));
if (frequencyElement != null)
{
JobCollectionRecurrenceFrequency frequencyInstance = (JobCollectionRecurrenceFrequency)Enum.Parse(typeof(JobCollectionRecurrenceFrequency), frequencyElement.Value, false);
maxRecurrenceInstance.Frequency = frequencyInstance;
}
XElement intervalElement = maxRecurrenceElement.Element(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure"));
if (intervalElement != null)
{
int intervalInstance = int.Parse(intervalElement.Value, CultureInfo.InvariantCulture);
maxRecurrenceInstance.Interval = intervalInstance;
}
}
}
}
XElement labelElement = resourceElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = TypeConversion.FromBase64String(labelElement.Value);
result.Label = labelInstance;
}
XElement operationStatusElement = resourceElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure"));
if (operationStatusElement != null)
{
JobCollectionGetResponse.OperationStatus operationStatusInstance = new JobCollectionGetResponse.OperationStatus();
result.LastOperationStatus = operationStatusInstance;
XElement errorElement = operationStatusElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
JobCollectionGetResponse.OperationStatusResponseDetails errorInstance = new JobCollectionGetResponse.OperationStatusResponseDetails();
operationStatusInstance.ResponseDetails = errorInstance;
XElement httpCodeElement = errorElement.Element(XName.Get("HttpCode", "http://schemas.microsoft.com/windowsazure"));
if (httpCodeElement != null)
{
HttpStatusCode httpCodeInstance = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpCodeElement.Value, false);
errorInstance.StatusCode = httpCodeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure"));
if (resultElement != null)
{
SchedulerOperationStatus resultInstance = (SchedulerOperationStatus)Enum.Parse(typeof(SchedulerOperationStatus), resultElement.Value, false);
operationStatusInstance.Status = resultInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// The name of the cloud service containing the job collection.
/// </param>
/// <param name='jobCollectionName'>
/// The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Job Collection operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<SchedulerOperationStatusResponse> UpdateAsync(string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters, CancellationToken cancellationToken)
{
SchedulerManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
JobCollectionUpdateResponse response = await client.JobCollections.BeginUpdatingAsync(cloudServiceName, jobCollectionName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
while ((result.Status != SchedulerOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != SchedulerOperationStatus.Succeeded)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
result.ETag = response.ETag;
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
using System.Runtime.InteropServices;
#if GRPC_CSHARP_SUPPORT_SYSTEM_MEMORY
using System.Buffers;
#endif
namespace Grpc.Core.Internal.Tests
{
public class DefaultDeserializationContextTest
{
FakeBufferReaderManager fakeBufferReaderManager;
[SetUp]
public void Init()
{
fakeBufferReaderManager = new FakeBufferReaderManager();
}
[TearDown]
public void Cleanup()
{
fakeBufferReaderManager.Dispose();
}
#if GRPC_CSHARP_SUPPORT_SYSTEM_MEMORY
[TestCase]
public void PayloadAsReadOnlySequence_ZeroSegmentPayload()
{
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> {}));
Assert.AreEqual(0, context.PayloadLength);
var sequence = context.PayloadAsReadOnlySequence();
Assert.AreEqual(ReadOnlySequence<byte>.Empty, sequence);
Assert.IsTrue(sequence.IsEmpty);
Assert.IsTrue(sequence.IsSingleSegment);
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void PayloadAsReadOnlySequence_SingleSegmentPayload(int segmentLength)
{
var origBuffer = GetTestBuffer(segmentLength);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
var sequence = context.PayloadAsReadOnlySequence();
Assert.AreEqual(origBuffer.Length, sequence.Length);
Assert.AreEqual(origBuffer.Length, sequence.First.Length);
Assert.IsTrue(sequence.IsSingleSegment);
CollectionAssert.AreEqual(origBuffer, sequence.First.ToArray());
}
[TestCase(0, 5, 10)]
[TestCase(1, 1, 1)]
[TestCase(10, 100, 1000)]
[TestCase(100, 100, 10)]
[TestCase(1000, 1000, 1000)]
public void PayloadAsReadOnlySequence_MultiSegmentPayload(int segmentLen1, int segmentLen2, int segmentLen3)
{
var origBuffer1 = GetTestBuffer(segmentLen1);
var origBuffer2 = GetTestBuffer(segmentLen2);
var origBuffer3 = GetTestBuffer(segmentLen3);
int totalLen = origBuffer1.Length + origBuffer2.Length + origBuffer3.Length;
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> { origBuffer1, origBuffer2, origBuffer3 }));
Assert.AreEqual(totalLen, context.PayloadLength);
var sequence = context.PayloadAsReadOnlySequence();
Assert.AreEqual(totalLen, sequence.Length);
var segmentEnumerator = sequence.GetEnumerator();
Assert.IsTrue(segmentEnumerator.MoveNext());
CollectionAssert.AreEqual(origBuffer1, segmentEnumerator.Current.ToArray());
Assert.IsTrue(segmentEnumerator.MoveNext());
CollectionAssert.AreEqual(origBuffer2, segmentEnumerator.Current.ToArray());
Assert.IsTrue(segmentEnumerator.MoveNext());
CollectionAssert.AreEqual(origBuffer3, segmentEnumerator.Current.ToArray());
Assert.IsFalse(segmentEnumerator.MoveNext());
}
#endif
[TestCase]
public void NullPayloadNotAllowed()
{
var context = new DefaultDeserializationContext();
Assert.Throws(typeof(InvalidOperationException), () => context.Initialize(fakeBufferReaderManager.CreateNullPayloadBufferReader()));
}
[TestCase]
public void PayloadAsNewByteBuffer_ZeroSegmentPayload()
{
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> {}));
Assert.AreEqual(0, context.PayloadLength);
var payload = context.PayloadAsNewBuffer();
Assert.AreEqual(0, payload.Length);
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void PayloadAsNewByteBuffer_SingleSegmentPayload(int segmentLength)
{
var origBuffer = GetTestBuffer(segmentLength);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
var payload = context.PayloadAsNewBuffer();
CollectionAssert.AreEqual(origBuffer, payload);
}
[TestCase(0, 5, 10)]
[TestCase(1, 1, 1)]
[TestCase(10, 100, 1000)]
[TestCase(100, 100, 10)]
[TestCase(1000, 1000, 1000)]
public void PayloadAsNewByteBuffer_MultiSegmentPayload(int segmentLen1, int segmentLen2, int segmentLen3)
{
var origBuffer1 = GetTestBuffer(segmentLen1);
var origBuffer2 = GetTestBuffer(segmentLen2);
var origBuffer3 = GetTestBuffer(segmentLen3);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> { origBuffer1, origBuffer2, origBuffer3 }));
var payload = context.PayloadAsNewBuffer();
var concatenatedOrigBuffers = new List<byte>();
concatenatedOrigBuffers.AddRange(origBuffer1);
concatenatedOrigBuffers.AddRange(origBuffer2);
concatenatedOrigBuffers.AddRange(origBuffer3);
Assert.AreEqual(concatenatedOrigBuffers.Count, context.PayloadLength);
Assert.AreEqual(concatenatedOrigBuffers.Count, payload.Length);
CollectionAssert.AreEqual(concatenatedOrigBuffers, payload);
}
[TestCase]
public void GetPayloadMultipleTimesIsIllegal()
{
var origBuffer = GetTestBuffer(100);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
var payload = context.PayloadAsNewBuffer();
CollectionAssert.AreEqual(origBuffer, payload);
// Getting payload multiple times is illegal
Assert.Throws(typeof(InvalidOperationException), () => context.PayloadAsNewBuffer());
#if GRPC_CSHARP_SUPPORT_SYSTEM_MEMORY
Assert.Throws(typeof(InvalidOperationException), () => context.PayloadAsReadOnlySequence());
#endif
}
[TestCase]
public void ResetContextAndReinitialize()
{
var origBuffer = GetTestBuffer(100);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
// Reset invalidates context
context.Reset();
Assert.AreEqual(0, context.PayloadLength);
Assert.Throws(typeof(NullReferenceException), () => context.PayloadAsNewBuffer());
#if GRPC_CSHARP_SUPPORT_SYSTEM_MEMORY
Assert.Throws(typeof(NullReferenceException), () => context.PayloadAsReadOnlySequence());
#endif
// Previously reset context can be initialized again
var origBuffer2 = GetTestBuffer(50);
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer2));
Assert.AreEqual(origBuffer2.Length, context.PayloadLength);
CollectionAssert.AreEqual(origBuffer2, context.PayloadAsNewBuffer());
}
private byte[] GetTestBuffer(int length)
{
var testBuffer = new byte[length];
for (int i = 0; i < testBuffer.Length; i++)
{
testBuffer[i] = (byte) i;
}
return testBuffer;
}
}
}
| |
//
// JSClassDefinition.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace JavaScriptCore
{
public class JSClassDefinition
{
private struct JSClassDefinitionNative
{
public int version;
public JSClassAttribute attributes;
public IntPtr class_name;
public IntPtr parent_class;
public IntPtr /* JSStaticValue[] */ static_values;
public IntPtr static_functions;
public JSObject.InitializeCallback initialize;
public JSObject.FinalizeCallback finalize;
public JSObject.HasPropertyCallback has_property;
public JSObject.GetPropertyCallback get_property;
public JSObject.SetPropertyCallback set_property;
public JSObject.DeletePropertyCallback delete_property;
public JSObject.GetPropertyNamesCallback get_property_names;
public JSObject.CallAsFunctionCallback call_as_function;
public JSObject.CallAsConstructorCallback call_as_constructor;
public JSObject.HasInstanceCallback has_instance;
public JSObject.ConvertToTypeCallback convert_to_type;
}
private JSClassDefinitionNative raw;
private Dictionary<string, MethodInfo> static_methods;
private JSObject.CallAsFunctionCallback static_function_callback;
public virtual string ClassName {
get { return GetType ().FullName.Replace (".", "_").Replace ("+", "_"); }
}
public JSClassDefinition ()
{
raw = new JSClassDefinitionNative ();
raw.class_name = Marshal.StringToHGlobalAnsi (ClassName);
InstallClassOverrides ();
InstallStaticMethods ();
}
private void InstallClassOverrides ()
{
Override ("OnInitialize", () => raw.initialize = new JSObject.InitializeCallback (JSInitialize));
Override ("OnFinalize", () => raw.finalize = new JSObject.FinalizeCallback (JSFinalize));
Override ("OnJSHasProperty", () => raw.has_property = new JSObject.HasPropertyCallback (JSHasProperty));
Override ("OnJSGetProperty", () => raw.get_property = new JSObject.GetPropertyCallback (JSGetProperty));
Override ("OnJSSetProperty", () => raw.set_property = new JSObject.SetPropertyCallback (JSSetProperty));
Override ("OnJSDeleteProperty", () => raw.delete_property = new JSObject.DeletePropertyCallback (JSDeleteProperty));
Override ("OnJSGetPropertyNames", () => raw.get_property_names = new JSObject.GetPropertyNamesCallback (JSGetPropertyNames));
Override ("OnJSCallAsConstructor", () => raw.call_as_constructor = new JSObject.CallAsConstructorCallback (JSCallAsConstructor));
}
private void InstallStaticMethods ()
{
List<JSStaticFunction> methods = null;
foreach (var method in GetType ().GetMethods (
BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic)) {
foreach (var _attr in method.GetCustomAttributes (typeof (JSStaticFunctionAttribute), false)) {
var attr = (JSStaticFunctionAttribute)_attr;
var p = method.GetParameters ();
if (method.ReturnType != typeof (JSValue) || p.Length != 3 &&
p[0].ParameterType != typeof (JSObject) ||
p[1].ParameterType != typeof (JSObject) ||
p[2].ParameterType != typeof (JSValue [])) {
throw new Exception (String.Format ("Invalid signature for method annotated " +
"with JSStaticFunctionAttribute: {0}:{1} ('{2}'); signature should be " +
"'JSValue:JSFunction,JSObject,JSValue[]'",
GetType ().FullName, method.Name, attr.Name));
}
if (static_methods == null) {
static_methods = new Dictionary<string, MethodInfo> ();
} else if (static_methods.ContainsKey (attr.Name)) {
throw new Exception ("Class already contains static method named '" + attr.Name + "'");
}
static_methods.Add (attr.Name, method);
if (methods == null) {
methods = new List<JSStaticFunction> ();
}
if (static_function_callback == null) {
static_function_callback = new JSObject.CallAsFunctionCallback (OnStaticFunctionCallback);
}
methods.Add (new JSStaticFunction () {
Name = attr.Name,
Attributes = attr.Attributes,
Callback = static_function_callback
});
}
}
if (methods != null && methods.Count > 0) {
var size = Marshal.SizeOf (typeof (JSStaticFunction));
var ptr = Marshal.AllocHGlobal (size * (methods.Count + 1));
for (int i = 0; i < methods.Count; i++) {
Marshal.StructureToPtr (methods[i],
new IntPtr (ptr.ToInt64 () + size * i), false);
}
Marshal.StructureToPtr (new JSStaticFunction (),
new IntPtr (ptr.ToInt64 () + size * methods.Count), false);
raw.static_functions = ptr;
}
}
private void Override (string methodName, Action handler)
{
var method = GetType ().GetMethod (methodName, BindingFlags.Instance | BindingFlags.NonPublic);
if (method != null && (method.Attributes & MethodAttributes.VtableLayoutMask) == 0) {
handler ();
}
}
[DllImport (JSContext.NATIVE_IMPORT, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr JSClassCreate (ref JSClassDefinition.JSClassDefinitionNative definition);
private JSClass class_handle;
public JSClass ClassHandle {
get { return class_handle ?? (class_handle = CreateClass ()); }
}
public JSClass CreateClass ()
{
return new JSClass (JSClassCreate (ref raw));
}
private IntPtr OnStaticFunctionCallback (IntPtr ctx, IntPtr function, IntPtr thisObject,
IntPtr argumentCount, IntPtr arguments, ref IntPtr exception)
{
var context = new JSContext (ctx);
var fn = new JSObject (ctx, function);
string fn_name = null;
if (fn.HasProperty ("name")) {
var prop = fn.GetProperty ("name");
if (prop != null && prop.IsString) {
fn_name = prop.StringValue;
}
}
MethodInfo method = null;
if (fn_name == null || !static_methods.TryGetValue (fn_name, out method)) {
return JSValue.NewUndefined (context).Raw;
}
var result = method.Invoke (null, new object [] {
fn,
new JSObject (context, thisObject),
JSValue.MarshalArray (ctx, arguments, argumentCount)
});
return result == null
? JSValue.NewUndefined (context).Raw
: ((JSValue)result).Raw;
}
private void JSInitialize (IntPtr ctx, IntPtr obj)
{
OnJSInitialize (new JSObject (ctx, obj));
}
protected virtual void OnJSInitialize (JSObject obj)
{
}
private void JSFinalize (IntPtr obj)
{
OnJSFinalize (new JSObject (obj));
}
protected virtual void OnJSFinalize (JSObject obj)
{
}
private bool JSHasProperty (IntPtr ctx, IntPtr obj, JSString propertyName)
{
return OnJSHasProperty (new JSObject (ctx, obj), propertyName.Value);
}
protected virtual bool OnJSHasProperty (JSObject obj, string propertyName)
{
return false;
}
private IntPtr JSGetProperty (IntPtr ctx, IntPtr obj, JSString propertyName, ref IntPtr exception)
{
var context = new JSContext (ctx);
return (OnJSGetProperty (new JSObject (context, obj),
propertyName.Value) ?? JSValue.NewNull (context)).Raw;
}
protected virtual JSValue OnJSGetProperty (JSObject obj, string propertyName)
{
return JSValue.NewUndefined (obj.Context);
}
private bool JSSetProperty (IntPtr ctx, IntPtr obj, JSString propertyName,
IntPtr value, ref IntPtr exception)
{
var context = new JSContext (ctx);
try {
return OnJSSetProperty (new JSObject (context, obj), propertyName.Value, new JSValue (context, value));
} catch (JSErrorException e) {
exception = e.Error.Raw;
return false;
}
}
protected virtual bool OnJSSetProperty (JSObject obj, string propertyName, JSValue value)
{
return false;
}
private bool JSDeleteProperty (IntPtr ctx, IntPtr obj, JSString propertyName, ref IntPtr exception)
{
return OnJSDeleteProperty (new JSObject (ctx, obj), propertyName.Value);
}
protected virtual bool OnJSDeleteProperty (JSObject obj, string propertyName)
{
return false;
}
private void JSGetPropertyNames (IntPtr ctx, IntPtr obj, JSPropertyNameAccumulator propertyNames)
{
OnJSGetPropertyNames (new JSObject (ctx, obj), propertyNames);
}
protected virtual void OnJSGetPropertyNames (JSObject obj, JSPropertyNameAccumulator propertyNames)
{
}
private IntPtr JSCallAsConstructor (IntPtr ctx, IntPtr constructor,
IntPtr argumentCount, IntPtr arguments, ref IntPtr exception)
{
var result = OnJSCallAsConstructor (new JSObject (ctx, constructor),
JSValue.MarshalArray (ctx, arguments, argumentCount));
return result == null
? JSValue.NewUndefined (new JSContext (ctx)).Raw
: ((JSValue)result).Raw;
}
protected virtual JSObject OnJSCallAsConstructor (JSObject constructor, JSValue [] args)
{
return null;
}
}
}
| |
/*
* 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;
namespace Lucene.Net.Util
{
// from org.apache.solr.util rev 555343
/// <summary>A variety of high efficiencly bit twiddling routines.
///
/// </summary>
/// <version> $Id$
/// </version>
public class BitUtil
{
/// <summary>Returns the number of bits set in the long </summary>
public static int Pop(long x)
{
/* Hacker's Delight 32 bit pop function:
* http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc
*
int pop(unsigned x) {
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x0000003F;
}
***/
// 64 bit java version of the C function from above
x = x - ((SupportClass.Number.URShift(x, 1)) & 0x5555555555555555L);
x = (x & 0x3333333333333333L) + ((SupportClass.Number.URShift(x, 2)) & 0x3333333333333333L);
x = (x + (SupportClass.Number.URShift(x, 4))) & 0x0F0F0F0F0F0F0F0FL;
x = x + (SupportClass.Number.URShift(x, 8));
x = x + (SupportClass.Number.URShift(x, 16));
x = x + (SupportClass.Number.URShift(x, 32));
return ((int) x) & 0x7F;
}
/// <summary> Returns the number of set bits in an array of longs. </summary>
public static long Pop_array(long[] A, int wordOffset, int numWords)
{
/*
* Robert Harley and David Seal's bit counting algorithm, as documented
* in the revisions of Hacker's Delight
* http://www.hackersdelight.org/revisions.pdf
* http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc
*
* This function was adapted to Java, and extended to use 64 bit words.
* if only we had access to wider registers like SSE from java...
*
* This function can be transformed to compute the popcount of other functions
* on bitsets via something like this:
* sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g'
*
*/
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for (i = wordOffset; i <= n - 8; i += 8)
{
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, A[i], A[i+1])
{
long b = A[i], c = A[i + 1];
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, A[i+2], A[i+3])
{
long b = A[i + 2], c = A[i + 3];
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, A[i+4], A[i+5])
{
long b = A[i + 4], c = A[i + 5];
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, A[i+6], A[i+7])
{
long b = A[i + 6], c = A[i + 7];
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += Pop(eights);
}
// handle trailing words in a binary-search manner...
// derived from the loop above by setting specific elements to 0.
// the original method in Hackers Delight used a simple for loop:
// for (i = i; i < n; i++) // Add in the last elements
// tot = tot + pop(A[i]);
if (i <= n - 4)
{
long twosA, twosB, foursA, eights;
{
long b = A[i], c = A[i + 1];
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = A[i + 2], c = A[i + 3];
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 4;
}
if (i <= n - 2)
{
long b = A[i], c = A[i + 1];
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 2;
}
if (i < n)
{
tot += Pop(A[i]);
}
tot += (Pop(fours) << 2) + (Pop(twos) << 1) + Pop(ones) + (tot8 << 3);
return tot;
}
/// <summary>Returns the popcount or cardinality of the two sets after an intersection.
/// Neither array is modified.
/// </summary>
public static long Pop_intersect(long[] A, long[] B, int wordOffset, int numWords)
{
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g'
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for (i = wordOffset; i <= n - 8; i += 8)
{
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, (A[i] & B[i]), (A[i+1] & B[i+1]))
{
long b = (A[i] & B[i]), c = (A[i + 1] & B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+2] & B[i+2]), (A[i+3] & B[i+3]))
{
long b = (A[i + 2] & B[i + 2]), c = (A[i + 3] & B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, (A[i+4] & B[i+4]), (A[i+5] & B[i+5]))
{
long b = (A[i + 4] & B[i + 4]), c = (A[i + 5] & B[i + 5]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+6] & B[i+6]), (A[i+7] & B[i+7]))
{
long b = (A[i + 6] & B[i + 6]), c = (A[i + 7] & B[i + 7]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += Pop(eights);
}
if (i <= n - 4)
{
long twosA, twosB, foursA, eights;
{
long b = (A[i] & B[i]), c = (A[i + 1] & B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = (A[i + 2] & B[i + 2]), c = (A[i + 3] & B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 4;
}
if (i <= n - 2)
{
long b = (A[i] & B[i]), c = (A[i + 1] & B[i + 1]);
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 2;
}
if (i < n)
{
tot += Pop((A[i] & B[i]));
}
tot += (Pop(fours) << 2) + (Pop(twos) << 1) + Pop(ones) + (tot8 << 3);
return tot;
}
/// <summary>Returns the popcount or cardinality of the union of two sets.
/// Neither array is modified.
/// </summary>
public static long Pop_union(long[] A, long[] B, int wordOffset, int numWords)
{
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \| B[\1]\)/g'
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for (i = wordOffset; i <= n - 8; i += 8)
{
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, (A[i] | B[i]), (A[i+1] | B[i+1]))
{
long b = (A[i] | B[i]), c = (A[i + 1] | B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+2] | B[i+2]), (A[i+3] | B[i+3]))
{
long b = (A[i + 2] | B[i + 2]), c = (A[i + 3] | B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, (A[i+4] | B[i+4]), (A[i+5] | B[i+5]))
{
long b = (A[i + 4] | B[i + 4]), c = (A[i + 5] | B[i + 5]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+6] | B[i+6]), (A[i+7] | B[i+7]))
{
long b = (A[i + 6] | B[i + 6]), c = (A[i + 7] | B[i + 7]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += Pop(eights);
}
if (i <= n - 4)
{
long twosA, twosB, foursA, eights;
{
long b = (A[i] | B[i]), c = (A[i + 1] | B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = (A[i + 2] | B[i + 2]), c = (A[i + 3] | B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 4;
}
if (i <= n - 2)
{
long b = (A[i] | B[i]), c = (A[i + 1] | B[i + 1]);
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 2;
}
if (i < n)
{
tot += Pop((A[i] | B[i]));
}
tot += (Pop(fours) << 2) + (Pop(twos) << 1) + Pop(ones) + (tot8 << 3);
return tot;
}
/// <summary>Returns the popcount or cardinality of A & ~B
/// Neither array is modified.
/// </summary>
public static long Pop_andnot(long[] A, long[] B, int wordOffset, int numWords)
{
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& ~B[\1]\)/g'
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for (i = wordOffset; i <= n - 8; i += 8)
{
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, (A[i] & ~B[i]), (A[i+1] & ~B[i+1]))
{
long b = (A[i] & ~ B[i]), c = (A[i + 1] & ~ B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+2] & ~B[i+2]), (A[i+3] & ~B[i+3]))
{
long b = (A[i + 2] & ~ B[i + 2]), c = (A[i + 3] & ~ B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, (A[i+4] & ~B[i+4]), (A[i+5] & ~B[i+5]))
{
long b = (A[i + 4] & ~ B[i + 4]), c = (A[i + 5] & ~ B[i + 5]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+6] & ~B[i+6]), (A[i+7] & ~B[i+7]))
{
long b = (A[i + 6] & ~ B[i + 6]), c = (A[i + 7] & ~ B[i + 7]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += Pop(eights);
}
if (i <= n - 4)
{
long twosA, twosB, foursA, eights;
{
long b = (A[i] & ~ B[i]), c = (A[i + 1] & ~ B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = (A[i + 2] & ~ B[i + 2]), c = (A[i + 3] & ~ B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 4;
}
if (i <= n - 2)
{
long b = (A[i] & ~ B[i]), c = (A[i + 1] & ~ B[i + 1]);
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 2;
}
if (i < n)
{
tot += Pop((A[i] & ~ B[i]));
}
tot += (Pop(fours) << 2) + (Pop(twos) << 1) + Pop(ones) + (tot8 << 3);
return tot;
}
public static long Pop_xor(long[] A, long[] B, int wordOffset, int numWords)
{
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for (i = wordOffset; i <= n - 8; i += 8)
{
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, (A[i] ^ B[i]), (A[i+1] ^ B[i+1]))
{
long b = (A[i] ^ B[i]), c = (A[i + 1] ^ B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+2] ^ B[i+2]), (A[i+3] ^ B[i+3]))
{
long b = (A[i + 2] ^ B[i + 2]), c = (A[i + 3] ^ B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, (A[i+4] ^ B[i+4]), (A[i+5] ^ B[i+5]))
{
long b = (A[i + 4] ^ B[i + 4]), c = (A[i + 5] ^ B[i + 5]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+6] ^ B[i+6]), (A[i+7] ^ B[i+7]))
{
long b = (A[i + 6] ^ B[i + 6]), c = (A[i + 7] ^ B[i + 7]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += Pop(eights);
}
if (i <= n - 4)
{
long twosA, twosB, foursA, eights;
{
long b = (A[i] ^ B[i]), c = (A[i + 1] ^ B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = (A[i + 2] ^ B[i + 2]), c = (A[i + 3] ^ B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 4;
}
if (i <= n - 2)
{
long b = (A[i] ^ B[i]), c = (A[i + 1] ^ B[i + 1]);
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += Pop(eights);
i += 2;
}
if (i < n)
{
tot += Pop((A[i] ^ B[i]));
}
tot += (Pop(fours) << 2) + (Pop(twos) << 1) + Pop(ones) + (tot8 << 3);
return tot;
}
/* python code to generate ntzTable
def ntz(val):
if val==0: return 8
i=0
while (val&0x01)==0:
i = i+1
val >>= 1
return i
print ','.join([ str(ntz(i)) for i in range(256) ])
***/
/// <summary>table of number of trailing zeros in a byte </summary>
public static readonly sbyte[] ntzTable = new sbyte[]{8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
/// <summary>Returns number of trailing zeros in a 64 bit long value. </summary>
public static int Ntz(long val)
{
// A full binary search to determine the low byte was slower than
// a linear search for nextSetBit(). This is most likely because
// the implementation of nextSetBit() shifts bits to the right, increasing
// the probability that the first non-zero byte is in the rhs.
//
// This implementation does a single binary search at the top level only
// so that all other bit shifting can be done on ints instead of longs to
// remain friendly to 32 bit architectures. In addition, the case of a
// non-zero first byte is checked for first because it is the most common
// in dense bit arrays.
int lower = (int) val;
int lowByte = lower & 0xff;
if (lowByte != 0)
return ntzTable[lowByte];
if (lower != 0)
{
lowByte = (SupportClass.Number.URShift(lower, 8)) & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 8;
lowByte = (SupportClass.Number.URShift(lower, 16)) & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 16;
// no need to mask off low byte for the last byte in the 32 bit word
// no need to check for zero on the last byte either.
return ntzTable[SupportClass.Number.URShift(lower, 24)] + 24;
}
else
{
// grab upper 32 bits
int upper = (int) (val >> 32);
lowByte = upper & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 32;
lowByte = (SupportClass.Number.URShift(upper, 8)) & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 40;
lowByte = (SupportClass.Number.URShift(upper, 16)) & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 48;
// no need to mask off low byte for the last byte in the 32 bit word
// no need to check for zero on the last byte either.
return ntzTable[SupportClass.Number.URShift(upper, 24)] + 56;
}
}
/// <summary>Returns number of trailing zeros in a 32 bit int value. </summary>
public static int Ntz(int val)
{
// This implementation does a single binary search at the top level only.
// In addition, the case of a non-zero first byte is checked for first
// because it is the most common in dense bit arrays.
int lowByte = val & 0xff;
if (lowByte != 0)
return ntzTable[lowByte];
lowByte = (SupportClass.Number.URShift(val, 8)) & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 8;
lowByte = (SupportClass.Number.URShift(val, 16)) & 0xff;
if (lowByte != 0)
return ntzTable[lowByte] + 16;
// no need to mask off low byte for the last byte.
// no need to check for zero on the last byte either.
return ntzTable[SupportClass.Number.URShift(val, 24)] + 24;
}
/// <summary>returns 0 based index of first set bit
/// (only works for x!=0)
/// <br/> This is an alternate implementation of ntz()
/// </summary>
public static int Ntz2(long x)
{
int n = 0;
int y = (int) x;
if (y == 0)
{
n += 32; y = (int) (SupportClass.Number.URShift(x, 32));
} // the only 64 bit shift necessary
if ((y & 0x0000FFFF) == 0)
{
n += 16; y = SupportClass.Number.URShift(y, 16);
}
if ((y & 0x000000FF) == 0)
{
n += 8; y = SupportClass.Number.URShift(y, 8);
}
return (ntzTable[y & 0xff]) + n;
}
/// <summary>returns 0 based index of first set bit
/// <br/> This is an alternate implementation of ntz()
/// </summary>
public static int Ntz3(long x)
{
// another implementation taken from Hackers Delight, extended to 64 bits
// and converted to Java.
// Many 32 bit ntz algorithms are at http://www.hackersdelight.org/HDcode/ntz.cc
int n = 1;
// do the first step as a long, all others as ints.
int y = (int) x;
if (y == 0)
{
n += 32; y = (int) (SupportClass.Number.URShift(x, 32));
}
if ((y & 0x0000FFFF) == 0)
{
n += 16; y = SupportClass.Number.URShift(y, 16);
}
if ((y & 0x000000FF) == 0)
{
n += 8; y = SupportClass.Number.URShift(y, 8);
}
if ((y & 0x0000000F) == 0)
{
n += 4; y = SupportClass.Number.URShift(y, 4);
}
if ((y & 0x00000003) == 0)
{
n += 2; y = SupportClass.Number.URShift(y, 2);
}
return n - (y & 1);
}
/// <summary>returns true if v is a power of two or zero</summary>
public static bool IsPowerOfTwo(int v)
{
return ((v & (v - 1)) == 0);
}
/// <summary>returns true if v is a power of two or zero</summary>
public static bool IsPowerOfTwo(long v)
{
return ((v & (v - 1)) == 0);
}
/// <summary>returns the next highest power of two, or the current value if it's already a power of two or zero</summary>
public static int NextHighestPowerOfTwo(int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/// <summary>returns the next highest power of two, or the current value if it's already a power of two or zero</summary>
public static long NextHighestPowerOfTwo(long v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmShrink
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmShrink() : base()
{
Load += frmShrink_Load;
KeyPress += frmShrink_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.TextBox _txtInteger_0;
private System.Windows.Forms.Button withEventsField_cmdShrinkAdd;
public System.Windows.Forms.Button cmdShrinkAdd {
get { return withEventsField_cmdShrinkAdd; }
set {
if (withEventsField_cmdShrinkAdd != null) {
withEventsField_cmdShrinkAdd.Click -= cmdShrinkAdd_Click;
}
withEventsField_cmdShrinkAdd = value;
if (withEventsField_cmdShrinkAdd != null) {
withEventsField_cmdShrinkAdd.Click += cmdShrinkAdd_Click;
}
}
}
public System.Windows.Forms.TextBox _txtInteger_5;
public System.Windows.Forms.TextBox _txtInteger_4;
public System.Windows.Forms.TextBox _txtInteger_3;
public System.Windows.Forms.TextBox _txtInteger_2;
public System.Windows.Forms.TextBox _txtInteger_1;
public System.Windows.Forms.Label _lbl_5;
public System.Windows.Forms.Label _lbl_4;
public System.Windows.Forms.Label _lbl_3;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_0;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtInteger As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmShrink));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdExit = new System.Windows.Forms.Button();
this._txtInteger_0 = new System.Windows.Forms.TextBox();
this.cmdShrinkAdd = new System.Windows.Forms.Button();
this._txtInteger_5 = new System.Windows.Forms.TextBox();
this._txtInteger_4 = new System.Windows.Forms.TextBox();
this._txtInteger_3 = new System.Windows.Forms.TextBox();
this._txtInteger_2 = new System.Windows.Forms.TextBox();
this._txtInteger_1 = new System.Windows.Forms.TextBox();
this._lbl_5 = new System.Windows.Forms.Label();
this._lbl_4 = new System.Windows.Forms.Label();
this._lbl_3 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.txtInteger = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtInteger, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Add a Shrink ...";
this.ClientSize = new System.Drawing.Size(344, 143);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmShrink";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(97, 52);
this.cmdExit.Location = new System.Drawing.Point(240, 78);
this.cmdExit.TabIndex = 13;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this._txtInteger_0.AutoSize = false;
this._txtInteger_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtInteger_0.Size = new System.Drawing.Size(43, 19);
this._txtInteger_0.Location = new System.Drawing.Point(24, 12);
this._txtInteger_0.TabIndex = 0;
this._txtInteger_0.Text = "0";
this._txtInteger_0.AcceptsReturn = true;
this._txtInteger_0.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_0.CausesValidation = true;
this._txtInteger_0.Enabled = true;
this._txtInteger_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_0.HideSelection = true;
this._txtInteger_0.ReadOnly = false;
this._txtInteger_0.MaxLength = 0;
this._txtInteger_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_0.Multiline = false;
this._txtInteger_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtInteger_0.TabStop = true;
this._txtInteger_0.Visible = true;
this._txtInteger_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_0.Name = "_txtInteger_0";
this.cmdShrinkAdd.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdShrinkAdd.Text = "Add Shrink";
this.cmdShrinkAdd.Size = new System.Drawing.Size(97, 19);
this.cmdShrinkAdd.Location = new System.Drawing.Point(240, 39);
this.cmdShrinkAdd.TabIndex = 11;
this.cmdShrinkAdd.BackColor = System.Drawing.SystemColors.Control;
this.cmdShrinkAdd.CausesValidation = true;
this.cmdShrinkAdd.Enabled = true;
this.cmdShrinkAdd.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdShrinkAdd.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdShrinkAdd.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdShrinkAdd.TabStop = true;
this.cmdShrinkAdd.Name = "cmdShrinkAdd";
this._txtInteger_5.AutoSize = false;
this._txtInteger_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtInteger_5.Size = new System.Drawing.Size(43, 19);
this._txtInteger_5.Location = new System.Drawing.Point(294, 12);
this._txtInteger_5.TabIndex = 5;
this._txtInteger_5.Text = "0";
this._txtInteger_5.AcceptsReturn = true;
this._txtInteger_5.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_5.CausesValidation = true;
this._txtInteger_5.Enabled = true;
this._txtInteger_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_5.HideSelection = true;
this._txtInteger_5.ReadOnly = false;
this._txtInteger_5.MaxLength = 0;
this._txtInteger_5.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_5.Multiline = false;
this._txtInteger_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_5.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtInteger_5.TabStop = true;
this._txtInteger_5.Visible = true;
this._txtInteger_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_5.Name = "_txtInteger_5";
this._txtInteger_4.AutoSize = false;
this._txtInteger_4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtInteger_4.Size = new System.Drawing.Size(43, 19);
this._txtInteger_4.Location = new System.Drawing.Point(240, 12);
this._txtInteger_4.TabIndex = 4;
this._txtInteger_4.Text = "0";
this._txtInteger_4.AcceptsReturn = true;
this._txtInteger_4.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_4.CausesValidation = true;
this._txtInteger_4.Enabled = true;
this._txtInteger_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_4.HideSelection = true;
this._txtInteger_4.ReadOnly = false;
this._txtInteger_4.MaxLength = 0;
this._txtInteger_4.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_4.Multiline = false;
this._txtInteger_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_4.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtInteger_4.TabStop = true;
this._txtInteger_4.Visible = true;
this._txtInteger_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_4.Name = "_txtInteger_4";
this._txtInteger_3.AutoSize = false;
this._txtInteger_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtInteger_3.Size = new System.Drawing.Size(43, 19);
this._txtInteger_3.Location = new System.Drawing.Point(186, 12);
this._txtInteger_3.TabIndex = 3;
this._txtInteger_3.Text = "0";
this._txtInteger_3.AcceptsReturn = true;
this._txtInteger_3.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_3.CausesValidation = true;
this._txtInteger_3.Enabled = true;
this._txtInteger_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_3.HideSelection = true;
this._txtInteger_3.ReadOnly = false;
this._txtInteger_3.MaxLength = 0;
this._txtInteger_3.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_3.Multiline = false;
this._txtInteger_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_3.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtInteger_3.TabStop = true;
this._txtInteger_3.Visible = true;
this._txtInteger_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_3.Name = "_txtInteger_3";
this._txtInteger_2.AutoSize = false;
this._txtInteger_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtInteger_2.Size = new System.Drawing.Size(43, 19);
this._txtInteger_2.Location = new System.Drawing.Point(132, 12);
this._txtInteger_2.TabIndex = 2;
this._txtInteger_2.Text = "0";
this._txtInteger_2.AcceptsReturn = true;
this._txtInteger_2.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_2.CausesValidation = true;
this._txtInteger_2.Enabled = true;
this._txtInteger_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_2.HideSelection = true;
this._txtInteger_2.ReadOnly = false;
this._txtInteger_2.MaxLength = 0;
this._txtInteger_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_2.Multiline = false;
this._txtInteger_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_2.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtInteger_2.TabStop = true;
this._txtInteger_2.Visible = true;
this._txtInteger_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_2.Name = "_txtInteger_2";
this._txtInteger_1.AutoSize = false;
this._txtInteger_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtInteger_1.Size = new System.Drawing.Size(43, 19);
this._txtInteger_1.Location = new System.Drawing.Point(78, 12);
this._txtInteger_1.TabIndex = 1;
this._txtInteger_1.Text = "0";
this._txtInteger_1.AcceptsReturn = true;
this._txtInteger_1.BackColor = System.Drawing.SystemColors.Window;
this._txtInteger_1.CausesValidation = true;
this._txtInteger_1.Enabled = true;
this._txtInteger_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtInteger_1.HideSelection = true;
this._txtInteger_1.ReadOnly = false;
this._txtInteger_1.MaxLength = 0;
this._txtInteger_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtInteger_1.Multiline = false;
this._txtInteger_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtInteger_1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtInteger_1.TabStop = true;
this._txtInteger_1.Visible = true;
this._txtInteger_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtInteger_1.Name = "_txtInteger_1";
this._lbl_5.Text = "1 X";
this._lbl_5.Size = new System.Drawing.Size(16, 13);
this._lbl_5.Location = new System.Drawing.Point(6, 15);
this._lbl_5.TabIndex = 12;
this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Enabled = true;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.UseMnemonic = true;
this._lbl_5.Visible = true;
this._lbl_5.AutoSize = true;
this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_5.Name = "_lbl_5";
this._lbl_4.Text = "X";
this._lbl_4.Size = new System.Drawing.Size(7, 13);
this._lbl_4.Location = new System.Drawing.Point(285, 15);
this._lbl_4.TabIndex = 10;
this._lbl_4.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_4.BackColor = System.Drawing.Color.Transparent;
this._lbl_4.Enabled = true;
this._lbl_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_4.UseMnemonic = true;
this._lbl_4.Visible = true;
this._lbl_4.AutoSize = true;
this._lbl_4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_4.Name = "_lbl_4";
this._lbl_3.Text = "X";
this._lbl_3.Size = new System.Drawing.Size(7, 13);
this._lbl_3.Location = new System.Drawing.Point(231, 15);
this._lbl_3.TabIndex = 9;
this._lbl_3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_3.BackColor = System.Drawing.Color.Transparent;
this._lbl_3.Enabled = true;
this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_3.UseMnemonic = true;
this._lbl_3.Visible = true;
this._lbl_3.AutoSize = true;
this._lbl_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_3.Name = "_lbl_3";
this._lbl_2.Text = "X";
this._lbl_2.Size = new System.Drawing.Size(7, 13);
this._lbl_2.Location = new System.Drawing.Point(177, 15);
this._lbl_2.TabIndex = 8;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this._lbl_1.Text = "X";
this._lbl_1.Size = new System.Drawing.Size(7, 13);
this._lbl_1.Location = new System.Drawing.Point(123, 15);
this._lbl_1.TabIndex = 7;
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = true;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this._lbl_0.Text = "X";
this._lbl_0.Size = new System.Drawing.Size(7, 13);
this._lbl_0.Location = new System.Drawing.Point(69, 15);
this._lbl_0.TabIndex = 6;
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = true;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this.Controls.Add(cmdExit);
this.Controls.Add(_txtInteger_0);
this.Controls.Add(cmdShrinkAdd);
this.Controls.Add(_txtInteger_5);
this.Controls.Add(_txtInteger_4);
this.Controls.Add(_txtInteger_3);
this.Controls.Add(_txtInteger_2);
this.Controls.Add(_txtInteger_1);
this.Controls.Add(_lbl_5);
this.Controls.Add(_lbl_4);
this.Controls.Add(_lbl_3);
this.Controls.Add(_lbl_2);
this.Controls.Add(_lbl_1);
this.Controls.Add(_lbl_0);
//Me.lbl.SetIndex(_lbl_5, CType(5, Short))
//Me.lbl.SetIndex(_lbl_4, CType(4, Short))
//Me.lbl.SetIndex(_lbl_3, CType(3, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lbl.SetIndex(_lbl_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//Me.txtInteger.SetIndex(_txtInteger_0, CType(0, Short))
//Me.txtInteger.SetIndex(_txtInteger_5, CType(5, Short))
//Me.txtInteger.SetIndex(_txtInteger_4, CType(4, Short))
//Me.txtInteger.SetIndex(_txtInteger_3, CType(3, Short))
//Me.txtInteger.SetIndex(_txtInteger_2, CType(2, Short))
//Me.txtInteger.SetIndex(_txtInteger_1, CType(1, Short))
//C() ''Type(Me.txtInteger, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in August, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Data;
namespace DotSpatial.Data
{
/// <summary>
/// This represents the column information for one column of a shapefile.
/// This specifies precision as well as the typical column information.
/// </summary>
public class Field : DataColumn
{
/// <summary>
/// Represents the number of decimals to preserve after a 0.
/// </summary>
private byte _decimalCount;
/// <summary>
/// The length of a field in bytes
/// </summary>
private byte _length;
#region Properties
/// <summary>
/// Creates a new default field empty field - needed for datatable copy and clone methods.
/// </summary>
public Field()
{
}
/// <summary>
/// Creates a new default field given the specified DataColumn. Numeric types
/// default to a size of 255, but will be shortened during the save opperation.
/// The default decimal count for double and long is 0, for Currency is 2, for float is
/// 3, and for double is 8. These can be changed by changing the DecimalCount property.
/// </summary>
/// <param name="inColumn">A System.Data.DataColumn to create a Field from</param>
public Field(DataColumn inColumn)
: base(inColumn.ColumnName, inColumn.DataType, inColumn.Expression, inColumn.ColumnMapping)
{
SetupDecimalCount();
if (inColumn.DataType == typeof(string))
{
_length = inColumn.MaxLength <= 254 ? (byte) inColumn.MaxLength : (byte) 254;
}
else if (inColumn.DataType == typeof(DateTime))
{
_length = 8;
}
else if (inColumn.DataType == typeof(bool))
{
_length = 1;
}
}
/// <summary>
/// Creates a new instance of a field given only a column name
/// </summary>
/// <param name="inColumnName">The string Column Name for the new field</param>
public Field(string inColumnName)
: base(inColumnName)
{
// can't setup decimal count without a data type
}
/// <summary>
/// Creates a new Field with a specific name for a specified data type
/// </summary>
/// <param name="inColumnName">The string name of the column</param>
/// <param name="inDataType">The System.Type describing the datatype of the field</param>
public Field(string inColumnName, Type inDataType)
: base(inColumnName, inDataType)
{
SetupDecimalCount();
}
/// <summary>
/// Creates a new field with a specific name and using a simplified enumeration of possible types.
/// </summary>
/// <param name="inColumnName">the string column name.</param>
/// <param name="type">The type enumeration that clarifies which basic data type to use.</param>
public Field(string inColumnName, FieldDataType type)
: base(inColumnName)
{
if (type == FieldDataType.Double) DataType = typeof(double);
if (type == FieldDataType.Integer) DataType = typeof(int);
if (type == FieldDataType.String) DataType = typeof(string);
}
/*
* Field Types Specified by the dBASE Format Specifications
*
* http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm
*
* Symbol | Data Type | Description
* -------+--------------+-------------------------------------------------------------------------------------
* B | Binary | 10 digits representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
* C | Character | All OEM code page characters - padded with blanks to the width of the field.
* D | Date | 8 bytes - date stored as a string in the format YYYYMMDD.
* N | Numeric | Number stored as a string, right justified, and padded with blanks to the width of the field.
* L | Logical | 1 byte - initialized to 0x20 (space) otherwise T or F.
* M | Memo | 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
* @ | Timestamp | 8 bytes - two longs, first for date, second for time. The date is the number of days since 01/01/4713 BC. Time is hours * 3600000L + minutes * 60000L + Seconds * 1000L
* I | Long | 4 bytes. Leftmost bit used to indicate sign, 0 negative.
* + |Autoincrement | Same as a Long
* F | Float | Number stored as a string, right justified, and padded with blanks to the width of the field.
* O | Double | 8 bytes - no conversions, stored as a double.
* G | OLE | 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
*/
/// <summary>
/// This creates a new instance. Since the data type is
/// </summary>
/// <param name="columnName"></param>
/// <param name="typeCode"></param>
/// <param name="length"></param>
/// <param name="decimalCount"></param>
public Field(string columnName, char typeCode, byte length, byte decimalCount)
: base(columnName)
{
Length = length;
ColumnName = columnName;
DecimalCount = decimalCount;
// Date or Timestamp
if (typeCode == 'D' || typeCode == '@')
{
// date
DataType = typeof(DateTime);
return;
}
if (typeCode == 'L')
{
DataType = typeof(bool);
return;
}
// Long or AutoIncrement
if (typeCode == 'I' || typeCode == '+')
{
DataType = typeof(int);
return;
}
if (typeCode == 'O')
{
DataType = typeof(double);
return;
}
if (typeCode == 'N' || typeCode == 'B' || typeCode == 'M' || typeCode == 'F' || typeCode == 'G')
{
// The strategy here is to assign the smallest type that we KNOW will be large enough
// to hold any value with the length (in digits) and characters.
// even though double can hold as high a value as a "Number" can go, it can't
// preserve the extraordinary 255 digit precision that a Number has. The strategy
// is to assess the length in characters and assign a numeric type where no
// value may exist outside the range. (They can always change the datatype later.)
// The basic encoding we are using here
if (decimalCount == 0)
{
if (length < 3)
{
// 0 to 255
DataType = typeof(byte);
return;
}
if (length < 5)
{
// -32768 to 32767
DataType = typeof(short); // Int16
return;
}
if (length < 10)
{
// -2147483648 to 2147483647
DataType = typeof(int); // Int32
return;
}
if (length < 19)
{
// -9223372036854775808 to -9223372036854775807
DataType = typeof(long); // Int64
return;
}
}
if (decimalCount > 15)
{
// we know this has too many significant digits to fit in a double:
// a double can hold 15-16 significant digits: https://msdn.microsoft.com/en-us/library/678hzkk9.aspx
DataType = typeof(string);
MaxLength = length;
return;
}
// Singles -3.402823E+38 to 3.402823E+38
// Doubles -1.79769313486232E+308 to 1.79769313486232E+308
// Decimals -79228162514264337593543950335 to 79228162514264337593543950335
// Doubles have the range to handle any number with the 255 character size,
// but won't preserve the precision that is possible. It is still
// preferable to have a numeric type in 99% of cases, and double is the easiest.
DataType = typeof(double);
return;
}
// Type code is either C or not recognized, in which case we will just end up with a string
// representation of whatever the characters are.
DataType = typeof(string);
MaxLength = length;
}
/// <summary>
/// This is the single character dBase code. Only some of these are supported with Esri.
/// C - Character (Chars, Strings, objects - as ToString(), and structs - as )
/// D - Date (DateTime)
/// T - Time (DateTime)
/// N - Number (Short, Integer, Long, Float, Double, byte)
/// L - Logic (True-False, Yes-No)
/// F - Float
/// B - Double
/// </summary>
public char TypeCharacter
{
get
{
if (DataType == typeof(bool)) return 'L';
if (DataType == typeof(DateTime)) return 'D';
// We are using numeric in most cases here, because that is the format most compatible with other
// Applications
if (DataType == typeof(float)) return 'N';
if (DataType == typeof(double)) return 'N';
if (DataType == typeof(decimal)) return 'N';
if (DataType == typeof(byte)) return 'N';
if (DataType == typeof(short)) return 'N';
if (DataType == typeof(int)) return 'N';
if (DataType == typeof(long)) return 'N';
// The default is to store it as a string type
return 'C';
}
}
/// <summary>
/// Gets or sets the number of places to keep after the 0 in number formats.
/// As far as dbf fields are concerned, all numeric datatypes use the same
/// database number format.
/// </summary>
public byte DecimalCount
{
get
{
return _decimalCount;
}
set
{
_decimalCount = value;
}
}
/// <summary>
/// The character length of the field
/// </summary>
public byte Length
{
get
{
return _length;
}
set
{
_length = value;
}
}
/// <summary>
/// The offset of the field on a row in the file
/// </summary>
public int DataAddress { get; set; }
///<summary>
/// Number Converter associated with this field.
///</summary>
public NumberConverter NumberConverter { get; set; }
/// <summary>
/// Internal method that decides an appropriate decimal count, given a data column
/// </summary>
private void SetupDecimalCount()
{
// Going this way, we want a large enough decimal count to hold any of the possible numeric values.
// We will try to make the length large enough to hold any values, but some doubles simply will be
// too large to be stored in this format, so we will throw exceptions if that happens later.
// These sizes represent the "maximized" length and decimal counts that will be shrunk in order
// to fit the data before saving.
if (DataType == typeof(float))
{
//_decimalCount = (byte)40; // Singles -3.402823E+38 to 3.402823E+38
//_length = (byte)40;
_length = 18;
_decimalCount = 6;
return;
}
if (DataType == typeof(double))
{
//_decimalCount = (byte)255; // Doubles -1.79769313486232E+308 to 1.79769313486232E+308
//_length = (byte)255;
_length = 18;
_decimalCount = 9;
return;
}
if (DataType == typeof(decimal))
{
_length = 18;
_decimalCount = 9; // Decimals -79228162514264337593543950335 to 79228162514264337593543950335
return;
}
if (DataType == typeof(byte))
{
// 0 to 255
_decimalCount = 0;
_length = 3;
return;
}
if (DataType == typeof(short))
{
// -32768 to 32767
_length = 6;
_decimalCount = 0;
return;
}
if (DataType == typeof(int))
{
// -2147483648 to 2147483647
_length = 11;
_decimalCount = 0;
return;
}
if (DataType == typeof(long))
{
// -9223372036854775808 to -9223372036854775807
_length = 20;
_decimalCount = 0;
return;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.Win32;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
public static class LoggingConstants
{
public const string DefaultVSRegistryRoot = @"Software\Microsoft\VisualStudio\15.0";
public const string BuildVerbosityRegistrySubKey = @"General";
public const string BuildVerbosityRegistryValue = "MSBuildLoggerVerbosity";
public const string UpToDateVerbosityRegistryValue = "U2DCheckVerbosity";
}
/// <summary>
/// This class implements an MSBuild logger that output events to VS outputwindow and tasklist.
/// </summary>
[ComVisible(true)]
public sealed class IDEBuildLogger : Logger
{
// TODO: Remove these constants when we have a version that supports getting the verbosity using automation.
private string buildVerbosityRegistryRoot = LoggingConstants.DefaultVSRegistryRoot;
// TODO: Re-enable this constants when we have a version that suppoerts getting the verbosity using automation.
private int currentIndent;
private IVsOutputWindowPane outputWindowPane;
private string errorString = SR.GetString(SR.Error, CultureInfo.CurrentUICulture);
private string warningString = SR.GetString(SR.Warning, CultureInfo.CurrentUICulture);
private bool isLogTaskDone;
private IVsHierarchy hierarchy;
private IServiceProvider serviceProvider;
private IVsLanguageServiceBuildErrorReporter2 errorReporter;
private bool haveCachedRegistry = false;
public string WarningString
{
get { return this.warningString; }
set { this.warningString = value; }
}
public string ErrorString
{
get { return this.errorString; }
set { this.errorString = value; }
}
public bool IsLogTaskDone
{
get { return this.isLogTaskDone; }
set { this.isLogTaskDone = value; }
}
/// <summary>
/// When building from within VS, setting this will
/// enable the logger to retrive the verbosity from
/// the correct registry hive.
/// </summary>
public string BuildVerbosityRegistryRoot
{
get { return buildVerbosityRegistryRoot; }
set { buildVerbosityRegistryRoot = value; }
}
/// <summary>
/// Set to null to avoid writing to the output window
/// </summary>
public IVsOutputWindowPane OutputWindowPane
{
get { return outputWindowPane; }
set { outputWindowPane = value; }
}
public IVsLanguageServiceBuildErrorReporter2 ErrorReporter
{
get { return errorReporter; }
set { errorReporter = value; }
}
internal IDEBuildLogger(IVsOutputWindowPane output, IVsHierarchy hierarchy, IVsLanguageServiceBuildErrorReporter2 errorReporter)
{
if (hierarchy == null)
throw new ArgumentNullException("hierarchy");
this.errorReporter = errorReporter;
this.outputWindowPane = output;
this.hierarchy = hierarchy;
IOleServiceProvider site;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hierarchy.GetSite(out site));
this.serviceProvider = new Shell.ServiceProvider (site);
}
public override void Initialize(IEventSource eventSource)
{
if (null == eventSource)
{
throw new ArgumentNullException("eventSource");
}
// Note that the MSBuild logger thread does not have an exception handler, so
// we swallow all exceptions (lest some random bad thing bring down the process).
eventSource.BuildStarted += new BuildStartedEventHandler(BuildStartedHandler);
eventSource.BuildFinished += new BuildFinishedEventHandler(BuildFinishedHandler);
eventSource.ProjectStarted += new ProjectStartedEventHandler(ProjectStartedHandler);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(ProjectFinishedHandler);
eventSource.TargetStarted += new TargetStartedEventHandler(TargetStartedHandler);
eventSource.TargetFinished += new TargetFinishedEventHandler(TargetFinishedHandler);
eventSource.TaskStarted += new TaskStartedEventHandler(TaskStartedHandler);
eventSource.TaskFinished += new TaskFinishedEventHandler(TaskFinishedHandler);
eventSource.CustomEventRaised += new CustomBuildEventHandler(CustomHandler);
eventSource.ErrorRaised += new BuildErrorEventHandler(ErrorHandler);
eventSource.WarningRaised += new BuildWarningEventHandler(WarningHandler);
eventSource.MessageRaised += new BuildMessageEventHandler(MessageHandler);
}
/// <summary>
/// This is the delegate for error events.
/// </summary>
private void ErrorHandler(object sender, BuildErrorEventArgs errorEvent)
{
try
{
AddToErrorList(
errorEvent,
errorEvent.Subcategory,
errorEvent.Code,
errorEvent.File,
errorEvent.LineNumber,
errorEvent.ColumnNumber,
errorEvent.EndLineNumber,
errorEvent.EndColumnNumber);
}
catch (Exception e)
{
Debug.Assert(false, "Problem adding error to error list: " + e.Message + " at " + e.TargetSite);
}
}
/// <summary>
/// This is the delegate for warning events.
/// </summary>
private void WarningHandler(object sender, BuildWarningEventArgs errorEvent)
{
try
{
AddToErrorList(
errorEvent,
errorEvent.Subcategory,
errorEvent.Code,
errorEvent.File,
errorEvent.LineNumber,
errorEvent.ColumnNumber,
errorEvent.EndLineNumber,
errorEvent.EndColumnNumber);
}
catch (Exception e)
{
Debug.Assert(false, "Problem adding warning to warning list: " + e.Message + " at " + e.TargetSite);
}
}
/// <summary>
/// Private internal class for capturing full compiler error line/column span information
/// </summary>
private class DefaultCompilerError : CompilerError
{
private int endLine;
private int endColumn;
public int EndLine
{
get { return endLine; }
set { endLine = value; }
}
public int EndColumn
{
get { return endColumn; }
set { endColumn = value; }
}
public DefaultCompilerError(string fileName,
int startLine,
int startColumn,
int endLine,
int endColumn,
string errorNumber,
string errorText)
: base(fileName, startLine, startColumn, errorNumber, errorText)
{
EndLine = endLine;
EndColumn = endColumn;
}
}
private void Output(string s)
{
// Various events can call SetOutputLogger(null), which will null out "this.OutputWindowPane".
// So we capture a reference to it. At some point in the future, after this build finishes,
// the pane reference we have will no longer accept input from us.
// But here there is no race, because
// - we only log user-invoked builds to the Output window
// - user-invoked buils always run MSBuild ASYNC
// - in an ASYNC build, the BuildCoda uses UIThread.Run() to schedule itself to be run on the UI thread
// - UIThread.Run() protects against re-entrancy and thus always preserves the queuing order of its actions
// - the pane is good until at least the point when BuildCoda runs and we declare to MSBuild that we are finished with this build
var pane = this.OutputWindowPane; // copy to capture in delegate
UIThread.Run(delegate()
{
try
{
pane.OutputStringThreadSafe(s);
}
catch (Exception e)
{
Debug.Assert(false, "We would like to know if this happens; exception in IDEBuildLogger.Output(): " + e.ToString());
// Don't crash process due to random exception, just swallow it
}
});
}
/// <summary>
/// Add the error/warning to the error list and potentially to the output window.
/// </summary>
private void AddToErrorList(
BuildEventArgs errorEvent,
string subcategory,
string errorCode,
string file,
int startLine,
int startColumn,
int endLine,
int endColumn)
{
if (file == null)
file = String.Empty;
bool isWarning = errorEvent is BuildWarningEventArgs;
Shell.TaskPriority priority = isWarning ? Shell.TaskPriority.Normal : Shell.TaskPriority.High;
TextSpan span;
span.iStartLine = startLine;
span.iStartIndex = startColumn;
span.iEndLine = endLine < startLine ? span.iStartLine : endLine;
span.iEndIndex = (endColumn < startColumn) && (span.iStartLine == span.iEndLine) ? span.iStartIndex : endColumn;
if (OutputWindowPane != null
&& (this.Verbosity != LoggerVerbosity.Quiet || errorEvent is BuildErrorEventArgs))
{
// Format error and output it to the output window
string message = this.FormatMessage(errorEvent.Message);
DefaultCompilerError e = new DefaultCompilerError(file,
span.iStartLine,
span.iStartIndex,
span.iEndLine,
span.iEndIndex,
errorCode,
message);
e.IsWarning = isWarning;
Output(GetFormattedErrorMessage(e));
}
UIThread.Run(delegate()
{
IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
if (openDoc == null)
return;
IVsWindowFrame frame;
IOleServiceProvider sp;
IVsUIHierarchy hier;
uint itemid;
Guid logicalView = VSConstants.LOGVIEWID_Code;
IVsTextLines buffer = null;
// JAF
// Notes about acquiring the buffer:
// If the file physically exists then this will open the document in the current project. It doesn't matter if the file is a member of the project.
// Also, it doesn't matter if this is an F# file. For example, an error in Microsoft.Common.targets will cause a file to be opened here.
// However, opening the document does not mean it will be shown in VS.
if (!Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(file, ref logicalView, out sp, out hier, out itemid, out frame)) && frame != null) {
object docData;
frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData);
// Get the text lines
buffer = docData as IVsTextLines;
if (buffer == null) {
IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider;
if (bufferProvider != null) {
bufferProvider.GetTextBuffer(out buffer);
}
}
}
// Need to adjust line and column indexing for the task window, which assumes zero-based values
if (span.iStartLine > 0 && span.iStartIndex > 0)
{
span.iStartLine -= 1;
span.iEndLine -= 1;
span.iStartIndex -= 1;
span.iEndIndex -= 1;
}
// Add error to task list
// Code below is for --flaterrors flag that is only used by the IDE
var stringThatIsAProxyForANewlineInFlatErrors = new string(new[] { (char)29 });
var taskText = errorEvent.Message.Replace(stringThatIsAProxyForANewlineInFlatErrors, Environment.NewLine);
if (errorReporter != null)
{
errorReporter.ReportError2(taskText, errorCode, (VSTASKPRIORITY) priority, span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, file);
}
});
}
/// <summary>
/// This is the delegate for Message event types
/// </summary>
private void MessageHandler(object sender, BuildMessageEventArgs messageEvent)
{
try
{
if (LogAtImportance(messageEvent.Importance))
{
LogEvent(sender, messageEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging message event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This is the delegate for BuildStartedHandler events.
/// </summary>
private void BuildStartedHandler(object sender, BuildStartedEventArgs buildEvent)
{
try
{
this.haveCachedRegistry = false;
if (LogAtImportance(MessageImportance.Normal))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging buildstarted event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
finally
{
if (errorReporter != null) {
errorReporter.ClearErrors();
}
}
}
/// <summary>
/// This is the delegate for BuildFinishedHandler events.
/// </summary>
/// <param name="sender"></param>
/// <param name="buildEvent"></param>
private void BuildFinishedHandler(object sender, BuildFinishedEventArgs buildEvent)
{
try
{
if (LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal :
MessageImportance.High))
{
if (this.outputWindowPane != null)
Output(Environment.NewLine);
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging buildfinished event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This is the delegate for ProjectStartedHandler events.
/// </summary>
private void ProjectStartedHandler(object sender, ProjectStartedEventArgs buildEvent)
{
try
{
if (LogAtImportance(MessageImportance.Normal))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging projectstarted event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This is the delegate for ProjectFinishedHandler events.
/// </summary>
private void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs buildEvent)
{
try
{
if (LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal
: MessageImportance.High))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging projectfinished event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This is the delegate for TargetStartedHandler events.
/// </summary>
private void TargetStartedHandler(object sender, TargetStartedEventArgs buildEvent)
{
try
{
if (LogAtImportance(MessageImportance.Normal))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging targetstarted event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
finally
{
++this.currentIndent;
}
}
/// <summary>
/// This is the delegate for TargetFinishedHandler events.
/// </summary>
private void TargetFinishedHandler(object sender, TargetFinishedEventArgs buildEvent)
{
try
{
--this.currentIndent;
if ((isLogTaskDone) &&
LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal
: MessageImportance.High))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging targetfinished event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This is the delegate for TaskStartedHandler events.
/// </summary>
private void TaskStartedHandler(object sender, TaskStartedEventArgs buildEvent)
{
try
{
if (LogAtImportance(MessageImportance.Normal))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging taskstarted event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
finally
{
++this.currentIndent;
}
}
/// <summary>
/// This is the delegate for TaskFinishedHandler events.
/// </summary>
private void TaskFinishedHandler(object sender, TaskFinishedEventArgs buildEvent)
{
try
{
--this.currentIndent;
if ((isLogTaskDone) &&
LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal
: MessageImportance.High))
{
LogEvent(sender, buildEvent);
}
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging taskfinished event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This is the delegate for CustomHandler events.
/// </summary>
/// <param name="sender"></param>
/// <param name="buildEvent"></param>
private void CustomHandler(object sender, CustomBuildEventArgs buildEvent)
{
try
{
LogEvent(sender, buildEvent);
}
catch (Exception e)
{
Debug.Assert(false, "Problem logging custom event: " + e.Message + " at " + e.TargetSite);
// swallow the exception
}
}
/// <summary>
/// This method takes a MessageImportance and returns true if messages
/// at importance i should be loggeed. Otherwise return false.
/// </summary>
private bool LogAtImportance(MessageImportance importance)
{
// If importance is too low for current settings, ignore the event
bool logIt = false;
this.SetVerbosity();
switch (this.Verbosity)
{
case LoggerVerbosity.Quiet:
logIt = false;
break;
case LoggerVerbosity.Minimal:
logIt = (importance == MessageImportance.High);
break;
case LoggerVerbosity.Normal:
logIt = (importance == MessageImportance.Normal) || (importance == MessageImportance.High);
break;
case LoggerVerbosity.Detailed:
logIt = (importance == MessageImportance.Low) || (importance == MessageImportance.Normal) || (importance == MessageImportance.High);
break;
case LoggerVerbosity.Diagnostic:
logIt = true;
break;
default:
Debug.Fail("Unknown Verbosity level. Ignoring will cause everything to be logged");
break;
}
return logIt;
}
/// <summary>
/// This is the method that does the main work of logging an event
/// when one is sent to this logger.
/// </summary>
private void LogEvent(object sender, BuildEventArgs buildEvent)
{
try
{
// Fill in the Message text
if (OutputWindowPane != null && !String.IsNullOrEmpty(buildEvent.Message))
{
int startingSize = this.currentIndent + buildEvent.Message.Length + 1;
StringBuilder msg = new StringBuilder(startingSize);
if (this.currentIndent > 0)
{
msg.Append('\t', this.currentIndent);
}
msg.AppendLine(buildEvent.Message);
Output(msg.ToString());
}
}
catch (Exception e)
{
try
{
System.Diagnostics.Debug.Assert(false, "Error thrown from IDEBuildLogger::LogEvent");
System.Diagnostics.Debug.Assert(false, e.ToString());
// For retail, also try to show in the output window.
Output(e.ToString());
}
catch
{
// We're going to throw the original exception anyway
}
throw;
}
}
/// <summary>
/// This is called when the build complete.
/// </summary>
private void ShutdownLogger()
{
}
/// <summary>
/// Format error messages for the task list
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private string GetFormattedErrorMessage(DefaultCompilerError e)
{
if (e == null) return String.Empty;
string errCode = (e.IsWarning) ? this.warningString : this.errorString;
StringBuilder fileRef = new StringBuilder();
// JAF:
// Even if fsc.exe returns a canonical message with no file at all, MSBuild will set the file to the name
// of the task (FSC). In principle, e.FileName will not be null or empty but handle this case anyway.
bool thereIsAFile = !string.IsNullOrEmpty(e.FileName);
bool thereIsASpan = e.Line!=0 || e.Column!=0 || e.EndLine!=0 || e.EndColumn!=0;
if (thereIsAFile) {
fileRef.AppendFormat(CultureInfo.CurrentUICulture, "{0}", e.FileName);
if (thereIsASpan) {
fileRef.AppendFormat(CultureInfo.CurrentUICulture, "({0},{1})", e.Line, e.Column);
}
fileRef.AppendFormat(CultureInfo.CurrentUICulture, ":");
}
fileRef.AppendFormat(CultureInfo.CurrentUICulture, " {0} {1}: {2}", errCode, e.ErrorNumber, e.ErrorText);
return fileRef.ToString();
}
/// <summary>
/// Formats the message that is to be output.
/// </summary>
/// <param name="message">The message string.</param>
/// <returns>The new message</returns>
private string FormatMessage(string message)
{
if (string.IsNullOrEmpty(message))
{
return Environment.NewLine;
}
StringBuilder sb = new StringBuilder(message.Length + Environment.NewLine.Length);
sb.AppendLine(message);
return sb.ToString();
}
/// <summary>
/// Sets the verbosity level.
/// </summary>
private void SetVerbosity()
{
// TODO: This should be replaced when we have a version that supports automation.
if (!this.haveCachedRegistry)
{
string verbosityKey = String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", BuildVerbosityRegistryRoot, LoggingConstants.BuildVerbosityRegistrySubKey);
using (RegistryKey subKey = Registry.CurrentUser.OpenSubKey(verbosityKey))
{
if (subKey != null)
{
object valueAsObject = subKey.GetValue(LoggingConstants.BuildVerbosityRegistryValue);
if (valueAsObject != null)
{
this.Verbosity = (LoggerVerbosity)((int)valueAsObject);
}
}
}
this.haveCachedRegistry = true;
}
// TODO: Continue this code to get the Verbosity when we have a version that supports automation to get the Verbosity.
//EnvDTE.DTE dte = this.serviceProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
//EnvDTE.Properties properties = dte.get_Properties(EnvironmentCategory, ProjectsAndSolutionSubCategory);
}
}
/// <summary>
/// Helper for logging to the output window
/// </summary>
public sealed class OutputWindowLogger
{
private readonly Func<bool> predicate;
private readonly Action<string> print;
/// <summary>
/// Helper to create output window logger for project up-to-date check
/// </summary>
/// <param name="pane">Output window pane to use for logging</param>
/// <returns>Logger</returns>
public static OutputWindowLogger CreateUpToDateCheckLogger(IVsOutputWindowPane pane)
{
string upToDateVerbosityKey =
String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", LoggingConstants.DefaultVSRegistryRoot, LoggingConstants.BuildVerbosityRegistrySubKey);
var shouldLog = false;
using (RegistryKey subKey = Registry.CurrentUser.OpenSubKey(upToDateVerbosityKey))
{
if (subKey != null)
{
object valueAsObject = subKey.GetValue(LoggingConstants.UpToDateVerbosityRegistryValue);
if (valueAsObject != null && valueAsObject is int)
{
shouldLog = ((int)valueAsObject) == 1;
}
}
}
return new OutputWindowLogger(() => shouldLog, pane);
}
/// <summary>
/// Creates a logger instance
/// </summary>
/// <param name="shouldLog">Predicate that will be called when logging. Should return true if logging is to be performed, false otherwise.</param>
/// <param name="pane">The output pane where logging should be targeted</param>
public OutputWindowLogger(Func<bool> shouldLog, IVsOutputWindowPane pane)
{
this.predicate = shouldLog;
if (pane is IVsOutputWindowPaneNoPump)
{
var asNoPump = pane as IVsOutputWindowPaneNoPump;
this.print = (s) => asNoPump.OutputStringNoPump(s);
}
else
{
this.print = (s) => pane.OutputStringThreadSafe(s);
}
}
/// <summary>
/// Logs a message to the output window, if the original predicate returns true
/// </summary>
/// <param name="message">Log message, can be a String.Format-style format string</param>
/// <param name="args">Optional aruments for format string</param>
public void WriteLine(string message, params object[] args)
{
if (this.predicate())
{
var s = String.Format(message, args);
s = String.Format("{0}{1}", s, Environment.NewLine);
this.print(s);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcvtv = Google.Cloud.Video.Transcoder.V1;
using sys = System;
namespace Google.Cloud.Video.Transcoder.V1
{
/// <summary>Resource name for the <c>Job</c> resource.</summary>
public sealed partial class JobName : gax::IResourceName, sys::IEquatable<JobName>
{
/// <summary>The possible contents of <see cref="JobName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
ProjectLocationJob = 1,
}
private static gax::PathTemplate s_projectLocationJob = new gax::PathTemplate("projects/{project}/locations/{location}/jobs/{job}");
/// <summary>Creates a <see cref="JobName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="JobName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static JobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new JobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="JobName"/> with the pattern <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="JobName"/> constructed from the provided ids.</returns>
public static JobName FromProjectLocationJob(string projectId, string locationId, string jobId) =>
new JobName(ResourceNameType.ProjectLocationJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), jobId: gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string jobId) =>
FormatProjectLocationJob(projectId, locationId, jobId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </returns>
public static string FormatProjectLocationJob(string projectId, string locationId, string jobId) =>
s_projectLocationJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)));
/// <summary>Parses the given resource name string into a new <see cref="JobName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="JobName"/> if successful.</returns>
public static JobName Parse(string jobName) => Parse(jobName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="JobName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="JobName"/> if successful.</returns>
public static JobName Parse(string jobName, bool allowUnparsed) =>
TryParse(jobName, allowUnparsed, out JobName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>Tries to parse the given resource name string into a new <see cref="JobName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="JobName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string jobName, out JobName result) => TryParse(jobName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="JobName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="JobName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string jobName, bool allowUnparsed, out JobName result)
{
gax::GaxPreconditions.CheckNotNull(jobName, nameof(jobName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationJob.TryParseName(jobName, out resourceName))
{
result = FromProjectLocationJob(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(jobName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private JobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string jobId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
JobId = jobId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="JobName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
public JobName(string projectId, string locationId, string jobId) : this(ResourceNameType.ProjectLocationJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), jobId: gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Job</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string JobId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationJob: return s_projectLocationJob.Expand(ProjectId, LocationId, JobId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as JobName);
/// <inheritdoc/>
public bool Equals(JobName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(JobName a, JobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(JobName a, JobName b) => !(a == b);
}
/// <summary>Resource name for the <c>JobTemplate</c> resource.</summary>
public sealed partial class JobTemplateName : gax::IResourceName, sys::IEquatable<JobTemplateName>
{
/// <summary>The possible contents of <see cref="JobTemplateName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>.
/// </summary>
ProjectLocationJobTemplate = 1,
}
private static gax::PathTemplate s_projectLocationJobTemplate = new gax::PathTemplate("projects/{project}/locations/{location}/jobTemplates/{job_template}");
/// <summary>Creates a <see cref="JobTemplateName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="JobTemplateName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static JobTemplateName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new JobTemplateName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="JobTemplateName"/> with the pattern
/// <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobTemplateId">The <c>JobTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="JobTemplateName"/> constructed from the provided ids.</returns>
public static JobTemplateName FromProjectLocationJobTemplate(string projectId, string locationId, string jobTemplateId) =>
new JobTemplateName(ResourceNameType.ProjectLocationJobTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), jobTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(jobTemplateId, nameof(jobTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="JobTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobTemplateId">The <c>JobTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="JobTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string jobTemplateId) =>
FormatProjectLocationJobTemplate(projectId, locationId, jobTemplateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="JobTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobTemplateId">The <c>JobTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="JobTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>.
/// </returns>
public static string FormatProjectLocationJobTemplate(string projectId, string locationId, string jobTemplateId) =>
s_projectLocationJobTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(jobTemplateId, nameof(jobTemplateId)));
/// <summary>Parses the given resource name string into a new <see cref="JobTemplateName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="jobTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="JobTemplateName"/> if successful.</returns>
public static JobTemplateName Parse(string jobTemplateName) => Parse(jobTemplateName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="JobTemplateName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="jobTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="JobTemplateName"/> if successful.</returns>
public static JobTemplateName Parse(string jobTemplateName, bool allowUnparsed) =>
TryParse(jobTemplateName, allowUnparsed, out JobTemplateName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="JobTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="jobTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="JobTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string jobTemplateName, out JobTemplateName result) =>
TryParse(jobTemplateName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="JobTemplateName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="jobTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="JobTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string jobTemplateName, bool allowUnparsed, out JobTemplateName result)
{
gax::GaxPreconditions.CheckNotNull(jobTemplateName, nameof(jobTemplateName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationJobTemplate.TryParseName(jobTemplateName, out resourceName))
{
result = FromProjectLocationJobTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(jobTemplateName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private JobTemplateName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string jobTemplateId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
JobTemplateId = jobTemplateId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="JobTemplateName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/jobTemplates/{job_template}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobTemplateId">The <c>JobTemplate</c> ID. Must not be <c>null</c> or empty.</param>
public JobTemplateName(string projectId, string locationId, string jobTemplateId) : this(ResourceNameType.ProjectLocationJobTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), jobTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(jobTemplateId, nameof(jobTemplateId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>JobTemplate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string JobTemplateId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationJobTemplate: return s_projectLocationJobTemplate.Expand(ProjectId, LocationId, JobTemplateId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as JobTemplateName);
/// <inheritdoc/>
public bool Equals(JobTemplateName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(JobTemplateName a, JobTemplateName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(JobTemplateName a, JobTemplateName b) => !(a == b);
}
public partial class Job
{
/// <summary>
/// <see cref="gcvtv::JobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcvtv::JobName JobName
{
get => string.IsNullOrEmpty(Name) ? null : gcvtv::JobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class JobTemplate
{
/// <summary>
/// <see cref="gcvtv::JobTemplateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcvtv::JobTemplateName JobTemplateName
{
get => string.IsNullOrEmpty(Name) ? null : gcvtv::JobTemplateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//FutileEngine by Matt Rix -
public class Futile : MonoBehaviour
{
static public Futile instance = null;
static public FScreen screen;
static public FAtlasManager atlasManager;
static public FStage stage;
static public FTouchManager touchManager;
static public bool isOpenGL; //assigned in Awake
static public int baseRenderQueueDepth = 3000;
static public bool shouldRemoveAtlasElementFileExtensions = true;
//These are set in FScreen
static public float displayScale; //set based on the resolution setting (the unit to pixel scale)
static public float displayScaleInverse; // 1/displayScale
static public float resourceScale; //set based on the resolution setting (the scale of assets)
static public float resourceScaleInverse; // 1/resourceScale
static public float screenPixelOffset; //set based on whether it's openGL or not
static public string resourceSuffix; //set based on the resLevel
//default element, a 16x16 white texture
static public FAtlasElement whiteElement;
static public Color white = Color.white; //unlike Futile.white, it doesn't create a new color every time
static internal int nextRenderLayerDepth = 0;
static private List<FStage> _stages;
static private bool _isDepthChangeNeeded = false;
public delegate void FutileUpdateDelegate();
public event FutileUpdateDelegate SignalUpdate;
public event FutileUpdateDelegate SignalFixedUpdate;
public event FutileUpdateDelegate SignalLateUpdate;
//configuration values
public bool shouldTrackNodesInRXProfiler = true;
private GameObject _cameraHolder;
private Camera _camera;
private bool _shouldRunGCNextUpdate = false; //use Futile.instance.ForceGarbageCollectionNextUpdate();
private FutileParams _futileParams;
private List<FDelayedCallback> _delayedCallbacks = new List<FDelayedCallback>();
// Use this for initialization
private void Awake ()
{
instance = this;
isOpenGL = SystemInfo.graphicsDeviceVersion.Contains("OpenGL");
enabled = false;
name = "Futile";
}
public void Init(FutileParams futileParams)
{
enabled = true;
_futileParams = futileParams;
Application.targetFrameRate = _futileParams.targetFrameRate;
FShader.Init(); //set up the basic shaders
FFacetType.Init(); //set up the types of facets (Quads, Triangles, etc)
screen = new FScreen(_futileParams);
//
//Camera setup from https://github.com/prime31/UIToolkit/blob/master/Assets/Plugins/UIToolkit/UI.cs
//
_cameraHolder = new GameObject();
_cameraHolder.transform.parent = gameObject.transform;
_camera = _cameraHolder.AddComponent<Camera>();
_camera.tag = "MainCamera";
_camera.name = "Camera";
//_camera.clearFlags = CameraClearFlags.Depth; //TODO: check if this is faster or not?
_camera.clearFlags = CameraClearFlags.SolidColor;
_camera.nearClipPlane = 0.0f;
_camera.farClipPlane = 500.0f;
_camera.depth = 100;
_camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
_camera.backgroundColor = _futileParams.backgroundColor;
//we multiply this stuff by scaleInverse to make sure everything is in points, not pixels
_camera.orthographic = true;
_camera.orthographicSize = screen.pixelHeight/2 * displayScaleInverse;
UpdateCameraPosition();
touchManager = new FTouchManager();
atlasManager = new FAtlasManager();
CreateDefaultAtlases();
_stages = new List<FStage>();
stage = new FStage("Futile.stage");
AddStage (stage);
}
public FDelayedCallback StartDelayedCallback(Action func, float delayTime)
{
if (delayTime <= 0) delayTime = 0.00001f; //super small delay for 0 to avoid divide by 0 errors
FDelayedCallback callback = new FDelayedCallback(func, delayTime);
_delayedCallbacks.Add(callback);
return callback;
}
public void StopDelayedCall(Action func)
{
int count = _delayedCallbacks.Count;
for (int d = 0; d<count; d++)
{
FDelayedCallback call = _delayedCallbacks[d];
if(call.func == func)
{
_delayedCallbacks.RemoveAt(d);
d--;
count--;
}
}
}
public void StopDelayedCall(FDelayedCallback callToRemove)
{
_delayedCallbacks.Remove(callToRemove);
}
public void CreateDefaultAtlases()
{
//atlas of plain white
Texture2D plainWhiteTex = new Texture2D(16,16);
plainWhiteTex.filterMode = FilterMode.Bilinear;
plainWhiteTex.wrapMode = TextureWrapMode.Clamp;
Color white = Futile.white;
//Color clear = new Color(1,1,1,0);
for(int r = 0; r<16; r++)
{
for(int c = 0; c<16; c++)
{
// if(c == 0 || r == 0) //clear the 0 edges
// {
// plainWhiteTex.SetPixel(c,r,clear);
// }
// else
// {
plainWhiteTex.SetPixel(c,r,white);
// }
}
}
plainWhiteTex.Apply();
atlasManager.LoadAtlasFromTexture("Futile_White",plainWhiteTex);
whiteElement = atlasManager.GetElementWithName("Futile_White");
}
static public void AddStage(FStage stageToAdd)
{
int stageIndex = _stages.IndexOf(stageToAdd);
if(stageIndex == -1) //add it if it's not a stage
{
stageToAdd.HandleAddedToFutile();
_stages.Add(stageToAdd);
UpdateStageIndices();
}
else if(stageIndex != _stages.Count-1) //if stage is already in the stages, put it at the top of the stages if it's not already
{
_stages.RemoveAt(stageIndex);
_stages.Add(stageToAdd);
UpdateStageIndices();
}
}
static public void AddStageAtIndex(FStage stageToAdd, int newIndex)
{
int stageIndex = _stages.IndexOf(stageToAdd);
if(newIndex > _stages.Count) //if it's past the end, make it at the end
{
newIndex = _stages.Count;
}
if(stageIndex == newIndex) return; //if it's already at the right index, just leave it there
if(stageIndex == -1) //add it if it's not in the stages already
{
stageToAdd.HandleAddedToFutile();
_stages.Insert(newIndex, stageToAdd);
}
else //if stage is already in the stages, move it to the desired index
{
_stages.RemoveAt(stageIndex);
if(stageIndex < newIndex)
{
_stages.Insert(newIndex-1, stageToAdd); //gotta subtract 1 to account for it moving in the order
}
else
{
_stages.Insert(newIndex, stageToAdd);
}
}
UpdateStageIndices();
}
static public void RemoveStage(FStage stageToRemove)
{
stageToRemove.HandleRemovedFromFutile();
stageToRemove.index = -1;
_stages.Remove(stageToRemove);
UpdateStageIndices();
}
static public void UpdateStageIndices ()
{
int stageCount = _stages.Count;
for(int s = 0; s<stageCount; s++)
{
_stages[s].index = s;
}
_isDepthChangeNeeded = true;
}
static public int GetStageCount()
{
return _stages.Count;
}
static public FStage GetStageAt(int index)
{
return _stages[index];
}
private void ProcessDelayedCallbacks()
{
int count = _delayedCallbacks.Count;
for (int d = 0; d<count; d++)
{
FDelayedCallback callback = _delayedCallbacks[d];
callback.timeRemaining -= Time.deltaTime;
if(callback.timeRemaining < 0)
{
callback.func();
_delayedCallbacks.RemoveAt(d);
d--;
count--;
}
}
}
private void Update()
{
ProcessDelayedCallbacks();
screen.Update();
touchManager.Update();
if(SignalUpdate != null) SignalUpdate();
for(int s = 0; s<_stages.Count; s++)
{
_stages[s].Redraw (false,_isDepthChangeNeeded);
}
_isDepthChangeNeeded = false;
if(_shouldRunGCNextUpdate)
{
_shouldRunGCNextUpdate = false;
GC.Collect();
}
}
private void LateUpdate()
{
nextRenderLayerDepth = 0;
for(int s = 0; s<_stages.Count; s++)
{
_stages[s].LateUpdate();
}
if(SignalLateUpdate != null) SignalLateUpdate();
}
private void FixedUpdate()
{
if(SignalFixedUpdate != null) SignalFixedUpdate();
}
private void OnApplicationQuit()
{
instance = null;
}
private void OnDestroy()
{
instance = null;
}
public void UpdateCameraPosition()
{
_camera.orthographicSize = screen.pixelHeight/2 * displayScaleInverse;
float camXOffset = ((screen.originX - 0.5f) * -screen.pixelWidth)*displayScaleInverse + screenPixelOffset;
float camYOffset = ((screen.originY - 0.5f) * -screen.pixelHeight)*displayScaleInverse - screenPixelOffset;
_camera.transform.position = new Vector3(camXOffset, camYOffset, -10.0f);
}
public void ForceGarbageCollectionNextUpdate()
{
_shouldRunGCNextUpdate = true;
}
new public Camera camera
{
get {return _camera;}
}
//
//THE MIGHTY LAND OF DEPRECATION
//
[Obsolete("Futile.IsLandscape() is obsolete, use Futile.screen.IsLandscape() instead")]
public bool IsLandscape()
{
throw new NotSupportedException("Obsolete! Use Futile.screen.IsLandscape() instead");
}
[Obsolete("Futile.originX is obsolete, use Futile.screen.originX instead")]
public float originX
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.originX instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.originX instead");}
}
[Obsolete("Futile.originY is obsolete, use Futile.screen.originY instead")]
public float originY
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.originY instead"); }
set {throw new NotSupportedException("Obsolete! Use Futile.screen.originY instead");}
}
[Obsolete("Futile.currentOrientation is obsolete, use Futile.screen.currentOrientation instead")]
public ScreenOrientation currentOrientation
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.currentOrientation instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.currentOrientation instead");}
}
[Obsolete("Futile.width is obsolete, use Futile.screen.width instead")]
static public float width
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.width instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.width instead");}
}
[Obsolete("Futile.height is obsolete, use Futile.screen.height instead")]
static public float height
{
get {throw new NotSupportedException("Obsolete! Use Futile.screen.height instead");}
set {throw new NotSupportedException("Obsolete! Use Futile.screen.height instead");}
}
}
public class FDelayedCallback
{
public float delayTime;
public float timeRemaining;
public Action func;
public FDelayedCallback(Action func, float delayTime)
{
this.func = func;
this.delayTime = delayTime;
this.timeRemaining = delayTime;
}
public float percentComplete //0.0f when started, 1.0f when finished
{
get
{
return Mathf.Clamp01(1.0f - timeRemaining/delayTime);
}
}
}
| |
// 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 MaxScalarDouble()
{
var test = new SimpleBinaryOpTest__MaxScalarDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaxScalarDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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 Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MaxScalarDouble testClass)
{
var result = Sse2.MaxScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MaxScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.MaxScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MaxScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__MaxScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.MaxScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_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 = Sse2.MaxScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_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 = Sse2.MaxScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_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(Sse2).GetMethod(nameof(Sse2.MaxScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MaxScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MaxScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.MaxScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.MaxScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(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<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.MaxScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.MaxScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.MaxScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MaxScalarDouble();
var result = Sse2.MaxScalar(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__MaxScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.MaxScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.MaxScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.MaxScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(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 = Sse2.MaxScalar(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 = Sse2.MaxScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&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(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Max(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MaxScalar)}<Double>(Vector128<Double>, Vector128<Double>): {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;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace Minjie
{
/// <summary>
/// This screen implements the actual game logic.
/// </summary>
/// <remarks>Based on a similar class in the Game State Management sample.</remarks>
class GameplayScreen : GameScreen
{
#region Constant Data
/// <summary>
/// The size of the game board.
/// </summary>
const int boardSize = 10;
/// <summary>
/// The size of the tile model.
/// </summary>
const float tileSize = 40.2f;
/// <summary>
/// The starting height of the pieces over the board.
/// </summary>
const float startingPieceHeight = 50f;
/// <summary>
/// The number of frames in the falling-piece animation.
/// </summary>
const int fallingPieceFrames = 10;
#endregion
#region Fields
ContentManager content;
Texture2D backgroundTexture;
Model tileModel, highlightTileModel;
Model whitePieceModel, blackPieceModel;
Model whitePieceTileModel, blackPieceTileModel;
Vector3 boardPosition;
int fallingPieceFrame = 0;
int lastPieceCount = 0;
Board board = new Board(boardSize);
Player player1, player2;
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public GameplayScreen(bool multiplayer)
{
board.Initialize();
lastPieceCount = board.PieceCount;
player1 = new LocalPlayer(BoardColors.White, PlayerIndex.One, boardSize);
if (multiplayer)
{
player2 = new LocalPlayer(BoardColors.Black, PlayerIndex.Two,
boardSize);
}
else
{
player2 = new AiPlayer(BoardColors.Black);
}
float boardPositionValue = -0.5f * tileSize * (float)boardSize +
tileSize / 2f;
boardPosition = new Vector3(boardPositionValue, 1f, boardPositionValue);
AudioManager.PlayMusic("Music_Game");
}
/// <summary>
/// Load graphics content for the game.
/// </summary>
public override void LoadContent()
{
if (content == null)
content = new ContentManager(ScreenManager.Game.Services, "Content");
backgroundTexture = content.Load<Texture2D>("Gameplay/game_screen");
tileModel = content.Load<Model>("Gameplay//tile");
highlightTileModel = content.Load<Model>("Gameplay//tile_highlight");
whitePieceModel = content.Load<Model>("Gameplay//p2_piece");
blackPieceModel = content.Load<Model>("Gameplay//p1_piece");
whitePieceTileModel = content.Load<Model>("Gameplay//p2_piece_tile");
blackPieceTileModel = content.Load<Model>("Gameplay//p1_piece_tile");
// reset the camera
Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
SimpleArcCamera.Reset((float)viewport.Width / (float)viewport.Height);
// once the load has finished, we use ResetElapsedTime to tell the game's
// timing mechanism that we have just finished a very long frame, and that
// it should not try to catch up.
ScreenManager.Game.ResetElapsedTime();
}
/// <summary>
/// Unload graphics content used by the game.
/// </summary>
public override void UnloadContent()
{
content.Unload();
}
#endregion
#region Update and Draw
/// <summary>
/// Updates the state of the game. This method checks the GameScreen.IsActive
/// property, so the game will stop updating when the pause menu is active,
/// or if you tab away to a different application.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (IsActive)
{
SimpleArcCamera.Update(gameTime);
if (fallingPieceFrame > 0)
{
fallingPieceFrame--;
if (fallingPieceFrame <= 0)
{
AudioManager.PlayCue("Drop");
}
}
if (fallingPieceFrame <= 0)
{
player1.Update(board);
if (board.PieceCount > lastPieceCount)
{
lastPieceCount = board.PieceCount;
fallingPieceFrame = fallingPieceFrames;
}
}
if (fallingPieceFrame <= 0)
{
player2.Update(board);
if (board.PieceCount > lastPieceCount)
{
lastPieceCount = board.PieceCount;
fallingPieceFrame = fallingPieceFrames;
}
}
if (board.GameOver)
{
GameResult gameResult = GameResult.Tied;
if (board.WhitePieceCount > board.BlackPieceCount)
{
gameResult = GameResult.Player1Won;
}
else if (board.BlackPieceCount > board.WhitePieceCount)
{
gameResult = GameResult.Player2Won;
}
ExitScreen();
ScreenManager.AddScreen(new GameOverScreen(gameResult));
}
}
}
/// <summary>
/// Lets the game respond to player input. Unlike the Update method,
/// this will only be called when the gameplay screen is active.
/// </summary>
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
if (input.ExitGame)
{
ExitScreen();
ScreenManager.AddScreen(new TitleScreen());
}
// update the input state for local players and the camera
SimpleArcCamera.InputState = input;
LocalPlayer.InputState = input;
}
/// <summary>
/// Draws the gameplay screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
// This game has a blue background. Why? Because!
ScreenManager.GraphicsDevice.Clear(Color.White);
// Our player and enemy are both actually just text strings.
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
spriteBatch.Draw(backgroundTexture, Vector2.Zero, Color.White);
spriteBatch.End();
ScreenManager.GraphicsDevice.RenderState.DepthBufferEnable = true;
Point cursorPosition = LocalPlayer.CursorPosition;
for (int row = 0; row < boardSize; row++)
{
for (int column = 0; column < boardSize; column++)
{
if ((fallingPieceFrame > 0) && (board.LastMove.Row == row) &&
(board.LastMove.Column == column))
{
int fall = fallingPieceFrames - fallingPieceFrame;
float height = startingPieceHeight - (fall + fall * fall / 2);
// do not let the piece fall through the board
if (height < 6)
{
height = 6;
}
DrawModel(board.CurrentColor == BoardColors.White ?
blackPieceModel : whitePieceModel, row, column, height);
DrawModel(tileModel, row, column, 0f);
}
else
{
if ((cursorPosition.X == row) && (cursorPosition.Y == column))
{
if (board[row, column] == BoardColors.Empty)
{
DrawModel(highlightTileModel, row, column, 0f);
}
DrawModel(board.CurrentColor == BoardColors.White ?
whitePieceModel : blackPieceModel, row, column,
startingPieceHeight);
}
else
{
DrawModel(tileModel, row, column, 0f);
}
if (board[row, column] == BoardColors.Black)
{
DrawModel(blackPieceTileModel, row, column, 0f);
}
else if (board[row, column] == BoardColors.White)
{
DrawModel(whitePieceTileModel, row, column, 0f);
}
}
}
}
}
/// <summary>
/// Draw the given model at the appropriate board position.
/// </summary>
/// <param name="model">The model to draw.</param>
/// <param name="row">The board row.</param>
/// <param name="column">The board column.</param>
/// <param name="height">The height above the board.</param>
/// <remarks>
/// We know that none of these models have nontrivial transforms,
/// so we can skip the bone transform code.
/// </remarks>
private void DrawModel(Model model, int row, int column, float height)
{
// if the model is null, fail silently - given nothing to draw
if (model == null)
{
return;
}
Matrix worldMatrix = Matrix.CreateTranslation(boardPosition +
new Vector3(row * tileSize, 1f + height, column * tileSize));
foreach (ModelMesh modelMesh in model.Meshes)
{
foreach (BasicEffect basicEffect in modelMesh.Effects)
{
basicEffect.EnableDefaultLighting();
basicEffect.View = SimpleArcCamera.ViewMatrix;
basicEffect.Projection = SimpleArcCamera.ProjectionMatrix;
basicEffect.World = worldMatrix;
}
modelMesh.Draw();
}
}
#endregion
}
}
| |
/**
* The MIT License (MIT)
*
* Copyright (c) 2012-2017 DragonBones team and other contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace DragonBones
{
/// <internal/>
/// <private/>
internal enum TweenState
{
None,
Once,
Always
}
/// <internal/>
/// <private/>
internal abstract class TimelineState : BaseObject
{
public int playState; // -1: start, 0: play, 1: complete;
public int currentPlayTimes;
public float currentTime;
protected TweenState _tweenState;
protected uint _frameRate;
protected int _frameValueOffset;
protected uint _frameCount;
protected uint _frameOffset;
protected int _frameIndex;
protected float _frameRateR;
protected float _position;
protected float _duration;
protected float _timeScale;
protected float _timeOffset;
protected DragonBonesData _dragonBonesData;
protected AnimationData _animationData;
protected TimelineData _timelineData;
protected Armature _armature;
protected AnimationState _animationState;
protected TimelineState _actionTimeline;
protected short[] _frameArray;
protected short[] _frameIntArray;
protected float[] _frameFloatArray;
protected ushort[] _timelineArray;
protected List<uint> _frameIndices;
protected override void _OnClear()
{
this.playState = -1;
this.currentPlayTimes = -1;
this.currentTime = -1.0f;
this._tweenState = TweenState.None;
this._frameRate = 0;
this._frameValueOffset = 0;
this._frameCount = 0;
this._frameOffset = 0;
this._frameIndex = -1;
this._frameRateR = 0.0f;
this._position = 0.0f;
this._duration = 0.0f;
this._timeScale = 1.0f;
this._timeOffset = 0.0f;
this._dragonBonesData = null; //
this._animationData = null; //
this._timelineData = null; //
this._armature = null; //
this._animationState = null; //
this._actionTimeline = null; //
this._frameArray = null; //
this._frameIntArray = null; //
this._frameFloatArray = null; //
this._timelineArray = null; //
this._frameIndices = null; //
}
protected abstract void _OnArriveAtFrame();
protected abstract void _OnUpdateFrame();
protected bool _SetCurrentTime(float passedTime)
{
var prevState = this.playState;
var prevPlayTimes = this.currentPlayTimes;
var prevTime = this.currentTime;
if (this._actionTimeline != null && this._frameCount <= 1)
{
// No frame or only one frame.
this.playState = this._actionTimeline.playState >= 0 ? 1 : -1;
this.currentPlayTimes = 1;
this.currentTime = this._actionTimeline.currentTime;
}
else if (this._actionTimeline == null || this._timeScale != 1.0f || this._timeOffset != 0.0f)
{
var playTimes = this._animationState.playTimes;
var totalTime = playTimes * this._duration;
passedTime *= this._timeScale;
if (this._timeOffset != 0.0f)
{
passedTime += this._timeOffset * this._animationData.duration;
}
if (playTimes > 0 && (passedTime >= totalTime || passedTime <= -totalTime))
{
if (this.playState <= 0 && this._animationState._playheadState == 3)
{
this.playState = 1;
}
this.currentPlayTimes = playTimes;
if (passedTime < 0.0f)
{
this.currentTime = 0.0f;
}
else
{
this.currentTime = this._duration + 0.000001f; // Precision problem
}
}
else
{
if (this.playState != 0 && this._animationState._playheadState == 3)
{
this.playState = 0;
}
if (passedTime < 0.0f)
{
passedTime = -passedTime;
this.currentPlayTimes = (int)(passedTime / this._duration);
this.currentTime = this._duration - (passedTime % this._duration);
}
else
{
this.currentPlayTimes = (int)(passedTime / this._duration);
this.currentTime = passedTime % this._duration;
}
}
this.currentTime += this._position;
}
else
{
// Multi frames.
this.playState = this._actionTimeline.playState;
this.currentPlayTimes = this._actionTimeline.currentPlayTimes;
this.currentTime = this._actionTimeline.currentTime;
}
if (this.currentPlayTimes == prevPlayTimes && this.currentTime == prevTime)
{
return false;
}
// Clear frame flag when timeline start or loopComplete.
if ((prevState < 0 && this.playState != prevState) || (this.playState <= 0 && this.currentPlayTimes != prevPlayTimes))
{
this._frameIndex = -1;
}
return true;
}
public virtual void Init(Armature armature, AnimationState animationState, TimelineData timelineData)
{
this._armature = armature;
this._animationState = animationState;
this._timelineData = timelineData;
this._actionTimeline = this._animationState._actionTimeline;
if (this == this._actionTimeline)
{
this._actionTimeline = null; //
}
this._frameRate = this._armature.armatureData.frameRate;
this._frameRateR = 1.0f / this._frameRate;
this._position = this._animationState._position;
this._duration = this._animationState._duration;
this._dragonBonesData = this._armature.armatureData.parent;
this._animationData = this._animationState._animationData;
if (this._timelineData != null)
{
this._frameIntArray = this._dragonBonesData.frameIntArray;
this._frameFloatArray = this._dragonBonesData.frameFloatArray;
this._frameArray = this._dragonBonesData.frameArray;
this._timelineArray = this._dragonBonesData.timelineArray;
this._frameIndices = this._dragonBonesData.frameIndices;
this._frameCount = this._timelineArray[this._timelineData.offset + (int)BinaryOffset.TimelineKeyFrameCount];
this._frameValueOffset = this._timelineArray[this._timelineData.offset + (int)BinaryOffset.TimelineFrameValueOffset];
var timelineScale = this._timelineArray[this._timelineData.offset + (int)BinaryOffset.TimelineScale];
this._timeScale = 100.0f / (timelineScale == 0 ? 100.0f : timelineScale);
this._timeOffset = this._timelineArray[this._timelineData.offset + (int)BinaryOffset.TimelineOffset] * 0.01f;
}
}
public virtual void FadeOut()
{
}
public virtual void Update(float passedTime)
{
if (this._SetCurrentTime(passedTime))
{
if (this._frameCount > 1)
{
int timelineFrameIndex = (int)Math.Floor(this.currentTime * this._frameRate); // uint
var frameIndex = this._frameIndices[(int)(this._timelineData as TimelineData).frameIndicesOffset + timelineFrameIndex];
if (this._frameIndex != frameIndex)
{
this._frameIndex = (int)frameIndex;
this._frameOffset = this._animationData.frameOffset + this._timelineArray[(this._timelineData as TimelineData).offset + (int)BinaryOffset.TimelineFrameOffset + this._frameIndex];
this._OnArriveAtFrame();
}
}
else if (this._frameIndex < 0)
{
this._frameIndex = 0;
if (this._timelineData != null)
{
// May be pose timeline.
this._frameOffset = this._animationData.frameOffset + this._timelineArray[this._timelineData.offset + (int)BinaryOffset.TimelineFrameOffset];
}
this._OnArriveAtFrame();
}
if (this._tweenState != TweenState.None)
{
this._OnUpdateFrame();
}
}
}
}
/// <internal/>
/// <private/>
internal abstract class TweenTimelineState : TimelineState
{
private static float _GetEasingValue(TweenType tweenType, float progress, float easing)
{
var value = progress;
switch (tweenType)
{
case TweenType.QuadIn:
value = (float)Math.Pow(progress, 2.0f);
break;
case TweenType.QuadOut:
value = 1.0f - (float)Math.Pow(1.0f - progress, 2.0f);
break;
case TweenType.QuadInOut:
value = 0.5f * (1.0f - (float)Math.Cos(progress * Math.PI));
break;
}
return (value - progress) * easing + progress;
}
private static float _GetEasingCurveValue(float progress, short[] samples, int count, int offset)
{
if (progress <= 0.0f)
{
return 0.0f;
}
else if (progress >= 1.0f)
{
return 1.0f;
}
var segmentCount = count + 1; // + 2 - 1
var valueIndex = (int)Math.Floor(progress * segmentCount);
var fromValue = valueIndex == 0 ? 0.0f : samples[offset + valueIndex - 1];
var toValue = (valueIndex == segmentCount - 1) ? 10000.0f : samples[offset + valueIndex];
return (fromValue + (toValue - fromValue) * (progress * segmentCount - valueIndex)) * 0.0001f;
}
protected TweenType _tweenType;
protected int _curveCount;
protected float _framePosition;
protected float _frameDurationR;
protected float _tweenProgress;
protected float _tweenEasing;
protected override void _OnClear()
{
base._OnClear();
this._tweenType = TweenType.None;
this._curveCount = 0;
this._framePosition = 0.0f;
this._frameDurationR = 0.0f;
this._tweenProgress = 0.0f;
this._tweenEasing = 0.0f;
}
protected override void _OnArriveAtFrame()
{
if (this._frameCount > 1 &&
(this._frameIndex != this._frameCount - 1 ||
this._animationState.playTimes == 0 ||
this._animationState.currentPlayTimes < this._animationState.playTimes - 1))
{
this._tweenType = (TweenType)this._frameArray[this._frameOffset + (int)BinaryOffset.FrameTweenType]; // TODO recode ture tween type.
this._tweenState = this._tweenType == TweenType.None ? TweenState.Once : TweenState.Always;
if (this._tweenType == TweenType.Curve)
{
this._curveCount = this._frameArray[this._frameOffset + (int)BinaryOffset.FrameTweenEasingOrCurveSampleCount];
}
else if (this._tweenType != TweenType.None && this._tweenType != TweenType.Line)
{
this._tweenEasing = this._frameArray[this._frameOffset + (int)BinaryOffset.FrameTweenEasingOrCurveSampleCount] * 0.01f;
}
this._framePosition = this._frameArray[this._frameOffset] * this._frameRateR;
if (this._frameIndex == this._frameCount - 1)
{
this._frameDurationR = 1.0f / (this._animationData.duration - this._framePosition);
}
else
{
var nextFrameOffset = this._animationData.frameOffset + this._timelineArray[(this._timelineData as TimelineData).offset + (int)BinaryOffset.TimelineFrameOffset + this._frameIndex + 1];
var frameDuration = this._frameArray[nextFrameOffset] * this._frameRateR - this._framePosition;
if (frameDuration > 0.0f)
{
this._frameDurationR = 1.0f / frameDuration;
}
else
{
this._frameDurationR = 0.0f;
}
}
}
else
{
this._tweenState = TweenState.Once;
}
}
protected override void _OnUpdateFrame()
{
if (this._tweenState == TweenState.Always)
{
this._tweenProgress = (this.currentTime - this._framePosition) * this._frameDurationR;
if (this._tweenType == TweenType.Curve)
{
this._tweenProgress = TweenTimelineState._GetEasingCurveValue(this._tweenProgress, this._frameArray, this._curveCount, (int)this._frameOffset + (int)BinaryOffset.FrameCurveSamples);
}
else if (this._tweenType != TweenType.Line)
{
this._tweenProgress = TweenTimelineState._GetEasingValue(this._tweenType, this._tweenProgress, this._tweenEasing);
}
}
else
{
this._tweenProgress = 0.0f;
}
}
}
/// <internal/>
/// <private/>
internal abstract class BoneTimelineState : TweenTimelineState
{
public Bone bone;
public BonePose bonePose;
protected override void _OnClear()
{
base._OnClear();
this.bone = null; //
this.bonePose = null; //
}
public void Blend(int state)
{
var blendWeight = this.bone._blendState.blendWeight;
var animationPose = this.bone.animationPose;
var result = this.bonePose.result;
if (state == 2)
{
animationPose.x += result.x * blendWeight;
animationPose.y += result.y * blendWeight;
animationPose.rotation += result.rotation * blendWeight;
animationPose.skew += result.skew * blendWeight;
animationPose.scaleX += (result.scaleX - 1.0f) * blendWeight;
animationPose.scaleY += (result.scaleY - 1.0f) * blendWeight;
}
else if (blendWeight != 1.0f)
{
animationPose.x = result.x * blendWeight;
animationPose.y = result.y * blendWeight;
animationPose.rotation = result.rotation * blendWeight;
animationPose.skew = result.skew * blendWeight;
animationPose.scaleX = (result.scaleX - 1.0f) * blendWeight + 1.0f;
animationPose.scaleY = (result.scaleY - 1.0f) * blendWeight + 1.0f;
}
else
{
animationPose.x = result.x;
animationPose.y = result.y;
animationPose.rotation = result.rotation;
animationPose.skew = result.skew;
animationPose.scaleX = result.scaleX;
animationPose.scaleY = result.scaleY;
}
if (this._animationState._fadeState != 0 || this._animationState._subFadeState != 0)
{
this.bone._transformDirty = true;
}
}
}
/// <internal/>
/// <private/>
internal abstract class SlotTimelineState : TweenTimelineState
{
public Slot slot;
protected override void _OnClear()
{
base._OnClear();
this.slot = null; //
}
}
/// <internal/>
/// <private/>
internal abstract class ConstraintTimelineState : TweenTimelineState
{
public Constraint constraint;
protected override void _OnClear()
{
base._OnClear();
this.constraint = null; //
}
}
}
| |
using System;
#if __UNIFIED__
using CoreGraphics;
using Foundation;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CGPoint = System.Drawing.PointF;
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using nfloat = System.Single;
#endif
namespace AdvancedColorPicker
{
/// <summary>
/// The view that represents a color picker.
/// </summary>
public class ColorPickerView : UIView
{
private CGSize satBrightIndicatorSize;
private HuePickerView huePicker;
private SaturationBrightnessPickerView satbrightPicker;
private SelectedColorPreviewView preview;
private HueIndicatorView hueIndicator;
private SaturationBrightnessIndicatorView satBrightIndicator;
/// <summary>
/// Initializes a new instance of the <see cref="ColorPickerView"/> class.
/// </summary>
public ColorPickerView()
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="ColorPickerView"/> class
/// with the specified frame.
/// </summary>
/// <param name="frame">The frame used by the view, expressed in iOS points.</param>
public ColorPickerView(CGRect frame)
: base(frame)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="ColorPickerView"/> class
/// with the specified initial selected color.
/// </summary>
/// <param name="color">The initial selected color.</param>
public ColorPickerView(UIColor color)
: base()
{
Initialize();
SelectedColor = color;
}
/// <summary>
/// Initializes this instance.
/// </summary>
protected void Initialize()
{
satBrightIndicatorSize = new CGSize(28, 28);
var selectedColorViewHeight = (nfloat)60;
var viewSpace = (nfloat)1;
preview = new SelectedColorPreviewView();
preview.Frame = new CGRect(0, 0, Bounds.Width, selectedColorViewHeight);
preview.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
preview.Layer.ShadowOpacity = 0.6f;
preview.Layer.ShadowOffset = new CGSize(0, 7);
preview.Layer.ShadowColor = UIColor.Black.CGColor;
satbrightPicker = new SaturationBrightnessPickerView();
satbrightPicker.Frame = new CGRect(0, selectedColorViewHeight + viewSpace, Bounds.Width, Bounds.Height - selectedColorViewHeight - selectedColorViewHeight - viewSpace - viewSpace);
satbrightPicker.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
satbrightPicker.ColorPicked += HandleColorPicked;
satbrightPicker.AutosizesSubviews = true;
huePicker = new HuePickerView();
huePicker.Frame = new CGRect(0, Bounds.Bottom - selectedColorViewHeight, Bounds.Width, selectedColorViewHeight);
huePicker.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin;
huePicker.HueChanged += HandleHueChanged;
var pos = huePicker.Frame.Width * huePicker.Hue;
hueIndicator = new HueIndicatorView();
hueIndicator.Frame = new CGRect(pos - 10, huePicker.Bounds.Y - 2, 20, huePicker.Bounds.Height + 2);
hueIndicator.UserInteractionEnabled = false;
hueIndicator.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
huePicker.AddSubview(hueIndicator);
var pos2 = new CGPoint(satbrightPicker.Saturation * satbrightPicker.Frame.Size.Width,
satbrightPicker.Frame.Size.Height - (satbrightPicker.Brightness * satbrightPicker.Frame.Size.Height));
satBrightIndicator = new SaturationBrightnessIndicatorView();
satBrightIndicator.Frame = new CGRect(pos2.X - satBrightIndicatorSize.Width / 2, pos2.Y - satBrightIndicatorSize.Height / 2, satBrightIndicatorSize.Width, satBrightIndicatorSize.Height);
satBrightIndicator.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin;
satBrightIndicator.UserInteractionEnabled = false;
satbrightPicker.AddSubview(satBrightIndicator);
AddSubviews(satbrightPicker, huePicker, preview);
}
/// <summary>
/// Gets or sets the selected color.
/// </summary>
/// <value>The selected color.</value>
public UIColor SelectedColor
{
get
{
return UIColor.FromHSB(satbrightPicker.Hue, satbrightPicker.Saturation, satbrightPicker.Brightness);
}
set
{
nfloat hue = 0, brightness = 0, saturation = 0, alpha = 0;
value?.GetHSBA(out hue, out saturation, out brightness, out alpha);
huePicker.Hue = hue;
satbrightPicker.Hue = hue;
satbrightPicker.Brightness = brightness;
satbrightPicker.Saturation = saturation;
preview.BackgroundColor = value;
PositionIndicators();
satbrightPicker.SetNeedsDisplay();
huePicker.SetNeedsDisplay();
}
}
/// <summary>
/// Occurs when the a color is selected.
/// </summary>
public event EventHandler<ColorPickedEventArgs> ColorPicked;
/// <summary>
/// Lays out subviews.
/// </summary>
public override void LayoutSubviews()
{
base.LayoutSubviews();
PositionIndicators();
}
private void PositionIndicators()
{
PositionHueIndicatorView();
PositionSatBrightIndicatorView();
}
private void PositionSatBrightIndicatorView()
{
Animate(0.3f, 0f, UIViewAnimationOptions.AllowUserInteraction, () =>
{
var x = satbrightPicker.Saturation * satbrightPicker.Frame.Size.Width;
var y = satbrightPicker.Frame.Size.Height - (satbrightPicker.Brightness * satbrightPicker.Frame.Size.Height);
var pos = new CGPoint(x, y);
var rect = new CGRect(
pos.X - satBrightIndicatorSize.Width / 2,
pos.Y - satBrightIndicatorSize.Height / 2,
satBrightIndicatorSize.Width,
satBrightIndicatorSize.Height);
satBrightIndicator.Frame = rect;
}, null);
}
private void PositionHueIndicatorView()
{
Animate(0.3f, 0f, UIViewAnimationOptions.AllowUserInteraction, () =>
{
var pos = huePicker.Frame.Width * huePicker.Hue;
var rect = new CGRect(
pos - 10,
huePicker.Bounds.Y - 2,
20,
huePicker.Bounds.Height + 2);
hueIndicator.Frame = rect;
}, () =>
{
hueIndicator.Hidden = false;
});
}
private void HandleColorPicked(object sender, EventArgs e)
{
PositionSatBrightIndicatorView();
preview.BackgroundColor = UIColor.FromHSB(satbrightPicker.Hue, satbrightPicker.Saturation, satbrightPicker.Brightness);
OnColorPicked(new ColorPickedEventArgs(SelectedColor));
}
private void HandleHueChanged(object sender, EventArgs e)
{
PositionHueIndicatorView();
satbrightPicker.Hue = huePicker.Hue;
satbrightPicker.SetNeedsDisplay();
HandleColorPicked(sender, e);
}
/// <summary>
/// Handles the <see cref="E:ColorPicked" /> event.
/// </summary>
/// <param name="e">The <see cref="ColorPickedEventArgs"/> instance containing the event data.</param>
protected virtual void OnColorPicked(ColorPickedEventArgs e)
{
var handler = ColorPicked;
if (handler != null)
{
handler(this, e);
}
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IdentityServerHost.Filters;
using IdentityServerHost.ViewModels;
using IdentityServerHost.Models;
using IdentityServerHost.Constants;
namespace IdentityServerHost.Controllers
{
[Authorize]
[SecurityHeaders]
public class DeviceController : Controller
{
private readonly IDeviceFlowInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IEventService _events;
private readonly ILogger<DeviceController> _logger;
public DeviceController(
IDeviceFlowInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
IEventService eventService,
ILogger<DeviceController> logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_events = eventService;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> Index([FromQuery(Name = "user_code")] string userCode)
{
if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture");
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return View("Error");
vm.ConfirmUserCode = true;
return View("UserCodeConfirmation", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserCodeCapture(string userCode)
{
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return View("Error");
return View("UserCodeConfirmation", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Callback(DeviceAuthorizationInputModel model)
{
if (model == null) throw new ArgumentNullException(nameof(model));
var result = await ProcessConsent(model);
if (result.HasValidationError) return View("Error");
return View("Success");
}
private async Task<ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model)
{
var result = new ProcessConsentResult();
var request = await _interaction.GetAuthorizationContextAsync(model.UserCode);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested));
}
// user clicked 'yes' - validate the data
else if (model.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.HandleRequestAsync(model.UserCode, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.UserCode, model);
}
return result;
}
private async Task<DeviceAuthorizationViewModel> BuildViewModelAsync(string userCode, DeviceAuthorizationInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(userCode);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(userCode, model, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
return null;
}
private DeviceAuthorizationViewModel CreateConsentViewModel(string userCode, DeviceAuthorizationInputModel model, Client client, Resources resources)
{
var vm = new DeviceAuthorizationViewModel
{
UserCode = userCode,
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new[]
{
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
namespace NLog.Targets
{
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using NLog.Common;
using NLog.Internal;
using Config;
/// <summary>
/// Calls the specified web service on each log message.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// The web service must implement a method that accepts a number of string parameters.
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" />
/// <p>The example web service that works with this example is shown below</p>
/// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" />
/// </example>
[Target("WebService")]
public sealed class WebServiceTarget : MethodCallTargetBase
{
private const string SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
private const string Soap12EnvelopeNamespace = "http://www.w3.org/2003/05/soap-envelope";
/// <summary>
/// dictionary that maps a concrete <see cref="HttpPostFormatterBase"/> implementation
/// to a specific <see cref="WebServiceProtocol"/>-value.
/// </summary>
private static Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>> _postFormatterFactories =
new Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>>()
{
{ WebServiceProtocol.Soap11, t => new HttpPostSoap11Formatter(t)},
{ WebServiceProtocol.Soap12, t => new HttpPostSoap12Formatter(t)},
{ WebServiceProtocol.HttpPost, t => new HttpPostFormEncodedFormatter(t)},
{ WebServiceProtocol.JsonPost, t => new HttpPostJsonFormatter(t)},
{ WebServiceProtocol.XmlPost, t => new HttpPostXmlDocumentFormatter(t)},
};
/// <summary>
/// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
/// </summary>
public WebServiceTarget()
{
this.Protocol = WebServiceProtocol.Soap11;
//default NO utf-8 bom
const bool writeBOM = false;
this.Encoding = new UTF8Encoding(writeBOM);
this.IncludeBOM = writeBOM;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
/// </summary>
/// <param name="name">Name of the target</param>
public WebServiceTarget(string name) : this()
{
this.Name = name;
}
/// <summary>
/// Gets or sets the web service URL.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public Uri Url { get; set; }
/// <summary>
/// Gets or sets the Web service method name. Only used with Soap.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string MethodName { get; set; }
/// <summary>
/// Gets or sets the Web service namespace. Only used with Soap.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string Namespace { get; set; }
/// <summary>
/// Gets or sets the protocol to be used when calling web service.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
[DefaultValue("Soap11")]
public WebServiceProtocol Protocol { get; set; }
/// <summary>
/// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property.
///
/// This will only work for UTF-8.
/// </summary>
public bool? IncludeBOM { get; set; }
/// <summary>
/// Gets or sets the encoding.
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs)
/// </summary>
/// <value>A value of <c>true</c> if Rfc3986; otherwise, <c>false</c> for legacy Rfc2396.</value>
/// <docgen category='Web Service Options' order='10' />
public bool EscapeDataRfc3986 { get; set; }
/// <summary>
/// Gets or sets a value whether escaping be done according to the old NLog style (Very non-standard)
/// </summary>
/// <value>A value of <c>true</c> if legacy encoding; otherwise, <c>false</c> for standard UTF8 encoding.</value>
/// <docgen category='Web Service Options' order='10' />
public bool EscapeDataNLogLegacy { get; set; }
/// <summary>
/// Gets or sets the name of the root XML element,
/// if POST of XML document chosen.
/// If so, this property must not be <c>null</c>.
/// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>).
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string XmlRoot { get; set; }
/// <summary>
/// Gets or sets the (optional) root namespace of the XML document,
/// if POST of XML document chosen.
/// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>).
/// </summary>
/// <docgen category='Web Service Options' order='10' />
public string XmlRootNamespace { get; set; }
/// <summary>
/// Calls the target method. Must be implemented in concrete classes.
/// </summary>
/// <param name="parameters">Method call parameters.</param>
protected override void DoInvoke(object[] parameters)
{
// method is not used, instead asynchronous overload will be used
throw new NotImplementedException();
}
/// <summary>
/// Invokes the web service method.
/// </summary>
/// <param name="parameters">Parameters to be passed.</param>
/// <param name="continuation">The continuation.</param>
protected override void DoInvoke(object[] parameters, AsyncContinuation continuation)
{
var request = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters));
Func<AsyncCallback, IAsyncResult> begin = (r) => request.BeginGetRequestStream(r, null);
Func<IAsyncResult, Stream> getStream = request.EndGetRequestStream;
DoInvoke(parameters, continuation, request, begin, getStream);
}
internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc,
Func<IAsyncResult, Stream> getStreamFunc)
{
Stream postPayload = null;
if (Protocol == WebServiceProtocol.HttpGet)
{
PrepareGetRequest(request);
}
else
{
postPayload = _postFormatterFactories[Protocol](this).PrepareRequest(request, parameters);
}
AsyncContinuation sendContinuation =
ex =>
{
if (ex != null)
{
continuation(ex);
return;
}
request.BeginGetResponse(
r =>
{
try
{
using (var response = request.EndGetResponse(r))
{
}
continuation(null);
}
catch (Exception ex2)
{
InternalLogger.Error(ex2, "Error when sending to Webservice.");
if (ex2.MustBeRethrown())
{
throw;
}
continuation(ex2);
}
},
null);
};
if (postPayload != null && postPayload.Length > 0)
{
postPayload.Position = 0;
beginFunc(
result =>
{
try
{
using (Stream stream = getStreamFunc(result))
{
WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding);
postPayload.Dispose();
}
sendContinuation(null);
}
catch (Exception ex)
{
postPayload.Dispose();
InternalLogger.Error(ex, "Error when sending to Webservice.");
if (ex.MustBeRethrown())
{
throw;
}
continuation(ex);
}
});
}
else
{
sendContinuation(null);
}
}
/// <summary>
/// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol.
/// </summary>
/// <param name="parameterValues"></param>
/// <returns></returns>
private Uri BuildWebServiceUrl(object[] parameterValues)
{
if (this.Protocol != WebServiceProtocol.HttpGet)
{
return this.Url;
}
UrlHelper.EscapeEncodingFlag encodingFlags = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986);
//if the protocol is HttpGet, we need to add the parameters to the query string of the url
var queryParameters = new StringBuilder();
string separator = string.Empty;
for (int i = 0; i < this.Parameters.Count; i++)
{
queryParameters.Append(separator);
queryParameters.Append(this.Parameters[i].Name);
queryParameters.Append("=");
string parameterValue = Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture);
UrlHelper.EscapeDataEncode(parameterValue, queryParameters, encodingFlags);
separator = "&";
}
var builder = new UriBuilder(this.Url);
//append our query string to the URL following
//the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx
if (builder.Query != null && builder.Query.Length > 1)
{
builder.Query = builder.Query.Substring(1) + "&" + queryParameters.ToString();
}
else
{
builder.Query = queryParameters.ToString();
}
return builder.Uri;
}
private void PrepareGetRequest(HttpWebRequest request)
{
request.Method = "GET";
}
/// <summary>
/// Write from input to output. Fix the UTF-8 bom
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="writeUtf8BOM"></param>
/// <param name="encoding"></param>
private static void WriteStreamAndFixPreamble(Stream input, Stream output, bool? writeUtf8BOM, Encoding encoding)
{
//only when utf-8 encoding is used, the Encoding preamble is optional
var nothingToDo = writeUtf8BOM == null || !(encoding is UTF8Encoding);
const int preambleSize = 3;
if (!nothingToDo)
{
//it's UTF-8
var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize;
//BOM already in Encoding.
nothingToDo = writeUtf8BOM.Value && hasBomInEncoding;
//Bom already not in Encoding
nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding;
}
var offset = nothingToDo ? 0 : preambleSize;
input.CopyWithOffset(output, offset);
}
/// <summary>
/// base class for POST formatters, that
/// implement former <c>PrepareRequest()</c> method,
/// that creates the content for
/// the requested kind of HTTP request
/// </summary>
private abstract class HttpPostFormatterBase
{
protected HttpPostFormatterBase(WebServiceTarget target)
{
Target = target;
}
protected abstract string ContentType { get; }
protected WebServiceTarget Target { get; private set; }
public MemoryStream PrepareRequest(HttpWebRequest request, object[] parameterValues)
{
InitRequest(request);
var ms = new MemoryStream();
WriteContent(ms, parameterValues);
return ms;
}
protected virtual void InitRequest(HttpWebRequest request)
{
request.Method = "POST";
request.ContentType = string.Format("{1}; charset={0}", Target.Encoding.WebName, ContentType);
}
protected abstract void WriteContent(MemoryStream ms, object[] parameterValues);
}
private class HttpPostFormEncodedFormatter : HttpPostTextFormatterBase
{
UrlHelper.EscapeEncodingFlag encodingFlags;
public HttpPostFormEncodedFormatter(WebServiceTarget target) : base(target)
{
encodingFlags = UrlHelper.GetUriStringEncodingFlags(target.EscapeDataNLogLegacy, true, target.EscapeDataRfc3986);
}
protected override string ContentType
{
get { return "application/x-www-form-urlencoded"; }
}
protected override string Separator
{
get { return "&"; }
}
protected override string GetFormattedContent(string parametersContent)
{
return parametersContent;
}
protected override string GetFormattedParameter(MethodCallParameter parameter, object value)
{
string parameterValue = Convert.ToString(value, CultureInfo.InvariantCulture);
if (string.IsNullOrEmpty(parameterValue))
{
return string.Concat(parameter.Name, "=");
}
var sb = new StringBuilder(parameter.Name.Length + parameterValue.Length + 20);
sb.Append(parameter.Name).Append("=");
UrlHelper.EscapeDataEncode(parameterValue, sb, encodingFlags);
return sb.ToString();
}
}
private class HttpPostJsonFormatter : HttpPostTextFormatterBase
{
public HttpPostJsonFormatter(WebServiceTarget target) : base(target)
{ }
protected override string ContentType
{
get { return "application/json"; }
}
protected override string Separator
{
get { return ","; }
}
protected override string GetFormattedContent(string parametersContent)
{
return string.Concat("{", parametersContent, "}");
}
protected override string GetFormattedParameter(MethodCallParameter parameter, object value)
{
return string.Format("\"{0}\":{1}",
parameter.Name,
GetJsonValueString(value));
}
private string GetJsonValueString(object value)
{
return ConfigurationItemFactory.Default.JsonSerializer.SerializeObject(value);
}
}
private class HttpPostSoap11Formatter : HttpPostSoapFormatterBase
{
public HttpPostSoap11Formatter(WebServiceTarget target) : base(target)
{
}
protected override string SoapEnvelopeNamespace
{
get { return WebServiceTarget.SoapEnvelopeNamespace; }
}
protected override string SoapName
{
get { return "soap"; }
}
protected override void InitRequest(HttpWebRequest request)
{
base.InitRequest(request);
string soapAction;
if (Target.Namespace.EndsWith("/", StringComparison.Ordinal))
{
soapAction = string.Concat(Target.Namespace, Target.MethodName);
}
else
{
soapAction = string.Concat(Target.Namespace, "/", Target.MethodName);
}
request.Headers["SOAPAction"] = soapAction;
}
}
private class HttpPostSoap12Formatter : HttpPostSoapFormatterBase
{
public HttpPostSoap12Formatter(WebServiceTarget target) : base(target)
{
}
protected override string SoapEnvelopeNamespace
{
get { return WebServiceTarget.Soap12EnvelopeNamespace; }
}
protected override string SoapName
{
get { return "soap12"; }
}
}
private abstract class HttpPostSoapFormatterBase : HttpPostXmlFormatterBase
{
protected HttpPostSoapFormatterBase(WebServiceTarget target) : base(target)
{
}
protected abstract string SoapEnvelopeNamespace { get; }
protected abstract string SoapName { get; }
protected override void WriteContent(MemoryStream ms, object[] parameterValues)
{
XmlWriter xtw = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = Target.Encoding });
xtw.WriteStartElement(SoapName, "Envelope", SoapEnvelopeNamespace);
xtw.WriteStartElement("Body", SoapEnvelopeNamespace);
xtw.WriteStartElement(Target.MethodName, Target.Namespace);
WriteAllParametersToCurrenElement(xtw, parameterValues);
xtw.WriteEndElement(); // methodname
xtw.WriteEndElement(); // Body
xtw.WriteEndElement(); // soap:Envelope
xtw.Flush();
}
}
private abstract class HttpPostTextFormatterBase : HttpPostFormatterBase
{
protected HttpPostTextFormatterBase(WebServiceTarget target) : base(target)
{
}
protected abstract string Separator { get; }
protected abstract string GetFormattedContent(string parametersContent);
protected abstract string GetFormattedParameter(MethodCallParameter parameter, object value);
protected override void WriteContent(MemoryStream ms, object[] parameterValues)
{
var sw = new StreamWriter(ms, Target.Encoding);
sw.Write(string.Empty);
var sb = new StringBuilder();
for (int i = 0; i < Target.Parameters.Count; i++)
{
if (sb.Length > 0) sb.Append(Separator);
sb.Append(GetFormattedParameter(Target.Parameters[i], parameterValues[i]));
}
string content = GetFormattedContent(sb.ToString());
sw.Write(content);
sw.Flush();
}
}
private class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase
{
protected override string ContentType
{
get { return "application/xml"; }
}
public HttpPostXmlDocumentFormatter(WebServiceTarget target) : base(target)
{
if (string.IsNullOrEmpty(target.XmlRoot))
throw new InvalidOperationException("WebServiceProtocol.Xml requires WebServiceTarget.XmlRoot to be set.");
}
protected override void WriteContent(MemoryStream ms, object[] parameterValues)
{
XmlWriter xtw = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = Target.Encoding, OmitXmlDeclaration = true, Indent = false });
xtw.WriteStartElement(Target.XmlRoot, Target.XmlRootNamespace);
WriteAllParametersToCurrenElement(xtw, parameterValues);
xtw.WriteEndElement();
xtw.Flush();
}
}
private abstract class HttpPostXmlFormatterBase : HttpPostFormatterBase
{
protected HttpPostXmlFormatterBase(WebServiceTarget target) : base(target)
{
}
protected override string ContentType
{
get { return "text/xml"; }
}
protected void WriteAllParametersToCurrenElement(XmlWriter currentXmlWriter, object[] parameterValues)
{
int i = 0;
foreach (MethodCallParameter par in Target.Parameters)
{
currentXmlWriter.WriteElementString(par.Name, Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture));
i++;
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysPermiso class.
/// </summary>
[Serializable]
public partial class SysPermisoCollection : ActiveList<SysPermiso, SysPermisoCollection>
{
public SysPermisoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysPermisoCollection</returns>
public SysPermisoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysPermiso o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_Permiso table.
/// </summary>
[Serializable]
public partial class SysPermiso : ActiveRecord<SysPermiso>, IActiveRecord
{
#region .ctors and Default Settings
public SysPermiso()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysPermiso(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysPermiso(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysPermiso(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_Permiso", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdPermiso = new TableSchema.TableColumn(schema);
colvarIdPermiso.ColumnName = "idPermiso";
colvarIdPermiso.DataType = DbType.Int32;
colvarIdPermiso.MaxLength = 0;
colvarIdPermiso.AutoIncrement = true;
colvarIdPermiso.IsNullable = false;
colvarIdPermiso.IsPrimaryKey = true;
colvarIdPermiso.IsForeignKey = false;
colvarIdPermiso.IsReadOnly = false;
colvarIdPermiso.DefaultSetting = @"";
colvarIdPermiso.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPermiso);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"((0))";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarIdPerfil = new TableSchema.TableColumn(schema);
colvarIdPerfil.ColumnName = "idPerfil";
colvarIdPerfil.DataType = DbType.Int32;
colvarIdPerfil.MaxLength = 0;
colvarIdPerfil.AutoIncrement = false;
colvarIdPerfil.IsNullable = false;
colvarIdPerfil.IsPrimaryKey = false;
colvarIdPerfil.IsForeignKey = true;
colvarIdPerfil.IsReadOnly = false;
colvarIdPerfil.DefaultSetting = @"((0))";
colvarIdPerfil.ForeignKeyTableName = "Sys_Perfil";
schema.Columns.Add(colvarIdPerfil);
TableSchema.TableColumn colvarIdMenu = new TableSchema.TableColumn(schema);
colvarIdMenu.ColumnName = "idMenu";
colvarIdMenu.DataType = DbType.Int32;
colvarIdMenu.MaxLength = 0;
colvarIdMenu.AutoIncrement = false;
colvarIdMenu.IsNullable = false;
colvarIdMenu.IsPrimaryKey = false;
colvarIdMenu.IsForeignKey = true;
colvarIdMenu.IsReadOnly = false;
colvarIdMenu.DefaultSetting = @"((0))";
colvarIdMenu.ForeignKeyTableName = "Sys_Menu";
schema.Columns.Add(colvarIdMenu);
TableSchema.TableColumn colvarPermiso = new TableSchema.TableColumn(schema);
colvarPermiso.ColumnName = "permiso";
colvarPermiso.DataType = DbType.String;
colvarPermiso.MaxLength = 1;
colvarPermiso.AutoIncrement = false;
colvarPermiso.IsNullable = false;
colvarPermiso.IsPrimaryKey = false;
colvarPermiso.IsForeignKey = false;
colvarPermiso.IsReadOnly = false;
colvarPermiso.DefaultSetting = @"((0))";
colvarPermiso.ForeignKeyTableName = "";
schema.Columns.Add(colvarPermiso);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_Permiso",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdPermiso")]
[Bindable(true)]
public int IdPermiso
{
get { return GetColumnValue<int>(Columns.IdPermiso); }
set { SetColumnValue(Columns.IdPermiso, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("IdPerfil")]
[Bindable(true)]
public int IdPerfil
{
get { return GetColumnValue<int>(Columns.IdPerfil); }
set { SetColumnValue(Columns.IdPerfil, value); }
}
[XmlAttribute("IdMenu")]
[Bindable(true)]
public int IdMenu
{
get { return GetColumnValue<int>(Columns.IdMenu); }
set { SetColumnValue(Columns.IdMenu, value); }
}
[XmlAttribute("Permiso")]
[Bindable(true)]
public string Permiso
{
get { return GetColumnValue<string>(Columns.Permiso); }
set { SetColumnValue(Columns.Permiso, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysPerfil ActiveRecord object related to this SysPermiso
///
/// </summary>
public DalSic.SysPerfil SysPerfil
{
get { return DalSic.SysPerfil.FetchByID(this.IdPerfil); }
set { SetColumnValue("idPerfil", value.IdPerfil); }
}
/// <summary>
/// Returns a SysMenu ActiveRecord object related to this SysPermiso
///
/// </summary>
public DalSic.SysMenu SysMenu
{
get { return DalSic.SysMenu.FetchByID(this.IdMenu); }
set { SetColumnValue("idMenu", value.IdMenu); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdEfector,int varIdPerfil,int varIdMenu,string varPermiso)
{
SysPermiso item = new SysPermiso();
item.IdEfector = varIdEfector;
item.IdPerfil = varIdPerfil;
item.IdMenu = varIdMenu;
item.Permiso = varPermiso;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdPermiso,int varIdEfector,int varIdPerfil,int varIdMenu,string varPermiso)
{
SysPermiso item = new SysPermiso();
item.IdPermiso = varIdPermiso;
item.IdEfector = varIdEfector;
item.IdPerfil = varIdPerfil;
item.IdMenu = varIdMenu;
item.Permiso = varPermiso;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdPermisoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdPerfilColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdMenuColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn PermisoColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdPermiso = @"idPermiso";
public static string IdEfector = @"idEfector";
public static string IdPerfil = @"idPerfil";
public static string IdMenu = @"idMenu";
public static string Permiso = @"permiso";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H01_ContinentColl (editable root list).<br/>
/// This is a generated base class of <see cref="H01_ContinentColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="H02_Continent"/> objects.
/// </remarks>
[Serializable]
public partial class H01_ContinentColl : BusinessListBase<H01_ContinentColl, H02_Continent>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="H02_Continent"/> item from the collection.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to be removed.</param>
public void Remove(int continent_ID)
{
foreach (var h02_Continent in this)
{
if (h02_Continent.Continent_ID == continent_ID)
{
Remove(h02_Continent);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="H02_Continent"/> item is in the collection.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to search for.</param>
/// <returns><c>true</c> if the H02_Continent is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int continent_ID)
{
foreach (var h02_Continent in this)
{
if (h02_Continent.Continent_ID == continent_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="H02_Continent"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to search for.</param>
/// <returns><c>true</c> if the H02_Continent is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int continent_ID)
{
foreach (var h02_Continent in DeletedList)
{
if (h02_Continent.Continent_ID == continent_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="H02_Continent"/> item of the <see cref="H01_ContinentColl"/> collection, based on a given Continent_ID.
/// </summary>
/// <param name="continent_ID">The Continent_ID.</param>
/// <returns>A <see cref="H02_Continent"/> object.</returns>
public H02_Continent FindH02_ContinentByContinent_ID(int continent_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Continent_ID.Equals(continent_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H01_ContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="H01_ContinentColl"/> collection.</returns>
public static H01_ContinentColl NewH01_ContinentColl()
{
return DataPortal.Create<H01_ContinentColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="H01_ContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="H01_ContinentColl"/> collection.</returns>
public static H01_ContinentColl GetH01_ContinentColl()
{
return DataPortal.Fetch<H01_ContinentColl>();
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H01_ContinentColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H01_ContinentColl()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="H01_ContinentColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IH01_ContinentCollDal>();
var data = dal.Fetch();
Fetch(data);
}
OnFetchPost(args);
foreach (var item in this)
{
item.FetchChildren();
}
}
/// <summary>
/// Loads all <see cref="H01_ContinentColl"/> collection items from the given list of H02_ContinentDto.
/// </summary>
/// <param name="data">The list of <see cref="H02_ContinentDto"/>.</param>
private void Fetch(List<H02_ContinentDto> data)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
foreach (var dto in data)
{
Add(H02_Continent.GetH02_Continent(dto));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H01_ContinentColl"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
base.Child_Update();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using BugsnagUnity;
using BugsnagUnity.Payload;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class Main : MonoBehaviour
{
#if UNITY_STANDALONE_OSX
[DllImport("NativeCrashy")]
private static extern void crashy_signal_runner(float num);
#endif
private Dictionary<string, string> _webGlArguments;
private string _fakeTrace = "Main.CUSTOM () (at Assets/Scripts/Main.cs:123)\nMain.CUSTOM () (at Assets/Scripts/Main.cs:123)";
private float _closeTime = 5;
public void Start()
{
#if UNITY_ANDROID || UNITY_IOS
return;
#endif
#if UNITY_WEBGL
ParseUrlParameters();
#endif
var scenario = GetEvnVar("BUGSNAG_SCENARIO");
var config = PrepareConfig(scenario);
Invoke("CloseApplication", _closeTime);
if (scenario != "ClearBugsnagCache")
{
Bugsnag.Start(config);
Bugsnag.AddMetadata("init", new Dictionary<string, object>(){
{"foo", "bar" },
});
Bugsnag.AddMetadata("test", "test1", "test1");
Bugsnag.AddMetadata("test", "test2", "test2");
Bugsnag.AddMetadata("custom", new Dictionary<string, object>(){
{"letter", "QX" },
{"better", 400 },
{"string-array", new string []{"1","2","3"} },
{"int-array", new int []{1,2,3} },
{"dict", new Dictionary<string,object>(){ {"test" , 123 } } }
});
Bugsnag.AddMetadata("app", new Dictionary<string, object>(){
{"buildno", "0.1" },
{"cache", null },
});
Bugsnag.ClearMetadata("init");
Bugsnag.ClearMetadata("test", "test2");
}
RunScenario(scenario);
}
void CloseApplication()
{
Application.Quit();
}
private void ParseUrlParameters()
{
//Expected url format for webgl tests
//http://localhost:8888/index.html?BUGSNAG_SCENARIO=MaxBreadcrumbs&BUGSNAG_APIKEY=123344343289478347238947&MAZE_ENDPOINT=http://localhost:9339
string parameters = Application.absoluteURL.Substring(Application.absoluteURL.IndexOf("?")+1);
var splitParams = parameters.Split(new char[] { '&', '=' });
_webGlArguments = new Dictionary<string, string>();
var currentindex = 0;
while (currentindex < splitParams.Length)
{
_webGlArguments.Add(splitParams[currentindex],splitParams[currentindex + 1]);
currentindex += 2;
}
}
private string GetWebGLEnvVar(string key)
{
foreach (var pair in _webGlArguments)
{
if (pair.Key == key)
{
return pair.Value;
}
}
throw new System.Exception("COULD NOT GET ENV VAR: " + key);
}
Configuration PrepareConfig(string scenario)
{
string apiKey = GetEvnVar("BUGSNAG_APIKEY");
var config = new Configuration(apiKey);
var endpoint = GetEvnVar("MAZE_ENDPOINT");
config.Endpoints = new EndpointConfiguration(endpoint + "/notify", endpoint + "/sessions");
config.AutoTrackSessions = scenario.Contains("AutoSession");
config.ScriptingBackend = FindScriptingBackend();
config.DotnetScriptingRuntime = FindDotnetScriptingRuntime();
config.DotnetApiCompatibility = FindDotnetApiCompatibility();
PrepareConfigForScenario(config, scenario);
return config;
}
private string GetEvnVar(string key)
{
#if UNITY_WEBGL
return GetWebGLEnvVar(key);
#else
return System.Environment.GetEnvironmentVariable(key);
#endif
}
void PrepareConfigForScenario(Configuration config, string scenario)
{
switch (scenario)
{
case "PersistEvent":
config.AutoDetectErrors = true;
config.Endpoints = new EndpointConfiguration("https://notify.def-not-bugsnag.com", "https://notify.def-not-bugsnag.com");
config.Context = "First Error";
break;
case "PersistEventReport":
config.AutoDetectErrors = true;
config.Context = "Second Error";
break;
case "PersistEventReportCallback":
config.AutoDetectErrors = true;
config.Context = "Second Error";
config.AddOnSendError((@event) => {
@event.App.BinaryArch = "Persist BinaryArch";
@event.Device.Id = "Persist Id";
@event.Errors[0].ErrorClass = "Persist ErrorClass";
@event.Errors[0].Stacktrace[0].Method = "Persist Method";
foreach (var crumb in @event.Breadcrumbs)
{
crumb.Message = "Persist Message";
}
@event.AddMetadata("Persist Section", new Dictionary<string, object> { { "Persist Key", "Persist Value" } });
return true;
});
break;
case "PersistSession":
config.AddOnSession((session)=> {
session.App.ReleaseStage = "First Session";
return true;
});
config.Endpoints = new EndpointConfiguration("https://notify.bugsdnag.com", "https://notify.bugsdnag.com");
config.AutoTrackSessions = true;
break;
case "PersistSessionReport":
config.AddOnSession((session) => {
session.App.ReleaseStage = "Second Session";
return true;
});
config.AutoTrackSessions = true;
break;
case "ClearFeatureFlagsInCallback":
config.AddOnSendError((@event) => {
@event.AddFeatureFlag("testName3", "testVariant3");
@event.ClearFeatureFlags();
return true;
});
break;
case "FeatureFlagsInCallback":
config.AddFeatureFlag("testName1", "testVariant1");
config.AddFeatureFlag("testName2", "testVariant1");
config.AddFeatureFlag("testName2", "testVariant2");
config.ClearFeatureFlag("testName1");
config.AddOnSendError((@event)=> {
@event.AddFeatureFlag("testName3", "testVariant3");
return true;
});
break;
case "FeatureFlagsConfigClearAll":
config.AddFeatureFlag("testName1", "testVariant1");
config.AddFeatureFlag("testName2", "testVariant1");
config.AddFeatureFlag("testName2", "testVariant2");
config.ClearFeatureFlags();
break;
case "FeatureFlagsInConfig":
config.AddFeatureFlag("testName1", "testVariant1");
config.AddFeatureFlag("testName2", "testVariant1");
config.AddFeatureFlag("testName2", "testVariant2");
config.ClearFeatureFlag("testName1");
break;
case "DisableErrorBreadcrumbs":
config.EnabledBreadcrumbTypes = new BreadcrumbType[] { BreadcrumbType.Log };
break;
case "InfLaunchDurationMark":
case "InfLaunchDuration":
config.LaunchDurationMillis = 0;
_closeTime = 8;
break;
case "LongLaunchDuration":
config.LaunchDurationMillis = 10000;
_closeTime = 12;
break;
case "ShortLaunchDuration":
config.LaunchDurationMillis = 1000;
_closeTime = 10;
break;
case "DisabledReleaseStage":
config.EnabledReleaseStages = new string[] { "test" };
config.ReleaseStage = "somevalue";
break;
case "EnabledReleaseStage":
config.EnabledReleaseStages = new string[] { "test" };
config.ReleaseStage = "test";
break;
case "RedactedKeys":
config.RedactedKeys = new string[] { "test", "password" };
break;
case "CustomAppType":
config.AppType = "test";
break;
case "DiscardErrorClass":
config.DiscardClasses = new string[] { "ExecutionEngineException" };
break;
case "EnableUnhandledExceptions":
config.EnabledErrorTypes = new EnabledErrorTypes()
{
ANRs = false,
AppHangs = false,
OOMs = false,
Crashes = false,
UnityLog = true
};
config.NotifyLogLevel = LogType.Exception;
break;
case "EnableLogLogs":
config.EnabledErrorTypes = new EnabledErrorTypes() {
ANRs = false,
AppHangs = false,
OOMs = false,
Crashes = false,
UnityLog = true
};
config.NotifyLogLevel = LogType.Log;
break;
case "DisableAllErrorTypes":
config.AutoDetectErrors = false;
config.NotifyLogLevel = LogType.Log;
break;
case "NewSession":
config.AutoTrackSessions = false;
break;
case "MaxBreadcrumbs":
config.MaximumBreadcrumbs = 5;
break;
case "DisableBreadcrumbs":
config.EnabledBreadcrumbTypes = new BreadcrumbType[0];
break;
case "OnlyLogBreadcrumbs":
config.EnabledBreadcrumbTypes = new BreadcrumbType[] { BreadcrumbType.Log };
config.BreadcrumbLogLevel = LogType.Log;
break;
case "LogExceptionOutsideNotifyReleaseStages":
config.ReleaseStage = "dev";
config.EnabledReleaseStages = new[] { "production" };
break;
case "NotifyOutsideNotifyReleaseStages":
config.ReleaseStage = "dev";
config.EnabledReleaseStages = new[] { "production" };
break;
case "NativeCrashOutsideNotifyReleaseStages":
config.ReleaseStage = "dev";
config.EnabledReleaseStages = new[] { "production" };
break;
case "UncaughtExceptionOutsideNotifyReleaseStages":
config.ReleaseStage = "dev";
config.EnabledReleaseStages = new[] { "production" };
break;
case "UncaughtExceptionAsUnhandled":
config.ReportExceptionLogsAsHandled = false;
break;
case "SetUserInConfigNativeCrash":
case "SetUserInConfigCsharpError":
config.SetUser("1","2","3");
break;
case "LogUnthrownAsUnhandled":
config.ReportExceptionLogsAsHandled = false;
break;
case "ReportLoggedWarning":
config.NotifyLogLevel = LogType.Warning;
config.EnabledErrorTypes.UnityLog = true;
break;
case "ReportLoggedError":
config.NotifyLogLevel = LogType.Warning;
config.EnabledErrorTypes.UnityLog = true;
break;
case "ReportLoggedWarningWithHandledConfig":
config.EnabledErrorTypes.UnityLog = true;
config.ReportExceptionLogsAsHandled = false;
config.NotifyLogLevel = LogType.Warning;
break;
case "ManualSessionCrash":
config.ReportExceptionLogsAsHandled = false;
break;
case "AutoSessionInNotifyReleaseStages":
config.ReleaseStage = "production";
config.EnabledReleaseStages = new[] { "production" };
break;
case "ManualSessionInNotifyReleaseStages":
config.ReleaseStage = "production";
config.EnabledReleaseStages = new[] { "production" };
break;
case "AutoSessionNotInNotifyReleaseStages":
config.EnabledReleaseStages = new[] { "no-op" };
break;
case "ManualSessionNotInNotifyReleaseStages":
config.EnabledReleaseStages = new[] { "no-op" };
break;
case "ManualSessionMixedEvents":
config.ReportExceptionLogsAsHandled = false;
config.NotifyLogLevel = LogType.Warning;
config.EnabledErrorTypes.UnityLog = true;
break;
case "UncaughtExceptionWithoutAutoNotify":
config.AutoDetectErrors = false;
break;
case "NotifyWithoutAutoNotify":
config.AutoDetectErrors = false;
break;
case "LoggedExceptionWithoutAutoNotify":
config.AutoDetectErrors = false;
config.ReportExceptionLogsAsHandled = false;
break;
case "NativeCrashWithoutAutoNotify":
config.AutoDetectErrors = false;
break;
case "NativeCrashReEnableAutoNotify":
config.AutoDetectErrors = false;
config.AutoDetectErrors = true;
break;
case "ReportLoggedWarningThreaded":
config.NotifyLogLevel = LogType.Warning;
config.EnabledErrorTypes.UnityLog = true;
break;
case "EventCallbacks":
config.AddOnError((@event)=> {
@event.App.BinaryArch = "BinaryArch";
@event.App.BundleVersion = "BundleVersion";
@event.App.CodeBundleId = "CodeBundleId";
@event.App.DsymUuid = "DsymUuid";
@event.App.Id = "Id";
@event.App.ReleaseStage = "ReleaseStage";
@event.App.Type = "Type";
@event.App.Version = "Version";
@event.App.InForeground = false;
@event.App.IsLaunching = false;
@event.Device.Id = "Id";
@event.Device.Jailbroken = true;
@event.Device.Locale = "Locale";
@event.Device.Manufacturer = "Manufacturer";
@event.Device.Model = "Model";
@event.Device.OsName = "OsName";
@event.Device.OsVersion = "OsVersion";
@event.Device.FreeDisk = 123;
@event.Device.FreeMemory = 123;
@event.Device.Orientation = "Orientation";
@event.Errors[0].ErrorClass = "ErrorClass";
@event.Errors[0].Stacktrace[0].Method = "Method";
foreach (var crumb in @event.Breadcrumbs)
{
crumb.Message = "Custom Message";
crumb.Type = BreadcrumbType.Request;
crumb.Metadata = new Dictionary<string, object> { {"test", "test" } };
}
@event.AddMetadata("test1", new Dictionary<string, object> { { "test", "test" } });
@event.AddMetadata("test2", new Dictionary<string, object> { { "test", "test" } });
@event.ClearMetadata("test2");
return true;
});
break;
default: // no special config required
break;
}
}
/**
* Runs the crashy code for a given scenario.
*/
void RunScenario(string scenario)
{
switch (scenario)
{
case "PersistDeviceId":
throw new Exception("PersistDeviceId");
case "FeatureFlagsAfterInitClearAll":
Bugsnag.AddFeatureFlag("testName1", "testVariant1");
Bugsnag.AddFeatureFlag("testName2", "testVariant1");
Bugsnag.AddFeatureFlag("testName2", "testVariant2");
Bugsnag.ClearFeatureFlags();
throw new Exception("FeatureFlags");
case "FeatureFlagsInCallback":
case "FeatureFlagsConfigClearAll":
case "FeatureFlagsInConfig":
case "ClearFeatureFlagsInCallback":
throw new Exception("FeatureFlags");
case "FeatureFlagsAfterInit":
Bugsnag.AddFeatureFlag("testName1", "testVariant1");
Bugsnag.AddFeatureFlag("testName2", "testVariant1");
Bugsnag.AddFeatureFlag("testName2", "testVariant2");
Bugsnag.ClearFeatureFlag("testName1");
throw new Exception("FeatureFlags");
case "SetUserAfterInitCsharpError":
Bugsnag.SetUser("1","2","3");
Bugsnag.Notify(new Exception("SetUserAfterInitCsharpError"));
break;
case "SetUserAfterInitNativeError":
Bugsnag.SetUser("1", "2", "3");
MacOSNativeCrash();
break;
case "LongLaunchDuration":
case "ShortLaunchDuration":
Invoke("LaunchException", 6);
break;
case "InfLaunchDurationMark":
Bugsnag.MarkLaunchCompleted();
throw new Exception("InfLaunchDurationMark");
break;
case "InfLaunchDuration":
Invoke("LaunchException",6);
break;
case "EventCallbacks":
DoNotify();
break;
case "BackgroundThreadCrash":
BackgroundThreadCrash();
break;
case "NotifyWithStrings":
NotifyWithStrings();
break;
case "CustomStacktrace":
CustomStacktrace();
break;
case "DisabledReleaseStage":
case "EnabledReleaseStage":
DoNotify();
break;
case "CustomAppType":
DoNotify();
break;
case "DiscardErrorClass":
DoUnhandledException(0);
break;
case "EnableUnhandledExceptions":
Debug.Log("LogLog");
Debug.LogException(new Exception("LogException"));
break;
case "EnableLogLogs":
Debug.Log("EnableLogLogs");
break;
case "DisableAllErrorTypes":
CheckDisabledErrorTypes();
break;
case "MaxBreadcrumbs":
LeaveBreadcrumbs();
DoUnhandledException(0);
break;
case "OnlyLogBreadcrumbs":
Debug.Log("Log");
DoUnhandledException(0);
break;
case "DisableBreadcrumbs":
DoUnhandledException(0);
break;
case "LogExceptionOutsideNotifyReleaseStages":
DoLogUnthrown();
break;
case "NotifyOutsideNotifyReleaseStages":
DoNotify();
break;
case "RedactedKeys":
AddKeysForRedaction();
DoNotify();
break;
case "NativeCrashOutsideNotifyReleaseStages":
MacOSNativeCrash();
break;
case "UncaughtExceptionOutsideNotifyReleaseStages":
DoUnhandledException(0);
break;
case "DebugLogBreadcrumbNotify":
LogLowLevelMessageAndNotify();
break;
case "ComplexBreadcrumbNotify":
LeaveComplexBreadcrumbAndNotify();
break;
case "DoubleNotify":
NotifyTwice();
break;
case "MessageBreadcrumbNotify":
LeaveMessageBreadcrumbAndNotify();
break;
case "Notify":
DoNotify();
break;
case "NotifyBackground":
new System.Threading.Thread(() => DoNotify()).Start();
break;
case "NotifyCallback":
DoNotifyWithCallback();
break;
case "NotifySeverity":
DoNotifyWithSeverity();
break;
case "LogUnthrown":
DoLogUnthrown();
break;
case "SetUserInConfigCsharpError":
case "UncaughtException":
DoUnhandledException(0);
break;
case "AssertionFailure":
MakeAssertionFailure(4);
break;
case "UncaughtExceptionAsUnhandled":
ThrowException();
break;
case "LogUnthrownAsUnhandled":
DebugLogException();
break;
case "ReportLoggedWarningThreaded":
new System.Threading.Thread(() => DoLogWarning()).Start();
break;
case "ReportLoggedWarning":
DoLogWarning();
break;
case "ReportLoggedError":
DoLogError();
break;
case "ReportLoggedWarningWithHandledConfig":
DoLogWarningWithHandledConfig();
break;
case "ManualSession":
Bugsnag.StartSession();
break;
case "ManualSessionCrash":
Bugsnag.StartSession();
ThrowException();
break;
case "ManualSessionNotify":
Bugsnag.StartSession();
DoNotify();
break;
case "AutoSessionInNotifyReleaseStages":
break;
case "ManualSessionInNotifyReleaseStages":
Bugsnag.StartSession();
break;
case "AutoSessionNotInNotifyReleaseStages":
break;
case "ManualSessionNotInNotifyReleaseStages":
Bugsnag.StartSession();
break;
case "ManualSessionMixedEvents":
Bugsnag.StartSession();
DoNotify();
DoLogWarning();
ThrowException();
break;
case "StoppedSession":
Bugsnag.StartSession();
Bugsnag.PauseSession();
DoNotify();
break;
case "ResumedSession":
RunResumedSession();
break;
case "NewSession":
RunNewSession();
break;
case "SetUserInConfigNativeCrash":
case "NativeCrash":
MacOSNativeCrash();
break;
case "UncaughtExceptionWithoutAutoNotify":
DoUnhandledException(0);
break;
case "NotifyWithoutAutoNotify":
DoNotify();
break;
case "LoggedExceptionWithoutAutoNotify":
DebugLogException();
break;
case "NativeCrashWithoutAutoNotify":
MacOSNativeCrash();
break;
case "NativeCrashReEnableAutoNotify":
MacOSNativeCrash();
break;
case "CheckForManualContextAfterSceneLoad":
StartCoroutine(SetManualContextReloadSceneAndNotify());
break;
case "AutoSessionNativeCrash":
new Thread(() =>
{
Thread.Sleep(900);
MacOSNativeCrash();
}).Start();
break;
case "AutoSession":
break;
case "DisableErrorBreadcrumbs":
DisableErrorBreadcrumbs();
break;
case "PersistEvent":
throw new Exception("First Event");
case "PersistEventReport":
case "PersistEventReportCallback":
throw new Exception("Second Event");
case "ClearBugsnagCache":
ClearBugsnagCache();
break;
case "PersistSession":
case "PersistSessionReport":
case "(noop)":
break;
default:
throw new ArgumentException("Unable to run unexpected scenario: " + scenario);
break;
}
}
private void ClearBugsnagCache()
{
var path = Application.persistentDataPath + "/Bugsnag";
if(Directory.Exists(path))
{
Directory.Delete(path, true);
}
}
private void DisableErrorBreadcrumbs()
{
Debug.Log("1");
Bugsnag.Notify(new Exception("1"));
Debug.Log("2");
Bugsnag.Notify(new Exception("2"));
}
private void BackgroundThreadCrash()
{
var bgThread = new Thread(()=> { Debug.LogException(new System.Exception("Background Thread Crash"));})
{
IsBackground = true
};
bgThread.Start();
}
private void AddKeysForRedaction()
{
Bugsnag.AddMetadata("User", new Dictionary<string, object>() {
{"test","test" },
{ "password","password" }
});
}
private void NotifyWithStrings()
{
Bugsnag.Notify("CUSTOM","CUSTOM", _fakeTrace);
}
private void CustomStacktrace()
{
Bugsnag.Notify(new System.Exception("CUSTOM"), _fakeTrace);
}
private void CheckEnabledErrorTypes()
{
Debug.Log("LogLog");
Debug.LogWarning("LogWarning");
Debug.LogError("LogError");
throw new System.Exception("Exception");
}
private void CheckDisabledErrorTypes()
{
Debug.Log("LogLog");
Debug.LogWarning("LogWarning");
Debug.LogError("LogError");
Bugsnag.Notify(new System.Exception("Notify"));
throw new System.Exception("Exception");
}
private void LeaveBreadcrumbs()
{
for (int i = 0; i < 6; i++)
{
Bugsnag.LeaveBreadcrumb("Crumb " + i);
}
}
void RunResumedSession()
{
// send 1st exception which should include session info
Bugsnag.StartSession();
Bugsnag.Notify(new System.Exception("First Error"));
// send 2nd exception after resuming a session
Bugsnag.PauseSession();
Bugsnag.ResumeSession();
Bugsnag.Notify(new System.Exception("Second Error"));
}
void RunNewSession()
{
StartCoroutine(DoRunNewSession());
}
private IEnumerator DoRunNewSession()
{
// send 1st exception which should include session info
Bugsnag.StartSession();
Bugsnag.Notify(new System.Exception("First Error"));
// stop tracking the existing session
Bugsnag.PauseSession();
yield return new WaitForSeconds(1);
Bugsnag.StartSession();
// send 2nd exception which should contain new session info
Bugsnag.Notify(new System.Exception("Second Error"));
}
void ThrowException()
{
throw new ExecutionEngineException("Invariant state failure");
}
void DoLogWarning()
{
Debug.LogWarning("Something went terribly awry");
}
void DoLogError()
{
Debug.LogError("Bad bad things");
}
void DoLogWarningWithHandledConfig()
{
Debug.LogWarning("Something went terribly awry");
}
void LeaveComplexBreadcrumbAndNotify()
{
Bugsnag.LeaveBreadcrumb("Reload", new Dictionary<string, object>() {
{ "preload", "launch" }
}, BreadcrumbType.Navigation);
Bugsnag.Notify(new System.Exception("Collective failure"));
}
void NotifyTwice()
{
StartCoroutine(NotifyTwiceCoroutine());
}
IEnumerator NotifyTwiceCoroutine()
{
Bugsnag.Notify(new System.Exception("Rollback failed"));
yield return new WaitForSeconds(1);
Bugsnag.Notify(new ExecutionEngineException("Invalid runtime"));
}
IEnumerator SetManualContextReloadSceneAndNotify()
{
Bugsnag.Context = "Manually-Set";
SceneManager.LoadScene(1,LoadSceneMode.Additive);
yield return new WaitForSeconds(0.5f);
Bugsnag.Notify(new System.Exception("ManualContext"));
}
void LeaveMessageBreadcrumbAndNotify()
{
Bugsnag.LeaveBreadcrumb("Initialize bumpers");
Bugsnag.Notify(new System.Exception("Collective failure"));
}
void LogLowLevelMessageAndNotify()
{
Debug.LogWarning("Failed to validate credentials");
Bugsnag.Notify(new ExecutionEngineException("Invalid runtime"));
}
void DoNotifyWithCallback()
{
Bugsnag.Notify(new System.Exception("blorb"), @event =>
{
@event.Errors[0].ErrorClass = "FunnyBusiness";
@event.Errors[0].ErrorMessage = "cake";
@event.AddMetadata("shape", new Dictionary<string, object>() {
{ "arc", "yes" },
});
return true;
});
}
void DoNotifyWithSeverity()
{
Bugsnag.Notify(new System.Exception("blorb"), Severity.Info);
}
void DoNotify()
{
Bugsnag.Notify(new System.Exception("blorb"));
}
void DebugLogException()
{
Debug.LogException(new System.Exception("WAT"));
}
void DoLogUnthrown()
{
Debug.LogException(new System.Exception("auth failed!"));
}
void LaunchException()
{
throw new Exception("Launch");
}
void DoUnhandledException(long counter)
{
var items = new int[] { 1, 2, 3 };
Debug.Log("Item #1 is: " + items[counter]);
throw new ExecutionEngineException("Promise Rejection");
}
void MakeAssertionFailure(int counter)
{
var items = new int[] { 1, 2, 3 };
Debug.Log("Item4 is: " + items[counter]);
}
/*** Determine runtime versions ***/
private static string FindScriptingBackend()
{
#if ENABLE_MONO
return "Mono";
#elif ENABLE_IL2CPP
return "IL2CPP";
#else
return "Unknown";
#endif
}
private static string FindDotnetScriptingRuntime()
{
#if NET_4_6
return ".NET 4.6 equivalent";
#else
return ".NET 3.5 equivalent";
#endif
}
private static string FindDotnetApiCompatibility()
{
#if NET_2_0_SUBSET
return ".NET 2.0 Subset";
#else
return ".NET 2.0";
#endif
}
private void MacOSNativeCrash()
{
#if UNITY_STANDALONE_OSX
crashy_signal_runner(8);
#endif
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_1_2_3 : EcmaTest
{
[Fact]
[Trait("Category", "15.1.2.3")]
public void ParesefloatTrimmedstringIsTheEmptyStringWhenInputstringDoesNotContainAnySuchCharacters()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/15.1.2.3-2-1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring2()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T2.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring3()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T3.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring4()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T4.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring5()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T5.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring6()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T6.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorUseTostring7()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A1_T7.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar2()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T10.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar3()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar4()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T3.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar5()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T4.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar6()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T5.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar7()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T6.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar8()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T7.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar9()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T8.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void OperatorRemoveLeadingStrwhitespacechar10()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T9.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void IfNeitherResult2NorAnyPrefixOfResult2SatisfiesTheSyntaxOfAStrdecimalliteralSee931ReturnNan()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A3_T1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void IfNeitherResult2NorAnyPrefixOfResult2SatisfiesTheSyntaxOfAStrdecimalliteralSee931ReturnNan2()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A3_T2.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void IfNeitherResult2NorAnyPrefixOfResult2SatisfiesTheSyntaxOfAStrdecimalliteralSee931ReturnNan3()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A3_T3.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral2()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T2.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral3()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T3.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral4()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T4.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral5()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T5.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral6()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T6.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ComputeTheLongestPrefixOfResult2WhichMightBeResult2ItselfWhichSatisfiesTheSyntaxOfAStrdecimalliteral7()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A4_T7.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ReturnTheNumberValueForTheMvOfResult4()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A5_T1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ReturnTheNumberValueForTheMvOfResult42()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A5_T2.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ReturnTheNumberValueForTheMvOfResult43()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A5_T3.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ReturnTheNumberValueForTheMvOfResult44()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A5_T4.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void ParsefloatMayInterpretOnlyALeadingPortionOfTheStringAsANumberValueItIgnoresAnyCharactersThatCannotBeInterpretedAsPartOfTheNotationOfAnDecimalLiteralAndNoIndicationIsGivenThatAnySuchCharactersWereIgnored()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A6.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheLengthPropertyOfParsefloatHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.1.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheLengthPropertyOfParsefloatHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.2.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheLengthPropertyOfParsefloatHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.3.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheLengthPropertyOfParsefloatIs1()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.4.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheParsefloatPropertyHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.5.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheParsefloatPropertyHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.6.js", false);
}
[Fact]
[Trait("Category", "15.1.2.3")]
public void TheParsefloatPropertyCanTBeUsedAsConstructor()
{
RunTest(@"TestCases/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.7.js", false);
}
}
}
| |
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Abp.Collections.Extensions;
namespace Abp.Extensions
{
/// <summary>
/// Extension methods for String class.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c)
{
return EnsureEndsWith(str, c, StringComparison.Ordinal);
}
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (str.EndsWith(c.ToString(), comparisonType))
{
return str;
}
return str + c;
}
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (str.EndsWith(c.ToString(culture), ignoreCase, culture))
{
return str;
}
return str + c;
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c)
{
return EnsureStartsWith(str, c, StringComparison.Ordinal);
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (str.StartsWith(c.ToString(), comparisonType))
{
return str;
}
return c + str;
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.StartsWith(c.ToString(culture), ignoreCase, culture))
{
return str;
}
return c + str;
}
/// <summary>
/// Indicates whether this string is null or an System.String.Empty string.
/// </summary>
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
/// <summary>
/// indicates whether this string is null, empty, or consists only of white-space characters.
/// </summary>
public static bool IsNullOrWhiteSpace(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
/// <summary>
/// Gets a substring of a string from beginning of the string.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
public static string Left(this string str, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < len)
{
throw new ArgumentException("len argument can not be bigger than given string's length!");
}
return str.Substring(0, len);
}
/// <summary>
/// Converts line endings in the string to <see cref="Environment.NewLine"/>.
/// </summary>
public static string NormalizeLineEndings(this string str)
{
return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine);
}
/// <summary>
/// Gets index of nth occurence of a char in a string.
/// </summary>
/// <param name="str">source string to be searched</param>
/// <param name="c">Char to search in <see cref="str"/></param>
/// <param name="n">Count of the occurence</param>
public static int NthIndexOf(this string str, char c, int n)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
var count = 0;
for (var i = 0; i < str.Length; i++)
{
if (str[i] != c)
{
continue;
}
if ((++count) == n)
{
return i;
}
}
return -1;
}
/// <summary>
/// Removes first occurrence of the given postfixes from end of the given string.
/// Ordering is important. If one of the postFixes is matched, others will not be tested.
/// </summary>
/// <param name="str">The string.</param>
/// <param name="postFixes">one or more postfix.</param>
/// <returns>Modified string or the same string if it has not any of given postfixes</returns>
public static string RemovePostFix(this string str, params string[] postFixes)
{
if (str == null)
{
return null;
}
if (str == string.Empty)
{
return string.Empty;
}
if (postFixes.IsNullOrEmpty())
{
return str;
}
foreach (var postFix in postFixes)
{
if (str.EndsWith(postFix))
{
return str.Left(str.Length - postFix.Length);
}
}
return str;
}
/// <summary>
/// Removes first occurrence of the given prefixes from beginning of the given string.
/// Ordering is important. If one of the preFixes is matched, others will not be tested.
/// </summary>
/// <param name="str">The string.</param>
/// <param name="preFixes">one or more prefix.</param>
/// <returns>Modified string or the same string if it has not any of given prefixes</returns>
public static string RemovePreFix(this string str, params string[] preFixes)
{
if (str == null)
{
return null;
}
if (str == string.Empty)
{
return string.Empty;
}
if (preFixes.IsNullOrEmpty())
{
return str;
}
foreach (var preFix in preFixes)
{
if (str.StartsWith(preFix))
{
return str.Right(str.Length - preFix.Length);
}
}
return str;
}
/// <summary>
/// Gets a substring of a string from end of the string.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
public static string Right(this string str, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < len)
{
throw new ArgumentException("len argument can not be bigger than given string's length!");
}
return str.Substring(str.Length - len, len);
}
/// <summary>
/// Uses string.Split method to split given string by given separator.
/// </summary>
public static string[] Split(this string str, string separator)
{
return str.Split(new[] { separator }, StringSplitOptions.None);
}
/// <summary>
/// Uses string.Split method to split given string by given separator.
/// </summary>
public static string[] Split(this string str, string separator, StringSplitOptions options)
{
return str.Split(new[] { separator }, options);
}
/// <summary>
/// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
/// </summary>
public static string[] SplitToLines(this string str)
{
return str.Split(Environment.NewLine);
}
/// <summary>
/// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
/// </summary>
public static string[] SplitToLines(this string str, StringSplitOptions options)
{
return str.Split(Environment.NewLine, options);
}
/// <summary>
/// Converts PascalCase string to camelCase string.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="invariantCulture">Invariant culture</param>
/// <returns>camelCase of the string</returns>
public static string ToCamelCase(this string str, bool invariantCulture = true)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return invariantCulture ? str.ToLowerInvariant() : str.ToLower();
}
return (invariantCulture ? char.ToLowerInvariant(str[0]) : char.ToLower(str[0])) + str.Substring(1);
}
/// <summary>
/// Converts PascalCase string to camelCase string in specified culture.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="culture">An object that supplies culture-specific casing rules</param>
/// <returns>camelCase of the string</returns>
public static string ToCamelCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToLower(culture);
}
return char.ToLower(str[0], culture) + str.Substring(1);
}
/// <summary>
/// Converts given PascalCase/camelCase string to sentence (by splitting words by space).
/// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence".
/// </summary>
/// <param name="str">String to convert.</param>
/// <param name="invariantCulture">Invariant culture</param>
public static string ToSentenceCase(this string str, bool invariantCulture = false)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
return Regex.Replace(
str,
"[a-z][A-Z]",
m => m.Value[0] + " " + (invariantCulture ? char.ToLowerInvariant(m.Value[1]) : char.ToLower(m.Value[1]))
);
}
/// <summary>
/// Converts given PascalCase/camelCase string to sentence (by splitting words by space).
/// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence".
/// </summary>
/// <param name="str">String to convert.</param>
/// <param name="culture">An object that supplies culture-specific casing rules.</param>
public static string ToSentenceCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1], culture));
}
/// <summary>
/// Converts string to enum value.
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">String value to convert</param>
/// <returns>Returns enum object</returns>
public static T ToEnum<T>(this string value)
where T : struct
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return (T)Enum.Parse(typeof(T), value);
}
/// <summary>
/// Converts string to enum value.
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">String value to convert</param>
/// <param name="ignoreCase">Ignore case</param>
/// <returns>Returns enum object</returns>
public static T ToEnum<T>(this string value, bool ignoreCase)
where T : struct
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return (T)Enum.Parse(typeof(T), value, ignoreCase);
}
public static string ToMd5(this string str)
{
using (var md5 = MD5.Create())
{
var inputBytes = Encoding.UTF8.GetBytes(str);
var hashBytes = md5.ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var hashByte in hashBytes)
{
sb.Append(hashByte.ToString("X2"));
}
return sb.ToString();
}
}
/// <summary>
/// Converts camelCase string to PascalCase string.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="invariantCulture">Invariant culture</param>
/// <returns>PascalCase of the string</returns>
public static string ToPascalCase(this string str, bool invariantCulture = true)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return invariantCulture ? str.ToUpperInvariant(): str.ToUpper();
}
return (invariantCulture ? char.ToUpperInvariant(str[0]) : char.ToUpper(str[0])) + str.Substring(1);
}
/// <summary>
/// Converts camelCase string to PascalCase string in specified culture.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="culture">An object that supplies culture-specific casing rules</param>
/// <returns>PascalCase of the string</returns>
public static string ToPascalCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToUpper(culture);
}
return char.ToUpper(str[0], culture) + str.Substring(1);
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string Truncate(this string str, int maxLength)
{
if (str == null)
{
return null;
}
if (str.Length <= maxLength)
{
return str;
}
return str.Left(maxLength);
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// It adds a "..." postfix to end of the string if it's truncated.
/// Returning string can not be longer than maxLength.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string TruncateWithPostfix(this string str, int maxLength)
{
return TruncateWithPostfix(str, maxLength, "...");
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// It adds given <paramref name="postfix"/> to end of the string if it's truncated.
/// Returning string can not be longer than maxLength.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string TruncateWithPostfix(this string str, int maxLength, string postfix)
{
if (str == null)
{
return null;
}
if (str == string.Empty || maxLength == 0)
{
return string.Empty;
}
if (str.Length <= maxLength)
{
return str;
}
if (maxLength <= postfix.Length)
{
return postfix.Left(maxLength);
}
return str.Left(maxLength - postfix.Length) + postfix;
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H01_ContinentColl (editable root list).<br/>
/// This is a generated base class of <see cref="H01_ContinentColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="H02_Continent"/> objects.
/// </remarks>
[Serializable]
public partial class H01_ContinentColl : BusinessListBase<H01_ContinentColl, H02_Continent>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="H02_Continent"/> item from the collection.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to be removed.</param>
public void Remove(int continent_ID)
{
foreach (var h02_Continent in this)
{
if (h02_Continent.Continent_ID == continent_ID)
{
Remove(h02_Continent);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="H02_Continent"/> item is in the collection.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to search for.</param>
/// <returns><c>true</c> if the H02_Continent is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int continent_ID)
{
foreach (var h02_Continent in this)
{
if (h02_Continent.Continent_ID == continent_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="H02_Continent"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to search for.</param>
/// <returns><c>true</c> if the H02_Continent is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int continent_ID)
{
foreach (var h02_Continent in DeletedList)
{
if (h02_Continent.Continent_ID == continent_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="H02_Continent"/> item of the <see cref="H01_ContinentColl"/> collection, based on a given Continent_ID.
/// </summary>
/// <param name="continent_ID">The Continent_ID.</param>
/// <returns>A <see cref="H02_Continent"/> object.</returns>
public H02_Continent FindH02_ContinentByContinent_ID(int continent_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Continent_ID.Equals(continent_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H01_ContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="H01_ContinentColl"/> collection.</returns>
public static H01_ContinentColl NewH01_ContinentColl()
{
return DataPortal.Create<H01_ContinentColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="H01_ContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="H01_ContinentColl"/> collection.</returns>
public static H01_ContinentColl GetH01_ContinentColl()
{
return DataPortal.Fetch<H01_ContinentColl>();
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H01_ContinentColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H01_ContinentColl()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="H01_ContinentColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IH01_ContinentCollDal>();
var data = dal.Fetch();
LoadCollection(data);
}
OnFetchPost(args);
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="H01_ContinentColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(H02_Continent.GetH02_Continent(dr));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H01_ContinentColl"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
base.Child_Update();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
public abstract class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
private bool _isReadOnly = false;
// The minimum supported DateTime range for the calendar.
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
string.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
using System;
using Google.GData.Analytics;
using NUnit.Framework;
namespace Google.GData.Client.UnitTests.Analytics
{
/// <summary>
///This is a test class for DataQueryTest and is intended
///to contain all DataQueryTest Unit Tests
///</summary>
[TestFixture, Category("Analytics")]
public class DataQueryTest
{
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
/// <summary>
/// A test for calculating the query by setting the paramaters
/// Parse complete query URL and check the results
///</summary>
[Test]
public void CalculateQueryTest()
{
const string baseUrlExpected = "http://test.com/";
const string dimensionExpected = "ga:productCategory,ga:productName";
const string metricExpected = "ga:itemRevenue,ga:itemQuantity";
const string idsExpected = "ga:1234";
const string filtersExpected = "ga:country%3D%3DCanada";
const string sortExpected = "ga:productCategory";
const string startDateExpected = "2009-04-1";
const string endDateExpected = "2009-04-25";
DataQuery target = new DataQuery();
target.BaseAddress = baseUrlExpected;
target.Dimensions = dimensionExpected;
target.Metrics = metricExpected;
target.Ids = idsExpected;
target.Filters = filtersExpected;
target.Sort = sortExpected;
target.GAStartDate = startDateExpected;
target.GAEndDate = endDateExpected;
Uri expectedResult =
new Uri(
string.Format(
"http://test.com?dimensions={0}&end-date={1}&filters={2}&ids={3}&metrics={4}&sort={5}&start-date={6}",
Utilities.UriEncodeReserved(dimensionExpected), Utilities.UriEncodeReserved(endDateExpected),
Utilities.UriEncodeReserved(filtersExpected), Utilities.UriEncodeReserved(idsExpected),
Utilities.UriEncodeReserved(metricExpected), Utilities.UriEncodeReserved(sortExpected),
Utilities.UriEncodeReserved(startDateExpected)));
Assert.AreEqual(expectedResult.AbsoluteUri, target.Uri.AbsoluteUri);
}
/// <summary>
///A test for DataQuery Constructor
///</summary>
[Test]
public void DataQueryConstructorTest1()
{
DataQuery target = new DataQuery();
Assert.IsNotNull(target);
}
/// <summary>
///A test for Dimensions parsing
///</summary>
[Test]
public void DimensionParseTest()
{
const string expected = "ga:productCategory,ga:productName";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?dimensions=" + expected);
string actual = target.Dimensions;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Dimensions property
///</summary>
[Test]
public void DimensionPropertyTest()
{
DataQuery target = new DataQuery();
const string expected = "ga:productCategory,ga:productName";
target.Dimensions = expected;
string actual = target.Dimensions;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Dynamic Advanced-Segment parsing
///</summary>
[Test]
public void DynamicSegmentParseTest()
{
const string expected = "dynamic::ga:country%3D%3DCanada";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?segment=" + expected);
string actual = target.Segment;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for EndDate
///</summary>
[Test]
public void EndDateTest()
{
DataQuery target = new DataQuery();
DateTime expected = DateTime.Now;
DateTime actual;
target.EndDate = expected;
actual = target.EndDate;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for ExtraParameters
///</summary>
[Test]
public void ExtraParametersTest()
{
DataQuery target = new DataQuery();
string expected = "TestValue";
string actual;
target.ExtraParameters = expected;
actual = target.ExtraParameters;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for DataQuery Constructor
///</summary>
[Test]
public void FeedQueryConstructorTest()
{
const string baseUri = "http://www.test.com/";
DataQuery target = new DataQuery(baseUri);
Assert.AreEqual(target.Uri, new Uri(baseUri));
}
/// <summary>
///A test for Filters parsing
///</summary>
[Test]
public void FiltersParseTest()
{
const string expected = "ga:country%3D%3DCanada";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?filters=" + expected);
string actual = target.Filters;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for GAEndDate parsing
///</summary>
[Test]
public void GAEndDateParseTest()
{
const string expected = "2009-04-25";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?end-date=" + expected);
string actual = target.GAEndDate;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for GAStartDate parsing
///</summary>
[Test]
public void GAStartDateParseTest()
{
const string expected = "2009-04-1";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?start-date=" + expected);
string actual = target.GAStartDate;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Ids parsing
///</summary>
[Test]
public void IdsParseTest()
{
const string expected = "ga:1234";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?ids=" + expected);
string actual = target.Ids;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Indexed Advanced-Segment parsing (Advanced Segments saved via web interface)
///</summary>
[Test]
public void IndexedSegmentParseTest()
{
const string expected = "gaid::-2";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?segment=" + expected);
string actual = target.Segment;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Metric parsing
///</summary>
[Test]
public void MetricParseTest()
{
const string expected = "ga:itemRevenue,ga:itemQuantity";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?metrics=" + expected);
string actual = target.Metrics;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for NumberToRetrieve
///</summary>
[Test]
public void NumberToRetrieveTest()
{
DataQuery target = new DataQuery();
int expected = 12;
int actual;
target.NumberToRetrieve = expected;
actual = target.NumberToRetrieve;
Assert.AreEqual(expected, actual);
}
/// <summary>
/// A test for parsing of a complete query
/// Parse complete query URL and check the results
///</summary>
[Test]
public void ParseTest()
{
const string dimensionExpected = "ga:productCategory,ga:productName";
const string metricExpected = "ga:itemRevenue,ga:itemQuantity";
const string idsExpected = "ga:1234";
const string filtersExpected = "ga:country%3D%3DCanada";
const string sortExpected = "ga:productCategory";
const string startDateExpected = "2009-04-1";
const string endDateExpected = "2009-04-25";
DataQuery target = new DataQuery();
target.Uri =
new Uri(
string.Format(
"http://test.com?ids={0}&dimensions={1}&metrics={2}&filters={3}&sort={4}&start-date={5}&end-date={6}",
idsExpected, dimensionExpected, metricExpected, filtersExpected, sortExpected, startDateExpected,
endDateExpected));
Assert.AreEqual("http://test.com/", target.BaseAddress);
Assert.AreEqual(dimensionExpected, target.Dimensions);
Assert.AreEqual(metricExpected, target.Metrics);
Assert.AreEqual(idsExpected, target.Ids);
Assert.AreEqual(filtersExpected, target.Filters);
Assert.AreEqual(sortExpected, target.Sort);
Assert.AreEqual(startDateExpected, target.GAStartDate);
Assert.AreEqual(endDateExpected, target.GAEndDate);
}
/// <summary>
///A test for Query
///</summary>
[Test]
public void QueryTest()
{
DataQuery target = new DataQuery();
string expected = "TestValue";
string actual;
target.Query = expected;
actual = target.Query;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Sort parsing
///</summary>
[Test]
public void SortParseTest()
{
const string expected = "ga:productCategory";
DataQuery target = new DataQuery();
//Force expected to be parsed
target.Uri = new Uri("http://test.com?sort=" + expected);
string actual = target.Sort;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for StartDate
///</summary>
[Test]
public void StartDateTest()
{
DataQuery target = new DataQuery();
DateTime expected = DateTime.Now;
DateTime actual;
target.StartDate = expected;
actual = target.StartDate;
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Uri
///</summary>
[Test]
public void UriTest()
{
DataQuery target = new DataQuery();
Uri expected = new Uri("http://www.test.com/");
Uri actual;
target.Uri = expected;
actual = target.Uri;
Assert.AreEqual(expected, actual);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using UOCApp.Helpers;
using UOCApp;
using UOCApp.Models;
using Xamarin.Forms;
namespace UOCApp
{
public partial class EntryPage : ContentPage
{
public ObstaclesPage obstaclesPage;
public EntryPage(string displayTime)
{
obstaclesPage = new ObstaclesPage();
InitializeComponent();
entry_Time.Text = displayTime;
}
private void NavHome(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Home");
Navigation.PopToRootAsync();
}
private void NavAbout(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Home");
Navigation.PushAsync(new AboutPage());
}
private void NavLeaderboard(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Leaderboard");
Navigation.PushAsync(new LeaderboardPage());
}
private void NavTimes(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Times");
Navigation.PushAsync(new TimesPage());
}
private void NavAdmin(object sender, EventArgs args)
{
//Console.WriteLine("Clicked Nav Admin");
Navigation.PushAsync(new AdminPage());
}
async void NavObstacle(object sender, EventArgs args)
{
//Console.WriteLine("Clicked Obstacles");
await Navigation.PushModalAsync(obstaclesPage);
}
private async void SaveResult(object sender, EventArgs args) //for debug
{
//Console.WriteLine("Clicked Save Result");
try
{
SharedResult sharedResult = new SharedResult(picker_Date.Date, ConvertTime(entry_Time.Text), false, false,
entry_Name.Text, Gender(), Grade(), entry_School.Text);
Result result = new Result();
result.result_id = null;
result.date = String.Format("{0:yyyy-MM-dd}", picker_Date.Date);
result.time = ConvertTime(entry_Time.Text);
result.shared = Convert.ToInt32(switch_Public.IsToggled);
result.student_name = entry_Name.Text;
result.student_gender = Gender();
result.student_grade = Grade();
var sure = await DisplayAlert("Confirm Save", "Please record accurate race times! \n \"Winners Don't Cheat, \n Champions Don't Lie!\"\n", "Save", "Back");
if (sure == true)
{
//selected obstacles can be obtained from obstaclesPage.obstacleList
// save to client database, unless in admin mode - TODO
var LocalID = App.databaseHelper.InsertResult(result, obstaclesPage.obstacleList);
if (LocalID >= 1) // verify local insertion success by primary key
{
if (switch_Public.IsToggled)
{ // did the user specify that they wish to post to the leaderboard?
if (!obstaclesPage.obstacleList.allComplete())//added dilibrate check to obstacle list due to known android bug
{
await DisplayAlert("Thank you!", "Your result has been saved", "OK");
await Navigation.PopToRootAsync(); // return to home once save complete
return;
}
if (await sharedResult.share((bool)switch_Official.IsToggled)) // post to server and return true if successful
{
await DisplayAlert("Thank you!", "Your result has been saved and shared with the leaderboard", "OK");
await Navigation.PopToRootAsync(); // return to home once save complete
return;
}
else
{
//Console.WriteLine ("Failed to share with leaderboard");
await DisplayAlert("Sorry", "Unable to connect to leaderboard. \n Check your internet connection.", "OK");
return;
}
}
await DisplayAlert("Thank you!", "Your result has been saved", "OK");
await Navigation.PopToRootAsync(); // return to home once save complete
return;
}
else
{
// fail to save locally
await DisplayAlert("Sorry", "Unable to save. \n Please try again", "OK");
return;
//Console.WriteLine ("Failed to save result");
}
}
else
{
//abort save, do nothing
return;
}
}
catch (ArgumentException e)
{ // fail to create a result instance, bad parameters
await DisplayAlert("Error", e.Message, "OK");
return;
//Console.WriteLine (e);
}
}
private String Gender()
{
// read the gender picker and assign values
var Gender = "";
var GenderIndex = picker_Gender.SelectedIndex;
switch (GenderIndex)
{
case 0:
Gender = "M";
break;
case 1:
Gender = "F";
break;
default:
// error behavior? no gender set, shouldn't be possible
Gender = null;
break;
}
return Gender;
}
private int Grade()
{
// read the grade picker and assign values
var Grade = 0;
var GradeIndex = picker_Grade.SelectedIndex;
switch (GradeIndex)
{
case 0:
Grade = -4;
break;
case 1:
Grade = 1;
break;
case 2:
Grade = 2;
break;
case 3:
Grade = 3;
break;
case 4:
Grade = 4;
break;
case 5:
Grade = 5;
break;
case 6:
Grade = 6;
break;
case 7:
Grade = 7;
break;
case 8: // GRADE_TEENAGER = -1
Grade = -1;
break;
case 9: // GRADE_ADULT = -2
Grade = -2;
break;
case 10: // GRADE_OLDADULT = -3
Grade = -3;
break;
default:
// error behavior? no grade set
break;
}
return Grade;
}
static decimal ConvertTime(string time)
{
try {
decimal result;
if (String.IsNullOrEmpty(time))
{
return 0;
}
if (time.Contains(':'))
{
//it's in mm:ss.iii format
int sepPos = time.IndexOf(':');
string minPart = time.Substring(0, sepPos);
string secPart = time.Substring(sepPos + 1);
result = (Convert.ToInt32(minPart) * 60) + Convert.ToDecimal(secPart);
}
else
{
//it's in ss.iii format so we can just convert it
result = Convert.ToDecimal(time);
}
return Decimal.Round(result, 3);
}
catch (FormatException)
{
throw new ArgumentException("Invalid Time\n Minimum 30 seconds\n Please enter as Minutes:Seconds");
}
}
public void ShareButtonStatus()
{
if (obstaclesPage.obstacleList.allComplete())
{
switch_Public.IsEnabled = true;
switch_Public.IsToggled = true;
label_obstacle.Opacity = 0;
}
else
{
switch_Public.IsToggled = false;
switch_Public.IsEnabled = false;
label_obstacle.Opacity = 1;
switch_Official.IsToggled = false;
}
}
public void OfficialButtonStatus()
{
bool loggedIn = false;
if (Application.Current.Properties.ContainsKey("loggedin"))
{
loggedIn = Convert.ToBoolean(Application.Current.Properties["loggedin"]);
}
if (loggedIn)
{
switch_Official.IsToggled = true;
switch_Official.IsEnabled = true;
switch_Official.Opacity = 1;
label_Official.Opacity = 1;
}
else
{
switch_Official.IsToggled = false;
switch_Official.IsEnabled = false;
switch_Official.Opacity = 0;
label_Official.Opacity = 0;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
OfficialButtonStatus(); // update the offical button status dependant on if the user is logged in or not
ShareButtonStatus(); // update the share buttons status dependant on if all obstacles are complete
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.IO;
using SFML.Window;
namespace SFML
{
namespace Audio
{
////////////////////////////////////////////////////////////
/// <summary>
/// Music defines a big sound played using streaming,
/// so usually what we call a music :)
/// </summary>
////////////////////////////////////////////////////////////
public class Music : ObjectBase
{
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the music from a file
/// </summary>
/// <param name="filename">Path of the music file to load</param>
////////////////////////////////////////////////////////////
public Music(string filename) :
base(sfMusic_createFromFile(filename))
{
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("music", filename);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the music from a custom stream
/// </summary>
/// <param name="stream">Source stream to read from</param>
////////////////////////////////////////////////////////////
public Music(Stream stream) :
base(IntPtr.Zero)
{
myStream = new StreamAdaptor(stream);
SetThis(sfMusic_createFromStream(myStream.InputStreamPtr));
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("music");
}
////////////////////////////////////////////////////////////
/// <summary>
/// Play the music
/// </summary>
////////////////////////////////////////////////////////////
public void Play()
{
sfMusic_play(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Pause the music
/// </summary>
////////////////////////////////////////////////////////////
public void Pause()
{
sfMusic_pause(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Stop the music
/// </summary>
////////////////////////////////////////////////////////////
public void Stop()
{
sfMusic_stop(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Samples rate, in samples per second
/// </summary>
////////////////////////////////////////////////////////////
public uint SampleRate
{
get {return sfMusic_getSampleRate(CPointer);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Number of channels (1 = mono, 2 = stereo)
/// </summary>
////////////////////////////////////////////////////////////
public uint ChannelCount
{
get {return sfMusic_getChannelCount(CPointer);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Current status of the music (see SoundStatus enum)
/// </summary>
////////////////////////////////////////////////////////////
public SoundStatus Status
{
get {return sfMusic_getStatus(CPointer);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Total duration of the music
/// </summary>
////////////////////////////////////////////////////////////
public TimeSpan Duration
{
get
{
long microseconds = sfMusic_getDuration(CPointer);
return TimeSpan.FromTicks(microseconds * TimeSpan.TicksPerMillisecond / 1000);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Loop state of the sound. Default value is false
/// </summary>
////////////////////////////////////////////////////////////
public bool Loop
{
get {return sfMusic_getLoop(CPointer);}
set {sfMusic_setLoop(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Pitch of the music. Default value is 1
/// </summary>
////////////////////////////////////////////////////////////
public float Pitch
{
get {return sfMusic_getPitch(CPointer);}
set {sfMusic_setPitch(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Volume of the music, in range [0, 100]. Default value is 100
/// </summary>
////////////////////////////////////////////////////////////
public float Volume
{
get {return sfMusic_getVolume(CPointer);}
set {sfMusic_setVolume(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// 3D position of the music. Default value is (0, 0, 0)
/// </summary>
////////////////////////////////////////////////////////////
public Vector3f Position
{
get {return sfMusic_getPosition(CPointer);;}
set {sfMusic_setPosition(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Is the music's position relative to the listener's position,
/// or is it absolute?
/// Default value is false (absolute)
/// </summary>
////////////////////////////////////////////////////////////
public bool RelativeToListener
{
get {return sfMusic_isRelativeToListener(CPointer);}
set {sfMusic_setRelativeToListener(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Minimum distance of the music. Closer than this distance,
/// the listener will hear the sound at its maximum volume.
/// The default value is 1
/// </summary>
////////////////////////////////////////////////////////////
public float MinDistance
{
get {return sfMusic_getMinDistance(CPointer);}
set {sfMusic_setMinDistance(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Attenuation factor. The higher the attenuation, the
/// more the sound will be attenuated with distance from listener.
/// The default value is 1
/// </summary>
////////////////////////////////////////////////////////////
public float Attenuation
{
get {return sfMusic_getAttenuation(CPointer);}
set {sfMusic_setAttenuation(CPointer, value);}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Current playing position
/// </summary>
////////////////////////////////////////////////////////////
public TimeSpan PlayingOffset
{
get
{
long microseconds = sfMusic_getPlayingOffset(CPointer);
return TimeSpan.FromTicks(microseconds * TimeSpan.TicksPerMillisecond / 1000);
}
set
{
long microseconds = value.Ticks / (TimeSpan.TicksPerMillisecond / 1000);
sfMusic_setPlayingOffset(CPointer, microseconds);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[Music]" +
" SampleRate(" + SampleRate + ")" +
" ChannelCount(" + ChannelCount + ")" +
" Status(" + Status + ")" +
" Duration(" + Duration + ")" +
" Loop(" + Loop + ")" +
" Pitch(" + Pitch + ")" +
" Volume(" + Volume + ")" +
" Position(" + Position + ")" +
" RelativeToListener(" + RelativeToListener + ")" +
" MinDistance(" + MinDistance + ")" +
" Attenuation(" + Attenuation + ")" +
" PlayingOffset(" + PlayingOffset + ")";
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
if (disposing)
{
if (myStream != null)
myStream.Dispose();
}
sfMusic_destroy(CPointer);
}
private StreamAdaptor myStream = null;
#region Imports
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfMusic_createFromFile(string Filename);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
unsafe static extern IntPtr sfMusic_createFromStream(IntPtr stream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_destroy(IntPtr MusicStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_play(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_pause(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_stop(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern SoundStatus sfMusic_getStatus(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern long sfMusic_getDuration(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfMusic_getChannelCount(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfMusic_getSampleRate(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setPitch(IntPtr Music, float Pitch);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setLoop(IntPtr Music, bool Loop);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setVolume(IntPtr Music, float Volume);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setPosition(IntPtr Music, Vector3f position);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setRelativeToListener(IntPtr Music, bool Relative);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setMinDistance(IntPtr Music, float MinDistance);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setAttenuation(IntPtr Music, float Attenuation);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfMusic_setPlayingOffset(IntPtr Music, long TimeOffset);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfMusic_getLoop(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfMusic_getPitch(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfMusic_getVolume(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Vector3f sfMusic_getPosition(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfMusic_isRelativeToListener(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfMusic_getMinDistance(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfMusic_getAttenuation(IntPtr Music);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern long sfMusic_getPlayingOffset(IntPtr Music);
#endregion
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using CodeOwls.SeeShell.Common;
using CodeOwls.SeeShell.Common.Charts;
using CodeOwls.SeeShell.Common.ViewModels;
using CodeOwls.SeeShell.Common.ViewModels.Charts;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Wpf;
using AreaSeries = OxyPlot.Series.AreaSeries;
using Axis = OxyPlot.Axes.Axis;
using CategoryAxis = OxyPlot.Axes.CategoryAxis;
using ColumnSeries = OxyPlot.Series.ColumnSeries;
using DateTimeAxis = OxyPlot.Axes.DateTimeAxis;
using LinearAxis = OxyPlot.Axes.LinearAxis;
using LineSeries = OxyPlot.Series.LineSeries;
using ScatterSeries = OxyPlot.Series.ScatterSeries;
using Series = OxyPlot.Series.Series;
using StairStepSeries = OxyPlot.Series.StairStepSeries;
namespace CodeOwls.SeeShell.Visualizations.ViewModels
{
public class OxyPlotVisualizationViewModelAdapter
{
private ChartViewModel _viewModel;
private PlotModel _plotModel;
private readonly VisualizationViewModel _vizualizationViewModel;
private readonly Log _log = new Log(typeof(OxyPlotVisualizationViewModelAdapter));
public event EventHandler PlotModelChanged;
public event EventHandler PlotDataUpdate;
public OxyPlotVisualizationViewModelAdapter(VisualizationViewModel viewModel)
{
_plotModel = new PlotModel();
_vizualizationViewModel = viewModel;
_viewModel = viewModel.DataViewModel as ChartViewModel;
_viewModel.ChartSeries.CollectionChanged += ChartSeries_CollectionChanged;
_vizualizationViewModel.PropertyChanged += _viewModel_PropertyChanged;
}
void ChartSeries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
using (_log.PushContext("ChartSeries_CollectionChanged [{0}]", e.Action))
{
CreatePlotModel();
}
}
void _viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Items" || e.PropertyName == "DataViewModel")
{
_viewModel = _vizualizationViewModel.DataViewModel as ChartViewModel;
CreatePlotModel();
}
}
static bool _inPlotModelCreation = false;
private void CreatePlotModel()
{
using (_log.PushContext("CreatePlotModel"))
{
if (_inPlotModelCreation) return;
_log.Debug("creating new plot model");
_inPlotModelCreation = true;
_plotModel = new PlotModel();
UpdateAxes();
UpdateSeries();
OnPlotModelChanged();
_inPlotModelCreation = false;
}
}
private void UpdateSeries()
{
foreach (var series in _viewModel.ChartSeries)
{
try
{
series.DataSource.Data.CollectionChanged -= Data_CollectionChanged;
}
catch
{
}
Series plotSeries = ConvertSeries(series);
_plotModel.Series.Add( plotSeries );
series.DataSource.Data.CollectionChanged += Data_CollectionChanged;
}
}
void Data_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
using (_log.PushContext("Data_CollectionChanged"))
{
OnPlotDataUpdate();
}
}
private Series ConvertSeries(ChartSeriesViewModel series)
{
Series newSeries = null;
var valueSeries = series.GetScaleForProperty(series.ValueMemberPath);
var labelSeries = series.GetScaleForProperty(series.LabelMemberPath);
switch (series.SeriesType)
{
case( ChartSeriesType.Column):
{
newSeries = new ColumnSeries
{
ValueField = series.ValueMemberPath,
ItemsSource = series.DataSource.Data,
FillColor = valueSeries.Color.ToOxyColor(),
StrokeColor = valueSeries.Color.ToOxyColor(),
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
case( ChartSeriesType.Line ):
{
newSeries = new LineSeries
{
ItemsSource = series.DataSource.Data,
DataFieldX = series.XMemberPath,
DataFieldY = series.YMemberPath,
MarkerType = MarkerType.Circle,
Color = valueSeries.Color.ToOxyColor(),
MarkerFill = valueSeries.Color.ToOxyColor(),
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
case( ChartSeriesType.Spline):
{
newSeries = new LineSeries
{
ItemsSource = series.DataSource.Data,
DataFieldX = series.XMemberPath,
DataFieldY = series.YMemberPath,
MarkerType = MarkerType.Circle,
Color = valueSeries.Color.ToOxyColor(),
MarkerFill = valueSeries.Color.ToOxyColor(),
Smooth = true,
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
case(ChartSeriesType.Area):
{
newSeries = new AreaSeries
{
ItemsSource = series.DataSource.Data,
DataFieldX = series.XMemberPath,
DataFieldY = series.YMemberPath,
Color = valueSeries.Color.ToOxyColor(),
Fill = valueSeries.Color.ToOxyColor(),
MarkerFill = valueSeries.Color.ToOxyColor(),
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
case( ChartSeriesType.SplineArea):
{
newSeries = new AreaSeries
{
ItemsSource = series.DataSource.Data,
DataFieldX = series.XMemberPath,
DataFieldY = series.YMemberPath,
Color = valueSeries.Color.ToOxyColor(),
Fill = valueSeries.Color.ToOxyColor(),
MarkerFill = valueSeries.Color.ToOxyColor(),
Smooth = true,
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
case(ChartSeriesType.Bubble):
{
newSeries = new ScatterSeries
{
ItemsSource = series.DataSource.Data,
DataFieldX = series.XMemberPath,
DataFieldY = series.YMemberPath,
DataFieldSize = series.RadiusMemberPath,
MarkerFill = valueSeries.Color.ToOxyColor(),
MarkerType = MarkerType.Circle,
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
case( ChartSeriesType.StepLine):
{
newSeries = new StairStepSeries
{
ItemsSource = series.DataSource.Data,
DataFieldX = series.XMemberPath,
DataFieldY = series.YMemberPath,
Color = valueSeries.Color.ToOxyColor(),
YAxisKey = valueSeries.Name,
XAxisKey = labelSeries.Name,
};
break;
}
default:
{
return null;
}
}
newSeries.Title = series.Name;
return newSeries;
}
private void UpdateAxes()
{
foreach (var axis in _viewModel.ChartAxes)
{
Axis plotAxis = ConvertAxis(axis);
_plotModel.Axes.Add( plotAxis );
}
}
private Axis ConvertAxis(ChartAxisViewModel axis)
{
Axis newAxis = null;
switch (axis.AxisType)
{
case (ChartAxisType.CategoryX):
{
newAxis = new CategoryAxis
{
LabelField = axis.ValueMemberPath,
ItemsSource = axis.DataSource.Data
};
break;
}
case (ChartAxisType.NumericX):
case (ChartAxisType.NumericY):
{
newAxis = new LinearAxis
{
};
break;
}
case(ChartAxisType.CategoryDateTimeX):
{
var dtaxis = new DateTimeAxis
{
IntervalType = DateTimeIntervalType.Auto,
};
var scale = axis.GetScaleForProperty(axis.ValueMemberPath);
if (null != scale)
{
scale.PropertyChanged += (s, a) =>
{
if( a.PropertyName != "Minimum" && a.PropertyName != "Maximum")
{
return;
}
var min = new DateTime((long)scale.Minimum);
var max = new DateTime((long)scale.Maximum);
var laxis = _plotModel.Axes.FirstOrDefault(x => x.Title == scale.Name) as DateTimeAxis;
if( null == laxis )
{
return;
}
var delta = max - min;
var lmax = 0.0d;
var lmin = 0.0d;
if (TimeSpan.FromSeconds(1) > delta)
{
laxis.IntervalType = DateTimeIntervalType.Seconds;
}
else if (TimeSpan.FromMinutes(1) > delta)
{
laxis.IntervalType = DateTimeIntervalType.Minutes;
}
else if (TimeSpan.FromHours(1) > delta)
{
laxis.IntervalType = DateTimeIntervalType.Hours;
}
else if (TimeSpan.FromDays(1) > delta)
{
laxis.IntervalType = DateTimeIntervalType.Days;
}
else if (TimeSpan.FromDays(30) > delta)
{
laxis.IntervalType = DateTimeIntervalType.Months;
}
else
{
laxis.IntervalType = DateTimeIntervalType.Auto;
}
//TODO: remove
laxis.IntervalType = DateTimeIntervalType.Seconds;
//laxis.Minimum = scale.Minimum;
//laxis.Maximum = scale.Maximum;
OnPlotModelChanged();
};
}
newAxis = dtaxis;
break;
}
}
if (null == newAxis)
{
return null;
}
switch (axis.AxisLocation)
{
case(AxisLocation.InsideBottom):
case(AxisLocation.OutsideBottom):
{
newAxis.Position = AxisPosition.Bottom;
break;
}
case (AxisLocation.InsideTop):
case (AxisLocation.OutsideTop):
{
newAxis.Position = AxisPosition.Top;
break;
}
case (AxisLocation.InsideLeft):
case (AxisLocation.OutsideLeft):
{
newAxis.Position = AxisPosition.Left;
break;
}
case (AxisLocation.InsideRight):
case (AxisLocation.OutsideRight):
{
newAxis.Position = AxisPosition.Right;
break;
}
default:
{
newAxis.Position = AxisPosition.None;
break;
}
}
newAxis.Title = axis.Name;
var series = axis.AxisScaleDescriptors.FirstOrDefault();
if (null != series)
{
newAxis.Title = series.Scale.Name;
}
newAxis.Key = newAxis.Title;
return newAxis;
}
public PlotModel PlotModel
{
get { return _plotModel; }
}
protected virtual void OnPlotModelChanged()
{
using (_log.PushContext("OnPlotModelChanged"))
{
var handler = PlotModelChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
}
static bool _inPlotUpdate = false;
protected virtual void OnPlotDataUpdate()
{
using (_log.PushContext("OnPlotDataUpdate"))
{
if (_inPlotUpdate) return;
_log.Debug( "updateing plot data");
_inPlotUpdate = true;
var handler = PlotDataUpdate;
if (handler != null) handler(this, EventArgs.Empty);
_inPlotUpdate = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using ALinq.Mapping;
using ALinq.SqlClient;
namespace ALinq.PostgreSQL
{
class PgsqlQueryConverter : QueryConverter
{
public PgsqlQueryConverter(IDataServices services, ITypeSystemProvider typeProvider, Translator translator, SqlFactory sql)
: base(services, typeProvider, translator, sql)
{
}
protected override SqlExpression GetReturnIdentityExpression(MetaDataMember idMember, bool isOutputFromInsert)
{
var name = "CURRVAL('" + PgsqlBuilder.GetSequenceName(idMember, translator.Provider.SqlIdentifier) + "') FROM " + idMember.DeclaringType.Table.TableName;//OracleSqlBuilder.GetSequenceName(idMember, translator.Provider.SqlIdentifier) + ".CURRVAL";
return new SqlVariable(idMember.Type, typeProvider.From(idMember.Type), name, this.dominatingExpression);
}
protected override SqlSelect GenerateSkipTake(SqlSelect sequence, SqlExpression skipExp, SqlExpression takeExp)
{
var valueType = typeof(int);
var sqlType = typeProvider.From(valueType);
//skipExp = skipExp != null ? sql.Value(typeof(int), typeProvider.From(typeof(int)), ((SqlValue)skipExp).Value, false, dominatingExpression)
// : sql.Value(typeof(int), typeProvider.From(typeof(int)), 0, false, dominatingExpression);
//takeExp = takeExp != null ? sql.Value(typeof(int), typeProvider.From(typeof(int)), ((SqlValue)takeExp).Value, false, dominatingExpression)
// : sql.Value(typeof(int), typeProvider.From(typeof(int)), 0, false, dominatingExpression);
//IEnumerable<SqlExpression> expressions = new[] { takeExp, sql.VariableFromName("OFFSET", dominatingExpression), skipExp };
//sequence.Top = new SqlFunctionCall(valueType, sqlType, "LIMIT", expressions, takeExp.SourceExpression)
// {
// Brackets = false,
// Comma = false
// };
//return sequence;
if (takeExp != null && skipExp != null)
{
IEnumerable<SqlExpression> expressions = new[] { takeExp, sql.VariableFromName("OFFSET", dominatingExpression), skipExp };
sequence.Top = new SqlFunctionCall(valueType, sqlType, "LIMIT", expressions, takeExp.SourceExpression)
{
Brackets = false,
Comma = false
};
}
else if (takeExp != null)
{
IEnumerable<SqlExpression> expressions = new[] { takeExp };
sequence.Top = new SqlFunctionCall(valueType, sqlType, "LIMIT", expressions, takeExp.SourceExpression)
{
Brackets = false,
Comma = false
};
}
else if (skipExp != null)
{
IEnumerable<SqlExpression> expressions = new[] { skipExp };
sequence.Top = new SqlFunctionCall(valueType, sqlType, "OFFSET", expressions, skipExp.SourceExpression)
{
Brackets = false,
Comma = false
};
}
return sequence;
}
protected override SqlNode VisitFirst(Expression sequence, LambdaExpression lambda, bool isFirst)
{
SqlSelect select = this.LockSelect(this.VisitSequence(sequence));
if (lambda != null)
{
this.map[lambda.Parameters[0]] = select.Selection;
select.Where = this.VisitExpression(lambda.Body);
}
if (isFirst)
{
var f = sql.FunctionCall(typeof(int), "LIMIT", new[] { sql.ValueFromObject(1, false, dominatingExpression) },
dominatingExpression);
f.Brackets = false;
f.Comma = false;
select.Top = f;
}
if (this.outerNode)
{
return select;
}
SqlNodeType nt = this.typeProvider.From(select.Selection.ClrType).CanBeColumn
? SqlNodeType.ScalarSubSelect
: SqlNodeType.Element;
return this.sql.SubSelect(nt, select, sequence.Type);
}
protected override SqlExpression GetInsertIdentityExpression(MetaDataMember member)
{
var exp = new SqlVariable(member.Type, typeProvider.From(member.Type),
"NEXTVAL('" + PgsqlBuilder.GetSequenceName(member, translator.Provider.SqlIdentifier) + "')", dominatingExpression);
//return new SqlMemberAssign(member.Member, exp);
return exp;
}
//protected override SqlNode VisitInsert(Expression item, LambdaExpression resultSelector)
//{
// if (item == null)
// {
// throw SqlClient.Error.ArgumentNull("item");
// }
// if (item.NodeType == ExpressionType.Lambda)
// {
// return CreateInsertExpression((LambdaExpression)item, resultSelector);
// //return VisitInsert1(item, resultSelector);
// }
// dominatingExpression = item;
// MetaTable table = Services.Model.GetTable(item.Type);
// Expression sourceExpression = Services.Context.GetTable(table.RowType.Type).Expression;
// var expression2 = item as ConstantExpression;
// if (expression2 == null)
// {
// throw SqlClient.Error.InsertItemMustBeConstant();
// }
// if (expression2.Value == null)
// {
// throw SqlClient.Error.ArgumentNull("item");
// }
// var bindings = new List<SqlMemberAssign>();
// MetaType inheritanceType = table.RowType.GetInheritanceType(expression2.Value.GetType());
// SqlExpression expression3 = sql.ValueFromObject(expression2.Value, true, sourceExpression);
// foreach (MetaDataMember member in inheritanceType.PersistentDataMembers)
// {
// if (!member.IsAssociation && !member.IsVersion)
// {
// if (member.IsDbGenerated)
// {
// var exp = new SqlVariable(member.Type, typeProvider.From(member.Type),
// "NEXTVAL('" + PgsqlBuilder.GetSequenceName(member, translator.Provider.SqlIdentifier) + "')", dominatingExpression);
// bindings.Add(new SqlMemberAssign(member.Member, exp));
// }
// else
// bindings.Add(new SqlMemberAssign(member.Member, sql.Member(expression3, member.Member)));
// }
// }
// ConstructorInfo constructor = inheritanceType.Type.GetConstructor(Type.EmptyTypes);
// SqlNew expr = sql.New(inheritanceType, constructor, null, null, bindings, item);
// SqlTable table2 = sql.Table(table, table.RowType, dominatingExpression);
// var insert = new SqlInsert(table2, expr, item);
// if (resultSelector == null)
// {
// return insert;
// }
// MetaDataMember dBGeneratedIdentityMember = inheritanceType.DBGeneratedIdentityMember;
// bool flag = false;
// if (dBGeneratedIdentityMember != null)
// {
// flag = IsDbGeneratedKeyProjectionOnly(resultSelector.Body, dBGeneratedIdentityMember);
// if ((dBGeneratedIdentityMember.Type == typeof(Guid)) &&
// ((ConverterStrategy & ConverterStrategy.CanOutputFromInsert) != ConverterStrategy.Default))
// {
// insert.OutputKey = new SqlColumn(dBGeneratedIdentityMember.Type,
// sql.Default(dBGeneratedIdentityMember), dBGeneratedIdentityMember.Name,
// dBGeneratedIdentityMember, null, dominatingExpression);
// if (!flag)
// {
// insert.OutputToLocal = true;
// }
// }
// }
// SqlSelect select;
// SqlSelect select2 = null;
// var alias = new SqlAlias(table2);
// var ref2 = new SqlAliasRef(alias);
// map.Add(resultSelector.Parameters[0], ref2);
// SqlExpression selection = VisitExpression(resultSelector.Body);
// SqlExpression expression5;
// if (dBGeneratedIdentityMember != null)
// {
// expression5 = sql.Binary(SqlNodeType.EQ, sql.Member(ref2, dBGeneratedIdentityMember.Member),
// GetIdentityExpression(dBGeneratedIdentityMember, insert.OutputKey != null));
// }
// else
// {
// SqlExpression right = VisitExpression(item);
// expression5 = sql.Binary(SqlNodeType.EQ2V, ref2, right);
// }
// select = new SqlSelect(selection, alias, resultSelector) { Where = expression5 };
// if ((dBGeneratedIdentityMember != null) && flag)
// {
// if (insert.OutputKey == null)
// {
// SqlExpression identityExpression = GetIdentityExpression(dBGeneratedIdentityMember, false);
// select2 = new SqlSelect(identityExpression, null, resultSelector);
// }
// select.DoNotOutput = true;
// }
// var block = new SqlBlock(dominatingExpression);
// block.Statements.Add(insert);
// if (select2 != null)
// {
// block.Statements.Add(select2);
// }
// block.Statements.Add(select);
// return block;
//}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
#if !NETMF
using System.Configuration;
#endif
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
namespace log4net.Util
{
/// <summary>
/// Utility class for system specific information.
/// </summary>
/// <remarks>
/// <para>
/// Utility class of static methods for system specific information.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Alexey Solofnenko</author>
public sealed class SystemInfo
{
#region Private Constants
private const string DEFAULT_NULL_TEXT = "(null)";
private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE";
#endregion
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
private SystemInfo()
{
}
#endregion Private Instance Constructors
#region Public Static Constructor
/// <summary>
/// Initialize default values for private static fields.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
static SystemInfo()
{
string nullText = DEFAULT_NULL_TEXT;
string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT;
#if !NETCF
// Look for log4net.NullText in AppSettings
string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText");
if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "].");
nullText = nullTextAppSettingsKey;
}
// Look for log4net.NotAvailableText in AppSettings
string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText");
if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "].");
notAvailableText = notAvailableTextAppSettingsKey;
}
#endif
s_notAvailableText = notAvailableText;
s_nullText = nullText;
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets the system dependent line terminator.
/// </summary>
/// <value>
/// The system dependent line terminator.
/// </value>
/// <remarks>
/// <para>
/// Gets the system dependent line terminator.
/// </para>
/// </remarks>
public static string NewLine
{
get
{
#if NETCF
return "\r\n";
#else
return System.Environment.NewLine;
#endif
}
}
/// <summary>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </summary>
/// <value>The base directory path for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ApplicationBaseDirectory
{
get
{
#if NETCF
return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar;
#else
return AppDomain.CurrentDomain.BaseDirectory;
#endif
}
}
/// <summary>
/// Gets the path to the configuration file for the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// The .NET Compact Framework 1.0 does not have a concept of a configuration
/// file. For this runtime, we use the entry assembly location as the root for
/// the configuration file name.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ConfigurationFileLocation
{
get
{
#if NETCF
return SystemInfo.EntryAssemblyLocation+".config";
#else
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
#endif
}
}
/// <summary>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the entry assembly.</value>
/// <remarks>
/// <para>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </para>
/// </remarks>
public static string EntryAssemblyLocation
{
get
{
#if NETCF
return SystemInfo.NativeEntryAssemblyLocation;
#else
return System.Reflection.Assembly.GetEntryAssembly().Location;
#endif
}
}
/// <summary>
/// Gets the ID of the current thread.
/// </summary>
/// <value>The ID of the current thread.</value>
/// <remarks>
/// <para>
/// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method
/// is used to obtain the thread ID for the current thread. This is the
/// operating system ID for the thread.
/// </para>
/// <para>
/// On the .NET Compact Framework 1.0 it is not possible to get the
/// operating system thread ID for the current thread. The native method
/// <c>GetCurrentThreadId</c> is implemented inline in a header file
/// and cannot be called.
/// </para>
/// <para>
/// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this
/// gives a stable id unrelated to the operating system thread ID which may
/// change if the runtime is using fibers.
/// </para>
/// </remarks>
public static int CurrentThreadId
{
get
{
#if NETCF_1_0
return System.Threading.Thread.CurrentThread.GetHashCode();
#elif NET_2_0 || NETCF_2_0 || MONO_2_0
return System.Threading.Thread.CurrentThread.ManagedThreadId;
#else
return AppDomain.GetCurrentThreadId();
#endif
}
}
/// <summary>
/// Get the host name or machine name for the current machine
/// </summary>
/// <value>
/// The hostname or machine name
/// </value>
/// <remarks>
/// <para>
/// Get the host name or machine name for the current machine
/// </para>
/// <para>
/// The host name (<see cref="System.Net.Dns.GetHostName"/>) or
/// the machine name (<c>Environment.MachineName</c>) for
/// the current machine, or if neither of these are available
/// then <c>NOT AVAILABLE</c> is returned.
/// </para>
/// </remarks>
public static string HostName
{
get
{
if (s_hostName == null)
{
// Get the DNS host name of the current machine
try
{
// Lookup the host name
s_hostName = System.Net.Dns.GetHostName();
}
catch (System.Net.Sockets.SocketException)
{
LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored.");
}
catch (System.Security.SecurityException)
{
// We may get a security exception looking up the hostname
// You must have Unrestricted DnsPermission to access resource
LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored.");
}
catch (Exception ex)
{
LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex);
}
// Get the NETBIOS machine name of the current machine
if (s_hostName == null || s_hostName.Length == 0)
{
try
{
#if (!SSCLI && !NETCF)
s_hostName = Environment.MachineName;
#endif
}
catch(InvalidOperationException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the machine name
// You must have Unrestricted EnvironmentPermission to access resource
}
}
// Couldn't find a value
if (s_hostName == null || s_hostName.Length == 0)
{
s_hostName = s_notAvailableText;
LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used");
}
}
return s_hostName;
}
}
/// <summary>
/// Get this application's friendly name
/// </summary>
/// <value>
/// The friendly name of this application as a string
/// </value>
/// <remarks>
/// <para>
/// If available the name of the application is retrieved from
/// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>.
/// </para>
/// <para>
/// Otherwise the file name of the entry assembly is used.
/// </para>
/// </remarks>
public static string ApplicationFriendlyName
{
get
{
if (s_appFriendlyName == null)
{
try
{
#if !NETCF
s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName;
#endif
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored.");
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
try
{
string assemblyLocation = SystemInfo.EntryAssemblyLocation;
s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation);
}
catch(System.Security.SecurityException)
{
// Caller needs path discovery permission
}
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
s_appFriendlyName = s_notAvailableText;
}
}
return s_appFriendlyName;
}
}
/// <summary>
/// Get the start time for the current process.
/// </summary>
/// <remarks>
/// <para>
/// This is the time at which the log4net library was loaded into the
/// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c>
/// this is not the start time for the current process.
/// </para>
/// <para>
/// The log4net library should be loaded by an application early during its
/// startup, therefore this start time should be a good approximation for
/// the actual start time.
/// </para>
/// <para>
/// Note that AppDomains may be loaded and unloaded within the
/// same process without the process terminating, however this start time
/// will be set per AppDomain.
/// </para>
/// </remarks>
public static DateTime ProcessStartTime
{
get { return s_processStartTime; }
}
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
/// <remarks>
/// <para>
/// Use this value to indicate a <c>null</c> has been encountered while
/// outputting a string representation of an item.
/// </para>
/// <para>
/// The default value is <c>(null)</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NullText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NullText
{
get { return s_nullText; }
set { s_nullText = value; }
}
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
/// <remarks>
/// <para>
/// Use this value when an unsupported feature is requested.
/// </para>
/// <para>
/// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NotAvailableText
{
get { return s_notAvailableText; }
set { s_notAvailableText = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Gets the assembly location path for the specified assembly.
/// </summary>
/// <param name="myAssembly">The assembly to get the location for.</param>
/// <returns>The location of the assembly.</returns>
/// <remarks>
/// <para>
/// This method does not guarantee to return the correct path
/// to the assembly. If only tries to give an indication as to
/// where the assembly was loaded from.
/// </para>
/// </remarks>
public static string AssemblyLocationInfo(Assembly myAssembly)
{
#if NETCF
return "Not supported on Microsoft .NET Compact Framework";
#else
if (myAssembly.GlobalAssemblyCache)
{
return "Global Assembly Cache";
}
else
{
try
{
#if NET_4_0
if (myAssembly.IsDynamic)
{
return "Dynamic Assembly";
}
#else
if (myAssembly is System.Reflection.Emit.AssemblyBuilder)
{
return "Dynamic Assembly";
}
else if(myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder")
{
return "Dynamic Assembly";
}
#endif
else
{
// This call requires FileIOPermission for access to the path
// if we don't have permission then we just ignore it and
// carry on.
return myAssembly.Location;
}
}
catch (NotSupportedException)
{
// The location information may be unavailable for dynamic assemblies and a NotSupportedException
// is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx
return "Dynamic Assembly";
}
catch (TargetInvocationException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (ArgumentException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (System.Security.SecurityException)
{
return "Location Permission Denied";
}
}
#endif
}
/// <summary>
/// Gets the fully qualified name of the <see cref="Type" />, including
/// the name of the assembly from which the <see cref="Type" /> was
/// loaded.
/// </summary>
/// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param>
/// <returns>The fully qualified name for the <see cref="Type" />.</returns>
/// <remarks>
/// <para>
/// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property,
/// but this method works on the .NET Compact Framework 1.0 as well as
/// the full .NET runtime.
/// </para>
/// </remarks>
public static string AssemblyQualifiedName(Type type)
{
return type.FullName + ", " + type.Assembly.FullName;
}
/// <summary>
/// Gets the short name of the <see cref="Assembly" />.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param>
/// <returns>The short name of the <see cref="Assembly" />.</returns>
/// <remarks>
/// <para>
/// The short name of the assembly is the <see cref="Assembly.FullName" />
/// without the version, culture, or public key. i.e. it is just the
/// assembly's file name without the extension.
/// </para>
/// <para>
/// Use this rather than <c>Assembly.GetName().Name</c> because that
/// is not available on the Compact Framework.
/// </para>
/// <para>
/// Because of a FileIOPermission security demand we cannot do
/// the obvious Assembly.GetName().Name. We are allowed to get
/// the <see cref="Assembly.FullName" /> of the assembly so we
/// start from there and strip out just the assembly name.
/// </para>
/// </remarks>
public static string AssemblyShortName(Assembly myAssembly)
{
string name = myAssembly.FullName;
int offset = name.IndexOf(',');
if (offset > 0)
{
name = name.Substring(0, offset);
}
return name.Trim();
// TODO: Do we need to unescape the assembly name string?
// Doc says '\' is an escape char but has this already been
// done by the string loader?
}
/// <summary>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param>
/// <returns>The file name of the assembly.</returns>
/// <remarks>
/// <para>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </para>
/// </remarks>
public static string AssemblyFileName(Assembly myAssembly)
{
#if NETCF
// This is not very good because it assumes that only
// the entry assembly can be an EXE. In fact multiple
// EXEs can be loaded in to a process.
string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly);
string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation);
if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0)
{
// assembly is entry assembly
return assemblyShortName + ".exe";
}
else
{
// assembly is not entry assembly
return assemblyShortName + ".dll";
}
#else
return System.IO.Path.GetFileName(myAssembly.Location);
#endif
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeType">A sibling type to use to load the type.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified, it will be loaded from the assembly
/// containing the specified relative type. If the type is not found in the assembly
/// then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
type = assembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in loaded assembly
LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
return type;
}
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
// In NETCF 2 and 3 arg versions seem to behave differently
// https://issues.apache.org/jira/browse/LOG4NET-113
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF_1_0
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF_1_0
return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]");
#elif NETCF_2_0
return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]");
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int16"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out short val)
{
#if NETCF
val = 0;
try
{
val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt16(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Lookup an application setting
/// </summary>
/// <param name="key">the application settings key to lookup</param>
/// <returns>the value for the key, or <c>null</c></returns>
/// <remarks>
/// <para>
/// Configuration APIs are not supported under the Compact Framework
/// </para>
/// </remarks>
public static string GetAppSetting(string key)
{
try
{
#if NETCF
// Configuration APIs are not suported under the Compact Framework
#elif NET_2_0
return ConfigurationManager.AppSettings[key];
#else
return ConfigurationSettings.AppSettings[key];
#endif
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not parse correctly.
LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
return null;
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
/// <summary>
/// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity.
/// </summary>
/// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns>
/// <remarks>
/// <para>
/// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer.
/// </para>
/// </remarks>
public static Hashtable CreateCaseInsensitiveHashtable()
{
#if NETCF_1_0
return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
#elif NETCF_2_0 || NET_2_0 || MONO_2_0
return new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
#endif
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the SystemInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(SystemInfo);
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
private static string s_nullText;
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
private static string s_notAvailableText;
/// <summary>
/// Start time for the current process.
/// </summary>
private static DateTime s_processStartTime = DateTime.Now;
#endregion
#region Compact Framework Helper Classes
#if NETCF_1_0
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("CoreDll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
| |
// The LaTeX documenter.
//
// Copyright (C) 2002 Thong Nguyen ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//
// This doucmenter won't be able to generate dvi or pdf files without
// a LaTeX compiler. You can download a free one from: http://www.miktex.org.
//
//
using System;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using NDoc.Core;
using NDoc.Core.Reflection;
namespace NDoc.Documenter.Latex
{
/// <summary>
/// LaTeX generating documenter class.
/// </summary>
public class LatexDocumenter: BaseReflectionDocumenter
{
//private string m_ResourceDirectory;
private static readonly char[] c_LatexEscapeChars =
{
'_',
'$',
'%',
'{',
'}',
'\\',
'#'
};
private static readonly string[] c_TempFileExtensions =
{
".log",
".aux"
};
private static readonly string[] c_KnownLatexOuputExtensions =
{
".pdf",
".dvi"
};
/// <summary>
/// Constructs a new LaTeX documenter.
/// </summary>
/// <remarks>
/// The documenter name is set to "LaTeX".
/// </remarks>
public LatexDocumenter( LatexDocumenterConfig config ) : base( config )
{
}
/// <summary>
/// Gets the Configuration object for this documenter.
/// </summary>
private LatexDocumenterConfig LatexConfig
{
get
{
return (LatexDocumenterConfig)Config;
}
}
/// <summary>
/// <see cref="BaseDocumenter.Build"/>
/// </summary>
/// <param name="project"></param>
public override void Build(Project project)
{
Workspace workspace = new LatexWorkspace( WorkingPath );
workspace.Clean();
workspace.Prepare();
#if NO_RESOURCES
// copy all of the xslt source files into the workspace
DirectoryInfo xsltSource = new DirectoryInfo( Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"..\..\..\Documenter\Latex\xslt") ) );
foreach ( FileInfo f in xsltSource.GetFiles( "*.xslt" ) )
{
string fname = Path.Combine( workspace.ResourceDirectory, f.Name );
f.CopyTo( fname, true );
File.SetAttributes( fname, FileAttributes.Normal );
}
#else
EmbeddedResources.WriteEmbeddedResources(
this.GetType().Module.Assembly,
"NDoc.Documenter.Latex.xslt",
workspace.ResourceDirectory );
#endif
string xmlBuffer = MakeXml(project);
// Create the output directory if it doesn't exist...
if (!Directory.Exists(LatexConfig.OutputDirectory))
{
Directory.CreateDirectory(LatexConfig.OutputDirectory);
}
else
{
// Delete temp files in the output directory.
OnDocBuildingStep(5, "Deleting temp files from last time...");
foreach (string s in c_TempFileExtensions)
{
File.Delete(LatexConfig.TexFileBaseName + s);
}
}
OnDocBuildingStep(10, "Scanning document text...");
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlBuffer);
MakeTextTeXCompatible(doc);
WriteTeXDocument(workspace, doc);
string text;
using (var file = File.OpenText(LatexConfig.TexFileFullPath))
{
text = file.ReadToEnd();
}
using (var file = File.CreateText(LatexConfig.TexFileFullPath))
{
file.Write(text.Replace("<", "<").Replace(">", ">"));
}
CompileTexDocument();
workspace.RemoveResourceDirectory();
}
private string WorkingPath
{
get
{
if ( Path.IsPathRooted( LatexConfig.OutputDirectory ) )
return LatexConfig.OutputDirectory;
return Path.GetFullPath( LatexConfig.OutputDirectory );
}
}
/// <summary>
/// Translates all text contained in the node (and it's children)
/// into LaTeX compatable text.
/// </summary>
/// <param name="node"></param>
private void MakeTextTeXCompatible(XmlNode node)
{
if (node == null)
{
return;
}
if (node.NodeType == XmlNodeType.Text)
{
StringBuilder builder = new
StringBuilder(node.Value.Length + (node.Value.Length / 2));
for (int i = 0; i < node.Value.Length; i++)
{
char c;
c = node.Value[i];
if
(Array.IndexOf(LatexDocumenter.c_LatexEscapeChars, c) >= 0)
{
// Replace char with LaTeX escape sequence.
builder.Append('\\').Append(c);
}
else
{
builder.Append(c);
}
}
node.Value = builder.ToString();
}
// Recursively change all the text in the node's children
if (node.HasChildNodes)
{
foreach (XmlNode n in node.ChildNodes)
{
MakeTextTeXCompatible(n);
}
}
// Change all the text in the attributes as well...
if (node.Attributes != null)
{
foreach (XmlAttribute n in node.Attributes)
{
MakeTextTeXCompatible(n);
}
}
}
/// <summary>
/// Returns the path to the output file.
/// </summary>
/// <remarks>
/// If a PDF or DVI file with the same name as the TeX file exists
/// the path to that file is returned.
/// </remarks>
public override string MainOutputFile
{
get
{
int i;
String s, retval;
retval = "";
i = 0;
foreach (string ext in c_KnownLatexOuputExtensions)
{
s = Path.Combine(
LatexConfig.OutputDirectory,
LatexConfig.TexFileBaseName
+ ext);
if (File.Exists(s))
{
retval = s;
break;
}
i++;
}
if (retval == "")
{
retval = LatexConfig.TexFileFullPath;
}
return retval;
}
}
/// <summary>
/// Calls the LaTeX processor to compile the TeX file into a DVI or PDF.
/// </summary>
private void CompileTexDocument()
{
Process process;
ProcessStartInfo startInfo;
if (LatexConfig.LatexCompiler == "")
{
return;
}
startInfo = new ProcessStartInfo(LatexConfig.LatexCompiler,
LatexConfig.TextFileFullName);
startInfo.WorkingDirectory = LatexConfig.OutputDirectory;
// Run LaTeX twice to resolve references.
for (int i = 0; i < 2; i++)
{
process = Process.Start(startInfo);
OnDocBuildingStep(40 + (i * 30), "Compiling TeX file via " + LatexConfig.LatexCompiler + "...");
if (process == null)
{
throw new DocumenterException("Unable to start the LaTeX compiler: ("
+ LatexConfig.LatexCompiler + ")");
}
process.WaitForExit();
}
}
/// <summary>
/// Uses XSLT to transform the current document into LaTeX source.
/// </summary>
private void WriteTeXDocument( Workspace workspace, XmlDocument document)
{
XmlWriter writer;
XsltArgumentList args;
XslTransform transform;
OnDocBuildingStep(0, "Loading XSLT files...");
transform = new XslTransform();
transform.Load(Path.Combine(workspace.ResourceDirectory, "document.xslt"));
args = new XsltArgumentList();
writer = new XmlTextWriter(LatexConfig.TexFileFullPath,
new UTF8Encoding( false ) );
OnDocBuildingStep(20, "Building TeX file...");
#if(NET_1_0)
//Use overload that is obsolete in v1.1
transform.Transform(document, args, writer);
#else
//Use new overload so we don't get obsolete warnings - clean compile :)
transform.Transform(document, args, writer, null);
#endif
writer.Close();
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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 NSubstitute;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using IBM.Cloud.SDK.Core.Http;
using IBM.Cloud.SDK.Core.Http.Exceptions;
using IBM.Cloud.SDK.Core.Authentication.NoAuth;
using IBM.Watson.Assistant.v1.Model;
using IBM.Cloud.SDK.Core.Model;
namespace IBM.Watson.Assistant.v1.UnitTests
{
[TestClass]
public class AssistantServiceUnitTests
{
#region Constructor
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void Constructor_HttpClient_Null()
{
AssistantService service = new AssistantService(httpClient: null);
}
[TestMethod]
public void ConstructorHttpClient()
{
AssistantService service = new AssistantService(new IBMHttpClient());
Assert.IsNotNull(service);
}
[TestMethod]
public void ConstructorExternalConfig()
{
var apikey = System.Environment.GetEnvironmentVariable("ASSISTANT_APIKEY");
System.Environment.SetEnvironmentVariable("ASSISTANT_APIKEY", "apikey");
AssistantService service = Substitute.For<AssistantService>("versionDate");
Assert.IsNotNull(service);
System.Environment.SetEnvironmentVariable("ASSISTANT_APIKEY", apikey);
}
[TestMethod]
public void Constructor()
{
AssistantService service = new AssistantService(new IBMHttpClient());
Assert.IsNotNull(service);
}
[TestMethod]
public void ConstructorAuthenticator()
{
AssistantService service = new AssistantService("versionDate", new NoAuthAuthenticator());
Assert.IsNotNull(service);
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void ConstructorNoVersion()
{
AssistantService service = new AssistantService(null, new NoAuthAuthenticator());
}
[TestMethod]
public void ConstructorNoUrl()
{
var apikey = System.Environment.GetEnvironmentVariable("ASSISTANT_APIKEY");
System.Environment.SetEnvironmentVariable("ASSISTANT_APIKEY", "apikey");
var url = System.Environment.GetEnvironmentVariable("ASSISTANT_SERVICE_URL");
System.Environment.SetEnvironmentVariable("ASSISTANT_SERVICE_URL", null);
AssistantService service = Substitute.For<AssistantService>("versionDate");
Assert.IsTrue(service.ServiceUrl == "https://api.us-south.assistant.watson.cloud.ibm.com");
System.Environment.SetEnvironmentVariable("ASSISTANT_SERVICE_URL", url);
System.Environment.SetEnvironmentVariable("ASSISTANT_APIKEY", apikey);
}
#endregion
[TestMethod]
public void Message_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var input = new MessageInput();
var intents = new List<RuntimeIntent>();
var entities = new List<RuntimeEntity>();
var alternateIntents = false;
var context = new Context();
var output = new OutputData();
var nodesVisitedDetails = false;
var result = service.Message(workspaceId: workspaceId, input: input, intents: intents, entities: entities, alternateIntents: alternateIntents, context: context, output: output, nodesVisitedDetails: nodesVisitedDetails);
JObject bodyObject = new JObject();
if (input != null)
{
bodyObject["input"] = JToken.FromObject(input);
}
if (intents != null && intents.Count > 0)
{
bodyObject["intents"] = JToken.FromObject(intents);
}
if (entities != null && entities.Count > 0)
{
bodyObject["entities"] = JToken.FromObject(entities);
}
bodyObject["alternate_intents"] = JToken.FromObject(alternateIntents);
if (context != null)
{
bodyObject["context"] = JToken.FromObject(context);
}
if (output != null)
{
bodyObject["output"] = JToken.FromObject(output);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/message");
}
[TestMethod]
public void ListWorkspaces_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListWorkspaces(pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void CreateWorkspace_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var name = "name";
var description = "description";
var language = "language";
var metadata = new Dictionary<string, object>();
metadata.Add("metadata", new object());
var learningOptOut = false;
var systemSettings = new WorkspaceSystemSettings();
var intents = new List<CreateIntent>();
var entities = new List<CreateEntity>();
var dialogNodes = new List<DialogNode>();
var counterexamples = new List<Counterexample>();
var webhooks = new List<Webhook>();
var result = service.CreateWorkspace(name: name, description: description, language: language, metadata: metadata, learningOptOut: learningOptOut, systemSettings: systemSettings, intents: intents, entities: entities, dialogNodes: dialogNodes, counterexamples: counterexamples, webhooks: webhooks);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(language))
{
bodyObject["language"] = JToken.FromObject(language);
}
if (metadata != null)
{
bodyObject["metadata"] = JToken.FromObject(metadata);
}
bodyObject["learning_opt_out"] = JToken.FromObject(learningOptOut);
if (systemSettings != null)
{
bodyObject["system_settings"] = JToken.FromObject(systemSettings);
}
if (intents != null && intents.Count > 0)
{
bodyObject["intents"] = JToken.FromObject(intents);
}
if (entities != null && entities.Count > 0)
{
bodyObject["entities"] = JToken.FromObject(entities);
}
if (dialogNodes != null && dialogNodes.Count > 0)
{
bodyObject["dialog_nodes"] = JToken.FromObject(dialogNodes);
}
if (counterexamples != null && counterexamples.Count > 0)
{
bodyObject["counterexamples"] = JToken.FromObject(counterexamples);
}
if (webhooks != null && webhooks.Count > 0)
{
bodyObject["webhooks"] = JToken.FromObject(webhooks);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
}
[TestMethod]
public void GetWorkspace_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var export = false;
var includeAudit = false;
var sort = "sort";
var result = service.GetWorkspace(workspaceId: workspaceId, export: export, includeAudit: includeAudit, sort: sort);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}");
}
[TestMethod]
public void UpdateWorkspace_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var name = "name";
var description = "description";
var language = "language";
var metadata = new Dictionary<string, object>();
metadata.Add("metadata", new object());
var learningOptOut = false;
var systemSettings = new WorkspaceSystemSettings();
var intents = new List<CreateIntent>();
var entities = new List<CreateEntity>();
var dialogNodes = new List<DialogNode>();
var counterexamples = new List<Counterexample>();
var webhooks = new List<Webhook>();
var append = false;
var result = service.UpdateWorkspace(workspaceId: workspaceId, name: name, description: description, language: language, metadata: metadata, learningOptOut: learningOptOut, systemSettings: systemSettings, intents: intents, entities: entities, dialogNodes: dialogNodes, counterexamples: counterexamples, webhooks: webhooks, append: append);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(language))
{
bodyObject["language"] = JToken.FromObject(language);
}
if (metadata != null)
{
bodyObject["metadata"] = JToken.FromObject(metadata);
}
bodyObject["learning_opt_out"] = JToken.FromObject(learningOptOut);
if (systemSettings != null)
{
bodyObject["system_settings"] = JToken.FromObject(systemSettings);
}
if (intents != null && intents.Count > 0)
{
bodyObject["intents"] = JToken.FromObject(intents);
}
if (entities != null && entities.Count > 0)
{
bodyObject["entities"] = JToken.FromObject(entities);
}
if (dialogNodes != null && dialogNodes.Count > 0)
{
bodyObject["dialog_nodes"] = JToken.FromObject(dialogNodes);
}
if (counterexamples != null && counterexamples.Count > 0)
{
bodyObject["counterexamples"] = JToken.FromObject(counterexamples);
}
if (webhooks != null && webhooks.Count > 0)
{
bodyObject["webhooks"] = JToken.FromObject(webhooks);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}");
}
[TestMethod]
public void DeleteWorkspace_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var result = service.DeleteWorkspace(workspaceId: workspaceId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}");
}
[TestMethod]
public void ListIntents_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var export = false;
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListIntents(workspaceId: workspaceId, export: export, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents");
}
[TestMethod]
public void CreateIntent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var description = "description";
var examples = new List<Example>();
var result = service.CreateIntent(workspaceId: workspaceId, intent: intent, description: description, examples: examples);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(intent))
{
bodyObject["intent"] = JToken.FromObject(intent);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (examples != null && examples.Count > 0)
{
bodyObject["examples"] = JToken.FromObject(examples);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents");
}
[TestMethod]
public void GetIntent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var export = false;
var includeAudit = false;
var result = service.GetIntent(workspaceId: workspaceId, intent: intent, export: export, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}");
}
[TestMethod]
public void UpdateIntent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var newIntent = "newIntent";
var newDescription = "newDescription";
var newExamples = new List<Example>();
var result = service.UpdateIntent(workspaceId: workspaceId, intent: intent, newIntent: newIntent, newDescription: newDescription, newExamples: newExamples);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newIntent))
{
bodyObject["intent"] = JToken.FromObject(newIntent);
}
if (!string.IsNullOrEmpty(newDescription))
{
bodyObject["description"] = JToken.FromObject(newDescription);
}
if (newExamples != null && newExamples.Count > 0)
{
bodyObject["examples"] = JToken.FromObject(newExamples);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}");
}
[TestMethod]
public void DeleteIntent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var result = service.DeleteIntent(workspaceId: workspaceId, intent: intent);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}");
}
[TestMethod]
public void ListExamples_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListExamples(workspaceId: workspaceId, intent: intent, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}/examples");
}
[TestMethod]
public void CreateExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var text = "text";
var mentions = new List<Mention>();
var result = service.CreateExample(workspaceId: workspaceId, intent: intent, text: text, mentions: mentions);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(text))
{
bodyObject["text"] = JToken.FromObject(text);
}
if (mentions != null && mentions.Count > 0)
{
bodyObject["mentions"] = JToken.FromObject(mentions);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}/examples");
}
[TestMethod]
public void GetExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var text = "text";
var includeAudit = false;
var result = service.GetExample(workspaceId: workspaceId, intent: intent, text: text, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}/examples/{text}");
}
[TestMethod]
public void UpdateExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var text = "text";
var newText = "newText";
var newMentions = new List<Mention>();
var result = service.UpdateExample(workspaceId: workspaceId, intent: intent, text: text, newText: newText, newMentions: newMentions);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newText))
{
bodyObject["text"] = JToken.FromObject(newText);
}
if (newMentions != null && newMentions.Count > 0)
{
bodyObject["mentions"] = JToken.FromObject(newMentions);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}/examples/{text}");
}
[TestMethod]
public void DeleteExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var intent = "intent";
var text = "text";
var result = service.DeleteExample(workspaceId: workspaceId, intent: intent, text: text);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/intents/{intent}/examples/{text}");
}
[TestMethod]
public void ListCounterexamples_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListCounterexamples(workspaceId: workspaceId, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/counterexamples");
}
[TestMethod]
public void CreateCounterexample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var text = "text";
var result = service.CreateCounterexample(workspaceId: workspaceId, text: text);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(text))
{
bodyObject["text"] = JToken.FromObject(text);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/counterexamples");
}
[TestMethod]
public void GetCounterexample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var text = "text";
var includeAudit = false;
var result = service.GetCounterexample(workspaceId: workspaceId, text: text, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/counterexamples/{text}");
}
[TestMethod]
public void UpdateCounterexample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var text = "text";
var newText = "newText";
var result = service.UpdateCounterexample(workspaceId: workspaceId, text: text, newText: newText);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newText))
{
bodyObject["text"] = JToken.FromObject(newText);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/counterexamples/{text}");
}
[TestMethod]
public void DeleteCounterexample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var text = "text";
var result = service.DeleteCounterexample(workspaceId: workspaceId, text: text);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/counterexamples/{text}");
}
[TestMethod]
public void ListEntities_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var export = false;
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListEntities(workspaceId: workspaceId, export: export, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities");
}
[TestMethod]
public void CreateEntity_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var description = "description";
var metadata = new Dictionary<string, object>();
metadata.Add("metadata", new object());
var fuzzyMatch = false;
var values = new List<CreateValue>();
var result = service.CreateEntity(workspaceId: workspaceId, entity: entity, description: description, metadata: metadata, fuzzyMatch: fuzzyMatch, values: values);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(entity))
{
bodyObject["entity"] = JToken.FromObject(entity);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (metadata != null)
{
bodyObject["metadata"] = JToken.FromObject(metadata);
}
bodyObject["fuzzy_match"] = JToken.FromObject(fuzzyMatch);
if (values != null && values.Count > 0)
{
bodyObject["values"] = JToken.FromObject(values);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities");
}
[TestMethod]
public void GetEntity_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var export = false;
var includeAudit = false;
var result = service.GetEntity(workspaceId: workspaceId, entity: entity, export: export, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}");
}
[TestMethod]
public void UpdateEntity_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var newEntity = "newEntity";
var newDescription = "newDescription";
var newMetadata = new Dictionary<string, object>();
newMetadata.Add("newMetadata", new object());
var newFuzzyMatch = false;
var newValues = new List<CreateValue>();
var result = service.UpdateEntity(workspaceId: workspaceId, entity: entity, newEntity: newEntity, newDescription: newDescription, newMetadata: newMetadata, newFuzzyMatch: newFuzzyMatch, newValues: newValues);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newEntity))
{
bodyObject["entity"] = JToken.FromObject(newEntity);
}
if (!string.IsNullOrEmpty(newDescription))
{
bodyObject["description"] = JToken.FromObject(newDescription);
}
if (newMetadata != null)
{
bodyObject["metadata"] = JToken.FromObject(newMetadata);
}
bodyObject["fuzzy_match"] = JToken.FromObject(newFuzzyMatch);
if (newValues != null && newValues.Count > 0)
{
bodyObject["values"] = JToken.FromObject(newValues);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}");
}
[TestMethod]
public void DeleteEntity_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var result = service.DeleteEntity(workspaceId: workspaceId, entity: entity);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}");
}
[TestMethod]
public void ListMentions_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var export = false;
var includeAudit = false;
var result = service.ListMentions(workspaceId: workspaceId, entity: entity, export: export, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/mentions");
}
[TestMethod]
public void ListValues_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var export = false;
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListValues(workspaceId: workspaceId, entity: entity, export: export, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values");
}
[TestMethod]
public void CreateValue_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var metadata = new Dictionary<string, object>();
metadata.Add("metadata", new object());
var type = "type";
var synonyms = new List<string>();
var patterns = new List<string>();
var result = service.CreateValue(workspaceId: workspaceId, entity: entity, value: value, metadata: metadata, type: type, synonyms: synonyms, patterns: patterns);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(value))
{
bodyObject["value"] = JToken.FromObject(value);
}
if (metadata != null)
{
bodyObject["metadata"] = JToken.FromObject(metadata);
}
if (!string.IsNullOrEmpty(type))
{
bodyObject["type"] = JToken.FromObject(type);
}
if (synonyms != null && synonyms.Count > 0)
{
bodyObject["synonyms"] = JToken.FromObject(synonyms);
}
if (patterns != null && patterns.Count > 0)
{
bodyObject["patterns"] = JToken.FromObject(patterns);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values");
}
[TestMethod]
public void GetValue_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var export = false;
var includeAudit = false;
var result = service.GetValue(workspaceId: workspaceId, entity: entity, value: value, export: export, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}");
}
[TestMethod]
public void UpdateValue_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var newValue = "newValue";
var newMetadata = new Dictionary<string, object>();
newMetadata.Add("newMetadata", new object());
var newType = "newType";
var newSynonyms = new List<string>();
var newPatterns = new List<string>();
var result = service.UpdateValue(workspaceId: workspaceId, entity: entity, value: value, newValue: newValue, newMetadata: newMetadata, newType: newType, newSynonyms: newSynonyms, newPatterns: newPatterns);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newValue))
{
bodyObject["value"] = JToken.FromObject(newValue);
}
if (newMetadata != null)
{
bodyObject["metadata"] = JToken.FromObject(newMetadata);
}
if (!string.IsNullOrEmpty(newType))
{
bodyObject["type"] = JToken.FromObject(newType);
}
if (newSynonyms != null && newSynonyms.Count > 0)
{
bodyObject["synonyms"] = JToken.FromObject(newSynonyms);
}
if (newPatterns != null && newPatterns.Count > 0)
{
bodyObject["patterns"] = JToken.FromObject(newPatterns);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}");
}
[TestMethod]
public void DeleteValue_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var result = service.DeleteValue(workspaceId: workspaceId, entity: entity, value: value);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}");
}
[TestMethod]
public void ListSynonyms_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListSynonyms(workspaceId: workspaceId, entity: entity, value: value, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms");
}
[TestMethod]
public void CreateSynonym_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var synonym = "synonym";
var result = service.CreateSynonym(workspaceId: workspaceId, entity: entity, value: value, synonym: synonym);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(synonym))
{
bodyObject["synonym"] = JToken.FromObject(synonym);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms");
}
[TestMethod]
public void GetSynonym_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var synonym = "synonym";
var includeAudit = false;
var result = service.GetSynonym(workspaceId: workspaceId, entity: entity, value: value, synonym: synonym, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms/{synonym}");
}
[TestMethod]
public void UpdateSynonym_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var synonym = "synonym";
var newSynonym = "newSynonym";
var result = service.UpdateSynonym(workspaceId: workspaceId, entity: entity, value: value, synonym: synonym, newSynonym: newSynonym);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newSynonym))
{
bodyObject["synonym"] = JToken.FromObject(newSynonym);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms/{synonym}");
}
[TestMethod]
public void DeleteSynonym_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var entity = "entity";
var value = "value";
var synonym = "synonym";
var result = service.DeleteSynonym(workspaceId: workspaceId, entity: entity, value: value, synonym: synonym);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms/{synonym}");
}
[TestMethod]
public void ListDialogNodes_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
long? pageLimit = 1;
var sort = "sort";
var cursor = "cursor";
var includeAudit = false;
var result = service.ListDialogNodes(workspaceId: workspaceId, pageLimit: pageLimit, sort: sort, cursor: cursor, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/dialog_nodes");
}
[TestMethod]
public void CreateDialogNode_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var dialogNode = "dialogNode";
var description = "description";
var conditions = "conditions";
var parent = "parent";
var previousSibling = "previousSibling";
var output = new DialogNodeOutput();
var context = new DialogNodeContext();
context.Add("context", new object());
var metadata = new Dictionary<string, object>();
metadata.Add("metadata", new object());
var nextStep = new DialogNodeNextStep();
var title = "title";
var type = "type";
var eventName = "eventName";
var variable = "variable";
var actions = new List<DialogNodeAction>();
var digressIn = "digressIn";
var digressOut = "digressOut";
var digressOutSlots = "digressOutSlots";
var userLabel = "userLabel";
var disambiguationOptOut = false;
var result = service.CreateDialogNode(workspaceId: workspaceId, dialogNode: dialogNode, description: description, conditions: conditions, parent: parent, previousSibling: previousSibling, output: output, context: context, metadata: metadata, nextStep: nextStep, title: title, type: type, eventName: eventName, variable: variable, actions: actions, digressIn: digressIn, digressOut: digressOut, digressOutSlots: digressOutSlots, userLabel: userLabel, disambiguationOptOut: disambiguationOptOut);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(dialogNode))
{
bodyObject["dialog_node"] = JToken.FromObject(dialogNode);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(conditions))
{
bodyObject["conditions"] = JToken.FromObject(conditions);
}
if (!string.IsNullOrEmpty(parent))
{
bodyObject["parent"] = JToken.FromObject(parent);
}
if (!string.IsNullOrEmpty(previousSibling))
{
bodyObject["previous_sibling"] = JToken.FromObject(previousSibling);
}
if (output != null)
{
bodyObject["output"] = JToken.FromObject(output);
}
if (context != null)
{
bodyObject["context"] = JToken.FromObject(context);
}
if (metadata != null)
{
bodyObject["metadata"] = JToken.FromObject(metadata);
}
if (nextStep != null)
{
bodyObject["next_step"] = JToken.FromObject(nextStep);
}
if (!string.IsNullOrEmpty(title))
{
bodyObject["title"] = JToken.FromObject(title);
}
if (!string.IsNullOrEmpty(type))
{
bodyObject["type"] = JToken.FromObject(type);
}
if (!string.IsNullOrEmpty(eventName))
{
bodyObject["event_name"] = JToken.FromObject(eventName);
}
if (!string.IsNullOrEmpty(variable))
{
bodyObject["variable"] = JToken.FromObject(variable);
}
if (actions != null && actions.Count > 0)
{
bodyObject["actions"] = JToken.FromObject(actions);
}
if (!string.IsNullOrEmpty(digressIn))
{
bodyObject["digress_in"] = JToken.FromObject(digressIn);
}
if (!string.IsNullOrEmpty(digressOut))
{
bodyObject["digress_out"] = JToken.FromObject(digressOut);
}
if (!string.IsNullOrEmpty(digressOutSlots))
{
bodyObject["digress_out_slots"] = JToken.FromObject(digressOutSlots);
}
if (!string.IsNullOrEmpty(userLabel))
{
bodyObject["user_label"] = JToken.FromObject(userLabel);
}
bodyObject["disambiguation_opt_out"] = JToken.FromObject(disambiguationOptOut);
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/dialog_nodes");
}
[TestMethod]
public void GetDialogNode_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var dialogNode = "dialogNode";
var includeAudit = false;
var result = service.GetDialogNode(workspaceId: workspaceId, dialogNode: dialogNode, includeAudit: includeAudit);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/dialog_nodes/{dialogNode}");
}
[TestMethod]
public void UpdateDialogNode_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var dialogNode = "dialogNode";
var newDialogNode = "newDialogNode";
var newDescription = "newDescription";
var newConditions = "newConditions";
var newParent = "newParent";
var newPreviousSibling = "newPreviousSibling";
var newOutput = new DialogNodeOutput();
var newContext = new DialogNodeContext();
newContext.Add("newContext", new object());
var newMetadata = new Dictionary<string, object>();
newMetadata.Add("newMetadata", new object());
var newNextStep = new DialogNodeNextStep();
var newTitle = "newTitle";
var newType = "newType";
var newEventName = "newEventName";
var newVariable = "newVariable";
var newActions = new List<DialogNodeAction>();
var newDigressIn = "newDigressIn";
var newDigressOut = "newDigressOut";
var newDigressOutSlots = "newDigressOutSlots";
var newUserLabel = "newUserLabel";
var newDisambiguationOptOut = false;
var result = service.UpdateDialogNode(workspaceId: workspaceId, dialogNode: dialogNode, newDialogNode: newDialogNode, newDescription: newDescription, newConditions: newConditions, newParent: newParent, newPreviousSibling: newPreviousSibling, newOutput: newOutput, newContext: newContext, newMetadata: newMetadata, newNextStep: newNextStep, newTitle: newTitle, newType: newType, newEventName: newEventName, newVariable: newVariable, newActions: newActions, newDigressIn: newDigressIn, newDigressOut: newDigressOut, newDigressOutSlots: newDigressOutSlots, newUserLabel: newUserLabel, newDisambiguationOptOut: newDisambiguationOptOut);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(newDialogNode))
{
bodyObject["dialog_node"] = JToken.FromObject(newDialogNode);
}
if (!string.IsNullOrEmpty(newDescription))
{
bodyObject["description"] = JToken.FromObject(newDescription);
}
if (!string.IsNullOrEmpty(newConditions))
{
bodyObject["conditions"] = JToken.FromObject(newConditions);
}
if (!string.IsNullOrEmpty(newParent))
{
bodyObject["parent"] = JToken.FromObject(newParent);
}
if (!string.IsNullOrEmpty(newPreviousSibling))
{
bodyObject["previous_sibling"] = JToken.FromObject(newPreviousSibling);
}
if (newOutput != null)
{
bodyObject["output"] = JToken.FromObject(newOutput);
}
if (newContext != null)
{
bodyObject["context"] = JToken.FromObject(newContext);
}
if (newMetadata != null)
{
bodyObject["metadata"] = JToken.FromObject(newMetadata);
}
if (newNextStep != null)
{
bodyObject["next_step"] = JToken.FromObject(newNextStep);
}
if (!string.IsNullOrEmpty(newTitle))
{
bodyObject["title"] = JToken.FromObject(newTitle);
}
if (!string.IsNullOrEmpty(newType))
{
bodyObject["type"] = JToken.FromObject(newType);
}
if (!string.IsNullOrEmpty(newEventName))
{
bodyObject["event_name"] = JToken.FromObject(newEventName);
}
if (!string.IsNullOrEmpty(newVariable))
{
bodyObject["variable"] = JToken.FromObject(newVariable);
}
if (newActions != null && newActions.Count > 0)
{
bodyObject["actions"] = JToken.FromObject(newActions);
}
if (!string.IsNullOrEmpty(newDigressIn))
{
bodyObject["digress_in"] = JToken.FromObject(newDigressIn);
}
if (!string.IsNullOrEmpty(newDigressOut))
{
bodyObject["digress_out"] = JToken.FromObject(newDigressOut);
}
if (!string.IsNullOrEmpty(newDigressOutSlots))
{
bodyObject["digress_out_slots"] = JToken.FromObject(newDigressOutSlots);
}
if (!string.IsNullOrEmpty(newUserLabel))
{
bodyObject["user_label"] = JToken.FromObject(newUserLabel);
}
bodyObject["disambiguation_opt_out"] = JToken.FromObject(newDisambiguationOptOut);
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/dialog_nodes/{dialogNode}");
}
[TestMethod]
public void DeleteDialogNode_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var dialogNode = "dialogNode";
var result = service.DeleteDialogNode(workspaceId: workspaceId, dialogNode: dialogNode);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/dialog_nodes/{dialogNode}");
}
[TestMethod]
public void ListLogs_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var workspaceId = "workspaceId";
var sort = "sort";
var filter = "filter";
long? pageLimit = 1;
var cursor = "cursor";
var result = service.ListLogs(workspaceId: workspaceId, sort: sort, filter: filter, pageLimit: pageLimit, cursor: cursor);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/workspaces/{workspaceId}/logs");
}
[TestMethod]
public void ListAllLogs_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var filter = "filter";
var sort = "sort";
long? pageLimit = 1;
var cursor = "cursor";
var result = service.ListAllLogs(filter: filter, sort: sort, pageLimit: pageLimit, cursor: cursor);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void DeleteUserData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
AssistantService service = new AssistantService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var customerId = "customerId";
var result = service.DeleteUserData(customerId: customerId);
request.Received().WithArgument("version", versionDate);
}
}
}
| |
using System;
using System.Linq;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Services.Localization;
using Nop.Services.Messages;
using Nop.Services.Security;
using Nop.Services.Stores;
namespace Nop.Services.Customers
{
/// <summary>
/// Customer registration service
/// </summary>
public partial class CustomerRegistrationService : ICustomerRegistrationService
{
#region Fields
private readonly ICustomerService _customerService;
private readonly IEncryptionService _encryptionService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly ILocalizationService _localizationService;
private readonly IStoreService _storeService;
private readonly RewardPointsSettings _rewardPointsSettings;
private readonly CustomerSettings _customerSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="customerService">Customer service</param>
/// <param name="encryptionService">Encryption service</param>
/// <param name="newsLetterSubscriptionService">Newsletter subscription service</param>
/// <param name="localizationService">Localization service</param>
/// <param name="storeService">Store service</param>
/// <param name="rewardPointsSettings">Reward points settings</param>
/// <param name="customerSettings">Customer settings</param>
public CustomerRegistrationService(ICustomerService customerService,
IEncryptionService encryptionService,
INewsLetterSubscriptionService newsLetterSubscriptionService,
ILocalizationService localizationService,
IStoreService storeService,
RewardPointsSettings rewardPointsSettings,
CustomerSettings customerSettings)
{
this._customerService = customerService;
this._encryptionService = encryptionService;
this._newsLetterSubscriptionService = newsLetterSubscriptionService;
this._localizationService = localizationService;
this._storeService = storeService;
this._rewardPointsSettings = rewardPointsSettings;
this._customerSettings = customerSettings;
}
#endregion
#region Methods
/// <summary>
/// Validate customer
/// </summary>
/// <param name="usernameOrEmail">Username or email</param>
/// <param name="password">Password</param>
/// <returns>Result</returns>
public virtual CustomerLoginResults ValidateCustomer(string usernameOrEmail, string password)
{
Customer customer = null;
if (_customerSettings.UsernamesEnabled)
customer = _customerService.GetCustomerByUsername(usernameOrEmail);
else
customer = _customerService.GetCustomerByEmail(usernameOrEmail);
if (customer == null)
return CustomerLoginResults.CustomerNotExist;
if (customer.Deleted)
return CustomerLoginResults.Deleted;
if (!customer.Active)
return CustomerLoginResults.NotActive;
//only registered can login
if (!customer.IsRegistered())
return CustomerLoginResults.NotRegistered;
string pwd = "";
switch (customer.PasswordFormat)
{
case PasswordFormat.Encrypted:
pwd = _encryptionService.EncryptText(password);
break;
case PasswordFormat.Hashed:
pwd = _encryptionService.CreatePasswordHash(password, customer.PasswordSalt, _customerSettings.HashedPasswordFormat);
break;
default:
pwd = password;
break;
}
bool isValid = pwd == customer.Password;
//save last login date
if (isValid)
{
customer.LastLoginDateUtc = DateTime.UtcNow;
_customerService.UpdateCustomer(customer);
return CustomerLoginResults.Successful;
}
else
return CustomerLoginResults.WrongPassword;
}
/// <summary>
/// Register customer
/// </summary>
/// <param name="request">Request</param>
/// <returns>Result</returns>
public virtual CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
if (request.Customer == null)
throw new ArgumentException("Can't load current customer");
var result = new CustomerRegistrationResult();
if (request.Customer.IsSearchEngineAccount())
{
result.AddError("Search engine can't be registered");
return result;
}
if (request.Customer.IsBackgroundTaskAccount())
{
result.AddError("Background task account can't be registered");
return result;
}
if (request.Customer.IsRegistered())
{
result.AddError("Current customer is already registered");
return result;
}
if (String.IsNullOrEmpty(request.Email))
{
result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided"));
return result;
}
if (!CommonHelper.IsValidEmail(request.Email))
{
result.AddError(_localizationService.GetResource("Common.WrongEmail"));
return result;
}
if (String.IsNullOrWhiteSpace(request.Password))
{
result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided"));
return result;
}
if (_customerSettings.UsernamesEnabled)
{
if (String.IsNullOrEmpty(request.Username))
{
result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided"));
return result;
}
}
//validate unique user
if (_customerService.GetCustomerByEmail(request.Email) != null)
{
result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists"));
return result;
}
if (_customerSettings.UsernamesEnabled)
{
if (_customerService.GetCustomerByUsername(request.Username) != null)
{
result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists"));
return result;
}
}
//at this point request is valid
request.Customer.Username = request.Username;
request.Customer.Email = request.Email;
request.Customer.PasswordFormat = request.PasswordFormat;
switch (request.PasswordFormat)
{
case PasswordFormat.Clear:
{
request.Customer.Password = request.Password;
}
break;
case PasswordFormat.Encrypted:
{
request.Customer.Password = _encryptionService.EncryptText(request.Password);
}
break;
case PasswordFormat.Hashed:
{
string saltKey = _encryptionService.CreateSaltKey(5);
request.Customer.PasswordSalt = saltKey;
request.Customer.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);
}
break;
default:
break;
}
request.Customer.Active = request.IsApproved;
//add to 'Registered' role
var registeredRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered);
if (registeredRole == null)
throw new NopException("'Registered' role could not be loaded");
request.Customer.CustomerRoles.Add(registeredRole);
//remove from 'Guests' role
var guestRole = request.Customer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == SystemCustomerRoleNames.Guests);
if (guestRole != null)
request.Customer.CustomerRoles.Remove(guestRole);
//Add reward points for customer registration (if enabled)
if (_rewardPointsSettings.Enabled &&
_rewardPointsSettings.PointsForRegistration > 0)
request.Customer.AddRewardPointsHistoryEntry(_rewardPointsSettings.PointsForRegistration, _localizationService.GetResource("RewardPoints.Message.EarnedForRegistration"));
_customerService.UpdateCustomer(request.Customer);
return result;
}
/// <summary>
/// Change password
/// </summary>
/// <param name="request">Request</param>
/// <returns>Result</returns>
public virtual PasswordChangeResult ChangePassword(ChangePasswordRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
var result = new PasswordChangeResult();
if (String.IsNullOrWhiteSpace(request.Email))
{
result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.EmailIsNotProvided"));
return result;
}
if (String.IsNullOrWhiteSpace(request.NewPassword))
{
result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.PasswordIsNotProvided"));
return result;
}
var customer = _customerService.GetCustomerByEmail(request.Email);
if (customer == null)
{
result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.EmailNotFound"));
return result;
}
var requestIsValid = false;
if (request.ValidateRequest)
{
//password
string oldPwd = "";
switch (customer.PasswordFormat)
{
case PasswordFormat.Encrypted:
oldPwd = _encryptionService.EncryptText(request.OldPassword);
break;
case PasswordFormat.Hashed:
oldPwd = _encryptionService.CreatePasswordHash(request.OldPassword, customer.PasswordSalt, _customerSettings.HashedPasswordFormat);
break;
default:
oldPwd = request.OldPassword;
break;
}
bool oldPasswordIsValid = oldPwd == customer.Password;
if (!oldPasswordIsValid)
result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.OldPasswordDoesntMatch"));
if (oldPasswordIsValid)
requestIsValid = true;
}
else
requestIsValid = true;
//at this point request is valid
if (requestIsValid)
{
switch (request.NewPasswordFormat)
{
case PasswordFormat.Clear:
{
customer.Password = request.NewPassword;
}
break;
case PasswordFormat.Encrypted:
{
customer.Password = _encryptionService.EncryptText(request.NewPassword);
}
break;
case PasswordFormat.Hashed:
{
string saltKey = _encryptionService.CreateSaltKey(5);
customer.PasswordSalt = saltKey;
customer.Password = _encryptionService.CreatePasswordHash(request.NewPassword, saltKey, _customerSettings.HashedPasswordFormat);
}
break;
default:
break;
}
customer.PasswordFormat = request.NewPasswordFormat;
_customerService.UpdateCustomer(customer);
}
return result;
}
/// <summary>
/// Sets a user email
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="newEmail">New email</param>
public virtual void SetEmail(Customer customer, string newEmail)
{
if (customer == null)
throw new ArgumentNullException("customer");
newEmail = newEmail.Trim();
string oldEmail = customer.Email;
if (!CommonHelper.IsValidEmail(newEmail))
throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));
if (newEmail.Length > 100)
throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));
var customer2 = _customerService.GetCustomerByEmail(newEmail);
if (customer2 != null && customer.Id != customer2.Id)
throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));
customer.Email = newEmail;
_customerService.UpdateCustomer(customer);
//update newsletter subscription (if required)
if (!String.IsNullOrEmpty(oldEmail) && !oldEmail.Equals(newEmail, StringComparison.InvariantCultureIgnoreCase))
{
foreach (var store in _storeService.GetAllStores())
{
var subscriptionOld = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(oldEmail, store.Id);
if (subscriptionOld != null)
{
subscriptionOld.Email = newEmail;
_newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);
}
}
}
}
/// <summary>
/// Sets a customer username
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="newUsername">New Username</param>
public virtual void SetUsername(Customer customer, string newUsername)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (!_customerSettings.UsernamesEnabled)
throw new NopException("Usernames are disabled");
if (!_customerSettings.AllowUsersToChangeUsernames)
throw new NopException("Changing usernames is not allowed");
newUsername = newUsername.Trim();
if (newUsername.Length > 100)
throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong"));
var user2 = _customerService.GetCustomerByUsername(newUsername);
if (user2 != null && customer.Id != user2.Id)
throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists"));
customer.Username = newUsername;
_customerService.UpdateCustomer(customer);
}
#endregion
}
}
| |
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.ComponentModel;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Abstract Cimindication event args, which containing all elements related to
/// an Cimindication.
/// </para>
/// </summary>
public abstract class CimIndicationEventArgs : EventArgs
{
/// <summary>
/// <para>
/// Returns an Object value for an operation context
/// </para>
/// </summary>
public Object Context
{
get
{
return context;
}
}
internal Object context;
}
/// <summary>
/// Cimindication exception event args, which containing occurred exception
/// </summary>
public class CimIndicationEventExceptionEventArgs : CimIndicationEventArgs
{
/// <summary>
/// <para>
/// Returns an exception
/// </para>
/// </summary>
public Exception Exception
{
get
{
return exception;
}
}
private Exception exception;
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="result"></param>
public CimIndicationEventExceptionEventArgs(Exception theException)
{
context = null;
this.exception = theException;
}
}
/// <summary>
/// Cimindication event args, which containing all elements related to
/// an Cimindication.
/// </summary>
public class CimIndicationEventInstanceEventArgs : CimIndicationEventArgs
{
/// <summary>
/// Get ciminstance of the indication object
/// </summary>
public CimInstance NewEvent
{
get
{
return (result == null) ? null : result.Instance;
}
}
/// <summary>
/// Get MachineId of the indication object
/// </summary>
public string MachineId
{
get
{
return (result == null) ? null : result.MachineId;
}
}
/// <summary>
/// Get BookMark of the indication object
/// </summary>
public string Bookmark
{
get
{
return (result == null) ? null : result.Bookmark;
}
}
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="result"></param>
public CimIndicationEventInstanceEventArgs(CimSubscriptionResult result)
{
context = null;
this.result = result;
}
/// <summary>
/// <para>
/// subscription result
/// </para>
/// </summary>
private CimSubscriptionResult result;
}
/// <summary>
/// <para>
/// A public class used to start/stop the subscription to specific indication source,
/// and listen to the incoming indications, event <see cref="CimIndicationArrived"/>
/// will be raised for each cimindication.
/// </para>
/// </summary>
public class CimIndicationWatcher
{
/// <summary>
/// status of <see cref="CimIndicationWatcher"/> object.
/// </summary>
internal enum Status
{
Default,
Started,
Stopped
}
/// <summary>
/// <para>
/// CimIndication arrived event
/// </para>
/// </summary>
public event EventHandler<CimIndicationEventArgs> CimIndicationArrived;
/// <summary>
/// <para>
/// Constructor with given computerName, namespace, queryExpression and timeout
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="nameSpace"></param>
/// <param name="queryExpression"></param>
/// <param name="opreationTimeout"></param>
public CimIndicationWatcher(
string computerName,
string theNamespace,
string queryDialect,
string queryExpression,
UInt32 operationTimeout)
{
ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName);
computerName = ConstValue.GetComputerName(computerName);
theNamespace = ConstValue.GetNamespace(theNamespace);
Initialize(computerName, null, theNamespace, queryDialect, queryExpression, operationTimeout);
}
/// <summary>
/// <para>
/// Constructor with given cimsession, namespace, queryExpression and timeout
/// </para>
/// </summary>
/// <param name="cimSession"></param>
/// <param name="nameSpace"></param>
/// <param name="queryExpression"></param>
/// <param name="opreationTimeout"></param>
public CimIndicationWatcher(
CimSession cimSession,
string theNamespace,
string queryDialect,
string queryExpression,
UInt32 operationTimeout)
{
ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName);
ValidationHelper.ValidateNoNullArgument(cimSession, cimSessionParameterName);
theNamespace = ConstValue.GetNamespace(theNamespace);
Initialize(null, cimSession, theNamespace, queryDialect, queryExpression, operationTimeout);
}
/// <summary>
/// <para>
/// Initialize
/// </para>
/// </summary>
private void Initialize(
string theComputerName,
CimSession theCimSession,
string theNameSpace,
string theQueryDialect,
string theQueryExpression,
UInt32 theOpreationTimeout)
{
enableRaisingEvents = false;
status = Status.Default;
myLock = new object();
cimRegisterCimIndication = new CimRegisterCimIndication();
cimRegisterCimIndication.OnNewSubscriptionResult += NewSubscriptionResultHandler;
this.cimSession = theCimSession;
this.nameSpace = theNameSpace;
this.queryDialect = ConstValue.GetQueryDialectWithDefault(theQueryDialect);
this.queryExpression = theQueryExpression;
this.opreationTimeout = theOpreationTimeout;
this.computerName = theComputerName;
}
/// <summary>
/// <para>
/// Hanlder of new subscription result
/// </para>
/// </summary>
/// <param name="src"></param>
/// <param name="args"></param>
private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs args)
{
EventHandler<CimIndicationEventArgs> temp = this.CimIndicationArrived;
if (temp != null)
{
// raise the event
CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs;
if (resultArgs != null)
temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result));
else
{
CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs;
if (exceptionArgs != null)
temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception));
}
}
}
/// <summary>
/// <para>
/// Will be called by admin\monad\src\eengine\EventManager.cs:
/// PSEventManager::ProcessNewSubscriber to start to listen to the Cim Indication.
/// </para>
/// <para>
/// If set EnableRaisingEvents to false, which will be ignored
/// </para>
/// </summary>
#if !CORECLR
[BrowsableAttribute(false)]
#endif
public bool EnableRaisingEvents
{
get
{
return enableRaisingEvents;
}
set
{
DebugHelper.WriteLogEx();
if (value && !enableRaisingEvents)
{
enableRaisingEvents = value;
Start();
}
}
}
private bool enableRaisingEvents;
/// <summary>
/// <para>
/// Start the subscription
/// </para>
/// </summary>
public void Start()
{
DebugHelper.WriteLogEx();
lock(myLock)
{
if (status == Status.Default)
{
if (this.cimSession == null)
{
cimRegisterCimIndication.RegisterCimIndication(
this.computerName,
this.nameSpace,
this.queryDialect,
this.queryExpression,
this.opreationTimeout);
}
else
{
cimRegisterCimIndication.RegisterCimIndication(
this.cimSession,
this.nameSpace,
this.queryDialect,
this.queryExpression,
this.opreationTimeout);
}
status = Status.Started;
}
}
}
/// <summary>
/// <para>
/// Unsubscribe the subscription
/// </para>
/// </summary>
public void Stop()
{
DebugHelper.WriteLogEx("Status = {0}", 0, this.status);
lock (this.myLock)
{
if (status == Status.Started)
{
if (this.cimRegisterCimIndication != null)
{
DebugHelper.WriteLog("Dispose CimRegisterCimIndication object", 4);
this.cimRegisterCimIndication.Dispose();
}
status = Status.Stopped;
}
}
}
#region internal method
/// <summary>
/// Set the cmdlet object to throw ThrowTerminatingError
/// in case there is a subscription failure
/// </summary>
/// <param name="cmdlet"></param>
internal void SetCmdlet(Cmdlet cmdlet)
{
if (this.cimRegisterCimIndication != null)
{
this.cimRegisterCimIndication.Cmdlet = cmdlet;
}
}
#endregion
#region private members
/// <summary>
/// <para>
/// CimRegisterCimIndication object
/// </para>
/// </summary>
private CimRegisterCimIndication cimRegisterCimIndication;
/// <summary>
/// the status of <see cref="CimIndicationWatcher"/> object
/// </summary>
private Status status;
/// <summary>
/// lock started field
/// </summary>
private object myLock;
/// <summary>
/// CimSession parameter name
/// </summary>
private const string cimSessionParameterName = "cimSession";
/// <summary>
/// QueryExpression parameter name
/// </summary>
private const string queryExpressionParameterName = "queryExpression";
#region parameters
/// <summary>
/// <para>
/// parameters used to start the subscription
/// </para>
/// </summary>
private string computerName;
private CimSession cimSession;
private string nameSpace;
private string queryDialect;
private string queryExpression;
private UInt32 opreationTimeout;
#endregion
#endregion
}
}//End namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.