context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DevicesOperations operations.
/// </summary>
public partial interface IDevicesOperations
{
/// <summary>
/// Complete minimal setup before using the device.
/// </summary>
/// <param name='parameters'>
/// The minimal properties to configure a device.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> ConfigureWithHttpMessagesAsync(ConfigureDeviceRequest parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the list of devices for the specified manager.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='expand'>
/// Specify $expand=details to populate additional fields related to
/// the device or $expand=rolloverdetails to populate additional fields
/// related to the service data encryption key rollover on device
/// </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<Device>>> ListByManagerWithHttpMessagesAsync(string resourceGroupName, string managerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the properties of the specified device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='expand'>
/// Specify $expand=details to populate additional fields related to
/// the device or $expand=rolloverdetails to populate additional fields
/// related to the service data encryption key rollover on device
/// </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<Device>> GetWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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 deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patches the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='parameters'>
/// Patch representation of the device.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<Device>> UpdateWithHttpMessagesAsync(string deviceName, DevicePatch parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorizes the specified device for service data encryption key
/// rollover.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> AuthorizeForServiceEncryptionKeyRolloverWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deactivates the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> DeactivateWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Downloads and installs the updates on the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> InstallUpdatesWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns all failover sets for a given device and their eligibility
/// for participating in a failover. A failover set refers to a set of
/// volume containers that need to be failed-over as a single unit to
/// maintain data integrity.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<FailoverSet>>> ListFailoverSetsWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the metrics for the specified device.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<Metrics>>> ListMetricsWithHttpMessagesAsync(ODataQuery<MetricFilter> odataQuery, string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the metric definitions for the specified device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<MetricDefinition>>> ListMetricDefinitionWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Scans for updates on the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> ScanForUpdatesWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the update summary of the specified device name.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<Updates>> GetUpdateSummaryWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Failovers a set of volume containers from a specified source device
/// to a target device.
/// </summary>
/// <param name='sourceDeviceName'>
/// The source device name on which failover is performed.
/// </param>
/// <param name='parameters'>
/// FailoverRequest containing the source device and the list of volume
/// containers to be failed over.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> FailoverWithHttpMessagesAsync(string sourceDeviceName, FailoverRequest parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Given a list of volume containers to be failed over from a source
/// device, this method returns the eligibility result, as a failover
/// target, for all devices under that resource.
/// </summary>
/// <param name='sourceDeviceName'>
/// The source device name on which failover is performed.
/// </param>
/// <param name='parameters'>
/// ListFailoverTargetsRequest containing the list of volume containers
/// to be failed over.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<FailoverTarget>>> ListFailoverTargetsWithHttpMessagesAsync(string sourceDeviceName, ListFailoverTargetsRequest parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Complete minimal setup before using the device.
/// </summary>
/// <param name='parameters'>
/// The minimal properties to configure a device.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> BeginConfigureWithHttpMessagesAsync(ConfigureDeviceRequest parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> BeginDeleteWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deactivates the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> BeginDeactivateWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Downloads and installs the updates on the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> BeginInstallUpdatesWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Scans for updates on the device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> BeginScanForUpdatesWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Failovers a set of volume containers from a specified source device
/// to a target device.
/// </summary>
/// <param name='sourceDeviceName'>
/// The source device name on which failover is performed.
/// </param>
/// <param name='parameters'>
/// FailoverRequest containing the source device and the list of volume
/// containers to be failed over.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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> BeginFailoverWithHttpMessagesAsync(string sourceDeviceName, FailoverRequest parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// Copyright (c) 2009-2010 Krueger Systems, 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.Collections.Generic;
using System.Linq;
using SQLite;
namespace OData.Touch
{
public class Repo : IDisposable
{
SQLiteConnection _db;
static string _path;
static Repo ()
{
_path = System.IO.Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "OData.sqlite");
Console.WriteLine (_path);
}
public Repo ()
{
_db = new SQLiteConnection (_path);
// _db.Trace = true;
}
public void Dispose ()
{
_db.Close ();
}
public void Initialize ()
{
_db.CreateTable<UserService> ();
_db.CreateTable<UserQuery> ();
_db.CreateTable<UserFeed> ();
_db.CreateTable<UserMetadataDocument> ();
}
public UserFeed GetFeed (int feedId)
{
var q = from f in _db.Table<UserFeed> ()
where f.Id == feedId
select f;
return q.FirstOrDefault ();
}
public UserService GetService (int serviceId)
{
var q = from f in _db.Table<UserService> ()
where f.Id == serviceId
select f;
return q.FirstOrDefault ();
}
public void Add (UserService service)
{
_db.Insert (service);
}
public void Save (UserQuery query)
{
_db.Update (query);
}
public void Add (UserQuery query)
{
_db.Insert (query);
}
public void DeleteQuery (int queryId)
{
_db.Execute ("delete from UserQuery where Id = ?", queryId);
}
public void DeleteService (UserService service)
{
_db.RunInTransaction (delegate {
_db.Execute ("delete from UserFeed where ServiceId = ?", service.Id);
_db.Execute ("delete from UserQuery where ServiceId = ?", service.Id);
_db.Execute ("delete from UserService where Id = ?", service.Id);
});
}
public List<UserQuery> GetQueries (UserService service)
{
var q = from qu in _db.Table<UserQuery> ()
where qu.ServiceId == service.Id
orderby qu.Name
select qu;
return q.ToList ();
}
public List<UserFeed> GetFeeds (UserService service)
{
var q = from f in _db.Table<UserFeed> ()
where f.ServiceId == service.Id
orderby f.Name
select f;
return q.ToList ();
}
public UserMetadataDocument FindMetadataDocument (string baseUrl, int serviceId)
{
var q = from f in _db.Table<UserMetadataDocument> ()
where f.ServiceId == serviceId && f.BaseUrl == baseUrl
select f;
return q.FirstOrDefault ();
}
public void UpdateMetadataDocuments (List<UserMetadataDocument> metaDocs, UserService service)
{
_db.RunInTransaction (delegate {
foreach (var f in metaDocs) {
f.ServiceId = service.Id;
var o = FindMetadataDocument (f.BaseUrl, service.Id);
if (o != null) {
f.Id = o.Id;
_db.Update (f);
} else {
_db.Insert (f);
}
}
});
}
UserFeed FindFeed (string name, int serviceId)
{
var q = from f in _db.Table<UserFeed> ()
where f.ServiceId == serviceId && f.Name == name
select f;
return q.FirstOrDefault ();
}
public void UpdateFeeds (List<UserFeed> feeds, UserService service)
{
_db.RunInTransaction (delegate {
foreach (var f in feeds) {
f.ServiceId = service.Id;
var o = FindFeed (f.Name, service.Id);
if (o != null) {
f.Id = o.Id;
_db.Update (f);
} else {
_db.Insert (f);
}
}
});
}
public void Save (UserService service)
{
_db.Update (service);
}
public List<UserService> GetActiveServices ()
{
var q = from s in _db.Table<UserService> ()
orderby s.Name
select s;
return q.ToList ();
}
public void InsertDefaultServices ()
{
var r = new List<UserService> ();
r.Add (new UserService {
Name = "Netflix",
ServiceRootUri = "http://odata.netflix.com/"
});
r.Add (new UserService {
Name = "Devexpress Channel",
ServiceRootUri = "http://media.devexpress.com/channel.svc"
});
r.Add (new UserService {
Name = "vanGuide",
ServiceRootUri = "http://vancouverdataservice.cloudapp.net/v1/"
});
r.Add (new UserService {
Name = "Open Government Data Initiative",
ServiceRootUri = "http://ogdi.cloudapp.net/v1/"
});
r.Add (new UserService {
Name = "Nerd Dinner",
ServiceRootUri = "http://www.nerddinner.com/Services/OData.svc/"
});
r.Add (new UserService {
Name = "Northwind",
ServiceRootUri = "http://services.odata.org/Northwind/Northwind.svc/"
});
r.Add (new UserService {
Name = "Stack Overflow",
ServiceRootUri = "http://odata.stackexchange.com/stackoverflow/atom"
});
r.Add (new UserService {
Name = "Super User",
ServiceRootUri = "http://odata.stackexchange.com/superuser/atom"
});
r.Add (new UserService {
Name = "Server Fault",
ServiceRootUri = "http://odata.stackexchange.com/serverfault/atom"
});
r.Add (new UserService {
Name = "Meta Stack Overflow",
ServiceRootUri = "http://odata.stackexchange.com/meta/atom"
});
_db.InsertAll (r);
}
}
}
| |
/*
Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use In source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using Tamir.SharpSsh.java.io;
using Tamir.SharpSsh.java.lang;
using Tamir.Streams;
namespace Tamir.SharpSsh.jsch
{
/* -*-mode:java; c-basic-offset:2; -*- */
public abstract class Channel : JavaRunnable
{
internal static int index = 0;
private static ArrayList pool = new ArrayList();
internal static Channel getChannel(String type)
{
if (type.Equals("session"))
{
return new ChannelSession();
}
if (type.Equals("shell"))
{
return new ChannelShell();
}
if (type.Equals("exec"))
{
return new ChannelExec();
}
if (type.Equals("x11"))
{
return new ChannelX11();
}
if (type.Equals("direct-tcpip"))
{
return new ChannelDirectTCPIP();
}
if (type.Equals("forwarded-tcpip"))
{
return new ChannelForwardedTCPIP();
}
if (type.Equals("sftp"))
{
return new ChannelSftp();
}
if (type.Equals("subsystem"))
{
return new ChannelSubsystem();
}
return null;
}
internal static Channel getChannel(int id, Session session)
{
lock (pool)
{
for (int i = 0; i < pool.Count; i++)
{
Channel c = (Channel)(pool[i]);
if (c.id == id && c.session == session) return c;
}
}
return null;
}
internal static void del(Channel c)
{
lock (pool)
{
pool.Remove(c);
}
}
internal int id;
internal int recipient = -1;
internal byte[] type = "foo".GetBytes();
internal int lwsize_max = 0x100000;
internal int lwsize = 0x100000; // local initial window size
internal int lmpsize = 0x4000; // local maximum packet size
internal int rwsize = 0; // remote initial window size
internal int rmpsize = 0; // remote maximum packet size
internal IO io = null;
internal JavaThread thread = null;
internal bool eof_local = false;
internal bool _eof_remote = false;
internal bool _close = false;
internal bool connected = false;
internal int exitstatus = -1;
internal int reply = 0;
internal Session session;
internal Channel()
{
lock (pool)
{
id = index++;
pool.Add(this);
}
}
internal virtual void setRecipient(int foo)
{
this.recipient = foo;
}
internal virtual int getRecipient()
{
return recipient;
}
public virtual void init()
{
}
public virtual void connect()
{
if (!session.isConnected())
{
throw new JSchException("session is down");
}
try
{
Buffer buf = new Buffer(100);
Packet packet = new Packet(buf);
// send
// byte SSH_MSG_CHANNEL_OPEN(90)
// string channel type //
// uint32 sender channel // 0
// uint32 initial window size // 0x100000(65536)
// uint32 maxmum packet size // 0x4000(16384)
packet.reset();
buf.putByte((byte)90);
buf.putString(this.type);
buf.putInt(this.id);
buf.putInt(this.lwsize);
buf.putInt(this.lmpsize);
session.write(packet);
int retry = 1000;
while (this.getRecipient() == -1 &&
session.isConnected() &&
retry > 0)
{
try
{
Thread.Sleep(50);
}
catch (Exception) { }
retry--;
}
if (!session.isConnected())
{
throw new JSchException("session is down");
}
if (retry == 0)
{
throw new JSchException("channel is not opened.");
}
connected = true;
start();
}
catch (Exception e)
{
connected = false;
if (e is JSchException) throw (JSchException)e;
}
}
public virtual void setXForwarding(bool foo)
{
}
public virtual void start()
{
}
public bool isEOF()
{
return _eof_remote;
}
internal virtual void getData(Buffer buf)
{
setRecipient(buf.getInt());
setRemoteWindowSize(buf.getInt());
setRemotePacketSize(buf.getInt());
}
public virtual void setInputStream(Stream In)
{
io.setInputStream(In, false);
}
public virtual void setInputStream(Stream In, bool dontclose)
{
io.setInputStream(In, dontclose);
}
public virtual void setOutputStream(Stream Out)
{
io.setOutputStream(Out, false);
}
public virtual void setOutputStream(Stream Out, bool dontclose)
{
io.setOutputStream(Out, dontclose);
}
public virtual void setExtOutputStream(Stream Out)
{
io.setExtOutputStream(Out, false);
}
public virtual void setExtOutputStream(Stream Out, bool dontclose)
{
io.setExtOutputStream(Out, dontclose);
}
public virtual InputStream getInputStream()
{
PipedInputStream In =
new MyPipedInputStream(
32 * 1024 // this value should be customizable.
);
io.setOutputStream(new PassiveOutputStream(In), false);
return In;
}
public virtual InputStream getExtInputStream()
{
PipedInputStream In =
new MyPipedInputStream(
32 * 1024 // this value should be customizable.
);
io.setExtOutputStream(new PassiveOutputStream(In), false);
return In;
}
public virtual Stream getOutputStream()
{
PipedOutputStream Out = new PipedOutputStream();
io.setInputStream(new PassiveInputStream(Out
, 32 * 1024
), false);
// io.setInputStream(new PassiveInputStream(Out), false);
return Out;
}
internal class MyPipedInputStream : PipedInputStream
{
internal MyPipedInputStream() : base()
{
;
}
internal MyPipedInputStream(int size)
: base()
{
buffer = new byte[size];
}
internal MyPipedInputStream(PipedOutputStream Out) : base(Out)
{
}
internal MyPipedInputStream(PipedOutputStream Out, int size)
: base(Out)
{
buffer = new byte[size];
}
}
internal virtual void setLocalWindowSizeMax(int foo)
{
this.lwsize_max = foo;
}
internal virtual void setLocalWindowSize(int foo)
{
this.lwsize = foo;
}
internal virtual void setLocalPacketSize(int foo)
{
this.lmpsize = foo;
}
[MethodImpl(MethodImplOptions.Synchronized)]
internal virtual void setRemoteWindowSize(int foo)
{
this.rwsize = foo;
}
[MethodImpl(MethodImplOptions.Synchronized)]
internal virtual void addRemoteWindowSize(int foo)
{
this.rwsize += foo;
}
internal virtual void setRemotePacketSize(int foo)
{
this.rmpsize = foo;
}
public virtual void run()
{
}
internal virtual void write(byte[] foo)
{
write(foo, 0, foo.Length);
}
internal virtual void write(byte[] foo, int s, int l)
{
try
{
// if(io.outs!=null)
io.put(foo, s, l);
}
catch (NullReferenceException) { }
}
internal virtual void write_ext(byte[] foo, int s, int l)
{
try
{
// if(io.out_ext!=null)
io.put_ext(foo, s, l);
}
catch (NullReferenceException) { }
}
internal virtual void eof_remote()
{
_eof_remote = true;
try
{
if (io.outs != null)
{
io.outs.Close();
io.outs = null;
}
}
catch (NullReferenceException) { }
catch (IOException) { }
}
internal virtual void eof()
{
if (_close) return;
if (eof_local) return;
eof_local = true;
try
{
Buffer buf = new Buffer(100);
Packet packet = new Packet(buf);
packet.reset();
buf.putByte((byte)Session.SSH_MSG_CHANNEL_EOF);
buf.putInt(getRecipient());
session.write(packet);
}
catch (Exception) { }
}
/*
http://www1.ietf.org/internet-drafts/draft-ietf-secsh-connect-24.txt
5.3 Closing a Channel
When a party will no longer send more data to a channel, it SHOULD
send SSH_MSG_CHANNEL_EOF.
byte SSH_MSG_CHANNEL_EOF
uint32 recipient_channel
No explicit response is sent to this message. However, the
application may send EOF to whatever is at the other end of the
channel. Note that the channel remains open after this message, and
more data may still be sent In the other direction. This message
does not consume window space and can be sent even if no window space
is available.
When either party wishes to terminate the channel, it sends
SSH_MSG_CHANNEL_CLOSE. Upon receiving this message, a party MUST
send back a SSH_MSG_CHANNEL_CLOSE unless it has already sent this
message for the channel. The channel is considered closed for a
party when it has both sent and received SSH_MSG_CHANNEL_CLOSE, and
the party may then reuse the channel number. A party MAY send
SSH_MSG_CHANNEL_CLOSE without having sent or received
SSH_MSG_CHANNEL_EOF.
byte SSH_MSG_CHANNEL_CLOSE
uint32 recipient_channel
This message does not consume window space and can be sent even if no
window space is available.
It is recommended that any data sent before this message is delivered
to the actual destination, if possible.
*/
internal virtual void close()
{
//System.Out.println("close!!!!");
if (_close) return;
_close = true;
try
{
Buffer buf = new Buffer(100);
Packet packet = new Packet(buf);
packet.reset();
buf.putByte((byte)Session.SSH_MSG_CHANNEL_CLOSE);
buf.putInt(getRecipient());
session.write(packet);
}
catch (Exception)
{
//e.printStackTrace();
}
}
public virtual bool isClosed()
{
return _close;
}
internal static void disconnect(Session session)
{
Channel[] channels = null;
int count = 0;
lock (pool)
{
channels = new Channel[pool.Count];
for (int i = 0; i < pool.Count; i++)
{
try
{
Channel c = ((Channel)(pool[i]));
if (c.session == session)
{
channels[count++] = c;
}
}
catch (Exception) { }
}
}
for (int i = 0; i < count; i++)
{
channels[i].disconnect();
}
}
public virtual void disconnect()
{
//System.Out.println(this+":disconnect "+io+" "+io.in);
if (!connected)
{
return;
}
connected = false;
close();
_eof_remote = eof_local = true;
thread = null;
try
{
if (io != null)
{
io.close();
}
}
catch (Exception)
{
//e.printStackTrace();
}
io = null;
del(this);
}
public virtual bool isConnected()
{
if (this.session != null)
{
return session.isConnected() && connected;
}
return false;
}
public virtual void sendSignal(String foo)
{
RequestSignal request = new RequestSignal();
request.setSignal(foo);
request.request(session, this);
}
internal class PassiveInputStream : MyPipedInputStream
{
internal PipedOutputStream Out;
internal PassiveInputStream(PipedOutputStream Out, int size)
: base(Out, size)
{
this.Out = Out;
}
internal PassiveInputStream(PipedOutputStream Out)
: base(Out)
{
this.Out = Out;
}
public override void close()
{
if (Out != null)
{
this.Out.Close();
}
Out = null;
}
}
internal class PassiveOutputStream : PipedOutputStream
{
internal PassiveOutputStream(PipedInputStream In)
: base(In)
{
}
}
internal virtual void setExitStatus(int foo)
{
exitstatus = foo;
}
public virtual int getExitStatus()
{
return exitstatus;
}
internal virtual void setSession(Session session)
{
this.session = session;
}
public virtual Session getSession()
{
return session;
}
public virtual int getId()
{
return id;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.TodoComments;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer
{
public const string Name = "Todo Comment Document Worker";
private readonly TodoCommentIncrementalAnalyzerProvider _owner;
private readonly Workspace _workspace;
private readonly TodoCommentTokens _todoCommentTokens;
private readonly TodoCommentState _state;
public TodoCommentIncrementalAnalyzer(Workspace workspace, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens)
{
_workspace = workspace;
_owner = owner;
_todoCommentTokens = todoCommentTokens;
_state = new TodoCommentState();
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
// remove cache
_state.Remove(document.Id);
return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, ImmutableArray<TodoItem>.Empty), cancellationToken);
}
public async Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
{
// it has an assumption that this will not be called concurrently for same document.
// in fact, in current design, it won't be even called concurrently for different documents.
// but, can be called concurrently for different documents in future if we choose to.
Contract.ThrowIfFalse(document.IsFromPrimaryBranch());
if (!document.Project.Solution.Options.GetOption(InternalFeatureOnOffOptions.TodoComments))
{
return;
}
// use tree version so that things like compiler option changes are considered
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData != null)
{
// check whether we can use the data as it is (can happen when re-using persisted data from previous VS session)
if (CheckVersions(document, textVersion, syntaxVersion, existingData))
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Project.Solution, document.Id, existingData.Items);
return;
}
}
var tokens = _todoCommentTokens.GetTokens(document, cancellationToken);
var comments = await GetTodoCommentsAsync(document, tokens, cancellationToken).ConfigureAwait(false);
var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false);
var data = new Data(textVersion, syntaxVersion, items);
await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false);
// * NOTE * cancellation can't throw after this point.
if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0)
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Project.Solution, document.Id, data.Items);
}
}
private async Task<IList<TodoComment>> GetTodoCommentsAsync(Document document, ImmutableArray<TodoCommentDescriptor> tokens, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<ITodoCommentService>();
if (service == null)
{
// no inproc support
return SpecializedCollections.EmptyList<TodoComment>();
}
return await service.GetTodoCommentsAsync(document, tokens, cancellationToken).ConfigureAwait(false);
}
private async Task<ImmutableArray<TodoItem>> CreateItemsAsync(Document document, IList<TodoComment> comments, CancellationToken cancellationToken)
{
var items = ImmutableArray.CreateBuilder<TodoItem>();
if (comments != null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = document.SupportsSyntaxTree ? await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null;
foreach (var comment in comments)
{
items.Add(CreateItem(document, text, syntaxTree, comment));
}
}
return items.ToImmutable();
}
private TodoItem CreateItem(Document document, SourceText text, SyntaxTree tree, TodoComment comment)
{
// make sure given position is within valid text range.
var textSpan = new TextSpan(Math.Min(text.Length, Math.Max(0, comment.Position)), 0);
var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan);
var originalLineInfo = location.GetLineSpan();
var mappedLineInfo = location.GetMappedLineSpan();
return new TodoItem(
comment.Descriptor.Priority,
comment.Message,
document.Project.Solution.Workspace,
document.Id,
mappedLine: mappedLineInfo.StartLinePosition.Line,
originalLine: originalLineInfo.StartLinePosition.Line,
mappedColumn: mappedLineInfo.StartLinePosition.Character,
originalColumn: originalLineInfo.StartLinePosition.Character,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
originalFilePath: document.FilePath);
}
public ImmutableArray<TodoItem> GetTodoItems(Workspace workspace, DocumentId id, CancellationToken cancellationToken)
{
var document = workspace.CurrentSolution.GetDocument(id);
if (document == null)
{
return ImmutableArray<TodoItem>.Empty;
}
// TODO let's think about what to do here. for now, let call it synchronously. also, there is no actual async-ness for the
// TryGetExistingDataAsync, API just happen to be async since our persistent API is async API. but both caller and implementor are
// actually not async.
var existingData = _state.TryGetExistingDataAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
if (existingData == null)
{
return ImmutableArray<TodoItem>.Empty;
}
return existingData.Items;
}
public IEnumerable<UpdatedEventArgs> GetTodoItemsUpdatedEventArgs(Workspace workspace, CancellationToken cancellationToken)
{
foreach (var documentId in _state.GetDocumentIds())
{
yield return new UpdatedEventArgs(Tuple.Create(this, documentId), workspace, documentId.ProjectId, documentId);
}
}
private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData)
{
// first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether
// we can use it cross-session.
return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion);
}
internal ImmutableArray<TodoItem> GetItems_TestingOnly(DocumentId documentId)
{
return _state.GetItems_TestingOnly(documentId);
}
private void RaiseTaskListUpdated(Workspace workspace, Solution solution, DocumentId documentId, ImmutableArray<TodoItem> items)
{
if (_owner != null)
{
_owner.RaiseTaskListUpdated(documentId, workspace, solution, documentId.ProjectId, documentId, items);
}
}
public void RemoveDocument(DocumentId documentId)
{
_state.Remove(documentId);
RaiseTaskListUpdated(_workspace, null, documentId, ImmutableArray<TodoItem>.Empty);
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return e.Option == TodoCommentOptions.TokenList;
}
private class Data
{
public readonly VersionStamp TextVersion;
public readonly VersionStamp SyntaxVersion;
public readonly ImmutableArray<TodoItem> Items;
public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray<TodoItem> items)
{
this.TextVersion = textVersion;
this.SyntaxVersion = syntaxVersion;
this.Items = items;
}
}
#region not used
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public void RemoveProject(ProjectId projectId)
{
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
[KnownFailure]
public class DiscardNull_Property : PortsTest
{
//The default number of bytes to read/write to verify the DiscardNull
private const int DEFAULT_NUM_CHARS_TO_WRITE = 8;
//The default number of null characters to be inserted into the characters written
private const int DEFUALT_NUM_NULL_CHAR = 1;
//The default number of chars to write with when testing timeout with Read(char[], int, int)
private const int DEFAULT_READ_CHAR_ARRAY_SIZE = 8;
//The default number of bytes to write with when testing timeout with Read(byte[], int, int)
private const int DEFAULT_READ_BYTE_ARRAY_SIZE = 8;
private delegate char[] ReadMethodDelegate(SerialPort com);
#region Test Cases
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_Default_Read_byte_int_int()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with Read_byte_int_int");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, Read_byte_int_int, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_Default_Read_char_int_int()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with Read_char_int_int");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, Read_char_int_int, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_Default_ReadByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with ReadByte");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, ReadByte, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_Default_ReadChar()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with ReadChar");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, ReadChar, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_Default_ReadLine()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with ReadLine");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, ReadLine, true);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_Default_ReadTo()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with ReadTo");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, ReadTo, true);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_Read_byte_int_int_Before()
{
Debug.WriteLine("Verifying true DiscardNull with Read_byte_int_int before open");
VerifyDiscardNullBeforeOpen(true, Read_byte_int_int, false);
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_Read_char_int_int_After()
{
Debug.WriteLine("Verifying true DiscardNull with Read_char_int_int after open");
VerifyDiscardNullAfterOpen(true, Read_char_int_int, false);
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_ReadByte_Before()
{
Debug.WriteLine("Verifying true DiscardNull with ReadByte before open");
VerifyDiscardNullBeforeOpen(true, ReadByte, false);
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_ReadChar_After()
{
Debug.WriteLine("Verifying true DiscardNull with ReadChar after open");
VerifyDiscardNullAfterOpen(true, ReadChar, false);
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_ReadLine_Before()
{
Debug.WriteLine("Verifying true DiscardNull with ReadLine before open");
VerifyDiscardNullBeforeOpen(true, ReadLine, true);
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_ReadTo_After()
{
Debug.WriteLine("Verifying true DiscardNull with ReadTo after open");
VerifyDiscardNullAfterOpen(true, ReadTo, true);
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_false_Read_byte_int_int_Before()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with Read_byte_int_int");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.DiscardNull = true;
com1.DiscardNull = false;
serPortProp.SetProperty("DiscardNull", false);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, Read_byte_int_int, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_true_true_Read_char_int_int_After()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with Read_char_int_int");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.DiscardNull = true;
com1.DiscardNull = true;
serPortProp.SetProperty("DiscardNull", true);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, Read_char_int_int, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DiscardNull_false_flase_Default_ReadByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default DiscardNull with ReadByte");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.DiscardNull = false;
com1.DiscardNull = false;
serPortProp.SetProperty("DiscardNull", false);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, ReadByte, false);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
#endregion
#region Verification for Test Cases
private void VerifyDiscardNullBeforeOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.DiscardNull = discardNull;
com1.Open();
serPortProp.SetProperty("DiscardNull", discardNull);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, readMethod, sendNewLine);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyDiscardNullAfterOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.DiscardNull = discardNull;
serPortProp.SetProperty("DiscardNull", discardNull);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyDiscardNull(com1, readMethod, sendNewLine);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyDiscardNull(SerialPort com1, ReadMethodDelegate readMethod, bool sendNewLine)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
char[] expectedChars;
char[] rcvChars;
int origReadTimeout;
char[] xmitChars = new char[DEFAULT_NUM_CHARS_TO_WRITE];
byte[] xmitBytes;
byte[] expectedBytes;
Random rndGen = new Random();
int numNulls = 0;
int expectedIndex;
origReadTimeout = com1.ReadTimeout;
//Generate some random chars to transfer
for (int i = 0; i < xmitChars.Length; i++)
{
//xmitChars[i] = (char)rndGen.Next(1, UInt16.MaxValue);
xmitChars[i] = (char)rndGen.Next(60, 80);
}
//Inject the null char randomly
for (int i = 0; i < DEFUALT_NUM_NULL_CHAR; i++)
{
int nullIndex = rndGen.Next(0, xmitChars.Length);
if ('\0' != xmitChars[nullIndex])
{
numNulls++;
}
xmitChars[nullIndex] = '\0';
}
xmitBytes = com1.Encoding.GetBytes(xmitChars);
if (com1.DiscardNull)
{
expectedIndex = 0;
expectedChars = new char[xmitChars.Length - numNulls];
for (int i = 0; i < xmitChars.Length; i++)
{
if ('\0' != xmitChars[i])
{
expectedChars[expectedIndex] = xmitChars[i];
expectedIndex++;
}
}
}
else
{
expectedChars = new char[xmitChars.Length];
Array.Copy(xmitChars, 0, expectedChars, 0, expectedChars.Length);
}
expectedBytes = com1.Encoding.GetBytes(expectedChars);
expectedChars = com1.Encoding.GetChars(expectedBytes);
com2.Open();
com2.Write(xmitBytes, 0, xmitBytes.Length);
TCSupport.WaitForReadBufferToLoad(com1, expectedBytes.Length);
if (sendNewLine)
com2.WriteLine("");
com1.ReadTimeout = 250;
rcvChars = readMethod(com1);
Assert.Equal(0, com1.BytesToRead);
Assert.Equal(expectedChars, rcvChars);
com1.ReadTimeout = origReadTimeout;
}
}
private char[] Read_byte_int_int(SerialPort com)
{
ArrayList receivedBytes = new ArrayList();
byte[] buffer = new byte[DEFAULT_READ_BYTE_ARRAY_SIZE];
int totalBytesRead = 0;
int numBytes;
while (true)
{
try
{
numBytes = com.Read(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
break;
}
receivedBytes.InsertRange(totalBytesRead, buffer);
totalBytesRead += numBytes;
}
if (totalBytesRead < receivedBytes.Count)
receivedBytes.RemoveRange(totalBytesRead, receivedBytes.Count - totalBytesRead);
return com.Encoding.GetChars((byte[])receivedBytes.ToArray(typeof(byte)));
}
private char[] Read_char_int_int(SerialPort com)
{
ArrayList receivedChars = new ArrayList();
char[] buffer = new char[DEFAULT_READ_CHAR_ARRAY_SIZE];
int totalCharsRead = 0;
int numChars;
while (true)
{
try
{
numChars = com.Read(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
break;
}
receivedChars.InsertRange(totalCharsRead, buffer);
totalCharsRead += numChars;
}
if (totalCharsRead < receivedChars.Count)
receivedChars.RemoveRange(totalCharsRead, receivedChars.Count - totalCharsRead);
return (char[])receivedChars.ToArray(typeof(char));
}
private char[] ReadByte(SerialPort com)
{
ArrayList receivedBytes = new ArrayList();
int rcvByte;
while (true)
{
try
{
rcvByte = com.ReadByte();
}
catch (TimeoutException)
{
break;
}
receivedBytes.Add((byte)rcvByte);
}
return com.Encoding.GetChars((byte[])receivedBytes.ToArray(typeof(byte)));
}
private char[] ReadChar(SerialPort com)
{
ArrayList receivedChars = new ArrayList();
int rcvChar;
while (true)
{
try
{
rcvChar = com.ReadChar();
}
catch (TimeoutException)
{
break;
}
receivedChars.Add((char)rcvChar);
}
return (char[])receivedChars.ToArray(typeof(char));
}
private char[] ReadLine(SerialPort com)
{
StringBuilder rcvStringBuilder = new StringBuilder();
string rcvString;
while (true)
{
try
{
rcvString = com.ReadLine();
}
catch (TimeoutException)
{
break;
}
rcvStringBuilder.Append(rcvString);
}
return rcvStringBuilder.ToString().ToCharArray();
}
private char[] ReadTo(SerialPort com)
{
StringBuilder rcvStringBuilder = new StringBuilder();
string rcvString;
while (true)
{
try
{
rcvString = com.ReadTo(com.NewLine);
}
catch (TimeoutException)
{
break;
}
rcvStringBuilder.Append(rcvString);
}
return rcvStringBuilder.ToString().ToCharArray();
}
#endregion
}
}
| |
/*============================================================================
File: Service1.cs
Summary: Contains class implementiong ASTrace service
Part of ASTrace
Date: January 2007
------------------------------------------------------------------------------
This file is part of the Microsoft SQL Server Code Samples.
Copyright (C) Microsoft Corporation. All rights reserved.
This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
============================================================================*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;
using Microsoft.SqlServer.Management.Trace;
using Microsoft.SqlServer.Management.Common;
namespace ASTrace
{
public partial class Trace : ServiceBase
{
List<Thread> workers = new List<Thread>();
string localPath;
List<string> _ServernamesList;
int _NumInstance;
TextWriter writer;
List<TraceServer> traceServers = new List<TraceServer>();
public Trace()
{
//Have seen errors here, normally when configuring for first time
//Note, the eventlog will need to create a source the very first time it runs and that needs admin privs.
try
{
InitializeComponent();
// Read registry to find out where the service executable is installed
Microsoft.Win32.RegistryKey software, microsoft, astrace;
software = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE");
microsoft = software.OpenSubKey("Microsoft");
astrace = microsoft.OpenSubKey("ASTrace");
localPath = (string)astrace.GetValue("path");
writer = new StreamWriter(localPath + "\\ASTraceService.log", true);
WriteLog(DateTime.Now.ToString() + ": Service Started in '" + localPath + "'");
}
catch (Exception ex)
{
StringBuilder messageText = new StringBuilder();
messageText.Append("Failed to write to log file ").AppendLine();
messageText.Append("Error: " + ex.Message).AppendLine();
while (ex.InnerException != null)
{
messageText.Append("INNER EXCEPTION: ");
messageText.Append(ex.InnerException.Message).AppendLine();
messageText.Append(ex.InnerException.StackTrace).AppendLine();
ex = ex.InnerException;
}
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Error);
}
}
protected override void OnStart(string[] args)
{
if (Properties.Settings.Default.AppendDateToSQLTable && Properties.Settings.Default.PreserveHistory)
{
StringBuilder messageText = new StringBuilder();
messageText.Append(DateTime.Now.ToString() + ": Both AppendDateToSQLTable and PreserveHistory cannot be true!");
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Error);
WriteLog(messageText.ToString());
Stop();
return;
}
//Initial startup so get the server list
string sServerNames = Properties.Settings.Default.AnalysisServerName + "," + Properties.Settings.Default.AnalysisServerNames;
_ServernamesList = new List<string>(sServerNames.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
//Get the number of servers so we can maintain legacy behaviour
_NumInstance = _ServernamesList.Count;
foreach (string SSASserver in _ServernamesList)
{
//Spin up a thread to write the trace to SQL
Thread worker = new Thread(DoWork);
workers.Add(worker);
//Start the tracing and pass SSAS Server name so we can handle retries
worker.Start(SSASserver);
}
}
bool ConnectOlap(out TraceServer traceServer, string SSASserver)
{
OlapConnectionInfo ci = new OlapConnectionInfo();
traceServer = new TraceServer();
StringBuilder messageText = new StringBuilder();
try
{
ci.UseIntegratedSecurity = true;
ci.ServerName = SSASserver;
string tracetemplate = localPath + "\\" + Properties.Settings.Default.TraceDefinition;
traceServer.InitializeAsReader(ci, tracetemplate);
lock (traceServers)
{
traceServers.Add(traceServer);
}
messageText.Append(
DateTime.Now.ToString()
+ ": Created trace for Analysis Server : '"
+ SSASserver
+ "'");
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Information);
return true;
}
catch (Exception e)
{
messageText.Append(DateTime.Now.ToString() + ": Cannot start Analysis Server trace: ").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": Analysis Server name: '" + SSASserver + "'").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": Trace definition : '" + localPath + "\\" + Properties.Settings.Default.TraceDefinition + "'").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": Error: " + e.Message).AppendLine();
messageText.Append(DateTime.Now.ToString() + ": Stack Trace: " + e.StackTrace).AppendLine();
while (e.InnerException != null)
{
messageText.Append("INNER EXCEPTION: ");
messageText.Append(e.InnerException.Message).AppendLine();
messageText.Append(e.InnerException.StackTrace).AppendLine();
e = e.InnerException;
}
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Error);
return false;
}
}
bool ConnectSQL(ref TraceServer traceServer, out TraceTable tableWriter, string SSASserver)
{
SqlConnectionInfo connInfo = new SqlConnectionInfo(Properties.Settings.Default.SQLServer);
StringBuilder messageText = new StringBuilder();
string _AppendInst = "_" + SSASserver;
string _SQLTable;
string _AppendDate;
//Maintains legacy logic where by a server with single instance does not have any inst names appended.
if (_NumInstance == 1)
_AppendInst = "";
//Append data to end of SQL table. Useful as an alternative to preserver SQL but data only survives 1 restart a day and you need cleanup logic in SQL Server
if (Properties.Settings.Default.AppendDateToSQLTable)
_AppendDate = "_" + DateTime.Now.ToString("yyyyMMdd");
else
_AppendDate = "";
_SQLTable =
Properties.Settings.Default.TraceTableName
+ _AppendInst
+ _AppendDate;
if (Properties.Settings.Default.PreserveHistory)
PreserveSQLHistory(ref _SQLTable);
tableWriter = new TraceTable();
try
{
connInfo.DatabaseName = Properties.Settings.Default.SQLServerDatabase;
tableWriter.InitializeAsWriter(traceServer, connInfo, _SQLTable);
messageText.Append(DateTime.Now.ToString() + ": Created Analysis Server trace table: '" + _SQLTable + "' on SQL Server: '" + Properties.Settings.Default.SQLServer
+ "' in database: " + Properties.Settings.Default.SQLServerDatabase + "'");
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Information);
return true;
}
catch (Exception e)
{
messageText.Append(DateTime.Now.ToString() + ": Cannot create Analysis Server trace table: '" + SSASserver + "'").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": SQL Server Name: '" + Properties.Settings.Default.SQLServer + "'").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": SQL Server Database : '" + Properties.Settings.Default.SQLServerDatabase + "'").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": SQL Server Table : '" + _SQLTable + "'").AppendLine();
messageText.Append(DateTime.Now.ToString() + ": Error: " + e.Message).AppendLine();
while (e.InnerException != null)
{
messageText.Append("INNER EXCEPTION: ");
messageText.Append(e.InnerException.Message).AppendLine();
messageText.Append(e.InnerException.StackTrace.ToString()).AppendLine();
e = e.InnerException;
}
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Error);
return false;
}
}
void PreserveSQLHistory(ref string _SQLTable)
{
string sHistorySuffix = "History";
if (_NumInstance > 1)
{
sHistorySuffix = "_History";
}
StringBuilder messageText = new StringBuilder();
try
{
SqlConnectionInfo connInfo = new SqlConnectionInfo(Properties.Settings.Default.SQLServer);
IDbConnection conn = connInfo.CreateConnectionObject();
conn.Open();
conn.ChangeDatabase(Properties.Settings.Default.SQLServerDatabase);
string sSQL = @"if object_id('[" + _SQLTable.Replace("'", "''") + @"]') is not null
select top 1 * from [" + _SQLTable.Replace("]", "]]") + "]";
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, (System.Data.SqlClient.SqlConnection)conn);
cmd.CommandTimeout = 0;
System.Data.SqlClient.SqlDataReader datareader = cmd.ExecuteReader();
string sColumns = "";
for (int i = 0; i < datareader.FieldCount; i++)
{
if (!string.IsNullOrEmpty(sColumns)) sColumns += ", ";
sColumns += "[" + datareader.GetName(i) + "]";
}
datareader.Close();
if (sColumns != "")
{
sSQL = @"
if object_id('[" + _SQLTable.Replace("'", "''") + @"]') is not null
begin
if object_id('[" + _SQLTable.Replace("'", "''") + sHistorySuffix + @"]') is null
begin
select * into [" + _SQLTable.Replace("]", "]]") + sHistorySuffix + "] from [" + _SQLTable.Replace("]", "]]") + @"]
end
else
begin
SET IDENTITY_INSERT [" + _SQLTable.Replace("]", "]]") + sHistorySuffix + @"] ON
insert into [" + _SQLTable.Replace("]", "]]") + sHistorySuffix + "] (" + sColumns + @")
select * from [" + _SQLTable.Replace("]", "]]") + @"]
SET IDENTITY_INSERT [" + _SQLTable.Replace("]", "]]") + sHistorySuffix + @"] OFF
end
end
";
cmd.CommandText = sSQL;
int iRowsPreserved = cmd.ExecuteNonQuery();
messageText.Append(DateTime.Now.ToString() + ": Successfully preserved " + iRowsPreserved + " rows of history to table: " + _SQLTable + sHistorySuffix);
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Information);
}
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
messageText.Append(DateTime.Now.ToString() + ": Cannot preserve history of trace table. ").AppendLine();
messageText.Append("Error: " + ex.Message).AppendLine();
messageText.Append(ex.StackTrace).AppendLine();
while (ex.InnerException != null)
{
messageText.Append("INNER EXCEPTION: ");
messageText.Append(ex.InnerException.Message).AppendLine();
messageText.Append(ex.InnerException.StackTrace).AppendLine();
ex = ex.InnerException;
}
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Warning);
}
}
void DoWork(object SSAS)
{
string SSASserver = (string)SSAS;
TraceTable _SQLDestTableWriter = null;
TraceServer _SSASSourceTraceServer = null;
int _RetryCounter = 0;
bool bFirstLoop = true;
while (bFirstLoop || _RetryCounter < Properties.Settings.Default.RestartRetries)
{
bFirstLoop = false;
try
{
//Grab connection to SSAS
bool bSuccess = ConnectOlap(out _SSASSourceTraceServer, SSASserver);
if (bSuccess)
{
//Grab connection to SQL and connect it with the SSAS trace
bSuccess = ConnectSQL(ref _SSASSourceTraceServer, out _SQLDestTableWriter, SSASserver);
if (bSuccess)
{
_RetryCounter = 0;
while (_SQLDestTableWriter.Write())
{
if (_SQLDestTableWriter.IsClosed)
throw new Exception("SQL connection closed unexpectedly.");
if (_SSASSourceTraceServer.IsClosed)
throw new Exception("SSAS connection closed unexpectedly.");
}
}
}
}
catch (Exception ex)
{
StringBuilder messageText = new StringBuilder();
messageText.Append(DateTime.Now.ToString() + ": Error reading trace: " + ex.Message).AppendLine();
messageText.Append(ex.StackTrace).AppendLine();
while (ex.InnerException != null)
{
messageText.Append("INNER EXCEPTION: ");
messageText.Append(ex.InnerException.Message).AppendLine();
messageText.Append(ex.InnerException.StackTrace).AppendLine();
ex = ex.InnerException;
}
WriteLog(messageText.ToString());
EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Warning);
}
try
{
_SSASSourceTraceServer.Stop();
_SSASSourceTraceServer.Close();
}
catch { }
try
{
_SQLDestTableWriter.Close();
}
catch { }
_RetryCounter++;
if (_RetryCounter < Properties.Settings.Default.RestartRetries)
{
StringBuilder messageText2 = new StringBuilder();
messageText2.Append(DateTime.Now.ToString() + ": Exception caught tracing server: " + SSASserver + ", retry " + _RetryCounter + " of " + Properties.Settings.Default.RestartRetries
+ ". Pausing for " + Properties.Settings.Default.RestartDelayMinutes + " minute(s) then restarting automatically"
).AppendLine();
WriteLog(messageText2.ToString());
EventLog.WriteEntry(this.ServiceName, messageText2.ToString(), EventLogEntryType.Warning);
System.Threading.Thread.Sleep(new TimeSpan(0, Properties.Settings.Default.RestartDelayMinutes, 0));
}
else
{
WriteLog(DateTime.Now.ToString() + ": Exceeded the number of allowed retries for server: " + SSASserver);
}
}
//if this one trace exceeded the number of retries so stop the service and stop all traces
Stop();
}
protected override void OnStop()
{
try
{
WriteLog(DateTime.Now.ToString() + ": Stopping");
writer.Close();
writer.Dispose();
}
catch { }
try
{
foreach (TraceServer ts in traceServers)
{
try
{
ts.Stop();
ts.Close();
ts.Dispose();
}
catch { }
}
}
catch { }
}
private void WriteLog(string sMessage)
{
lock (writer)
{
try
{
writer.WriteLine(sMessage);
writer.Flush();
}
catch { }
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Globalization;
using System.Linq;
using NLog.Layouts;
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// Keeps logging configuration and provides simple API
/// to modify it.
/// </summary>
///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks>
public class LoggingConfiguration
{
private readonly IDictionary<string, Target> targets =
new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase);
private List<object> configItems = new List<object>();
/// <summary>
/// Variables defined in xml or in API. name is case case insensitive.
/// </summary>
private readonly Dictionary<string, SimpleLayout> variables = new Dictionary<string, SimpleLayout>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Initializes a new instance of the <see cref="LoggingConfiguration" /> class.
/// </summary>
public LoggingConfiguration()
{
this.LoggingRules = new List<LoggingRule>();
}
/// <summary>
/// Use the old exception log handling of NLog 3.0?
/// </summary>
[Obsolete("This option will be removed in NLog 5")]
public bool ExceptionLoggingOldStyle { get; set; }
/// <summary>
/// Gets the variables defined in the configuration.
/// </summary>
public IDictionary<string, SimpleLayout> Variables
{
get
{
return variables;
}
}
/// <summary>
/// Gets a collection of named targets specified in the configuration.
/// </summary>
/// <returns>
/// A list of named targets.
/// </returns>
/// <remarks>
/// Unnamed targets (such as those wrapped by other targets) are not returned.
/// </remarks>
public ReadOnlyCollection<Target> ConfiguredNamedTargets
{
get { return new List<Target>(this.targets.Values).AsReadOnly(); }
}
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// </summary>
public virtual IEnumerable<string> FileNamesToWatch
{
get { return ArrayHelper.Empty<string>(); }
}
/// <summary>
/// Gets the collection of logging rules.
/// </summary>
public IList<LoggingRule> LoggingRules { get; private set; }
/// <summary>
/// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>.
/// </summary>
/// <value>
/// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/>
/// </value>
[CanBeNull]
public CultureInfo DefaultCultureInfo { get; set; }
/// <summary>
/// Gets all targets.
/// </summary>
public ReadOnlyCollection<Target> AllTargets
{
get
{
var configTargets = this.configItems.OfType<Target>();
return configTargets.Concat(targets.Values).Distinct(TargetNameComparer).ToList().AsReadOnly();
}
}
/// <summary>
/// Compare on name
/// </summary>
private static IEqualityComparer<Target> TargetNameComparer = new TargetNameEq();
/// <summary>
/// Compare on name
/// </summary>
private class TargetNameEq : IEqualityComparer<Target>
{
public bool Equals(Target x, Target y)
{
return string.Equals(x.Name, y.Name);
}
public int GetHashCode(Target obj)
{
return (obj.Name != null ? obj.Name.GetHashCode() : 0);
}
}
/// <summary>
/// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>.
/// </summary>
/// <param name="target">
/// The target object with a non <see langword="null"/> <see cref="Target.Name"/>
/// </param>
/// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception>
public void AddTarget([NotNull] Target target)
{
if (target == null) throw new ArgumentNullException("target");
AddTarget(target.Name, target);
}
/// <summary>
/// Registers the specified target object under a given name.
/// </summary>
/// <param name="name">
/// Name of the target.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
public void AddTarget(string name, Target target)
{
if (name == null)
{
throw new ArgumentException("Target name cannot be null", "name");
}
InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName);
this.targets[name] = target;
}
/// <summary>
/// Finds the target with the specified name.
/// </summary>
/// <param name="name">
/// The name of the target to be found.
/// </param>
/// <returns>
/// Found target or <see langword="null"/> when the target is not found.
/// </returns>
public Target FindTargetByName(string name)
{
Target value;
if (!this.targets.TryGetValue(name, out value))
{
return null;
}
return value;
}
/// <summary>
/// Finds the target with the specified name and specified type.
/// </summary>
/// <param name="name">
/// The name of the target to be found.
/// </param>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <returns>
/// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/>
/// </returns>
public TTarget FindTargetByName<TTarget>(string name)
where TTarget : Target
{
return FindTargetByName(name) as TTarget;
}
/// <summary>
/// Add a rule with min- and maxLevel.
/// </summary>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
/// <param name="targetName">Name of the target to be written when the rule matches.</param>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
public void AddRule(LogLevel minLevel, LogLevel maxLevel, string targetName, string loggerNamePattern = "*")
{
var target = FindTargetByName(targetName);
if (target == null)
{
throw new NLogRuntimeException("Target '{0}' not found", targetName);
}
AddRule(minLevel, maxLevel, target, loggerNamePattern);
}
/// <summary>
/// Add a rule with min- and maxLevel.
/// </summary>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern = "*")
{
LoggingRules.Add(new LoggingRule(loggerNamePattern, minLevel, maxLevel, target));
}
/// <summary>
/// Add a rule for one loglevel.
/// </summary>
/// <param name="level">log level needed to trigger this rule. </param>
/// <param name="targetName">Name of the target to be written when the rule matches.</param>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
public void AddRuleForOneLevel(LogLevel level, string targetName, string loggerNamePattern = "*")
{
var target = FindTargetByName(targetName);
if (target == null)
{
throw new NLogConfigurationException("Target '{0}' not found", targetName);
}
AddRuleForOneLevel(level, target, loggerNamePattern);
}
/// <summary>
/// Add a rule for one loglevel.
/// </summary>
/// <param name="level">log level needed to trigger this rule. </param>
/// <param name="target">Target to be written to when the rule matches.</param>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*")
{
var loggingRule = new LoggingRule(loggerNamePattern, target);
loggingRule.EnableLoggingForLevel(level);
LoggingRules.Add(loggingRule);
}
/// <summary>
/// Add a rule for alle loglevels.
/// </summary>
/// <param name="targetName">Name of the target to be written when the rule matches.</param>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
public void AddRuleForAllLevels(string targetName, string loggerNamePattern = "*")
{
var target = FindTargetByName(targetName);
if (target == null)
{
throw new NLogRuntimeException("Target '{0}' not found", targetName);
}
AddRuleForAllLevels(target, loggerNamePattern);
}
/// <summary>
/// Add a rule for alle loglevels.
/// </summary>
/// <param name="target">Target to be written to when the rule matches.</param>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
public void AddRuleForAllLevels(Target target, string loggerNamePattern = "*")
{
var loggingRule = new LoggingRule(loggerNamePattern, target);
loggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);
LoggingRules.Add(loggingRule);
}
/// <summary>
/// Called by LogManager when one of the log configuration files changes.
/// </summary>
/// <returns>
/// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration.
/// </returns>
public virtual LoggingConfiguration Reload()
{
return this;
}
/// <summary>
/// Removes the specified named target.
/// </summary>
/// <param name="name">
/// Name of the target.
/// </param>
public void RemoveTarget(string name)
{
this.targets.Remove(name);
}
/// <summary>
/// Installs target-specific objects on current system.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <remarks>
/// Installation typically runs with administrative permissions.
/// </remarks>
public void Install(InstallationContext installationContext)
{
if (installationContext == null)
{
throw new ArgumentNullException("installationContext");
}
this.InitializeAll();
var configItemsList = GetInstallableItems();
foreach (IInstallable installable in configItemsList)
{
installationContext.Info("Installing '{0}'", installable);
try
{
installable.Install(installationContext);
installationContext.Info("Finished installing '{0}'.", installable);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Install of '{0}' failed.", installable);
if (exception.MustBeRethrownImmediately())
{
throw;
}
installationContext.Error("Install of '{0}' failed: {1}.", installable, exception);
}
}
}
/// <summary>
/// Uninstalls target-specific objects from current system.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <remarks>
/// Uninstallation typically runs with administrative permissions.
/// </remarks>
public void Uninstall(InstallationContext installationContext)
{
if (installationContext == null)
{
throw new ArgumentNullException("installationContext");
}
this.InitializeAll();
var configItemsList = GetInstallableItems();
foreach (IInstallable installable in configItemsList)
{
installationContext.Info("Uninstalling '{0}'", installable);
try
{
installable.Uninstall(installationContext);
installationContext.Info("Finished uninstalling '{0}'.", installable);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Uninstall of '{0}' failed.", installable);
if (exception.MustBeRethrownImmediately())
{
throw;
}
installationContext.Error("Uninstall of '{0}' failed: {1}.", installable, exception);
}
}
}
/// <summary>
/// Closes all targets and releases any unmanaged resources.
/// </summary>
internal void Close()
{
InternalLogger.Debug("Closing logging configuration...");
var supportsInitializesList = GetSupportsInitializes();
foreach (ISupportsInitialize initialize in supportsInitializesList)
{
InternalLogger.Trace("Closing {0}", initialize);
try
{
initialize.Close();
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Exception while closing.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
InternalLogger.Debug("Finished closing logging configuration.");
}
/// <summary>
/// Log to the internal (NLog) logger the information about the <see cref="Target"/> and <see
/// cref="LoggingRule"/> associated with this <see cref="LoggingConfiguration"/> instance.
/// </summary>
/// <remarks>
/// The information are only recorded in the internal logger if Debug level is enabled, otherwise nothing is
/// recorded.
/// </remarks>
internal void Dump()
{
if (!InternalLogger.IsDebugEnabled)
{
return;
}
InternalLogger.Debug("--- NLog configuration dump ---");
InternalLogger.Debug("Targets:");
var targetList = this.targets.Values.ToList();
foreach (Target target in targetList)
{
InternalLogger.Debug("{0}", target);
}
InternalLogger.Debug("Rules:");
var loggingRules = this.LoggingRules.ToList();
foreach (LoggingRule rule in loggingRules)
{
InternalLogger.Debug("{0}", rule);
}
InternalLogger.Debug("--- End of NLog configuration dump ---");
}
/// <summary>
/// Flushes any pending log messages on all appenders.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
internal void FlushAllTargets(AsyncContinuation asyncContinuation)
{
var uniqueTargets = new List<Target>();
var loggingRules = this.LoggingRules.ToList();
foreach (var rule in loggingRules)
{
var targetList = rule.Targets.ToList();
foreach (var target in targetList)
{
if (!uniqueTargets.Contains(target))
{
uniqueTargets.Add(target);
}
}
}
AsyncHelpers.ForEachItemInParallel(uniqueTargets, asyncContinuation, (target, cont) => target.Flush(cont));
}
/// <summary>
/// Validates the configuration.
/// </summary>
internal void ValidateConfig()
{
var roots = new List<object>();
var loggingRules = this.LoggingRules.ToList();
foreach (LoggingRule rule in loggingRules)
{
roots.Add(rule);
}
var targetList = this.targets.Values.ToList();
foreach (Target target in targetList)
{
roots.Add(target);
}
this.configItems = ObjectGraphScanner.FindReachableObjects<object>(roots.ToArray());
// initialize all config items starting from most nested first
// so that whenever the container is initialized its children have already been
InternalLogger.Info("Found {0} configuration items", this.configItems.Count);
foreach (object o in this.configItems)
{
PropertyHelper.CheckRequiredParameters(o);
}
}
internal void InitializeAll()
{
this.ValidateConfig();
var supportsInitializes = GetSupportsInitializes(true);
foreach (ISupportsInitialize initialize in supportsInitializes)
{
InternalLogger.Trace("Initializing {0}", initialize);
try
{
initialize.Initialize(this);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error during initialization of " + initialize, exception);
}
}
}
}
internal void EnsureInitialized()
{
this.InitializeAll();
}
private List<IInstallable> GetInstallableItems()
{
return this.configItems.OfType<IInstallable>().ToList();
}
private List<ISupportsInitialize> GetSupportsInitializes(bool reverse = false)
{
var items = this.configItems.OfType<ISupportsInitialize>();
if (reverse)
{
items = items.Reverse();
}
return items.ToList();
}
/// <summary>
/// Copies all variables from provided dictionary into current configuration variables.
/// </summary>
/// <param name="masterVariables">Master variables dictionary</param>
internal void CopyVariables(IDictionary<string, SimpleLayout> masterVariables)
{
foreach (var variable in masterVariables)
{
this.Variables[variable.Key] = variable.Value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Alensia.Core.Collection;
using Alensia.Core.Common;
using Alensia.Core.UI.Cursor;
using Alensia.Core.UI.Property;
using Malee;
using UniRx;
using UnityEngine;
using UnityEngine.Assertions;
namespace Alensia.Core.UI
{
public class UIStyle : ScriptableObject, INamed
{
public string Name => name;
public UIStyle Parent => _parent;
public CursorSet CursorSet => _cursorSet;
public IDirectory<UnsettableColor> Colors => _colorsLookup;
public IDirectory<ColorSet> ColorSets => _colorSetLookup;
public IDirectory<ImageAndColor> ImagesAndColors => _imagesAndColorsLookup;
public IDirectory<ImageAndColorSet> ImageAndColorSets => _imageAndColorSetLookup;
public IDirectory<TextStyle> TextStyles => _textStyleLookup;
public IDirectory<TextStyleSet> TextStyleSets => _textStyleSetLookup;
[SerializeField] private UIStyle _parent;
[SerializeField] private CursorSet _cursorSet;
[SerializeField, Reorderable] private ColorItemList _colors;
[SerializeField, Reorderable] private ColorSetItemList _colorSets;
[SerializeField, Reorderable] private ImageAndColorItemList _imagesAndColors;
[SerializeField, Reorderable] private ImageAndColorSetItemList _imageAndColorSets;
[SerializeField, Reorderable] private TextStyleItemList _textStyles;
[SerializeField, Reorderable] private TextStyleSetItemList _textStyleSets;
[NonSerialized] private StyleItemLookup<ColorItem, UnsettableColor> _colorsLookup;
[NonSerialized] private StyleItemLookup<ColorSetItem, ColorSet> _colorSetLookup;
[NonSerialized] private StyleItemLookup<ImageAndColorItem, ImageAndColor> _imagesAndColorsLookup;
[NonSerialized] private StyleItemLookup<ImageAndColorSetItem, ImageAndColorSet> _imageAndColorSetLookup;
[NonSerialized] private StyleItemLookup<TextStyleItem, TextStyle> _textStyleLookup;
[NonSerialized] private StyleItemLookup<TextStyleSetItem, TextStyleSet> _textStyleSetLookup;
internal EditorUIContext EditorUIContext;
private void OnValidate()
{
UpdateItems();
EditorUIContext?.RefreshStyle();
}
private void OnEnable() => UpdateItems();
private void UpdateItems()
{
_colorsLookup = new StyleItemLookup<ColorItem, UnsettableColor>(_colors, _parent?._colorsLookup);
_colorSetLookup = new StyleItemLookup<ColorSetItem, ColorSet>(_colorSets, _parent?._colorSetLookup);
_imagesAndColorsLookup = new StyleItemLookup<ImageAndColorItem, ImageAndColor>(
_imagesAndColors, _parent?._imagesAndColorsLookup);
_imageAndColorSetLookup = new StyleItemLookup<ImageAndColorSetItem, ImageAndColorSet>(
_imageAndColorSets, _parent?._imageAndColorSetLookup);
_textStyleLookup = new StyleItemLookup<TextStyleItem, TextStyle>(
_textStyles, _parent?._textStyleLookup);
_textStyleSetLookup = new StyleItemLookup<TextStyleSetItem, TextStyleSet>(
_textStyleSets, _parent?._textStyleSetLookup);
}
}
[Serializable]
internal class UIStyleList : ReorderableArray<UIStyle>
{
}
internal class StyleItemLookup<TItem, TValue> : IDirectory<TValue>
where TItem : UIStyleItem<TValue>
where TValue : class
{
public IDirectory<TValue> Parent { get; }
private readonly IDictionary<string, TValue> _dictionary;
public StyleItemLookup(IEnumerable<TItem> items, IDirectory<TValue> parent)
{
Parent = parent;
var list = items?
.GroupBy(i => i.Name)
.ToDictionary(g => g.Key, g => g.First().Value);
_dictionary = list ?? new Dictionary<string, TValue>();
}
public bool Contains(string key)
{
Assert.IsNotNull(key, "key != null");
var found = _dictionary.ContainsKey(key);
return found || Parent != null && Parent.Contains(key);
}
public TValue this[string key]
{
get
{
Assert.IsNotNull(key, "key != null");
TValue value;
_dictionary.TryGetValue(key, out value);
return value ?? Parent?[key];
}
}
}
internal abstract class UIStyleItem<T> : INamed where T : class
{
public string Name => _name;
public T Value => _value;
[SerializeField] private string _name;
[SerializeField] private T _value;
protected UIStyleItem(string name, T value)
{
Assert.IsNotNull(name, "name != null");
Assert.IsNotNull(value, "value != null");
_name = name;
_value = value;
}
}
[Serializable]
internal class TextStyleItem : UIStyleItem<TextStyle>
{
internal TextStyleItem(string name, TextStyle value) : base(name, value)
{
}
}
[Serializable]
internal class TextStyleItemList : ReorderableArray<TextStyleItem>
{
}
[Serializable]
internal class TextStyleSetItem : UIStyleItem<TextStyleSet>
{
internal TextStyleSetItem(string name, TextStyleSet value) : base(name, value)
{
}
}
[Serializable]
internal class TextStyleSetItemList : ReorderableArray<TextStyleSetItem>
{
}
[Serializable]
internal class ImageAndColorItem : UIStyleItem<ImageAndColor>
{
internal ImageAndColorItem(string name, ImageAndColor value) : base(name, value)
{
}
}
[Serializable]
internal class ImageAndColorItemList : ReorderableArray<ImageAndColorItem>
{
}
[Serializable]
internal class ImageAndColorSetItem : UIStyleItem<ImageAndColorSet>
{
internal ImageAndColorSetItem(string name, ImageAndColorSet value) : base(name, value)
{
}
}
[Serializable]
internal class ImageAndColorSetItemList : ReorderableArray<ImageAndColorSetItem>
{
}
[Serializable]
internal class ColorItem : UIStyleItem<UnsettableColor>
{
internal ColorItem(string name, UnsettableColor value) : base(name, value)
{
}
}
[Serializable]
internal class ColorItemList : ReorderableArray<ColorItem>
{
}
[Serializable]
internal class ColorSetItem : UIStyleItem<ColorSet>
{
internal ColorSetItem(string name, ColorSet value) : base(name, value)
{
}
}
[Serializable]
internal class ColorSetItemList : ReorderableArray<ColorSetItem>
{
}
[Serializable]
public class UIStyleReactiveProperty : ReactiveProperty<UIStyle>
{
public UIStyleReactiveProperty()
{
}
public UIStyleReactiveProperty(
UIStyle initialValue) : base(initialValue)
{
}
public UIStyleReactiveProperty(IObservable<UIStyle> source) : base(source)
{
}
public UIStyleReactiveProperty(IObservable<UIStyle> source, UIStyle initialValue) : base(source, initialValue)
{
}
}
}
| |
using Lucene.Net.Codecs;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace Lucene.Net.Index
{
/*
* 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 Codec = Lucene.Net.Codecs.Codec;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
using DocValuesProducer = Lucene.Net.Codecs.DocValuesProducer;
using FieldsProducer = Lucene.Net.Codecs.FieldsProducer;
using ICoreDisposedListener = Lucene.Net.Index.SegmentReader.ICoreDisposedListener;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using PostingsFormat = Lucene.Net.Codecs.PostingsFormat;
using StoredFieldsReader = Lucene.Net.Codecs.StoredFieldsReader;
using TermVectorsReader = Lucene.Net.Codecs.TermVectorsReader;
/// <summary>
/// Holds core readers that are shared (unchanged) when
/// <see cref="SegmentReader"/> is cloned or reopened
/// </summary>
internal sealed class SegmentCoreReaders
{
// Counts how many other readers share the core objects
// (freqStream, proxStream, tis, etc.) of this reader;
// when coreRef drops to 0, these core objects may be
// closed. A given instance of SegmentReader may be
// closed, even though it shares core objects with other
// SegmentReaders:
private readonly AtomicInt32 @ref = new AtomicInt32(1);
internal readonly FieldsProducer fields;
internal readonly DocValuesProducer normsProducer;
internal readonly int termsIndexDivisor;
internal readonly StoredFieldsReader fieldsReaderOrig;
internal readonly TermVectorsReader termVectorsReaderOrig;
internal readonly CompoundFileDirectory cfsReader;
// TODO: make a single thread local w/ a
// Thingy class holding fieldsReader, termVectorsReader,
// normsProducer
internal readonly DisposableThreadLocal<StoredFieldsReader> fieldsReaderLocal;
private class AnonymousFieldsReaderLocal : DisposableThreadLocal<StoredFieldsReader>
{
private readonly SegmentCoreReaders outerInstance;
public AnonymousFieldsReaderLocal(SegmentCoreReaders outerInstance)
{
this.outerInstance = outerInstance;
}
protected internal override StoredFieldsReader InitialValue()
{
return (StoredFieldsReader)outerInstance.fieldsReaderOrig.Clone();
}
}
internal readonly DisposableThreadLocal<TermVectorsReader> termVectorsLocal;
private class AnonymousTermVectorsLocal : DisposableThreadLocal<TermVectorsReader>
{
private readonly SegmentCoreReaders outerInstance;
public AnonymousTermVectorsLocal(SegmentCoreReaders outerInstance)
{
this.outerInstance = outerInstance;
}
protected internal override TermVectorsReader InitialValue()
{
return (outerInstance.termVectorsReaderOrig == null) ? null : (TermVectorsReader)outerInstance.termVectorsReaderOrig.Clone();
}
}
internal readonly DisposableThreadLocal<IDictionary<string, object>> normsLocal = new DisposableThreadLocalAnonymousInnerClassHelper3();
private class DisposableThreadLocalAnonymousInnerClassHelper3 : DisposableThreadLocal<IDictionary<string, object>>
{
public DisposableThreadLocalAnonymousInnerClassHelper3()
{
}
protected internal override IDictionary<string, object> InitialValue()
{
return new Dictionary<string, object>();
}
}
private readonly ISet<ICoreDisposedListener> coreClosedListeners = new ConcurrentHashSet<ICoreDisposedListener>(new IdentityComparer<ICoreDisposedListener>());
internal SegmentCoreReaders(SegmentReader owner, Directory dir, SegmentCommitInfo si, IOContext context, int termsIndexDivisor)
{
fieldsReaderLocal = new AnonymousFieldsReaderLocal(this);
termVectorsLocal = new AnonymousTermVectorsLocal(this);
if (termsIndexDivisor == 0)
{
throw new System.ArgumentException("indexDivisor must be < 0 (don't load terms index) or greater than 0 (got 0)");
}
Codec codec = si.Info.Codec;
Directory cfsDir; // confusing name: if (cfs) its the cfsdir, otherwise its the segment's directory.
bool success = false;
try
{
if (si.Info.UseCompoundFile)
{
cfsDir = cfsReader = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(si.Info.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context, false);
}
else
{
cfsReader = null;
cfsDir = dir;
}
FieldInfos fieldInfos = owner.FieldInfos;
this.termsIndexDivisor = termsIndexDivisor;
PostingsFormat format = codec.PostingsFormat;
SegmentReadState segmentReadState = new SegmentReadState(cfsDir, si.Info, fieldInfos, context, termsIndexDivisor);
// Ask codec for its Fields
fields = format.FieldsProducer(segmentReadState);
Debug.Assert(fields != null);
// ask codec for its Norms:
// TODO: since we don't write any norms file if there are no norms,
// kinda jaky to assume the codec handles the case of no norms file at all gracefully?!
if (fieldInfos.HasNorms)
{
normsProducer = codec.NormsFormat.NormsProducer(segmentReadState);
Debug.Assert(normsProducer != null);
}
else
{
normsProducer = null;
}
fieldsReaderOrig = si.Info.Codec.StoredFieldsFormat.FieldsReader(cfsDir, si.Info, fieldInfos, context);
if (fieldInfos.HasVectors) // open term vector files only as needed
{
termVectorsReaderOrig = si.Info.Codec.TermVectorsFormat.VectorsReader(cfsDir, si.Info, fieldInfos, context);
}
else
{
termVectorsReaderOrig = null;
}
success = true;
}
finally
{
if (!success)
{
DecRef();
}
}
}
internal int RefCount
{
get
{
return @ref.Get();
}
}
internal void IncRef()
{
int count;
while ((count = @ref.Get()) > 0)
{
if (@ref.CompareAndSet(count, count + 1))
{
return;
}
}
throw new ObjectDisposedException(this.GetType().FullName, "SegmentCoreReaders is already closed");
}
internal NumericDocValues GetNormValues(FieldInfo fi)
{
Debug.Assert(normsProducer != null);
IDictionary<string, object> normFields = normsLocal.Get();
object ret;
normFields.TryGetValue(fi.Name, out ret);
var norms = ret as NumericDocValues;
if (norms == null)
{
norms = normsProducer.GetNumeric(fi);
normFields[fi.Name] = norms;
}
return norms;
}
internal void DecRef()
{
if (@ref.DecrementAndGet() == 0)
{
Exception th = null;
try
{
IOUtils.Dispose(termVectorsLocal, fieldsReaderLocal, normsLocal, fields, termVectorsReaderOrig, fieldsReaderOrig, cfsReader, normsProducer);
}
catch (Exception throwable)
{
th = throwable;
}
finally
{
NotifyCoreClosedListeners(th);
}
}
}
private void NotifyCoreClosedListeners(Exception th)
{
lock (coreClosedListeners)
{
foreach (ICoreDisposedListener listener in coreClosedListeners)
{
// SegmentReader uses our instance as its
// coreCacheKey:
try
{
listener.OnDispose(this);
}
catch (Exception t)
{
if (th == null)
{
th = t;
}
else
{
th.AddSuppressed(t);
}
}
}
IOUtils.ReThrowUnchecked(th);
}
}
internal void AddCoreDisposedListener(ICoreDisposedListener listener)
{
coreClosedListeners.Add(listener);
}
internal void RemoveCoreDisposedListener(ICoreDisposedListener listener)
{
coreClosedListeners.Remove(listener);
}
/// <summary>
/// Returns approximate RAM bytes used </summary>
public long RamBytesUsed()
{
return ((normsProducer != null) ? normsProducer.RamBytesUsed() : 0) +
((fields != null) ? fields.RamBytesUsed() : 0) +
((fieldsReaderOrig != null) ? fieldsReaderOrig.RamBytesUsed() : 0) +
((termVectorsReaderOrig != null) ? termVectorsReaderOrig.RamBytesUsed() : 0);
}
}
}
| |
// Copyright (c) 2010, Eric Maupin
// 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 Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using Gablarski.Audio;
using Gablarski.Messages;
using Gablarski.Server;
using Gablarski.Tests.Mocks;
using NUnit.Framework;
using Tempest;
using Tempest.Tests;
namespace Gablarski.Tests
{
[TestFixture]
public class ServerSourceHandlerTests
{
private IGablarskiServerContext context;
private IServerSourceManager manager;
private IServerUserManager userManager;
private ServerSourceHandler handler;
private MockServerConnection server;
private ConnectionBuffer client;
private MockPermissionsProvider permissions;
private UserInfo user;
private MockConnectionProvider provider;
private const int defaultBitrate = 96000;
private const int maxBitrate = 192000;
private const int minBitrate = 32000;
[SetUp]
public void Setup()
{
permissions = new MockPermissionsProvider();
LobbyChannelProvider channels = new LobbyChannelProvider();
channels.SaveChannel (new ChannelInfo
{
Name = "Channel 2"
});
this.provider = new MockConnectionProvider (GablarskiProtocol.Instance);
this.provider.Start (MessageTypes.All);
userManager = new ServerUserManager();
MockServerContext c;
context = c = new MockServerContext (provider)
{
Settings = new ServerSettings
{
Name = "Server",
DefaultAudioBitrate = defaultBitrate,
MaximumAudioBitrate = maxBitrate,
MinimumAudioBitrate = minBitrate
},
UserManager = userManager,
PermissionsProvider = permissions,
ChannelsProvider = channels
};
c.Users = new ServerUserHandler (context, userManager);
manager = new ServerSourceManager (context);
handler = new ServerSourceHandler (context, manager);
user = UserInfoTests.GetTestUser (1, 1, false);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
client = new ConnectionBuffer (cs.Item1);
server = cs.Item2;
userManager.Connect (server);
userManager.Join (server, user);
}
[TearDown]
public void Teardown()
{
handler = null;
manager = null;
context = null;
server = null;
permissions = null;
}
[Test]
public void CtorNull()
{
Assert.Throws<ArgumentNullException> (() => new ServerSourceHandler (null, manager));
Assert.Throws<ArgumentNullException> (() => new ServerSourceHandler (context, null));
}
[Test]
public void Enumerable()
{
var source = manager.Create ("Name", user, AudioSourceTests.GetTestSource().CodecSettings);
var source2 = manager.Create ("Name2", user, AudioSourceTests.GetTestSource().CodecSettings);
Assert.Contains (source, handler.ToList());
Assert.Contains (source2, handler.ToList());
}
#region RequestSourceMessage
[Test]
public void RequestSourceNotConnected()
{
var cs = this.provider.GetConnections (GablarskiProtocol.Instance);
var cl = new ConnectionBuffer (cs.Item1);
cs.Item2.DisconnectAsync().Wait();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (cs.Item2,
new RequestSourceMessage ("Name", AudioCodecArgsTests.GetTestArgs())));
cl.AssertNoMessage();
}
[Test]
public void RequestSourceNotJoined()
{
var cs = this.provider.GetConnections (GablarskiProtocol.Instance);
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (cs.Item2);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (cs.Item2,
new RequestSourceMessage ("Name", AudioCodecArgsTests.GetTestArgs())));
cl.AssertNoMessage();
}
[Test]
public void RequestSource()
{
GetSourceFromRequest();
}
public AudioSource GetSourceFromRequest()
{
return GetSourceFromRequest (server, client);
}
public AudioSource GetSourceFromRequest (MockServerConnection serverConnection, ConnectionBuffer clientConnection)
{
permissions.EnablePermissions (userManager.GetUser (serverConnection).UserId, PermissionName.RequestSource);
var audioArgs = new AudioCodecArgs (AudioFormat.Mono16bitLPCM, 64000, AudioSourceTests.FrameSize, 10);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (serverConnection,
new RequestSourceMessage ("Name", audioArgs)));
var result = clientConnection.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
Assert.AreEqual ("Name", result.SourceName);
Assert.AreEqual ("Name", result.Source.Name);
AudioCodecArgsTests.AssertAreEqual (audioArgs, result.Source.CodecSettings);
clientConnection.AssertNoMessage();
return result.Source;
}
[Test]
public void RequestSourceDefaultBitrate()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = new AudioCodecArgs (AudioFormat.Mono16bitLPCM, 0, AudioSourceTests.FrameSize, 10);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server, new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
Assert.AreEqual ("Name", result.SourceName);
Assert.AreEqual ("Name", result.Source.Name);
audioArgs.Bitrate = defaultBitrate;
AudioCodecArgsTests.AssertAreEqual (audioArgs, result.Source.CodecSettings);
client.AssertNoMessage();
}
[Test]
public void RequestSourceExceedMaxBitrate()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = new AudioCodecArgs (AudioFormat.Mono16bitLPCM, 200000, AudioSourceTests.FrameSize, 10);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server, new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
Assert.AreEqual ("Name", result.SourceName);
Assert.AreEqual ("Name", result.Source.Name);
audioArgs.Bitrate = maxBitrate;
AudioCodecArgsTests.AssertAreEqual (audioArgs, result.Source.CodecSettings);
client.AssertNoMessage();
}
[Test]
public void RequestSourceBelowMinBitrate()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = new AudioCodecArgs (AudioFormat.Mono16bitLPCM, 1, AudioSourceTests.FrameSize, 10);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server, new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
Assert.AreEqual ("Name", result.SourceName);
Assert.AreEqual ("Name", result.Source.Name);
audioArgs.Bitrate = minBitrate;
AudioCodecArgsTests.AssertAreEqual (audioArgs, result.Source.CodecSettings);
client.AssertNoMessage();
}
[Test]
public void RequestSourceDuplicateSourceName()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = AudioCodecArgsTests.GetTestArgs();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name", audioArgs)));
result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.FailedDuplicateSourceName, result.SourceResult);
}
[Test]
public void RequestSourceNotification()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2));
var audioArgs = AudioCodecArgsTests.GetTestArgs();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name", audioArgs)));
var sourceAdded = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, sourceAdded.SourceResult);
Assert.AreEqual ("Name", sourceAdded.SourceName);
AudioCodecArgsTests.AssertAreEqual (audioArgs, sourceAdded.Source.CodecSettings);
cl.AssertNoMessage();
}
#endregion
#region RequestSourceListMessage
[Test]
public void RequestSourceListNotConnected()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
c.DisconnectAsync().Wait();
handler.RequestSourceListMessage (new MessageEventArgs<RequestSourceListMessage> (c, new RequestSourceListMessage ()));
cl.AssertNoMessage();
}
[Test]
public void RequestSourceListEmpty()
{
handler.RequestSourceListMessage (new MessageEventArgs<RequestSourceListMessage> (server, new RequestSourceListMessage()));
var list = client.DequeueAndAssertMessage<SourceListMessage>();
Assert.IsEmpty (list.Sources.ToList());
client.AssertNoMessage();
}
[Test]
public void RequestSourceList()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = AudioCodecArgsTests.GetTestArgs();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
client.AssertNoMessage();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name2", audioArgs)));
var result2 = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result2.SourceResult);
client.AssertNoMessage();
handler.RequestSourceListMessage (new MessageEventArgs<RequestSourceListMessage> (server, new RequestSourceListMessage()));
var list = client.DequeueAndAssertMessage<SourceListMessage>();
Assert.AreEqual (2, list.Sources.Count());
Assert.Contains (result.Source, list.Sources.ToList());
Assert.Contains (result2.Source, list.Sources.ToList());
client.AssertNoMessage();
}
[Test]
public void RequestSourceListFromViewer()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = AudioCodecArgsTests.GetTestArgs();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name2", audioArgs)));
var result2 = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result2.SourceResult);
client.AssertNoMessage();
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2));
handler.RequestSourceListMessage (new MessageEventArgs<RequestSourceListMessage> (c, new RequestSourceListMessage()));
var list = cl.DequeueAndAssertMessage<SourceListMessage>();
Assert.AreEqual (2, list.Sources.Count());
Assert.Contains (result.Source, list.Sources.ToList());
Assert.Contains (result2.Source, list.Sources.ToList());
cl.AssertNoMessage();
}
[Test]
public void RequestUpdatedSourceList()
{
permissions.EnablePermissions (user.UserId, PermissionName.RequestSource);
var audioArgs = AudioCodecArgsTests.GetTestArgs();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name", audioArgs)));
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result.SourceResult);
handler.RequestSourceListMessage (new MessageEventArgs<RequestSourceListMessage> (server, new RequestSourceListMessage()));
var list = client.DequeueAndAssertMessage<SourceListMessage>();
Assert.AreEqual (1, list.Sources.Count());
Assert.Contains (result.Source, list.Sources.ToList());
client.AssertNoMessage();
handler.RequestSourceMessage (new MessageEventArgs<RequestSourceMessage> (server,
new RequestSourceMessage ("Name2", audioArgs)));
var result2 = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.Succeeded, result2.SourceResult);
handler.RequestSourceListMessage (new MessageEventArgs<RequestSourceListMessage> (server, new RequestSourceListMessage()));
list = client.DequeueAndAssertMessage<SourceListMessage>();
Assert.AreEqual (2, list.Sources.Count());
Assert.Contains (result.Source, list.Sources.ToList());
Assert.Contains (result2.Source, list.Sources.ToList());
client.AssertNoMessage();
}
#endregion
#region RequestMuteSourceMessage
[Test]
public void RequestMuteNotConnected()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
c.DisconnectAsync().Wait();
var source = GetSourceFromRequest();
handler.RequestMuteSourceMessage (new MessageEventArgs<RequestMuteSourceMessage> (c,
new RequestMuteSourceMessage (source, true)));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void RequestMuteNotJoined()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
var source = GetSourceFromRequest();
Assert.AreEqual (SourceResult.NewSource, cl.DequeueAndAssertMessage<SourceResultMessage>().SourceResult);
handler.RequestMuteSourceMessage (new MessageEventArgs<RequestMuteSourceMessage> (c,
new RequestMuteSourceMessage (source, true)));
var denied = cl.DequeueAndAssertMessage<PermissionDeniedMessage>();
Assert.AreEqual (GablarskiMessageType.RequestMuteSource, denied.DeniedMessage);
cl.AssertNoMessage();
}
[Test]
public void RequestMuteWithoutPermission()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2));
var source = GetSourceFromRequest();
Assert.AreEqual (SourceResult.NewSource, cl.DequeueAndAssertMessage<SourceResultMessage>().SourceResult);
cl.AssertNoMessage();
handler.RequestMuteSourceMessage (new MessageEventArgs<RequestMuteSourceMessage> (c,
new RequestMuteSourceMessage (source, true)));
var denied = cl.DequeueAndAssertMessage<PermissionDeniedMessage>();
Assert.AreEqual (GablarskiMessageType.RequestMuteSource, denied.DeniedMessage);
cl.AssertNoMessage();
}
// [Test]
// public void RequestMuteWithPermission()
// {
// var u = UserInfoTests.GetTestUser (2);
// var c = new MockServerConnection();
// userManager.Connect (c);
// userManager.Join (c, u);
// permissions.SetPermissions (u.UserId, new[] { new Permission (PermissionName.MuteAudioSource, true) });
//
// var source = GetSourceFromRequest();
// Assert.AreEqual (SourceResult.NewSource, cl.DequeueAndAssertMessage<SourceResultMessage>().SourceResult);
//
// handler.RequestMuteSourceMessage (new MessageReceivedEventArgs (c,
// new RequestMuteSourceMessage (source, true)));
//
// var mute = cl.DequeueAndAssertMessage<MutedMessage>();
// Assert.AreEqual (false, mute.Unmuted);
// Assert.AreEqual (source.Id, mute.Target);
// Assert.AreEqual (MuteType.AudioSource, mute.Type);
// cl.AssertNoMessage();
//
// mute = client.DequeueAndAssertMessage<MutedMessage>();
// Assert.AreEqual (false, mute.Unmuted);
// Assert.AreEqual (source.Id, mute.Target);
// Assert.AreEqual (MuteType.AudioSource, mute.Type);
// cl.AssertNoMessage();
// }
#endregion
#region ClientAudioSourceStateChangeMessage
[Test]
public void ClientAudioSourceStateChangeNotConnected()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
c.DisconnectAsync().Wait();
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = 1, Starting = true }));
client.AssertNoMessage();
cl.AssertNoMessage();
}
[Test]
public void ClientAudioSourceStateChangeNotJoined()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = 1, Starting = true }));
client.AssertNoMessage();
cl.AssertNoMessage();
}
[Test]
public void ClientAudioSourceStateChangeNotOwnedSource()
{
var u = UserInfoTests.GetTestUser (2, 1, false);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, u);
var s = manager.Create ("Name", user, new AudioCodecArgs());
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = s.Id, Starting = true }));
client.AssertNoMessage();
cl.AssertNoMessage();
}
[Test]
public void ClientAudioSourceStateChangedUserMuted()
{
var u = UserInfoTests.GetTestUser (2, 1, true);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, u);
var s = manager.Create ("Name", u, new AudioCodecArgs ());
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = s.Id, Starting = true }));
client.AssertNoMessage();
cl.AssertNoMessage();
}
[Test]
public void ClientAudioSourceStateChangedSourceMuted()
{
var u = UserInfoTests.GetTestUser (2, 1, false);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, u);
var s = manager.Create ("Name", u, new AudioCodecArgs ());
manager.ToggleMute (s);
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = s.Id, Starting = true }));
client.AssertNoMessage();
cl.AssertNoMessage();
}
[Test]
public void ClientAudioSourceStateChangedSameChannel()
{
var u = UserInfoTests.GetTestUser (2, 1, false);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, u);
var s = manager.Create ("Name", u, new AudioCodecArgs ());
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = s.Id, Starting = true }));
cl.AssertNoMessage();
var change = client.DequeueAndAssertMessage<AudioSourceStateChangeMessage>();
Assert.AreEqual (s.Id, change.SourceId);
Assert.AreEqual (true, change.Starting);
}
[Test]
public void ClientAudioSourceStateChangedDifferentChannel()
{
var u = UserInfoTests.GetTestUser (2, 2, false);
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, u);
var s = manager.Create ("Name", u, new AudioCodecArgs ());
handler.ClientAudioSourceStateChangeMessage (new MessageEventArgs<ClientAudioSourceStateChangeMessage> (c,
new ClientAudioSourceStateChangeMessage { SourceId = s.Id, Starting = true }));
cl.AssertNoMessage();
var change = client.DequeueAndAssertMessage<AudioSourceStateChangeMessage>();
Assert.AreEqual (s.Id, change.SourceId);
Assert.AreEqual (true, change.Starting);
}
#endregion
#region ClientAudioDataMessage
[Test]
public void SendAudioDataMessageNotConnected()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
c.DisconnectAsync().Wait();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (c,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = 1,
TargetType = TargetType.Channel,
TargetIds = new [] { 1 }
}));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void SendAudioDataMessageNotJoined()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (c,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = 1,
TargetType = TargetType.Channel,
TargetIds = new [] { 1 }
}));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void SendAudioDataMessageUnknownSource()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = 1,
TargetType = TargetType.Channel,
TargetIds = new [] { 1 }
}));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void SendAudioDataMessageSourceNotOwned()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (c,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { 1 }
}));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void SendAudioDataMessageSourceMuted ()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
var s = GetSourceFromRequest();
manager.ToggleMute (s);
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { 1 }
}));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void SendAudioDataMessageUserMuted()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, true));
var s = GetSourceFromRequest (c, cl);
var result = client.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
client.AssertNoMessage();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (c,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { 1 }
}));
cl.AssertNoMessage();
client.AssertNoMessage();
}
[Test]
public void SendAudioDataMessageToUser()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
var u = UserInfoTests.GetTestUser (2, 2, false);
userManager.Join (c, u);
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
permissions.EnablePermissions (user.UserId, PermissionName.SendAudio);
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.User,
TargetIds = new [] { u.UserId }
}));
client.AssertNoMessage();
Assert.AreEqual (s.Id, cl.DequeueAndAssertMessage<ServerAudioDataMessage>().SourceId);
}
[Test]
public void SendAudioDataMessageToUserWithoutPermission()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
var u = UserInfoTests.GetTestUser (2, 2, false);
userManager.Join (c, u);
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.User,
TargetIds = new [] { u.UserId }
}));
cl.AssertNoMessage();
Assert.AreEqual (GablarskiMessageType.ClientAudioData, client.DequeueAndAssertMessage<PermissionDeniedMessage>().DeniedMessage);
}
[Test]
public void SendAudioDataMessageToCurrentChannel()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
permissions.EnablePermissions (user.UserId, PermissionName.SendAudio);
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { user.CurrentChannelId }
}));
client.AssertNoMessage();
Assert.AreEqual (s.Id, cl.DequeueAndAssertMessage<ServerAudioDataMessage>().SourceId);
}
[Test]
public void SendAudioDataMessageToCurrentChannelWithoutPermission()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { user.CurrentChannelId }
}));
cl.AssertNoMessage();
Assert.AreEqual (GablarskiMessageType.ClientAudioData, client.DequeueAndAssertMessage<PermissionDeniedMessage>().DeniedMessage);
}
[Test]
public void SendAudioDataMessageToMultipleChannels()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
var cs2 = provider.GetConnections (GablarskiProtocol.Instance);
var c2 = cs2.Item2;
var cl2 = new ConnectionBuffer (cs.Item1);
userManager.Connect (c2);
userManager.Join (c2, UserInfoTests.GetTestUser (3, 2, false));
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
result = cl2.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl2.AssertNoMessage();
permissions.EnablePermissions (user.UserId, PermissionName.SendAudio, PermissionName.SendAudioToMultipleTargets);
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { 1, 2 }
}));
client.AssertNoMessage();
Assert.AreEqual (s.Id, cl.DequeueAndAssertMessage<ServerAudioDataMessage>().SourceId);
Assert.AreEqual (s.Id, cl2.DequeueAndAssertMessage<ServerAudioDataMessage>().SourceId);
}
[Test]
public void SendAudioDataMessageToMultipleChannelsWithoutPermission()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
userManager.Join (c, UserInfoTests.GetTestUser (2, 1, false));
var cs2 = provider.GetConnections (GablarskiProtocol.Instance);
var c2 = cs2.Item2;
var cl2 = new ConnectionBuffer (cs.Item1);
userManager.Connect (c2);
userManager.Join (c2, UserInfoTests.GetTestUser (3, 2, false));
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
result = cl2.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl2.AssertNoMessage();
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.Channel,
TargetIds = new [] { 1, 2 }
}));
cl.AssertNoMessage();
cl2.AssertNoMessage();
Assert.AreEqual (GablarskiMessageType.ClientAudioData, client.DequeueAndAssertMessage<PermissionDeniedMessage>().DeniedMessage);
}
[Test]
public void SendAudioDataMessageToMultipleUsers()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
var u1 = UserInfoTests.GetTestUser (2, 1, false);
userManager.Join (c, u1);
var cs2 = provider.GetConnections (GablarskiProtocol.Instance);
var c2 = cs2.Item2;
var cl2 = new ConnectionBuffer (cs.Item1);
userManager.Connect (c2);
var u2 = UserInfoTests.GetTestUser (3, 2, false);
userManager.Join (c2, u2);
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
result = cl2.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl2.AssertNoMessage();
permissions.EnablePermissions (user.UserId, PermissionName.SendAudio, PermissionName.SendAudioToMultipleTargets);
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.User,
TargetIds = new [] { u1.UserId, u2.UserId }
}));
client.AssertNoMessage();
Assert.AreEqual (s.Id, cl.DequeueAndAssertMessage<ServerAudioDataMessage>().SourceId);
Assert.AreEqual (s.Id, cl2.DequeueAndAssertMessage<ServerAudioDataMessage>().SourceId);
}
[Test]
public void SendAudioDataMessageToMultipleUsersWithoutPermission()
{
var cs = provider.GetConnections (GablarskiProtocol.Instance);
var c = cs.Item2;
var cl = new ConnectionBuffer (cs.Item1);
userManager.Connect (c);
var u1 = UserInfoTests.GetTestUser (2, 1, false);
userManager.Join (c, u1);
var cs2 = provider.GetConnections (GablarskiProtocol.Instance);
var c2 = cs2.Item2;
var cl2 = new ConnectionBuffer (cs.Item1);
userManager.Connect (c2);
var u2 = UserInfoTests.GetTestUser (3, 1, false);
userManager.Join (c2, u2);
var s = GetSourceFromRequest();
var result = cl.DequeueAndAssertMessage<SourceResultMessage>();
Assert.AreEqual (SourceResult.NewSource, result.SourceResult);
cl.AssertNoMessage();
permissions.EnablePermissions (user.UserId, PermissionName.SendAudio);
handler.OnClientAudioDataMessage (new MessageEventArgs<ClientAudioDataMessage> (server,
new ClientAudioDataMessage
{
Data = new [] { new byte[512] },
SourceId = s.Id,
TargetType = TargetType.User,
TargetIds = new [] { u1.UserId, u2.UserId }
}));
cl.AssertNoMessage();
Assert.AreEqual (GablarskiMessageType.ClientAudioData, client.DequeueAndAssertMessage<PermissionDeniedMessage>().DeniedMessage);
}
#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;
using System.Xml;
using System.Xml.Schema;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Reflection;
namespace System.Xml.Xsl
{
/// <summary>
/// Implementation of read-only IList and IList<T> interfaces. Derived classes can inherit from
/// this class and implement only two methods, Count and Item, rather than the entire IList interface.
/// </summary>
internal abstract class ListBase<T> : IList<T>, System.Collections.IList
{
//-----------------------------------------------
// Abstract IList methods that must be
// implemented by derived classes
//-----------------------------------------------
public abstract int Count { get; }
public abstract T this[int index] { get; set; }
//-----------------------------------------------
// Implemented by base class -- accessible on
// ListBase
//-----------------------------------------------
public virtual bool Contains(T value)
{
return IndexOf(value) != -1;
}
public virtual int IndexOf(T value)
{
for (int i = 0; i < Count; i++)
if (value.Equals(this[i]))
return i;
return -1;
}
public virtual void CopyTo(T[] array, int index)
{
for (int i = 0; i < Count; i++)
array[index + i] = this[i];
}
public virtual IListEnumerator<T> GetEnumerator()
{
return new IListEnumerator<T>(this);
}
public virtual bool IsFixedSize
{
get { return true; }
}
public virtual bool IsReadOnly
{
get { return true; }
}
public virtual void Add(T value)
{
Insert(Count, value);
}
public virtual void Insert(int index, T value)
{
throw new NotSupportedException();
}
public virtual bool Remove(T value)
{
int index = IndexOf(value);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
public virtual void RemoveAt(int index)
{
throw new NotSupportedException();
}
public virtual void Clear()
{
for (int index = Count - 1; index >= 0; index--)
RemoveAt(index);
}
//-----------------------------------------------
// Implemented by base class -- only accessible
// after casting to IList
//-----------------------------------------------
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new IListEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new IListEnumerator<T>(this);
}
bool System.Collections.ICollection.IsSynchronized
{
get { return IsReadOnly; }
}
object System.Collections.ICollection.SyncRoot
{
get { return this; }
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
for (int i = 0; i < Count; i++)
array.SetValue(this[i], index);
}
object System.Collections.IList.this[int index]
{
get { return this[index]; }
set
{
if (!IsCompatibleType(value.GetType()))
throw new ArgumentException(SR.Arg_IncompatibleParamType, nameof(value));
this[index] = (T)value;
}
}
int System.Collections.IList.Add(object value)
{
if (!IsCompatibleType(value.GetType()))
throw new ArgumentException(SR.Arg_IncompatibleParamType, nameof(value));
Add((T)value);
return Count - 1;
}
void System.Collections.IList.Clear()
{
Clear();
}
bool System.Collections.IList.Contains(object value)
{
if (!IsCompatibleType(value.GetType()))
return false;
return Contains((T)value);
}
int System.Collections.IList.IndexOf(object value)
{
if (!IsCompatibleType(value.GetType()))
return -1;
return IndexOf((T)value);
}
void System.Collections.IList.Insert(int index, object value)
{
if (!IsCompatibleType(value.GetType()))
throw new ArgumentException(SR.Arg_IncompatibleParamType, nameof(value));
Insert(index, (T)value);
}
void System.Collections.IList.Remove(object value)
{
if (IsCompatibleType(value.GetType()))
{
Remove((T)value);
}
}
//-----------------------------------------------
// Helper methods and classes
//-----------------------------------------------
private static bool IsCompatibleType(object value)
{
if ((value == null && !typeof(T).IsValueType) || (value is T))
return true;
return false;
}
}
/// <summary>
/// Implementation of IEnumerator<T> and IEnumerator over an IList<T>.
/// </summary>
internal struct IListEnumerator<T> : IEnumerator<T>, System.Collections.IEnumerator
{
private IList<T> _sequence;
private int _index;
private T _current;
/// <summary>
/// Constructor.
/// </summary>
public IListEnumerator(IList<T> sequence)
{
_sequence = sequence;
_index = 0;
_current = default(T);
}
/// <summary>
/// No-op.
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Return current item. Return default value if before first item or after last item in the list.
/// </summary>
public T Current
{
get { return _current; }
}
/// <summary>
/// Return current item. Throw exception if before first item or after last item in the list.
/// </summary>
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0)
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
if (_index > _sequence.Count)
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
return _current;
}
}
/// <summary>
/// Advance enumerator to next item in list. Return false if there are no more items.
/// </summary>
public bool MoveNext()
{
if (_index < _sequence.Count)
{
_current = _sequence[_index];
_index++;
return true;
}
_current = default(T);
return false;
}
/// <summary>
/// Set the enumerator to its initial position, which is before the first item in the list.
/// </summary>
void System.Collections.IEnumerator.Reset()
{
_index = 0;
_current = default(T);
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 UIKit;
using Foundation;
using System;
using System.IO;
using System.Threading;
using Sensus.Probes;
using Sensus.Context;
using Sensus.Probes.Movement;
using Sensus.Probes.Location;
using Xamarin.Forms;
using MessageUI;
using AVFoundation;
using CoreBluetooth;
using CoreFoundation;
using System.Threading.Tasks;
using TTGSnackBar;
namespace Sensus.iOS
{
public class iOSSensusServiceHelper : SensusServiceHelper
{
#region static members
private const int BLUETOOTH_ENABLE_TIMEOUT_MS = 15000;
#endregion
private DateTime _nextToastTime;
private readonly object _toastLocker = new object();
public override bool IsCharging
{
get
{
return UIDevice.CurrentDevice.BatteryState == UIDeviceBatteryState.Charging || UIDevice.CurrentDevice.BatteryState == UIDeviceBatteryState.Full;
}
}
public override float BatteryChargePercent
{
get
{
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
return UIDevice.CurrentDevice.BatteryLevel * 100f;
}
}
public override bool WiFiConnected
{
get
{
return NetworkConnectivity.LocalWifiConnectionStatus() == NetworkStatus.ReachableViaWiFiNetwork;
}
}
public override string DeviceId
{
get
{
return UIDevice.CurrentDevice.IdentifierForVendor.AsString();
}
}
public override string OperatingSystem
{
get
{
return UIDevice.CurrentDevice.SystemName + " " + UIDevice.CurrentDevice.SystemVersion;
}
}
protected override bool IsOnMainThread
{
get { return NSThread.IsMain; }
}
public override string Version
{
get
{
return NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"].ToString();
}
}
public iOSSensusServiceHelper()
{
_nextToastTime = DateTime.Now;
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
}
protected override Task ProtectedFlashNotificationAsync(string message, Action callback)
{
return Task.Run(() =>
{
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
TTGSnackbar snackbar = new TTGSnackbar(message);
snackbar.Duration = TimeSpan.FromSeconds(5);
snackbar.Show();
callback?.Invoke();
});
});
}
public override Task ShareFileAsync(string path, string subject, string mimeType)
{
return SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
{
if (!MFMailComposeViewController.CanSendMail)
{
await FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
return;
}
NSData data = NSData.FromUrl(NSUrl.FromFilename(path));
if (data == null)
{
await FlashNotificationAsync("No file to share.");
return;
}
MFMailComposeViewController mailer = new MFMailComposeViewController();
mailer.SetSubject(subject);
mailer.AddAttachmentData(data, mimeType, Path.GetFileName(path));
mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
});
}
public override Task SendEmailAsync(string toAddress, string subject, string message)
{
return SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
{
if (MFMailComposeViewController.CanSendMail)
{
MFMailComposeViewController mailer = new MFMailComposeViewController();
mailer.SetToRecipients(new string[] { toAddress });
mailer.SetSubject(subject);
mailer.SetMessageBody(message, false);
mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
}
else
{
await FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
}
});
}
public override Task TextToSpeechAsync(string text)
{
return Task.Run(() =>
{
try
{
new AVSpeechSynthesizer().SpeakUtterance(new AVSpeechUtterance(text));
}
catch (Exception ex)
{
Logger.Log("Failed to speak utterance: " + ex.Message, LoggingLevel.Normal, GetType());
}
});
}
public override Task<string> RunVoicePromptAsync(string prompt, Action postDisplayCallback)
{
return Task.Run(() =>
{
string input = null;
ManualResetEvent dialogDismissWait = new ManualResetEvent(false);
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
#region set up dialog
ManualResetEvent dialogShowWait = new ManualResetEvent(false);
UIAlertView dialog = new UIAlertView("Sensus is requesting input...", prompt, default(IUIAlertViewDelegate), "Cancel", "OK");
dialog.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
dialog.Dismissed += (o, e) =>
{
dialogDismissWait.Set();
};
dialog.Presented += (o, e) =>
{
dialogShowWait.Set();
if (postDisplayCallback != null)
{
postDisplayCallback();
}
};
dialog.Clicked += (o, e) =>
{
if (e.ButtonIndex == 1)
{
input = dialog.GetTextField(0).Text;
}
};
dialog.Show();
#endregion
#region voice recognizer
Task.Run(() =>
{
// wait for the dialog to be shown so it doesn't hide our speech recognizer activity
dialogShowWait.WaitOne();
// there's a slight race condition between the dialog showing and speech recognition showing. pause here to prevent the dialog from hiding the speech recognizer.
Thread.Sleep(1000);
// TODO: Add speech recognition
});
#endregion
});
dialogDismissWait.WaitOne();
return input;
});
}
public override bool EnableProbeWhenEnablingAll(Probe probe)
{
// polling for locations doesn't work very well in iOS, since it depends on the user. don't enable probes that need location polling by default.
return !(probe is PollingLocationProbe) &&
!(probe is PollingSpeedProbe) &&
!(probe is PollingPointsOfInterestProximityProbe);
}
public override ImageSource GetQrCodeImageSource(string contents)
{
return ImageSource.FromStream(() =>
{
UIImage bitmap = BarcodeWriter.Write(contents);
MemoryStream ms = new MemoryStream();
bitmap.AsPNG().AsStream().CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
return ms;
});
}
/// <summary>
/// Enables the Bluetooth adapter, or prompts the user to do so if we cannot do this programmatically. Must not be called from the UI thread.
/// </summary>
/// <returns><c>true</c>, if Bluetooth was enabled, <c>false</c> otherwise.</returns>
/// <param name="lowEnergy">If set to <c>true</c> low energy.</param>
/// <param name="rationale">Rationale.</param>
public override bool EnableBluetooth(bool lowEnergy, string rationale)
{
base.EnableBluetooth(lowEnergy, rationale);
bool enabled = false;
ManualResetEvent enableWait = new ManualResetEvent(false);
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
try
{
CBCentralManager manager = new CBCentralManager(DispatchQueue.MainQueue);
manager.UpdatedState += (sender, e) =>
{
if (manager.State == CBCentralManagerState.PoweredOn)
{
enabled = true;
enableWait.Set();
}
};
if (manager.State == CBCentralManagerState.PoweredOn)
{
enabled = true;
enableWait.Set();
}
}
catch (Exception ex)
{
Logger.Log("Failed while requesting Bluetooth enable: " + ex.Message, LoggingLevel.Normal, GetType());
enableWait.Set();
}
});
// the base class will ensure that we're not on the main thread, making the following wait okay.
if (!enableWait.WaitOne(BLUETOOTH_ENABLE_TIMEOUT_MS))
{
Logger.Log("Timed out while waiting for user to enable Bluetooth.", LoggingLevel.Normal, GetType());
}
return enabled;
}
#region methods not implemented in ios
public override Task PromptForAndReadTextFileAsync(string promptTitle, Action<string> callback)
{
return Task.Run(async () =>
{
await FlashNotificationAsync("This is not supported on iOS.");
});
}
public override void KeepDeviceAwake()
{
}
public override void LetDeviceSleep()
{
}
public override Task BringToForegroundAsync()
{
return Task.CompletedTask;
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 10/5/2009 2:06:00 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// PointSizeRangeControl
/// </summary>
[DefaultEvent("SizeRangeChanged")]
public class FeatureSizeRangeControl : UserControl
{
private Button btnEdit;
private CheckBox chkSizeRange;
private GroupBox grpSizeRange;
private Label label1;
private Label label2;
private NumericUpDown nudEnd;
private NumericUpDown nudStart;
#region Private Variables
private bool _ignore;
private DetailedLineSymbolDialog _lineDialog;
private DetailedPointSymbolDialog _pointDialog;
private IFeatureScheme _scheme;
private FeatureSizeRange _sizeRange;
private LineSymbolView lsvEnd;
private LineSymbolView lsvStart;
private PointSymbolView psvEnd;
private PointSymbolView psvStart;
private TrackBar trkEnd;
private TrackBar trkStart;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of PointSizeRangeControl
/// </summary>
public FeatureSizeRangeControl()
{
InitializeComponent();
_pointDialog = new DetailedPointSymbolDialog();
_pointDialog.ChangesApplied += _pointDialog_ChangesApplied;
_lineDialog = new DetailedLineSymbolDialog();
_lineDialog.ChangesApplied += _lineDialog_ChangesApplied;
}
private void _lineDialog_ChangesApplied(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Symbolizer = _lineDialog.Symbolizer;
UpdateControls();
}
private void _pointDialog_ChangesApplied(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Symbolizer = _pointDialog.Symbolizer;
UpdateControls();
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the point scheme to work with.
/// </summary>
public IFeatureScheme Scheme
{
get { return _scheme; }
set
{
_scheme = value;
IPointScheme ps = _scheme as IPointScheme;
if (ps != null)
{
if (ps.Categories.Count > 0)
{
_sizeRange.Symbolizer = ps.Categories[0].Symbolizer;
}
}
ILineScheme ls = _scheme as ILineScheme;
if (ls != null)
{
if (ls.Categories.Count > 0)
{
_sizeRange.Symbolizer = ls.Categories[0].Symbolizer;
}
}
UpdateControls();
}
}
#endregion
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FeatureSizeRangeControl));
this.nudStart = new System.Windows.Forms.NumericUpDown();
this.nudEnd = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.grpSizeRange = new System.Windows.Forms.GroupBox();
this.chkSizeRange = new System.Windows.Forms.CheckBox();
this.lsvStart = new DotSpatial.Symbology.Forms.LineSymbolView();
this.psvStart = new DotSpatial.Symbology.Forms.PointSymbolView();
this.lsvEnd = new DotSpatial.Symbology.Forms.LineSymbolView();
this.trkEnd = new System.Windows.Forms.TrackBar();
this.btnEdit = new System.Windows.Forms.Button();
this.trkStart = new System.Windows.Forms.TrackBar();
this.label2 = new System.Windows.Forms.Label();
this.psvEnd = new DotSpatial.Symbology.Forms.PointSymbolView();
((System.ComponentModel.ISupportInitialize)(this.nudStart)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudEnd)).BeginInit();
this.grpSizeRange.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trkEnd)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trkStart)).BeginInit();
this.SuspendLayout();
//
// nudStart
//
resources.ApplyResources(this.nudStart, "nudStart");
this.nudStart.Maximum = new decimal(new int[] {
128,
0,
0,
0});
this.nudStart.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nudStart.Name = "nudStart";
this.nudStart.Value = new decimal(new int[] {
5,
0,
0,
0});
this.nudStart.ValueChanged += new System.EventHandler(this.nudStart_ValueChanged);
//
// nudEnd
//
resources.ApplyResources(this.nudEnd, "nudEnd");
this.nudEnd.Maximum = new decimal(new int[] {
128,
0,
0,
0});
this.nudEnd.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nudEnd.Name = "nudEnd";
this.nudEnd.Value = new decimal(new int[] {
20,
0,
0,
0});
this.nudEnd.ValueChanged += new System.EventHandler(this.nudEnd_ValueChanged);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// grpSizeRange
//
this.grpSizeRange.Controls.Add(this.chkSizeRange);
this.grpSizeRange.Controls.Add(this.lsvStart);
this.grpSizeRange.Controls.Add(this.psvStart);
this.grpSizeRange.Controls.Add(this.lsvEnd);
this.grpSizeRange.Controls.Add(this.trkEnd);
this.grpSizeRange.Controls.Add(this.btnEdit);
this.grpSizeRange.Controls.Add(this.trkStart);
this.grpSizeRange.Controls.Add(this.label2);
this.grpSizeRange.Controls.Add(this.nudStart);
this.grpSizeRange.Controls.Add(this.nudEnd);
this.grpSizeRange.Controls.Add(this.label1);
this.grpSizeRange.Controls.Add(this.psvEnd);
resources.ApplyResources(this.grpSizeRange, "grpSizeRange");
this.grpSizeRange.Name = "grpSizeRange";
this.grpSizeRange.TabStop = false;
//
// chkSizeRange
//
resources.ApplyResources(this.chkSizeRange, "chkSizeRange");
this.chkSizeRange.Name = "chkSizeRange";
this.chkSizeRange.UseVisualStyleBackColor = true;
this.chkSizeRange.CheckedChanged += new System.EventHandler(this.chkSizeRange_CheckedChanged);
//
// lsvStart
//
this.lsvStart.BackColor = System.Drawing.Color.White;
this.lsvStart.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
resources.ApplyResources(this.lsvStart, "lsvStart");
this.lsvStart.Name = "lsvStart";
//
// psvStart
//
this.psvStart.BackColor = System.Drawing.Color.White;
this.psvStart.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
resources.ApplyResources(this.psvStart, "psvStart");
this.psvStart.Name = "psvStart";
//
// lsvEnd
//
this.lsvEnd.BackColor = System.Drawing.Color.White;
this.lsvEnd.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
resources.ApplyResources(this.lsvEnd, "lsvEnd");
this.lsvEnd.Name = "lsvEnd";
//
// trkEnd
//
resources.ApplyResources(this.trkEnd, "trkEnd");
this.trkEnd.Maximum = 128;
this.trkEnd.Minimum = 1;
this.trkEnd.Name = "trkEnd";
this.trkEnd.TickFrequency = 16;
this.trkEnd.Value = 20;
this.trkEnd.Scroll += new System.EventHandler(this.trkEnd_Scroll);
//
// btnEdit
//
resources.ApplyResources(this.btnEdit, "btnEdit");
this.btnEdit.Name = "btnEdit";
this.btnEdit.UseVisualStyleBackColor = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// trkStart
//
resources.ApplyResources(this.trkStart, "trkStart");
this.trkStart.Maximum = 128;
this.trkStart.Minimum = 1;
this.trkStart.Name = "trkStart";
this.trkStart.TickFrequency = 16;
this.trkStart.Value = 5;
this.trkStart.Scroll += new System.EventHandler(this.trkStart_Scroll);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// psvEnd
//
this.psvEnd.BackColor = System.Drawing.Color.White;
this.psvEnd.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
resources.ApplyResources(this.psvEnd, "psvEnd");
this.psvEnd.Name = "psvEnd";
//
// FeatureSizeRangeControl
//
this.Controls.Add(this.grpSizeRange);
this.Name = "FeatureSizeRangeControl";
resources.ApplyResources(this, "$this");
((System.ComponentModel.ISupportInitialize)(this.nudStart)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudEnd)).EndInit();
this.grpSizeRange.ResumeLayout(false);
this.grpSizeRange.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trkEnd)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trkStart)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Gets or sets the point Size Range, which controls the symbolizer,
/// as well as allowing the creation of a dynamically sized version
/// of the symbolizer.
/// </summary>
public FeatureSizeRange SizeRange
{
get { return _sizeRange; }
set
{
_sizeRange = value;
UpdateControls();
}
}
/// <summary>
/// Occurs when either the sizes or the template has changed.
/// </summary>
public event EventHandler<SizeRangeEventArgs> SizeRangeChanged;
/// <summary>
/// Initializes this point size range control
/// </summary>
/// <param name="args"></param>
public void Initialize(SizeRangeEventArgs args)
{
if (_sizeRange == null) return;
_sizeRange.Start = args.StartSize;
_sizeRange.End = args.EndSize;
_sizeRange.Symbolizer = args.Template;
_sizeRange.UseSizeRange = args.UseSizeRange;
IPointSymbolizer ps = args.Template as IPointSymbolizer;
if (ps != null)
{
psvStart.Visible = true;
psvEnd.Visible = true;
lsvStart.Visible = false;
lsvEnd.Visible = false;
}
ILineSymbolizer ls = args.Template as ILineSymbolizer;
if (ls != null)
{
lsvStart.Visible = true;
lsvEnd.Visible = true;
psvStart.Visible = false;
psvEnd.Visible = false;
}
}
private void nudStart_ValueChanged(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Start = (int)nudStart.Value;
UpdateControls();
}
/// <summary>
/// Handles the inter-connectivity of the various controls and updates
/// them all to match the latest value.
/// </summary>
public void UpdateControls()
{
if (_ignore) return;
_ignore = true;
if (_sizeRange == null)
{
_ignore = false;
return;
}
chkSizeRange.Checked = _sizeRange.UseSizeRange;
trkStart.Value = (int)_sizeRange.Start;
trkEnd.Value = (int)_sizeRange.End;
IPointSymbolizer ps = _sizeRange.Symbolizer as IPointSymbolizer;
if (ps != null)
{
Color color = ps.GetFillColor();
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.StartColor;
}
if (chkSizeRange.Checked)
{
psvStart.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.Start, color) as IPointSymbolizer;
}
else
{
IPointSymbolizer sm = ps.Copy();
sm.SetFillColor(color);
psvStart.Symbolizer = sm;
}
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.EndColor;
}
if (chkSizeRange.Checked)
{
psvEnd.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.End, color) as IPointSymbolizer;
}
else
{
IPointSymbolizer sm = ps.Copy();
sm.SetFillColor(color);
psvEnd.Symbolizer = sm;
}
}
ILineSymbolizer ls = _sizeRange.Symbolizer as ILineSymbolizer;
if (ls != null)
{
Color color = ls.GetFillColor();
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.StartColor;
}
if (chkSizeRange.Checked)
{
lsvStart.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.Start, color) as ILineSymbolizer;
}
else
{
ILineSymbolizer sm = ls.Copy();
sm.SetFillColor(color);
lsvStart.Symbolizer = sm;
}
if (_scheme != null && _scheme.EditorSettings.UseColorRange)
{
color = _scheme.EditorSettings.EndColor;
}
if (chkSizeRange.Checked)
{
lsvEnd.Symbolizer = _sizeRange.GetSymbolizer(_sizeRange.End, color) as ILineSymbolizer;
}
else
{
ILineSymbolizer sm = ls.Copy();
sm.SetFillColor(color);
lsvEnd.Symbolizer = sm;
}
}
nudStart.Value = (decimal)_sizeRange.Start;
nudEnd.Value = (decimal)_sizeRange.End;
_ignore = false;
OnSizeRangeChanged();
}
private void nudEnd_ValueChanged(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.End = (int)nudEnd.Value;
UpdateControls();
}
private void trkEnd_Scroll(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.End = trkEnd.Value;
UpdateControls();
}
private void trkStart_Scroll(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.Start = trkStart.Value;
UpdateControls();
}
private void chkSizeRange_CheckedChanged(object sender, EventArgs e)
{
if (_sizeRange == null) return;
_sizeRange.UseSizeRange = chkSizeRange.Checked;
UpdateControls();
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (_sizeRange == null) return;
IPointSymbolizer ps = _sizeRange.Symbolizer as IPointSymbolizer;
if (ps != null)
{
_pointDialog.Symbolizer = _sizeRange.Symbolizer as IPointSymbolizer;
_pointDialog.ShowDialog(this);
}
ILineSymbolizer ls = _sizeRange.Symbolizer as ILineSymbolizer;
if (ls != null)
{
_lineDialog.Symbolizer = _sizeRange.Symbolizer as ILineSymbolizer;
_lineDialog.ShowDialog(this);
}
}
/// <summary>
/// Fires the SizeRangeChanged event args
/// </summary>
protected virtual void OnSizeRangeChanged()
{
if (SizeRangeChanged != null) SizeRangeChanged(this, new SizeRangeEventArgs(_sizeRange));
}
}
}
| |
namespace Loon.Utils.Collection
{
using Loon.Core;
public class ArrayNode<T>
{
public ArrayNode<T> next;
public ArrayNode<T> previous;
public T data;
public ArrayNode()
{
this.next = null;
this.previous = null;
this.data = default(T);
}
}
public class Array<T> : LRelease {
private ArrayNode<T> _items = null ;
private int _length = 0;
private bool _close = false;
private ArrayNode<T> _next_tmp = null, _previous_tmp = null;
private int _next_count = 0, _previous_count = 0;
public Array()
{
Clear();
}
public void InsertBetween(Array<T> previous, Array<T> next, Array<T> newNode)
{
InsertBetween(previous._items, next._items, newNode._items);
}
public void InsertBetween(ArrayNode<T> previous, ArrayNode<T> next,
ArrayNode<T> newNode)
{
if (_close)
{
return;
}
if (previous == this._items && next != this._items)
{
this.AddFront(newNode.data);
}
else if (previous != this._items && next == this._items)
{
this.AddBack(newNode.data);
}
else
{
newNode.next = next;
newNode.previous = previous;
previous.next = newNode;
next.previous = newNode;
}
}
public void Add(T data)
{
ArrayNode<T> newNode = new ArrayNode<T>();
ArrayNode<T> o = this._items.next;
newNode.data = data;
if (o == this._items)
{
this.AddFront(data);
}
else
{
for (; o != this._items; )
{
o = o.next;
}
if (o == this._items)
{
this.AddBack(newNode.data);
}
}
}
public void AddFront(T data)
{
if (_close)
{
return;
}
ArrayNode<T> newNode = new ArrayNode<T>();
newNode.data = data;
newNode.next = this._items.next;
this._items.next.previous = newNode;
this._items.next = newNode;
newNode.previous = this._items;
_length++;
}
public void AddBack(T data)
{
if (_close)
{
return;
}
ArrayNode<T> newNode = new ArrayNode<T>();
newNode.data = data;
newNode.previous = this._items.previous;
this._items.previous.next = newNode;
this._items.previous = newNode;
newNode.next = this._items;
_length++;
}
public T Get(int idx)
{
if (_close)
{
return default(T);
}
int size = _length - 1;
if (0 <= idx && idx <= size)
{
ArrayNode<T> o = this._items.next;
int count = 0;
for (; count < idx; )
{
o = o.next;
count++;
}
return o.data;
}
else if (idx == size)
{
return _items.data;
}
return default(T);
}
public void Set(int idx, T v)
{
if (_close)
{
return;
}
int size = _length - 1;
if (0 <= idx && idx <= size)
{
ArrayNode<T> o = this._items.next;
int count = 0;
for (; count < idx; )
{
o = o.next;
count++;
}
o.data = v;
}
else if (idx == size)
{
_items.data = v;
}
}
public ArrayNode<T> Node()
{
return _items;
}
public bool Contains(T data)
{
return Contains(data, false);
}
public bool Contains(T data, bool identity)
{
if (_close)
{
return false;
}
ArrayNode<T> o = this._items.next;
for (; o != this._items; )
{
if ((identity || data == null) && (object)o.data == (object)data)
{
return true;
}
else if (data.Equals(o.data))
{
return true;
}
o = o.next;
}
return false;
}
public int IndexOf(T data)
{
return IndexOf(data, false);
}
public int IndexOf(T data, bool identity)
{
if (_close)
{
return -1;
}
int count = 0;
ArrayNode<T> o = this._items.next;
for (; o != this._items && count < _length; )
{
if ((identity || data == null) && (object)o.data == (object)data)
{
return count;
}
else if (data.Equals(o.data))
{
return count;
}
o = o.next;
count++;
}
return -1;
}
public int LastIndexOf(T data)
{
return LastIndexOf(data, false);
}
public int LastIndexOf(T data, bool identity)
{
if (_close)
{
return -1;
}
int count = _length - 1;
ArrayNode<T> o = this._items.previous;
for (; o != this._items && count > 0; )
{
if ((identity || data == null) && (object)o.data == (object)data)
{
return count;
}
else if (data.Equals(o.data))
{
return count;
}
o = o.previous;
count--;
}
return -1;
}
public ArrayNode<T> Find(T data)
{
if (_close)
{
return null;
}
ArrayNode<T> o = this._items.next;
for (; o != this._items && !data.Equals(o.data); )
{
o = o.next;
}
if (o == this._items)
{
return null;
}
return o;
}
public bool Remove(int idx)
{
if (_close)
{
return false;
}
int size = _length - 1;
if (0 <= idx && idx <= size)
{
ArrayNode<T> o = this._items.next;
int count = 0;
for (; count < idx; )
{
o = o.next;
count++;
}
return Remove(o.data);
}
else if (idx == size)
{
return Remove(_items.data);
}
return false;
}
public bool Remove(T data)
{
if (_close)
{
return false;
}
ArrayNode<T> toDelete = this.Find(data);
if (toDelete != this._items && toDelete != null)
{
toDelete.previous.next = toDelete.next;
toDelete.next.previous = toDelete.previous;
_length--;
return true;
}
return false;
}
public T Pop()
{
T o = default(T);
if (!IsEmpty())
{
o = this._items.previous.data;
Remove(o);
}
return o;
}
public bool IsFirst(Array<T> o)
{
if (o._items.previous == this._items)
{
return true;
}
return false;
}
public bool IsLast(Array<T> o)
{
if (o._items.next == this._items)
{
return true;
}
return false;
}
public T Random()
{
if (_length == 0)
{
return default(T);
}
return Get(MathUtils.Random(0, _length - 1));
}
public override string ToString()
{
return ToString(',');
}
public T Next()
{
if (IsEmpty())
{
return default(T);
}
if (_next_count == 0)
{
_next_tmp = this._items.next;
_next_count++;
return _next_tmp.data;
}
if (_next_tmp != this._items && _next_count < _length)
{
_next_tmp = _next_tmp.next;
_next_count++;
return _next_tmp.data;
}
else
{
StopNext();
return default(T);
}
}
public int IdxNext()
{
return _next_count;
}
public void StopNext()
{
_next_tmp = null;
_next_count = 0;
}
public T Previous()
{
if (IsEmpty())
{
return default(T);
}
if (_previous_count == 0)
{
_previous_tmp = this._items.previous;
_previous_count++;
return _previous_tmp.data;
}
if (_previous_tmp != this._items && _previous_count < _length)
{
_previous_tmp = _previous_tmp.previous;
_previous_count++;
return _previous_tmp.data;
}
else
{
StopPrevious();
return default(T);
}
}
public int IdxPrevious()
{
return _previous_count;
}
public void StopPrevious()
{
_previous_tmp = null;
_previous_count = 0;
}
public string ToString(char split)
{
if (IsEmpty())
{
return "[]";
}
ArrayNode<T> o = this._items.next;
System.Text.StringBuilder buffer = new System.Text.StringBuilder(
CollectionUtils.INITIAL_CAPACITY);
buffer.Append('[');
int count = 0;
for (; o != this._items; )
{
buffer.Append(o.data);
if (count != _length - 1)
{
buffer.Append(split);
}
o = o.next;
count++;
}
buffer.Append(']');
return buffer.ToString();
}
public override bool Equals(object o) {
if (o == (object) this) {
return true;
}
Array<object> array = (Array<object>) o;
int n = _length;
if (n != array._length) {
return false;
}
ArrayNode<T> items1 = this._items;
ArrayNode<object> items2 = array._items;
for (int i = 0; i < n; i++) {
object o1 = items1.next;
object o2 = items2.next;
if (!((o1 == null) ? o2 == null : o1.Equals(o2))) {
return false;
}
}
return true;
}
public T First()
{
if (this.IsEmpty())
{
return default(T);
}
else
{
return this._items.next.data;
}
}
public T Last()
{
if (this.IsEmpty())
{
return default(T);
}
else
{
return this._items.previous.data;
}
}
public void Clear()
{
this._close = false;
this._length = 0;
this.StopNext();
this.StopPrevious();
this._items = null;
this._items = new ArrayNode<T>();
this._items.next = this._items;
this._items.previous = this._items;
}
public int Size()
{
return _length;
}
public bool IsEmpty()
{
return _close || _length == 0 || this._items.next == this._items;
}
public bool IsClose()
{
return _close;
}
public Array<T> Copy()
{
Array<T> newlist = new Array<T>();
newlist._items.next = this._items;
newlist._items.previous = this._items;
return newlist;
}
public override int GetHashCode()
{
return base.GetHashCode() + _length;
}
public void Dispose()
{
_close = true;
_length = 0;
_items = null;
}
/*
public static void main(String[] args) {
Array<String> s = new Array<String>();
s.add("A");
s.add("B");
s.add("C");
s.add("X");
System.out.println(s.first());
System.out.println(s.last());
s.set(0, "D");
System.out.println(s.contains("A"));
System.out.println(s.contains("D"));
System.out.println(s.indexOf("B"));
System.out.println(s.indexOf("Z"));
System.out.println("last:" + s.lastIndexOf("C"));
System.out.println(s.remove("X"));
for (; s.idxNext() < s.size();) {
String t = s.next();
System.out.println("1:" + t);
}
s.stopNext();
for (;;) {
String t = s.previous();
if (t != null) {
System.out.println("2:" + t);
} else {
break;
}
}
for (;;) {
String t = s.next();
if (t != null) {
System.out.println("3:" + t);
} else {
break;
}
}
for (;;) {
String t = s.next();
if (t != null) {
System.out.println("4:" + t);
} else {
break;
}
}
s.clear();
for (;;) {
String t = s.next();
if (t != null) {
System.out.println("5:" + t);
} else {
break;
}
}
}*/
}
}
| |
// 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;
namespace System.Globalization
{
// Gregorian Calendars use Era Info
internal class EraInfo
{
internal int era; // The value of the era.
internal long ticks; // The time in ticks when the era starts
internal int yearOffset; // The offset to Gregorian year when the era starts.
// Gregorian Year = Era Year + yearOffset
// Era Year = Gregorian Year - yearOffset
internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may
// be affected by the DateTime.MinValue;
internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1)
internal string eraName; // The era name
internal string abbrevEraName; // Abbreviated Era Name
internal string englishEraName; // English era name
internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear)
{
this.era = era;
this.yearOffset = yearOffset;
this.minEraYear = minEraYear;
this.maxEraYear = maxEraYear;
this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
}
internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear,
string eraName, string abbrevEraName, string englishEraName)
{
this.era = era;
this.yearOffset = yearOffset;
this.minEraYear = minEraYear;
this.maxEraYear = maxEraYear;
this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
this.eraName = eraName;
this.abbrevEraName = abbrevEraName;
this.englishEraName = englishEraName;
}
}
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
internal class GregorianCalendarHelper
{
// 1 tick = 100ns = 10E-7 second
// Number of 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;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
internal int MaxYear
{
get
{
return (m_maxYear);
}
}
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
internal int m_maxYear = 9999;
internal int m_minYear;
internal Calendar m_Cal;
internal EraInfo[] m_EraInfo;
internal int[] m_eras = null;
// Construct an instance of gregorian calendar.
internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo)
{
m_Cal = cal;
m_EraInfo = eraInfo;
m_maxYear = m_EraInfo[0].maxEraYear;
m_minYear = m_EraInfo[0].minEraYear; ;
}
// EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset
// Era Year = Gregorian Year - yearOffset
// EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue;
// EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1)
private int GetYearOffset(int year, int era, bool throwOnError)
{
if (year < 0)
{
if (throwOnError)
{
throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return -1;
}
if (era == Calendar.CurrentEra)
{
era = m_Cal.CurrentEraValue;
}
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (era == m_EraInfo[i].era)
{
if (year >= m_EraInfo[i].minEraYear)
{
if (year <= m_EraInfo[i].maxEraYear)
{
return m_EraInfo[i].yearOffset;
}
else if (!LocalAppContextSwitches.EnforceJapaneseEraYearRanges)
{
// If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before
// introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year
// can exist in one of these eras. otherwise, we'll throw.
// Note, we always return the offset associated with the requested era.
//
// Here is some example:
// if we are getting the era number 4 (Heisei) and getting the year number 32. if the era 4 has year range from 1 to 31
// then year 32 exceeded the range of era 4 and we'll try to find out if the years difference (32 - 31 = 1) would lay in
// the subsequent eras (e.g era 5 and up)
int remainingYears = year - m_EraInfo[i].maxEraYear;
for (int j = i - 1; j >= 0; j--)
{
if (remainingYears <= m_EraInfo[j].maxEraYear)
{
return m_EraInfo[i].yearOffset;
}
remainingYears -= m_EraInfo[j].maxEraYear;
}
}
}
if (throwOnError)
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(
SR.ArgumentOutOfRange_Range,
m_EraInfo[i].minEraYear,
m_EraInfo[i].maxEraYear));
}
break; // no need to iterate more on eras.
}
}
if (throwOnError)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
return -1;
}
/*=================================GetGregorianYear==========================
**Action: Get the Gregorian year value for the specified year in an era.
**Returns: The Gregorian year value.
**Arguments:
** year the year value in Japanese calendar
** era the Japanese emperor era value.
**Exceptions:
** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
============================================================================*/
internal int GetGregorianYear(int year, int era)
{
return GetYearOffset(year, era, throwOnError: true) + year;
}
internal bool IsValidYear(int year, int era)
{
return GetYearOffset(year, era, throwOnError: false) >= 0;
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal virtual int GetDatePart(long ticks, int part)
{
CheckTicksRange(ticks);
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n / DaysPer400Years;
// n = day number within 400-year period
n -= y400 * DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4) y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / DaysPer4Years;
// n = day number within 4-year period
n -= y4 * DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * DaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
/*=================================GetAbsoluteDate==========================
**Action: Gets the absolute date for the given Gregorian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns: the absolute date
**Arguments:
** year the Gregorian year
** month the Gregorian month
** day the day
**Exceptions:
** ArgumentOutOfRangException if year, month, day value is valid.
**Note:
** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
** Number of Days in Prior Years (both common and leap years) +
** Number of Days in Prior Months of Current Year +
** Number of Days in Current Month
**
============================================================================*/
internal static long GetAbsoluteDate(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
if (day >= 1 && (day <= days[month] - days[month - 1]))
{
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
internal static long DateToTicks(int year, int month, int day)
{
return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// 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)
{
//TimeSpan.TimeToTicks is a family access function which does no error checking, so
//we need to put some error checking out here.
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
SR.Format(
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
return (InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal void CheckTicksRange(long ticks)
{
if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
SR.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
m_Cal.MinSupportedDateTime,
m_Cal.MaxSupportedDateTime));
}
}
// 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 DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
SR.Format(
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
CheckTicksRange(time.Ticks);
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime);
return (new DateTime(ticks));
}
// 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 DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// 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 DayOfWeek GetDayOfWeek(DateTime time)
{
CheckTicksRange(time.Ticks);
return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public int GetDaysInMonth(int year, int month, int era)
{
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
return (days[month] - days[month - 1]);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public int GetDaysInYear(int year, int era)
{
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
// Returns the era for the specified DateTime value.
public int GetEra(DateTime time)
{
long ticks = time.Ticks;
// The assumption here is that m_EraInfo is listed in reverse order.
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (ticks >= m_EraInfo[i].ticks)
{
return (m_EraInfo[i].era);
}
}
throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era);
}
public int[] Eras
{
get
{
if (m_eras == null)
{
m_eras = new int[m_EraInfo.Length];
for (int i = 0; i < m_EraInfo.Length; i++)
{
m_eras[i] = m_EraInfo[i].era;
}
}
return ((int[])m_eras.Clone());
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public int GetMonthsInYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public int GetYear(DateTime time)
{
long ticks = time.Ticks;
int year = GetDatePart(ticks, DatePartYear);
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (ticks >= m_EraInfo[i].ticks)
{
return (year - m_EraInfo[i].yearOffset);
}
}
throw new ArgumentException(SR.Argument_NoEra);
}
// Returns the year that match the specified Gregorian year. The returned value is an
// integer between 1 and 9999.
//
public int GetYear(int year, DateTime time)
{
long ticks = time.Ticks;
for (int i = 0; i < m_EraInfo.Length; i++)
{
// while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
// and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
// using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
// which will end up with zero as calendar year.
// We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset)
{
return (year - m_EraInfo[i].yearOffset);
}
}
throw new ArgumentException(SR.Argument_NoEra);
}
// 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 bool IsLeapDay(int year, int month, int day, int era)
{
// year/month/era checking is done in GetDaysInMonth()
if (day < 1 || day > GetDaysInMonth(year, month, era))
{
throw new ArgumentOutOfRangeException(
nameof(day),
SR.Format(
SR.ArgumentOutOfRange_Range,
1,
GetDaysInMonth(year, month, era)));
}
if (!IsLeapYear(year, era))
{
return (false);
}
if (month == 2 && day == 29)
{
return (true);
}
return (false);
}
// 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 int GetLeapMonth(int year, int era)
{
year = GetGregorianYear(year, era);
return (0);
}
// 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 bool IsLeapMonth(int year, int month, int era)
{
year = GetGregorianYear(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(
nameof(month),
SR.Format(
SR.ArgumentOutOfRange_Range,
1,
12));
}
return (false);
}
// 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 bool IsLeapYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
year = GetGregorianYear(year, era);
long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond);
CheckTicksRange(ticks);
return (new DateTime(ticks));
}
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
CheckTicksRange(time.Ticks);
// Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear()
// can call GetYear() that exceeds the supported range of the Gregorian-based calendars.
return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek));
}
public int ToFourDigitYear(int year, int twoDigitYearMax)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
if (year < 100)
{
int y = year % 100;
return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y);
}
if (year < m_minYear || year > m_maxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear));
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class SetLength : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// TODO: Add your set up steps here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
#region Helper methods
private bool TestLength(MemoryStream ms, long expectedLength)
{
if (ms.Length != expectedLength)
{
Log.Exception("Expected length " + expectedLength + " but got, " + ms.Length);
return false;
}
return true;
}
private bool TestPosition(MemoryStream ms, long expectedPosition)
{
if (ms.Position != expectedPosition)
{
Log.Exception("Expected position " + expectedPosition + " but got, " + ms.Position);
return false;
}
return true;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public MFTestResults ObjectDisposed()
{
MemoryStream ms = new MemoryStream();
ms.Close();
MFTestResults result = MFTestResults.Pass;
try
{
try
{
long length = ms.Length;
Log.Exception( "Expected ObjectDisposedException, but got length " + length );
return MFTestResults.Fail;
}
catch (ObjectDisposedException)
{ /*Pass Case */
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults LengthTests()
{
MFTestResults result = MFTestResults.Pass;
try
{
using (MemoryStream ms = new MemoryStream())
{
Log.Comment("Set initial length to 50, and position to 50");
ms.SetLength(50);
ms.Position = 50;
if (!TestLength(ms, 50))
return MFTestResults.Fail;
Log.Comment("Write 'foo bar'");
StreamWriter sw = new StreamWriter(ms);
sw.Write("foo bar");
sw.Flush();
if (!TestLength(ms, 57))
return MFTestResults.Fail;
Log.Comment("Shorten Length to 30");
ms.SetLength(30);
if (!TestLength(ms, 30))
return MFTestResults.Fail;
Log.Comment("Verify position was adjusted");
if (!TestPosition(ms, 30))
return MFTestResults.Fail;
Log.Comment("Extend length to 100");
ms.SetLength(100);
if (!TestLength(ms, 100))
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults InvalidSetLength()
{
MFTestResults result = MFTestResults.Pass;
try
{
using (MemoryStream ms = new MemoryStream())
{
try
{
Log.Comment("-1");
ms.SetLength(-1);
Log.Exception( "Expected ArgumentOutOfRangeException, but set length" );
return MFTestResults.Fail;
}
catch (ArgumentOutOfRangeException aoore)
{
/* pass case */ Log.Comment( "Got correct exception: " + aoore.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("-10000");
ms.SetLength(-10000);
Log.Exception( "Expected ArgumentOutOfRangeException, but set length" );
return MFTestResults.Fail;
}
catch (ArgumentOutOfRangeException aoore)
{
/* pass case */ Log.Comment( "Got correct exception: " + aoore.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("long.MinValue");
ms.SetLength(long.MinValue);
Log.Exception( "Expected ArgumentOutOfRangeException, but set length" );
return MFTestResults.Fail;
}
catch (ArgumentOutOfRangeException aoore)
{
/* pass case */ Log.Comment( "Got correct exception: " + aoore.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("long.MaxValue");
ms.SetLength(long.MaxValue);
Log.Exception( "Expected IOException, but set length" );
return MFTestResults.Fail;
}
catch (ArgumentOutOfRangeException aoore)
{
/* pass case */ Log.Comment( "Got correct exception: " + aoore.Message );
result = MFTestResults.Pass;
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( ObjectDisposed, "ObjectDisposed" ),
new MFTestMethod( LengthTests, "LengthTests" ),
new MFTestMethod( InvalidSetLength, "InvalidSetLength" ),
};
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Vector3I.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Math.Algebra.Vectors
{
using System;
using System.Globalization;
using Slash.Math.Utils;
using Slash.Serialization.Dictionary;
/// <summary>
/// 3-dimensional integer vector.
/// </summary>
[Serializable]
[DictionarySerializable]
public struct Vector3I
{
#region Constants
/// <summary>
/// Unrotated forward vector.
/// </summary>
public static Vector3I Forward = new Vector3I(0, 0, 1);
/// <summary>
/// All vector components are 1.
/// </summary>
public static Vector3I One = new Vector3I(1, 1, 1);
/// <summary>
/// Unrotated side vector.
/// </summary>
public static Vector3I Right = new Vector3I(1, 0, 0);
/// <summary>
/// Unrotated up vector.
/// </summary>
public static Vector3I Up = new Vector3I(0, 1, 0);
/// <summary>
/// All vector components are 0.
/// </summary>
public static Vector3I Zero = new Vector3I(0, 0, 0);
#endregion
#region Fields
/// <summary>
/// X component.
/// </summary>
[DictionarySerializable]
public readonly int X;
/// <summary>
/// Y component.
/// </summary>
[DictionarySerializable]
public readonly int Y;
/// <summary>
/// Z component.
/// </summary>
[DictionarySerializable]
public readonly int Z;
#endregion
#region Constructors and Destructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="vector"> Initial vector. </param>
public Vector3I(Vector3I vector)
{
this.X = vector.X;
this.Y = vector.Y;
this.Z = vector.Z;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="x"> Initial x value. </param>
/// <param name="y"> Initial y value. </param>
/// <param name="z"> Initial z value. </param>
public Vector3I(int x, int y, int z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="values">
/// int array which contains the initial vector value. Value at index 0 is taken as the initial x
/// value, value at index 1 is taken as the initial y value, value at index 2 is taken as the initial z value.
/// </param>
public Vector3I(params int[] values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (values.Length < 3)
{
throw new ArgumentException("Expected a int array which size is at least 3.", "values");
}
this.X = values[0];
this.Y = values[1];
this.Z = values[2];
}
#endregion
#region Properties
/// <summary>
/// Indicates if at least one vector component is not zero.
/// </summary>
public bool IsNonZero
{
get
{
return this.X != 0 || this.Y != 0 || this.Z != 0;
}
}
/// <summary>
/// Indicates if all vector components are zero.
/// </summary>
public bool IsZero
{
get
{
return this.X == 0 && this.Y == 0 && this.Z == 0;
}
}
/// <summary>
/// Magnitude of the vector.
/// </summary>
public float Magnitude
{
get
{
return MathUtils.Sqrt(this.SquareMagnitude);
}
}
/// <summary>
/// Square magnitude of the vector.
/// </summary>
public int SquareMagnitude
{
get
{
return (this.X * this.X) + (this.Y * this.Y) + (this.Z * this.Z);
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Calculates the dot product of this and the passed vector. See http://en.wikipedia.org/wiki/Dot_product for more
/// details.
/// </summary>
/// <param name="vector"> Vector to calculate dot product with. </param>
/// <returns> Dot product of this and the passed vector. </returns>
public int CalculateDotProduct(Vector3I vector)
{
return Dot(this, vector);
}
/// <summary>
/// Calculates the dot product of the two passed vectors. See http://en.wikipedia.org/wiki/Dot_product for more details.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Dot product of the two passed vectors. </returns>
public static int Dot(Vector3I a, Vector3I b)
{
return (a.X * b.X) + (a.Y * b.Y) + (a.Z * b.Z);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to the current
/// <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />;
/// otherwise, false.
/// </returns>
/// <param name="obj">
/// The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />.
/// </param>
/// <filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals((Vector3I)obj);
}
/// <summary>
/// Determines whether the specified <see cref="Vector3I" /> is equal to the current <see cref="Vector3I" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="Vector3I" /> is equal to the current <see cref="Vector3I" />; otherwise, false.
/// </returns>
/// <param name="other">
/// The <see cref="Vector3I" /> to compare with the current <see cref="Vector3I" />.
/// </param>
public bool Equals(Vector3I other)
{
return this.X == other.X && this.Y == other.Y && this.Z == other.Z;
}
/// <summary>
/// Calculates the distance between this and the passed vector.
/// </summary>
/// <param name="vector"> Vector to compute distance to. </param>
/// <returns> Distance between this and the passed vector. </returns>
public float GetDistance(Vector3I vector)
{
return MathUtils.Sqrt(this.GetSquareDistance(vector));
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object" />.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
unchecked
{
int hashCode = this.X;
hashCode = (hashCode * 397) ^ this.Y;
hashCode = (hashCode * 397) ^ this.Z;
return hashCode;
}
}
/// <summary>
/// Returns the normalized vector.
/// </summary>
/// <returns> Normalized vector. </returns>
public Vector3F GetNormalized()
{
float magnitude = this.Magnitude;
if (magnitude != 0.0f)
{
return new Vector3F(this.X / magnitude, this.Y / magnitude, this.Z / magnitude);
}
return Vector3F.Zero;
}
/// <summary>
/// Calculates the square distance between this and the passed vector.
/// </summary>
/// <param name="vector"> Vector to compute square distance to. </param>
/// <returns> Square distance between this and the passed vector. </returns>
public int GetSquareDistance(Vector3I vector)
{
return MathUtils.Pow2(vector.X - this.X) + MathUtils.Pow2(vector.Y - this.Y)
+ MathUtils.Pow2(vector.Z - this.Z);
}
/// <summary>
/// Returns a vector that is made from the largest components of two vectors.
/// </summary>
/// <param name="lhs"> First vector. </param>
/// <param name="rhs"> Second vector. </param>
/// <returns>Vector that is made from the largest components of two vectors.</returns>
public static Vector3I Max(Vector3I lhs, Vector3I rhs)
{
return new Vector3I(MathUtils.Max(lhs.X, rhs.X), MathUtils.Max(lhs.Y, rhs.Y), MathUtils.Max(lhs.Z, rhs.Z));
}
/// <summary>
/// Returns a vector that is made from the smallest components of two vectors.
/// </summary>
/// <param name="lhs"> First vector. </param>
/// <param name="rhs"> Second vector. </param>
/// <returns>Vector that is made from the smallest components of two vectors.</returns>
public static Vector3I Min(Vector3I lhs, Vector3I rhs)
{
return new Vector3I(MathUtils.Min(lhs.X, rhs.X), MathUtils.Min(lhs.Y, rhs.Y), MathUtils.Min(lhs.Z, rhs.Z));
}
/// <summary>
/// Sums the components of the passed vectors and returns the resulting vector.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Vector which components are the sum of the respective components of the two passed vectors. </returns>
public static Vector3I operator +(Vector3I a, Vector3I b)
{
return new Vector3I(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
/// <summary>
/// Divides each component of the passed vector by the passed value.
/// </summary>
/// <param name="a"> Vector to divide by the value. </param>
/// <param name="b"> Value to divide by. </param>
/// <returns>
/// Vector where each component is the result of the particular component of the passed vector divided by the
/// passed int value.
/// </returns>
public static Vector3F operator /(Vector3I a, float b)
{
return new Vector3F(a.X / b, a.Y / b, a.Z / b);
}
/// <summary>
/// Multiplies each vector component of the two passed vectors.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Vector which components are the product of the respective components of the passed vectors. </returns>
public static Vector3I operator *(Vector3I a, Vector3I b)
{
return new Vector3I(a.X * b.X, a.Y * b.Y, a.Z * b.Z);
}
/// <summary>
/// Multiplies each vector component with the passed int value.
/// </summary>
/// <param name="a"> Vector to multiply. </param>
/// <param name="b"> int value to multiply by. </param>
/// <returns> Vector which components are the product of the respective component of the passed vector and the int value. </returns>
public static Vector3I operator *(Vector3I a, int b)
{
return new Vector3I(a.X * b, a.Y * b, a.Z * b);
}
/// <summary>
/// Multiplies each vector component with the passed int value.
/// </summary>
/// <param name="a"> int value to multiply by. </param>
/// <param name="b"> Vector to multiply. </param>
/// <returns> Vector which components are the product of the respective component of the passed vector and the int value. </returns>
public static Vector3I operator *(int a, Vector3I b)
{
return new Vector3I(a * b.X, a * b.Y, a * b.Z);
}
/// <summary>
/// Subtracts the components of the second passed vector from the first passed.
/// </summary>
/// <param name="a"> First vector. </param>
/// <param name="b"> Second vector. </param>
/// <returns> Vector which components are the difference of the respective components of the two passed vectors. </returns>
public static Vector3I operator -(Vector3I a, Vector3I b)
{
return new Vector3I(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
/// <summary>
/// Negates each component of the passed vector.
/// </summary>
/// <param name="a"> Vector to negate. </param>
/// <returns> Vector which components have the negated value of the respective components of the passed vector. </returns>
public static Vector3I operator -(Vector3I a)
{
return new Vector3I(-a.X, -a.Y, -a.Z);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
return string.Format(
"({0},{1},{2})",
this.X.ToString(CultureInfo.InvariantCulture.NumberFormat),
this.Y.ToString(CultureInfo.InvariantCulture.NumberFormat),
this.Z.ToString(CultureInfo.InvariantCulture.NumberFormat));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace ImTools.V2
{
/// <summary>Immutable array based on wide hash tree, where each node is sub-array with predefined size: 32 is by default.
/// Array supports only append, no remove.</summary>
public class ImArray<T>
{
/// <summary>Node array size. When the item added to same node, array will be copied.
/// So if array is too big performance will degrade. Should be power of two: e.g. 2, 4, 8, 16, 32...</summary>
public const int NODE_ARRAY_SIZE = 32;
/// <summary>Empty/default value to start from.</summary>
public static readonly ImArray<T> Empty = new ImArray<T>(0);
/// <summary>Number of items in array.</summary>
public readonly int Length;
/// <summary>Appends value and returns new array.</summary>
public virtual ImArray<T> Append(T value) =>
Length < NODE_ARRAY_SIZE
? new ImArray<T>(Length + 1, _items.AppendOrUpdate(value))
: new Tree(Length, ImMap<object>.Empty.AddOrUpdate(0, _items)).Append(value);
/// <summary>Returns item stored at specified index. Method relies on underlying array for index range checking.</summary>
/// <param name="index">Index to look for item.</param> <returns>Found item.</returns>
/// <exception cref="ArgumentOutOfRangeException">from underlying node array.</exception>
public virtual object Get(int index) => _items[index];
/// <summary>Returns index of first equal value in array if found, or -1 otherwise.</summary>
/// <param name="value">Value to look for.</param> <returns>Index of first equal value, or -1 otherwise.</returns>
public virtual int IndexOf(T value)
{
if (_items == null || _items.Length == 0)
return -1;
for (var i = 0; i < _items.Length; ++i)
{
var item = _items[i];
if (ReferenceEquals(item, value) || Equals(item, value))
return i;
}
return -1;
}
#region Implementation
private readonly object[] _items;
private ImArray(int length, object[] items = null)
{
Length = length;
_items = items;
}
private sealed class Tree : ImArray<T>
{
private const int NODE_ARRAY_BIT_MASK = NODE_ARRAY_SIZE - 1; // for length 32 will be 11111 binary.
private const int NODE_ARRAY_BIT_COUNT = 5; // number of set bits in NODE_ARRAY_BIT_MASK.
public override ImArray<T> Append(T value)
{
var key = Length >> NODE_ARRAY_BIT_COUNT;
var nodeItems = _tree.GetValueOrDefault(key) as object[];
return new Tree(Length + 1, _tree.AddOrUpdate(key, nodeItems.AppendOrUpdate(value)));
}
public override object Get(int index) =>
((object[])_tree.GetValueOrDefault(index >> NODE_ARRAY_BIT_COUNT))[index & NODE_ARRAY_BIT_MASK];
public override int IndexOf(T value)
{
foreach (var node in _tree.Enumerate())
{
var nodeItems = (object[])node.Value;
if (!nodeItems.IsNullOrEmpty())
{
for (var i = 0; i < nodeItems.Length; ++i)
{
var item = nodeItems[i];
if (ReferenceEquals(item, value) || Equals(item, value))
return node.Key << NODE_ARRAY_BIT_COUNT | i;
}
}
}
return -1;
}
public Tree(int length, ImMap<object> tree)
: base(length)
{
_tree = tree;
}
private readonly ImMap<object> _tree;
}
#endregion
}
[TestFixture]
public class ImTreeArrayTests
{
[Test]
public void Append_to_end()
{
var store = ImArray<string>.Empty;
store = store
.Append("a")
.Append("b")
.Append("c")
.Append("d");
Assert.AreEqual("d", store.Get(3));
Assert.AreEqual("c", store.Get(2));
Assert.AreEqual("b", store.Get(1));
Assert.AreEqual("a", store.Get(0));
}
[Test]
public void Indexed_store_get_or_add()
{
var store = ImArray<string>.Empty;
store = store
.Append("a")
.Append("b")
.Append("c")
.Append("d");
var i = store.Length - 1;
Assert.AreEqual("d", store.Get(i));
}
[Test]
public void IndexOf_with_empty_store()
{
var store = ImArray<string>.Empty;
Assert.AreEqual(-1, store.IndexOf("a"));
}
[Test]
public void IndexOf_non_existing_item()
{
var store = ImArray<string>.Empty;
store = store.Append("a");
Assert.AreEqual(-1, store.IndexOf("b"));
}
[Test]
public void IndexOf_existing_item()
{
var store = ImArray<string>.Empty;
store = store
.Append("a")
.Append("b")
.Append("c");
Assert.AreEqual(1, store.IndexOf("b"));
}
[Test]
public void Append_for_full_node_and_get_node_last_item()
{
var nodeArrayLength = ImArray<int>.NODE_ARRAY_SIZE;
var array = ImArray<int>.Empty;
for (var i = 0; i <= nodeArrayLength; i++)
array = array.Append(i);
var item = array.Get(nodeArrayLength);
Assert.That(item, Is.EqualTo(nodeArrayLength));
}
/// <remarks>Issue #17 Append-able Array stops to work over 64 elements. (dev. branch)</remarks>
[Test]
public void Append_and_get_items_in_multiple_node_array()
{
var list = new List<Foo>();
var array = ImArray<Foo>.Empty;
for (var index = 0; index < 129; ++index)
{
var item = new Foo { Index = index };
list.Add(item);
array = array.Append(item);
}
for (var index = 0; index < list.Count; ++index)
{
var listItem = list[index];
var arrayItem = array.Get(index);
Assert.AreEqual(index, listItem.Index);
Assert.AreEqual(index, ((Foo)arrayItem).Index);
}
}
class Foo
{
public int Index;
}
}
}
| |
//
// System.Security.Cryptography.SHA1CryptoServiceProvider.cs
//
// Authors:
// Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu)
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright 2001 by Matthew S. Ford.
// Copyright (C) 2004, 2005, 2008 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Note:
// The MS Framework includes two (almost) identical class for SHA1.
// SHA1Managed is a 100% managed implementation.
// SHA1CryptoServiceProvider (this file) is a wrapper on CryptoAPI.
// Mono must provide those two class for binary compatibility.
// In our case both class are wrappers around a managed internal class SHA1Internal.
namespace System.Security.Cryptography
{
internal class SHA1Internal
{
private const int BLOCK_SIZE_BYTES = 64;
private uint[] _H; // these are my chaining variables
private ulong count;
private byte[] _ProcessingBuffer; // Used to start data when passed less than a block worth.
private int _ProcessingBufferCount; // Counts how much data we have stored that still needs processed.
private uint[] buff;
public SHA1Internal()
{
_H = new uint[5];
_ProcessingBuffer = new byte[BLOCK_SIZE_BYTES];
buff = new uint[80];
Initialize();
}
public void HashCore(byte[] rgb, int ibStart, int cbSize)
{
int i;
if (_ProcessingBufferCount != 0)
{
if (cbSize < (BLOCK_SIZE_BYTES - _ProcessingBufferCount))
{
System.Buffer.BlockCopy(rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, cbSize);
_ProcessingBufferCount += cbSize;
return;
}
else
{
i = (BLOCK_SIZE_BYTES - _ProcessingBufferCount);
System.Buffer.BlockCopy(rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, i);
ProcessBlock(_ProcessingBuffer, 0);
_ProcessingBufferCount = 0;
ibStart += i;
cbSize -= i;
}
}
for (i = 0; i < cbSize - cbSize % BLOCK_SIZE_BYTES; i += BLOCK_SIZE_BYTES)
{
ProcessBlock(rgb, (uint)(ibStart + i));
}
if (cbSize % BLOCK_SIZE_BYTES != 0)
{
System.Buffer.BlockCopy(rgb, cbSize - cbSize % BLOCK_SIZE_BYTES + ibStart, _ProcessingBuffer, 0, cbSize % BLOCK_SIZE_BYTES);
_ProcessingBufferCount = cbSize % BLOCK_SIZE_BYTES;
}
}
public byte[] HashFinal()
{
byte[] hash = new byte[20];
ProcessFinalBlock(_ProcessingBuffer, 0, _ProcessingBufferCount);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
hash[i * 4 + j] = (byte)(_H[i] >> (8 * (3 - j)));
}
return hash;
}
public void Initialize()
{
count = 0;
_ProcessingBufferCount = 0;
_H[0] = 0x67452301;
_H[1] = 0xefcdab89;
_H[2] = 0x98badcfe;
_H[3] = 0x10325476;
_H[4] = 0xC3D2E1F0;
}
private void ProcessBlock(byte[] inputBuffer, uint inputOffset)
{
uint a, b, c, d, e;
count += BLOCK_SIZE_BYTES;
// abc removal would not work on the fields
uint[] _H = this._H;
uint[] buff = this.buff;
InitialiseBuff(buff, inputBuffer, inputOffset);
FillBuff(buff);
a = _H[0];
b = _H[1];
c = _H[2];
d = _H[3];
e = _H[4];
// This function was unrolled because it seems to be doubling our performance with current compiler/VM.
// Possibly roll up if this changes.
// ---- Round 1 --------
int i = 0;
while (i < 20)
{
e += ((a << 5) | (a >> 27)) + (((c ^ d) & b) ^ d) + 0x5A827999 + buff[i];
b = (b << 30) | (b >> 2);
d += ((e << 5) | (e >> 27)) + (((b ^ c) & a) ^ c) + 0x5A827999 + buff[i + 1];
a = (a << 30) | (a >> 2);
c += ((d << 5) | (d >> 27)) + (((a ^ b) & e) ^ b) + 0x5A827999 + buff[i + 2];
e = (e << 30) | (e >> 2);
b += ((c << 5) | (c >> 27)) + (((e ^ a) & d) ^ a) + 0x5A827999 + buff[i + 3];
d = (d << 30) | (d >> 2);
a += ((b << 5) | (b >> 27)) + (((d ^ e) & c) ^ e) + 0x5A827999 + buff[i + 4];
c = (c << 30) | (c >> 2);
i += 5;
}
// ---- Round 2 --------
while (i < 40)
{
e += ((a << 5) | (a >> 27)) + (b ^ c ^ d) + 0x6ED9EBA1 + buff[i];
b = (b << 30) | (b >> 2);
d += ((e << 5) | (e >> 27)) + (a ^ b ^ c) + 0x6ED9EBA1 + buff[i + 1];
a = (a << 30) | (a >> 2);
c += ((d << 5) | (d >> 27)) + (e ^ a ^ b) + 0x6ED9EBA1 + buff[i + 2];
e = (e << 30) | (e >> 2);
b += ((c << 5) | (c >> 27)) + (d ^ e ^ a) + 0x6ED9EBA1 + buff[i + 3];
d = (d << 30) | (d >> 2);
a += ((b << 5) | (b >> 27)) + (c ^ d ^ e) + 0x6ED9EBA1 + buff[i + 4];
c = (c << 30) | (c >> 2);
i += 5;
}
// ---- Round 3 --------
while (i < 60)
{
e += ((a << 5) | (a >> 27)) + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC + buff[i];
b = (b << 30) | (b >> 2);
d += ((e << 5) | (e >> 27)) + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC + buff[i + 1];
a = (a << 30) | (a >> 2);
c += ((d << 5) | (d >> 27)) + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC + buff[i + 2];
e = (e << 30) | (e >> 2);
b += ((c << 5) | (c >> 27)) + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC + buff[i + 3];
d = (d << 30) | (d >> 2);
a += ((b << 5) | (b >> 27)) + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC + buff[i + 4];
c = (c << 30) | (c >> 2);
i += 5;
}
// ---- Round 4 --------
while (i < 80)
{
e += ((a << 5) | (a >> 27)) + (b ^ c ^ d) + 0xCA62C1D6 + buff[i];
b = (b << 30) | (b >> 2);
d += ((e << 5) | (e >> 27)) + (a ^ b ^ c) + 0xCA62C1D6 + buff[i + 1];
a = (a << 30) | (a >> 2);
c += ((d << 5) | (d >> 27)) + (e ^ a ^ b) + 0xCA62C1D6 + buff[i + 2];
e = (e << 30) | (e >> 2);
b += ((c << 5) | (c >> 27)) + (d ^ e ^ a) + 0xCA62C1D6 + buff[i + 3];
d = (d << 30) | (d >> 2);
a += ((b << 5) | (b >> 27)) + (c ^ d ^ e) + 0xCA62C1D6 + buff[i + 4];
c = (c << 30) | (c >> 2);
i += 5;
}
_H[0] += a;
_H[1] += b;
_H[2] += c;
_H[3] += d;
_H[4] += e;
}
private static void InitialiseBuff(uint[] buff, byte[] input, uint inputOffset)
{
buff[0] = (uint)((input[inputOffset + 0] << 24) | (input[inputOffset + 1] << 16) | (input[inputOffset + 2] << 8) | (input[inputOffset + 3]));
buff[1] = (uint)((input[inputOffset + 4] << 24) | (input[inputOffset + 5] << 16) | (input[inputOffset + 6] << 8) | (input[inputOffset + 7]));
buff[2] = (uint)((input[inputOffset + 8] << 24) | (input[inputOffset + 9] << 16) | (input[inputOffset + 10] << 8) | (input[inputOffset + 11]));
buff[3] = (uint)((input[inputOffset + 12] << 24) | (input[inputOffset + 13] << 16) | (input[inputOffset + 14] << 8) | (input[inputOffset + 15]));
buff[4] = (uint)((input[inputOffset + 16] << 24) | (input[inputOffset + 17] << 16) | (input[inputOffset + 18] << 8) | (input[inputOffset + 19]));
buff[5] = (uint)((input[inputOffset + 20] << 24) | (input[inputOffset + 21] << 16) | (input[inputOffset + 22] << 8) | (input[inputOffset + 23]));
buff[6] = (uint)((input[inputOffset + 24] << 24) | (input[inputOffset + 25] << 16) | (input[inputOffset + 26] << 8) | (input[inputOffset + 27]));
buff[7] = (uint)((input[inputOffset + 28] << 24) | (input[inputOffset + 29] << 16) | (input[inputOffset + 30] << 8) | (input[inputOffset + 31]));
buff[8] = (uint)((input[inputOffset + 32] << 24) | (input[inputOffset + 33] << 16) | (input[inputOffset + 34] << 8) | (input[inputOffset + 35]));
buff[9] = (uint)((input[inputOffset + 36] << 24) | (input[inputOffset + 37] << 16) | (input[inputOffset + 38] << 8) | (input[inputOffset + 39]));
buff[10] = (uint)((input[inputOffset + 40] << 24) | (input[inputOffset + 41] << 16) | (input[inputOffset + 42] << 8) | (input[inputOffset + 43]));
buff[11] = (uint)((input[inputOffset + 44] << 24) | (input[inputOffset + 45] << 16) | (input[inputOffset + 46] << 8) | (input[inputOffset + 47]));
buff[12] = (uint)((input[inputOffset + 48] << 24) | (input[inputOffset + 49] << 16) | (input[inputOffset + 50] << 8) | (input[inputOffset + 51]));
buff[13] = (uint)((input[inputOffset + 52] << 24) | (input[inputOffset + 53] << 16) | (input[inputOffset + 54] << 8) | (input[inputOffset + 55]));
buff[14] = (uint)((input[inputOffset + 56] << 24) | (input[inputOffset + 57] << 16) | (input[inputOffset + 58] << 8) | (input[inputOffset + 59]));
buff[15] = (uint)((input[inputOffset + 60] << 24) | (input[inputOffset + 61] << 16) | (input[inputOffset + 62] << 8) | (input[inputOffset + 63]));
}
private static void FillBuff(uint[] buff)
{
uint val;
for (int i = 16; i < 80; i += 8)
{
val = buff[i - 3] ^ buff[i - 8] ^ buff[i - 14] ^ buff[i - 16];
buff[i] = (val << 1) | (val >> 31);
val = buff[i - 2] ^ buff[i - 7] ^ buff[i - 13] ^ buff[i - 15];
buff[i + 1] = (val << 1) | (val >> 31);
val = buff[i - 1] ^ buff[i - 6] ^ buff[i - 12] ^ buff[i - 14];
buff[i + 2] = (val << 1) | (val >> 31);
val = buff[i + 0] ^ buff[i - 5] ^ buff[i - 11] ^ buff[i - 13];
buff[i + 3] = (val << 1) | (val >> 31);
val = buff[i + 1] ^ buff[i - 4] ^ buff[i - 10] ^ buff[i - 12];
buff[i + 4] = (val << 1) | (val >> 31);
val = buff[i + 2] ^ buff[i - 3] ^ buff[i - 9] ^ buff[i - 11];
buff[i + 5] = (val << 1) | (val >> 31);
val = buff[i + 3] ^ buff[i - 2] ^ buff[i - 8] ^ buff[i - 10];
buff[i + 6] = (val << 1) | (val >> 31);
val = buff[i + 4] ^ buff[i - 1] ^ buff[i - 7] ^ buff[i - 9];
buff[i + 7] = (val << 1) | (val >> 31);
}
}
private void ProcessFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
ulong total = count + (ulong)inputCount;
int paddingSize = (56 - (int)(total % BLOCK_SIZE_BYTES));
if (paddingSize < 1)
paddingSize += BLOCK_SIZE_BYTES;
int length = inputCount + paddingSize + 8;
byte[] fooBuffer = (length == 64) ? _ProcessingBuffer : new byte[length];
for (int i = 0; i < inputCount; i++)
fooBuffer[i] = inputBuffer[i + inputOffset];
fooBuffer[inputCount] = 0x80;
for (int i = inputCount + 1; i < inputCount + paddingSize; i++)
fooBuffer[i] = 0x00;
// I deal in bytes. The algorithm deals in bits.
ulong size = total << 3;
AddLength(size, fooBuffer, inputCount + paddingSize);
ProcessBlock(fooBuffer, 0);
if (length == 128)
ProcessBlock(fooBuffer, 64);
}
internal void AddLength(ulong length, byte[] buffer, int position)
{
buffer[position++] = (byte)(length >> 56);
buffer[position++] = (byte)(length >> 48);
buffer[position++] = (byte)(length >> 40);
buffer[position++] = (byte)(length >> 32);
buffer[position++] = (byte)(length >> 24);
buffer[position++] = (byte)(length >> 16);
buffer[position++] = (byte)(length >> 8);
buffer[position] = (byte)(length);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Amusoft.EventManagement;
using Caliburn.Micro;
using WMPR.Client.Caliburn;
using WMPR.Client.Extensions;
using WMPR.Client.Framework;
using WMPR.Client.Interfaces;
using WMPR.Client.Model;
using WMPR.Client.Utility;
using WMPR.Client.ViewModels.Windows;
using WMPR.DataProvider;
namespace WMPR.Client.ViewModels.Sections
{
public class EncounterConfigurationViewModel : ScreenValidationBase, IMainTabsControl
{
public EncounterConfigurationViewModel()
{
SaveCommand = new RelayCommand(SaveExecute);
NewTemplateCommand = new RelayCommand(NewTemplateExecute);
AvailableTokenList = $"{RequestWildcard.ReportId.Key} {RequestWildcard.FightId.Key} {RequestWildcard.FightStart.Key} {RequestWildcard.FightEnd.Key}";
}
public EncounterConfigurationViewModel(EncounterConfigurationData configurationData) : this()
{
this.ConfigurationData = configurationData;
BossMapping = configurationData.MappingKey;
Templates = new ObservableCollection<TemplateViewModel>(configurationData.Templates ?? new List<TemplateViewModel>());
foreach (var template in Templates)
{
UpdateParserOptions(template);
}
}
private void UpdateParserOptions(TemplateViewModel template)
{
template.ParserTypeChanged -= TemplateOnParserTypeChanged;
template.ParserTypeChanged += TemplateOnParserTypeChanged;
if (template.ParserTypeOptions.Count > 0)
return;
var parsers = ParserFactory.GetParsers().ToList();
for (var index = 0; index < parsers.Count; index++)
{
var parser = parsers[index];
template.ParserTypeOptions.Add(new SelectorOption<string>(parser.GetType().FullName, parser.GetDisplayName()));
}
var view = CollectionViewSource.GetDefaultView(template.ParserTypeOptions);
var activeIndex = template.ParserTypeOptions.IndexOf(d => d.Value == template.ParserTypeName);
if (activeIndex >= 0)
{
view.MoveCurrentToPosition(activeIndex);
UpdateFieldOptions(template, ParserFactory.GetParser(template.ParserTypeName));
}
}
private void TemplateOnParserTypeChanged(object sender, EventArgs eventArgs)
{
var template = sender as TemplateViewModel;
if (template == null)
return;
UpdateFieldOptions(template, ParserFactory.GetParser(template.ParserTypeName));
}
private void UpdateFieldOptions(TemplateViewModel template, IWarcraftLogsContentParser parser)
{
if (template == null)
return;
template.FieldOptions.Clear();
if (parser == null)
return;
var keys = parser.GetTemplateKeys().ToList();
for (var index = 0; index < keys.Count; index++)
{
var templateKey = keys[index];
template.FieldOptions.Add(new SelectorOption<string>(templateKey, templateKey));
if (template.FieldWildcard == templateKey)
{
var changed = CollectionViewSource.GetDefaultView(template.FieldOptions)?.MoveCurrentToPosition(index);
}
}
if (string.IsNullOrEmpty(template.FieldWildcard))
{
var changed = CollectionViewSource.GetDefaultView(template.FieldOptions)?.MoveCurrentToFirst();
}
}
private void NewTemplateExecute(object obj)
{
var templateViewModel = new TemplateViewModel();
UpdateParserOptions(templateViewModel);
Templates.Add(templateViewModel);
}
public override string DisplayName => $"Konfig ({BossMapping})";
public EncounterConfigurationData ConfigurationData { get; set; }
private string _availableTokenList;
public string AvailableTokenList
{
get { return _availableTokenList; }
set
{
if (object.Equals(_availableTokenList, value))
return;
_availableTokenList = value;
NotifyOfPropertyChange(nameof(AvailableTokenList));
}
}
private void PromptAsEditExecute(object obj)
{
ITabsHost host;
if (DI.TryGetService<ITabsHost>(out host))
{
host.Activate(this);
}
}
private async void SaveExecute(object obj)
{
IEncounterConfigurationManager host;
if (DI.TryGetService<IEncounterConfigurationManager>(out host))
{
var saveData = new EncounterConfigurationData()
{
MappingKey = BossMapping,
Templates = Templates.ToList()
};
await host.SaveAsync(saveData);
}
}
private ObservableCollection<TemplateViewModel> _templates;
public ObservableCollection<TemplateViewModel> Templates
{
get { return _templates ?? (_templates = new ObservableCollection<TemplateViewModel>()); }
set
{
if (object.Equals(_templates, value))
return;
_templates = value;
NotifyOfPropertyChange(nameof(Templates));
}
}
private string _bossMapping;
public string BossMapping
{
get { return _bossMapping; }
set
{
if (object.Equals(_bossMapping, value))
return;
_bossMapping = value;
NotifyOfPropertyChange(nameof(BossMapping));
NotifyOfPropertyChange(nameof(DisplayName));
}
}
public bool IsValidForBoss(string bossName)
{
if (string.IsNullOrEmpty(BossMapping))
return false;
bossName = bossName.ToUpper();
return BossMapping.ToUpper().Split('|',',').Contains(bossName);
}
private ICommand _newTemplateCommand;
public ICommand NewTemplateCommand
{
get { return _newTemplateCommand; }
set
{
if (object.Equals(_newTemplateCommand, value))
return;
_newTemplateCommand = value;
NotifyOfPropertyChange(nameof(NewTemplateCommand));
}
}
private ICommand _saveCommand;
public ICommand SaveCommand
{
get { return _saveCommand; }
set
{
if (object.Equals(_saveCommand, value))
return;
_saveCommand = value;
NotifyOfPropertyChange(nameof(SaveCommand));
}
}
private ICommand _promptAsEditCommand;
public ICommand PromptAsEditCommand
{
get { return _promptAsEditCommand ?? (_promptAsEditCommand = new RelayCommand(PromptAsEditExecute)); }
set
{
if (object.Equals(_promptAsEditCommand, value))
return;
_promptAsEditCommand = value;
NotifyOfPropertyChange(nameof(PromptAsEditCommand));
}
}
public int Order { get; }
}
public class TemplateViewModel : PropertyChangedBase
{
private FightRequestTemplate _template;
[DataMember]
public FightRequestTemplate Template
{
get { return _template ?? (_template = new FightRequestTemplate(Guid.NewGuid().ToString(), String.Empty)); }
set
{
if (object.Equals(_template, value))
return;
_template = value;
NotifyOfPropertyChange(nameof(Template));
}
}
private string _parserTypeName;
[DataMember]
public string ParserTypeName
{
get { return _parserTypeName; }
set
{
if (object.Equals(_parserTypeName, value))
return;
_parserTypeName = value;
NotifyOfPropertyChange(nameof(ParserTypeName));
_parserTypeChanged?.Raise(this, EventArgs.Empty);
}
}
private string _fieldWildcard;
[DataMember]
public string FieldWildcard
{
get { return _fieldWildcard; }
set
{
if (object.Equals(_fieldWildcard, value))
return;
_fieldWildcard = value;
NotifyOfPropertyChange(nameof(FieldWildcard));
}
}
private readonly WeakEvent _parserTypeChanged = new WeakEvent();
public event EventHandler ParserTypeChanged
{
add { _parserTypeChanged.Add(value); }
remove { _parserTypeChanged.Remove(value); }
}
private ObservableCollection<SelectorOption<string>> _parserTypeOptions;
public ObservableCollection<SelectorOption<string>> ParserTypeOptions
{
get { return _parserTypeOptions ?? (_parserTypeOptions = new ObservableCollection<SelectorOption<string>>()); }
set
{
if (object.Equals(_parserTypeOptions, value))
return;
_parserTypeOptions = value;
NotifyOfPropertyChange(nameof(ParserTypeOptions));
}
}
private ObservableCollection<SelectorOption<string>> _fieldOptions;
public ObservableCollection<SelectorOption<string>> FieldOptions
{
get { return _fieldOptions ?? (_fieldOptions = new ObservableCollection<SelectorOption<string>>()); }
set
{
if (object.Equals(_fieldOptions, value))
return;
_fieldOptions = value;
NotifyOfPropertyChange(nameof(FieldOptions));
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Filename: SIPClientUserAgent.cs
//
// Description: Implementation of a SIP Client User Agent that can be used to initiate SIP calls.
//
// History:
// 22 Feb 2008 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2009 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery PTY LTD.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Net;
using SIPSorcery.Net;
using SIPSorcery.Sys;
using log4net;
namespace SIPSorcery.SIP.App
{
public class SIPClientUserAgent : ISIPClientUserAgent
{
private const int DNS_LOOKUP_TIMEOUT = 5000;
private const char OUTBOUNDPROXY_AS_ROUTESET_CHAR = '<'; // If this character exists in the call descriptor OutboundProxy setting it gets treated as a Route set.
private static ILog logger = AppState.logger;
private static ILog rtccLogger = AppState.GetLogger("rtcc");
private static string m_userAgent = SIPConstants.SIP_USERAGENT_STRING;
private static readonly int m_defaultSIPPort = SIPConstants.DEFAULT_SIP_PORT;
private static readonly string m_sdpContentType = SDP.SDP_MIME_CONTENTTYPE;
//private static readonly int m_rtccInitialReservationSeconds = SIPSorcery.Entities.CustomerAccountDataLayer.INITIAL_RESERVATION_SECONDS;
private SIPTransport m_sipTransport;
private SIPEndPoint m_localSIPEndPoint;
private SIPMonitorLogDelegate Log_External;
public string Owner { get; private set; } // If the UAC is authenticated holds the username of the client.
public string AdminMemberId { get; private set; } // If the UAC is authenticated holds the username of the client.
// Real-time call control properties.
public string AccountCode { get; set; }
public decimal ReservedCredit { get; set; }
public int ReservedSeconds { get; set; }
public decimal Rate { get; set; }
private SIPCallDescriptor m_sipCallDescriptor; // Describes the server leg of the call from the sipswitch.
private SIPEndPoint m_serverEndPoint;
private UACInviteTransaction m_serverTransaction;
private bool m_callCancelled; // It's possible for the call to be cancelled before the INVITE has been sent. This could occur if a DNS lookup on the server takes a while.
private bool m_hungupOnCancel; // Set to true if a call has been cancelled AND and then an Ok response was received AND a BYE has been sent to hang it up. This variable is used to stop another BYE transaction being generated.
private int m_serverAuthAttempts; // Used to determine if credentials for a server leg call fail.
private SIPNonInviteTransaction m_cancelTransaction; // If the server call is cancelled this transaction contains the CANCEL in case it needs to be resent.
private SIPEndPoint m_outboundProxy; // If the system needs to use an outbound proxy for every request this will be set and overrides any user supplied values.
private SIPDialogue m_sipDialogue;
#if !SILVERLIGHT
//private SIPSorcery.Entities.CustomerAccountDataLayer m_customerAccountDataLayer = new SIPSorcery.Entities.CustomerAccountDataLayer();
private RtccGetCustomerDelegate RtccGetCustomer_External;
private RtccGetRateDelegate RtccGetRate_External;
private RtccGetBalanceDelegate RtccGetBalance_External;
private RtccReserveInitialCreditDelegate RtccReserveInitialCredit_External;
private RtccUpdateCdrDelegate RtccUpdateCdr_External;
#endif
public event SIPCallResponseDelegate CallTrying;
public event SIPCallResponseDelegate CallRinging;
public event SIPCallResponseDelegate CallAnswered;
public event SIPCallFailedDelegate CallFailed;
public UACInviteTransaction ServerTransaction
{
get { return m_serverTransaction; }
}
public bool IsUACAnswered
{
get { return m_serverTransaction.TransactionFinalResponse != null; }
}
public SIPDialogue SIPDialogue
{
get { return m_sipDialogue; }
}
public SIPCallDescriptor CallDescriptor
{
get { return m_sipCallDescriptor; }
}
public SIPClientUserAgent(
SIPTransport sipTransport,
SIPEndPoint outboundProxy,
string owner,
string adminMemberId,
SIPMonitorLogDelegate logDelegate
)
{
m_sipTransport = sipTransport;
m_outboundProxy = (outboundProxy != null) ? SIPEndPoint.ParseSIPEndPoint(outboundProxy.ToString()) : null;
Owner = owner;
AdminMemberId = adminMemberId;
Log_External = logDelegate;
// If external logging is not required assign an empty handler to stop null reference exceptions.
if (Log_External == null)
{
Log_External = (e) => { };
}
}
#if !SILVERLIGHT
public SIPClientUserAgent(
SIPTransport sipTransport,
SIPEndPoint outboundProxy,
string owner,
string adminMemberId,
SIPMonitorLogDelegate logDelegate,
RtccGetCustomerDelegate rtccGetCustomer,
RtccGetRateDelegate rtccGetRate,
RtccGetBalanceDelegate rtccGetBalance,
RtccReserveInitialCreditDelegate rtccReserveInitialCredit,
RtccUpdateCdrDelegate rtccUpdateCdr
) : this(sipTransport, outboundProxy, owner, adminMemberId, logDelegate)
{
RtccGetCustomer_External = rtccGetCustomer;
RtccGetRate_External = rtccGetRate;
RtccGetBalance_External = rtccGetBalance;
RtccReserveInitialCredit_External = rtccReserveInitialCredit;
RtccUpdateCdr_External = rtccUpdateCdr;
}
#endif
public void Call(SIPCallDescriptor sipCallDescriptor)
{
try
{
m_sipCallDescriptor = sipCallDescriptor;
SIPURI callURI = SIPURI.ParseSIPURI(sipCallDescriptor.Uri);
SIPRouteSet routeSet = null;
if (!m_callCancelled)
{
// If the outbound proxy is a loopback address, as it will normally be for local deployments, then it cannot be overriden.
if (m_outboundProxy != null && IPAddress.IsLoopback(m_outboundProxy.Address))
{
m_serverEndPoint = m_outboundProxy;
}
else if (!sipCallDescriptor.ProxySendFrom.IsNullOrBlank())
{
// If the binding has a specific proxy end point sent then the request needs to be forwarded to the proxy's default end point for it to take care of.
SIPEndPoint outboundProxyEndPoint = SIPEndPoint.ParseSIPEndPoint(sipCallDescriptor.ProxySendFrom);
m_outboundProxy = new SIPEndPoint(SIPProtocolsEnum.udp, new IPEndPoint(outboundProxyEndPoint.Address, m_defaultSIPPort));
m_serverEndPoint = m_outboundProxy;
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "SIPClientUserAgent Call using alternate outbound proxy of " + m_outboundProxy + ".", Owner));
}
else if (m_outboundProxy != null)
{
// Using the system outbound proxy only, no additional user routing requirements.
m_serverEndPoint = m_outboundProxy;
}
// A custom route set may have been specified for the call.
if (m_sipCallDescriptor.RouteSet != null && m_sipCallDescriptor.RouteSet.IndexOf(OUTBOUNDPROXY_AS_ROUTESET_CHAR) != -1)
{
try
{
routeSet = new SIPRouteSet();
routeSet.PushRoute(new SIPRoute(m_sipCallDescriptor.RouteSet, true));
}
catch
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Error an outbound proxy value was not recognised in SIPClientUserAgent Call. " + m_sipCallDescriptor.RouteSet + ".", Owner));
}
}
// No outbound proxy, determine the forward destination based on the SIP request.
if (m_serverEndPoint == null)
{
SIPDNSLookupResult lookupResult = null;
if (routeSet == null || routeSet.Length == 0)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Attempting to resolve " + callURI.Host + ".", Owner));
lookupResult = m_sipTransport.GetURIEndPoint(callURI, false);
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Route set for call " + routeSet.ToString() + ".", Owner));
lookupResult = m_sipTransport.GetURIEndPoint(routeSet.TopRoute.URI, false);
}
if (lookupResult.LookupError != null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "DNS error resolving " + callURI.Host + ", " + lookupResult.LookupError + ". Call cannot proceed.", Owner));
}
else
{
m_serverEndPoint = lookupResult.GetSIPEndPoint();
}
}
if (m_callCancelled)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Call was cancelled during DNS resolution of " + callURI.Host, Owner));
FireCallFailed(this, "Cancelled by caller");
}
else if (m_serverEndPoint != null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Switching to " + SIPURI.ParseSIPURI(m_sipCallDescriptor.Uri).CanonicalAddress + " via " + m_serverEndPoint + ".", Owner));
m_localSIPEndPoint = m_sipTransport.GetDefaultSIPEndPoint(m_serverEndPoint);
if (m_localSIPEndPoint == null)
{
throw new ApplicationException("The call could not locate an appropriate SIP transport channel for protocol " + callURI.Protocol + ".");
}
string content = sipCallDescriptor.Content;
if (content.IsNullOrBlank())
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Body on UAC call was empty.", Owner));
}
else if (m_sipCallDescriptor.ContentType == m_sdpContentType)
{
if (!m_sipCallDescriptor.MangleResponseSDP)
{
IPEndPoint sdpEndPoint = SDP.GetSDPRTPEndPoint(content);
if (sdpEndPoint != null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC call was set to NOT mangle, RTP socket " + sdpEndPoint.ToString() + ".", Owner));
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC call was set to NOT mangle, RTP socket could not be determined.", Owner));
}
}
else
{
IPEndPoint sdpEndPoint = SDP.GetSDPRTPEndPoint(content);
if (sdpEndPoint != null)
{
if (!IPSocket.IsPrivateAddress(sdpEndPoint.Address.ToString()))
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC call had public IP not mangled, RTP socket " + sdpEndPoint.ToString() + ".", Owner));
}
else
{
bool wasSDPMangled = false;
if (sipCallDescriptor.MangleIPAddress != null)
{
if (sdpEndPoint != null)
{
content = SIPPacketMangler.MangleSDP(content, sipCallDescriptor.MangleIPAddress.ToString(), out wasSDPMangled);
}
}
if (wasSDPMangled)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC call had RTP socket mangled from " + sdpEndPoint.ToString() + " to " + sipCallDescriptor.MangleIPAddress.ToString() + ":" + sdpEndPoint.Port + ".", Owner));
}
else if (sdpEndPoint != null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC could not be mangled, using original RTP socket of " + sdpEndPoint.ToString() + ".", Owner));
}
}
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP RTP socket on UAC call could not be determined.", Owner));
}
}
}
SIPRequest switchServerInvite = GetInviteRequest(m_sipCallDescriptor, CallProperties.CreateBranchId(), CallProperties.CreateNewCallId(), m_localSIPEndPoint, routeSet, content, sipCallDescriptor.ContentType);
// Now that we have a destination socket create a new UAC transaction for forwarded leg of the call.
m_serverTransaction = m_sipTransport.CreateUACTransaction(switchServerInvite, m_serverEndPoint, m_localSIPEndPoint, m_outboundProxy);
m_serverTransaction.CDR.DialPlanContextID = m_sipCallDescriptor.DialPlanContextID;
#region Real-time call control processing.
string rtccError = null;
if (m_serverTransaction.CDR != null)
{
m_serverTransaction.CDR.Owner = Owner;
m_serverTransaction.CDR.AdminMemberId = AdminMemberId;
m_serverTransaction.CDR.Updated();
#if !SILVERLIGHT
if (m_sipCallDescriptor.AccountCode != null && RtccGetCustomer_External != null)
{
//var customerAccount = m_customerAccountDataLayer.CheckAccountCode(Owner, m_sipCallDescriptor.AccountCode);
var customerAccount = RtccGetCustomer_External(Owner, m_sipCallDescriptor.AccountCode);
if (customerAccount == null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "A billable call could not proceed as no account exists for account code or number " + m_sipCallDescriptor.AccountCode + ".", Owner));
rtccLogger.Debug("A billable call could not proceed as no account exists for account code or number " + m_sipCallDescriptor.AccountCode + " and owner " + Owner + ".");
rtccError = "Real-time call control invalid account code";
}
else
{
AccountCode = customerAccount.AccountCode;
string rateDestination = m_sipCallDescriptor.Uri;
if (SIPURI.TryParse(m_sipCallDescriptor.Uri))
{
rateDestination = SIPURI.ParseSIPURIRelaxed(m_sipCallDescriptor.Uri).User;
}
//var rate = m_customerAccountDataLayer.GetRate(Owner, m_sipCallDescriptor.RateCode, rateDestination, customerAccount.RatePlan);
var rate = RtccGetRate_External(Owner, m_sipCallDescriptor.RateCode, rateDestination, customerAccount.RatePlan);
if (rate == null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "A billable call could not proceed as no rate could be determined for destination " + rateDestination + ".", Owner));
rtccLogger.Debug("A billable call could not proceed as no rate could be determined for destination " + rateDestination + " and owner " + Owner + ".");
rtccError = "Real-time call control no rate";
}
else
{
Rate = rate.RatePerIncrement;
if (rate.RatePerIncrement == 0 && rate.SetupCost == 0)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "The rate and setup cost for the " + rateDestination + "were both zero. The call will be allowed to proceed with no RTCC reservation.", Owner));
}
else
{
//decimal balance = m_customerAccountDataLayer.GetBalance(AccountCode);
decimal balance = RtccGetBalance_External(AccountCode);
if (balance < Rate)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "A billable call could not proceed as the available credit for " + AccountCode + " was not sufficient for 60 seconds to destination " + rateDestination + ".", Owner));
rtccLogger.Debug("A billable call could not proceed as the available credit for " + AccountCode + " was not sufficient for 60 seconds to destination " + rateDestination + " and owner " + Owner + ".");
rtccError = "Real-time call control insufficient credit";
}
else
{
int intialSeconds = 0;
//var reservationCost = m_customerAccountDataLayer.ReserveInitialCredit(AccountCode, rate, m_serverTransaction.CDR, out intialSeconds);
var reservationCost = RtccReserveInitialCredit_External(AccountCode, rate.ID, m_serverTransaction.CDR, out intialSeconds);
if (reservationCost == Decimal.MinusOne)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call will not proceed as the intial real-time call control credit reservation failed.", Owner));
rtccLogger.Debug("Call will not proceed as the intial real-time call control credit reservation failed for owner " + Owner + ".");
rtccError = "Real-time call control initial reservation failed";
}
else
{
ReservedCredit = reservationCost;
ReservedSeconds = intialSeconds;
}
}
}
}
}
}
#endif
}
// If this is a billable call attempt to reserve the first chunk of credit.
//if (m_serverTransaction.CDR != null && AccountCode.NotNullOrBlank())
//{
// m_serverTransaction.CDR.AccountCode = AccountCode;
// m_serverTransaction.CDR.Rate = Rate;
// //m_serverTransaction.CDR.Cost = ReservedCredit;
// //m_serverTransaction.CDR.SecondsReserved = ReservedSeconds;
// var reservationCost = m_customerAccountDataLayer.ReserveInitialCredit(AccountCode, Rate, m_rtccInitialReservationSeconds);
// if (reservationCost == Decimal.MinusOne)
// {
// Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call will not proceed as the intial real-time call control credit reservation failed.", Owner));
// }
// else
// {
// m_serverTransaction.CDR.SecondsReserved = m_rtccInitialReservationSeconds;
// m_serverTransaction.CDR.Cost = reservationCost;
// }
//}
#endregion
if (rtccError == null)
{
m_serverTransaction.UACInviteTransactionInformationResponseReceived += ServerInformationResponseReceived;
m_serverTransaction.UACInviteTransactionFinalResponseReceived += ServerFinalResponseReceived;
m_serverTransaction.UACInviteTransactionTimedOut += ServerTimedOut;
m_serverTransaction.TransactionTraceMessage += TransactionTraceMessage;
m_serverTransaction.SendInviteRequest(m_serverEndPoint, m_serverTransaction.TransactionRequest);
}
else
{
m_serverTransaction.CancelCall(rtccError);
FireCallFailed(this, rtccError);
}
}
else
{
if (routeSet == null || routeSet.Length == 0)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Forward leg failed, could not resolve URI host " + callURI.Host, Owner));
m_serverTransaction.CancelCall("Unresolvable destination " + callURI.Host);
FireCallFailed(this, "unresolvable destination " + callURI.Host);
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Forward leg failed, could not resolve top Route host " + routeSet.TopRoute.Host, Owner));
m_serverTransaction.CancelCall("Unresolvable destination " + routeSet.TopRoute.Host);
FireCallFailed(this, "unresolvable destination " + routeSet.TopRoute.Host);
}
}
}
}
catch (ApplicationException appExcp)
{
if (m_serverTransaction != null)
{
m_serverTransaction.CancelCall(appExcp.Message);
}
FireCallFailed(this, appExcp.Message);
}
catch (Exception excp)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Exception UserAgentClient Call. " + excp.Message, Owner));
if (m_serverTransaction != null)
{
m_serverTransaction.CancelCall("Unknown exception");
}
FireCallFailed(this, excp.Message);
}
}
public void Cancel()
{
try
{
m_callCancelled = true;
// Cancel server call.
if (m_serverTransaction == null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Cancelling forwarded call leg " + m_sipCallDescriptor.Uri + ", server transaction has not been created yet no CANCEL request required.", Owner));
}
else if (m_cancelTransaction != null)
{
if (m_cancelTransaction.TransactionState != SIPTransactionStatesEnum.Completed)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Call " + m_serverTransaction.TransactionRequest.URI.ToString() + " has already been cancelled once, trying again.", Owner));
m_cancelTransaction.SendRequest(m_cancelTransaction.TransactionRequest);
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Call " + m_serverTransaction.TransactionRequest.URI.ToString() + " has already responded to CANCEL, probably overlap in messages not re-sending.", Owner));
}
}
else //if (m_serverTransaction.TransactionState == SIPTransactionStatesEnum.Proceeding || m_serverTransaction.TransactionState == SIPTransactionStatesEnum.Trying)
{
//logger.Debug("Cancelling forwarded call leg, sending CANCEL to " + ForwardedTransaction.TransactionRequest.URI.ToString() + " (transid: " + ForwardedTransaction.TransactionId + ").");
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Cancelling forwarded call leg, sending CANCEL to " + m_serverTransaction.TransactionRequest.URI.ToString() + ".", Owner));
// No reponse has been received from the server so no CANCEL request neccessary, stop any retransmits of the INVITE.
m_serverTransaction.CancelCall();
SIPRequest cancelRequest = GetCancelRequest(m_serverTransaction.TransactionRequest);
m_cancelTransaction = m_sipTransport.CreateNonInviteTransaction(cancelRequest, m_serverEndPoint, m_serverTransaction.LocalSIPEndPoint, m_outboundProxy);
m_cancelTransaction.TransactionTraceMessage += TransactionTraceMessage;
//m_cancelTransaction.SendRequest(m_serverEndPoint, cancelRequest);
m_cancelTransaction.SendReliableRequest();
}
//else
//{
// No reponse has been received from the server so no CANCEL request neccessary, stop any retransmits of the INVITE.
// m_serverTransaction.CancelCall();
// Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Cancelling forwarded call leg " + m_sipCallDescriptor.Uri.ToString() + ", no response from server has been received so no CANCEL request required.", Owner));
//}
FireCallFailed(this, "Call cancelled by user.");
}
catch (Exception excp)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Exception CancelServerCall. " + excp.Message, Owner));
}
}
public void Update(CRMHeaders crmHeaders)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Sending UPDATE to " + m_serverTransaction.TransactionRequest.URI.ToString() + ".", Owner));
SIPRequest updateRequest = GetUpdateRequest(m_serverTransaction.TransactionRequest, crmHeaders);
SIPNonInviteTransaction updateTransaction = m_sipTransport.CreateNonInviteTransaction(updateRequest, m_serverEndPoint, m_serverTransaction.LocalSIPEndPoint, m_outboundProxy);
updateTransaction.TransactionTraceMessage += TransactionTraceMessage;
updateTransaction.SendReliableRequest();
}
private void ServerFinalResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
{
try
{
//if (Thread.CurrentThread.Name.IsNullOrBlank())
//{
// Thread.CurrentThread.Name = THREAD_NAME + DateTime.Now.ToString("HHmmss") + "-" + Crypto.GetRandomString(3);
//}
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Response " + sipResponse.StatusCode + " " + sipResponse.ReasonPhrase + " for " + m_serverTransaction.TransactionRequest.URI.ToString() + ".", Owner));
//m_sipTrace += "Received " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " " + localEndPoint + "<-" + remoteEndPoint + "\r\n" + sipResponse.ToString();
m_serverTransaction.UACInviteTransactionInformationResponseReceived -= ServerInformationResponseReceived;
m_serverTransaction.UACInviteTransactionFinalResponseReceived -= ServerFinalResponseReceived;
m_serverTransaction.TransactionTraceMessage -= TransactionTraceMessage;
if (m_callCancelled && sipResponse.Status == SIPResponseStatusCodesEnum.RequestTerminated)
{
// No action required. Correctly received request terminated on an INVITE we cancelled.
}
else if (m_callCancelled)
{
#region Call has been cancelled, hangup.
if (m_hungupOnCancel)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "A cancelled call to " + m_sipCallDescriptor.Uri + " has been answered AND has already been hungup, no further action being taken.", Owner));
}
else
{
m_hungupOnCancel = true;
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "A cancelled call to " + m_sipCallDescriptor.Uri + " has been answered, hanging up.", Owner));
if (sipResponse.Header.Contact != null && sipResponse.Header.Contact.Count > 0)
{
SIPURI byeURI = sipResponse.Header.Contact[0].ContactURI;
SIPRequest byeRequest = GetByeRequest(sipResponse, byeURI, localSIPEndPoint);
//SIPEndPoint byeEndPoint = m_sipTransport.GetRequestEndPoint(byeRequest, m_outboundProxy, true);
// if (byeEndPoint != null)
// {
SIPNonInviteTransaction byeTransaction = m_sipTransport.CreateNonInviteTransaction(byeRequest, null, localSIPEndPoint, m_outboundProxy);
byeTransaction.SendReliableRequest();
// }
// else
// {
// Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Could not end BYE on cancelled call as request end point could not be determined " + byeRequest.URI.ToString(), Owner));
//}
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "No contact header provided on response for cancelled call to " + m_sipCallDescriptor.Uri + " no further action.", Owner));
}
}
#endregion
}
else if (sipResponse.Status == SIPResponseStatusCodesEnum.ProxyAuthenticationRequired || sipResponse.Status == SIPResponseStatusCodesEnum.Unauthorised)
{
//logger.Debug("AuthReqd Final response " + sipResponse.StatusCode + " " + sipResponse.ReasonPhrase + " for " + m_serverTransaction.TransactionRequest.URI.ToString() + ".");
#region Authenticate client call to third party server.
if (!m_callCancelled)
{
if (m_sipCallDescriptor.Password.IsNullOrBlank())
{
// No point trying to authenticate if there is no password to use.
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Forward leg failed, authentication was requested but no credentials were available.", Owner));
FireCallFailed(this, "Authentication requested when no credentials available");
}
else if (m_serverAuthAttempts == 0)
{
m_serverAuthAttempts = 1;
// Resend INVITE with credentials.
string username = (m_sipCallDescriptor.AuthUsername != null && m_sipCallDescriptor.AuthUsername.Trim().Length > 0) ? m_sipCallDescriptor.AuthUsername : m_sipCallDescriptor.Username;
SIPAuthorisationDigest authRequest = sipResponse.Header.AuthenticationHeader.SIPDigest;
authRequest.SetCredentials(username, m_sipCallDescriptor.Password, m_sipCallDescriptor.Uri, SIPMethodsEnum.INVITE.ToString());
SIPRequest authInviteRequest = m_serverTransaction.TransactionRequest;
//if (SIPProviderMagicJack.IsMagicJackRequest(sipResponse))
//{
// authInviteRequest.Header.AuthenticationHeader = SIPProviderMagicJack.GetAuthenticationHeader(sipResponse);
//}
//else
//{
authInviteRequest.Header.AuthenticationHeader = new SIPAuthenticationHeader(authRequest);
authInviteRequest.Header.AuthenticationHeader.SIPDigest.Response = authRequest.Digest;
//}
authInviteRequest.Header.Vias.TopViaHeader.Branch = CallProperties.CreateBranchId();
authInviteRequest.Header.CSeq = authInviteRequest.Header.CSeq + 1;
// Create a new UAC transaction to establish the authenticated server call.
var originalCallTransaction = m_serverTransaction;
m_serverTransaction = m_sipTransport.CreateUACTransaction(authInviteRequest, m_serverEndPoint, localSIPEndPoint, m_outboundProxy);
if (m_serverTransaction.CDR != null)
{
m_serverTransaction.CDR.Owner = Owner;
m_serverTransaction.CDR.AdminMemberId = AdminMemberId;
m_serverTransaction.CDR.DialPlanContextID = m_sipCallDescriptor.DialPlanContextID;
m_serverTransaction.CDR.Updated();
if (AccountCode != null)
{
//var rtccCDR = new SIPSorcery.Entities.CDR()
//{
// ID = m_serverTransaction.CDR.CDRId.ToString(),
// Owner = m_serverTransaction.CDR.Owner,
// AdminMemberID = m_serverTransaction.CDR.AdminMemberId,
// Inserted = DateTimeOffset.UtcNow.ToString("o"),
// Created = DateTimeOffset.UtcNow.ToString("o"),
// DstHost = "",
// DstURI = m_sipCallDescriptor.Uri,
// CallID = "",
// FromHeader = m_sipCallDescriptor.From,
// LocalSocket = "udp:0.0.0.0:5060",
// RemoteSocket = "udp:0.0.0.0:5060",
// Direction = m_serverTransaction.CDR.CallDirection.ToString(),
// DialPlanContextID = m_sipCallDescriptor.DialPlanContextID.ToString()
//};
#if !SILVERLIGHT
//m_customerAccountDataLayer.UpdateRealTimeCallControlCDRID(originalCallTransaction.CDR.CDRId.ToString(), m_serverTransaction.CDR);
RtccUpdateCdr_External(originalCallTransaction.CDR.CDRId.ToString(), m_serverTransaction.CDR);
#endif
//m_serverTransaction.CDR.AccountCode = AccountCode;
//m_serverTransaction.CDR.Rate = Rate;
// Transfer any credit reservations from the original call to the new call.
//m_serverTransaction.CDR.SecondsReserved = originalCallTransaction.CDR.SecondsReserved;
//m_serverTransaction.CDR.Cost = originalCallTransaction.CDR.Cost;
//m_serverTransaction.CDR.IncrementSeconds = originalCallTransaction.CDR.IncrementSeconds;
//originalCallTransaction.CDR.SecondsReserved = 0;
//originalCallTransaction.CDR.Cost = 0;
//originalCallTransaction.CDR.ReconciliationResult = "reallocated";
//originalCallTransaction.CDR.IsHangingUp = true;
}
logger.Debug("RTCC reservation was reallocated from CDR " + originalCallTransaction.CDR.CDRId + " to " + m_serverTransaction.CDR.CDRId + " for owner " + Owner + ".");
}
m_serverTransaction.UACInviteTransactionInformationResponseReceived += ServerInformationResponseReceived;
m_serverTransaction.UACInviteTransactionFinalResponseReceived += ServerFinalResponseReceived;
m_serverTransaction.UACInviteTransactionTimedOut += ServerTimedOut;
m_serverTransaction.TransactionTraceMessage += TransactionTraceMessage;
//logger.Debug("Sending authenticated switchcall INVITE to " + ForwardedCallStruct.Host + ".");
m_serverTransaction.SendInviteRequest(m_serverEndPoint, authInviteRequest);
//m_sipTrace += "Sending " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " " + localEndPoint + "->" + ForwardedTransaction.TransactionRequest.GetRequestEndPoint() + "\r\n" + ForwardedTransaction.TransactionRequest.ToString();
}
else
{
//logger.Debug("Authentication of client call to switch server failed.");
FireCallFailed(this, "Authentication with provided credentials failed");
}
}
#endregion
}
else
{
if (sipResponse.StatusCode >= 200 && sipResponse.StatusCode <= 299)
{
if (sipResponse.Body.IsNullOrBlank())
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Body on UAC response was empty.", Owner));
}
else if (m_sipCallDescriptor.ContentType == m_sdpContentType)
{
if (!m_sipCallDescriptor.MangleResponseSDP)
{
IPEndPoint sdpEndPoint = SDP.GetSDPRTPEndPoint(sipResponse.Body);
string sdpSocket = (sdpEndPoint != null) ? sdpEndPoint.ToString() : "could not determine";
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC response was set to NOT mangle, RTP socket " + sdpEndPoint.ToString() + ".", Owner));
}
else
{
//m_callInProgress = false; // the call is now established
//logger.Debug("Final response " + sipResponse.StatusCode + " " + sipResponse.ReasonPhrase + " for " + ForwardedTransaction.TransactionRequest.URI.ToString() + ".");
// Determine of response SDP should be mangled.
IPEndPoint sdpEndPoint = SDP.GetSDPRTPEndPoint(sipResponse.Body);
//Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAC response SDP was mangled from sdp=" + sdpEndPoint.Address.ToString() + ", proxyfrom=" + sipResponse.Header.ProxyReceivedFrom + ", mangle=" + m_sipCallDescriptor.MangleResponseSDP + ".", null));
if (sdpEndPoint != null)
{
if (!IPSocket.IsPrivateAddress(sdpEndPoint.Address.ToString()))
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC response had public IP not mangled, RTP socket " + sdpEndPoint.ToString() + ".", Owner));
}
else
{
bool wasSDPMangled = false;
string publicIPAddress = null;
if (!sipResponse.Header.ProxyReceivedFrom.IsNullOrBlank())
{
IPAddress remoteUASAddress = SIPEndPoint.ParseSIPEndPoint(sipResponse.Header.ProxyReceivedFrom).Address;
if (IPSocket.IsPrivateAddress(remoteUASAddress.ToString()) && m_sipCallDescriptor.MangleIPAddress != null)
{
// If the response has arrived here on a private IP address then it must be
// for a local version install and an incoming call that needs it's response mangled.
if(!IPSocket.IsPrivateAddress(m_sipCallDescriptor.MangleIPAddress.ToString()))
{
publicIPAddress = m_sipCallDescriptor.MangleIPAddress.ToString();
}
}
else
{
publicIPAddress = remoteUASAddress.ToString();
}
}
else if (!IPSocket.IsPrivateAddress(remoteEndPoint.Address.ToString()) && remoteEndPoint.Address != IPAddress.Any)
{
publicIPAddress = remoteEndPoint.Address.ToString();
}
else if (m_sipCallDescriptor.MangleIPAddress != null)
{
publicIPAddress = m_sipCallDescriptor.MangleIPAddress.ToString();
}
if (publicIPAddress != null)
{
sipResponse.Body = SIPPacketMangler.MangleSDP(sipResponse.Body, publicIPAddress, out wasSDPMangled);
}
if (wasSDPMangled)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC response had RTP socket mangled from " + sdpEndPoint.ToString() + " to " + publicIPAddress + ":" + sdpEndPoint.Port + ".", Owner));
}
else if (sdpEndPoint != null)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP on UAC response could not be mangled, RTP socket " + sdpEndPoint.ToString() + ".", Owner));
}
}
}
else
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SDP RTP socket on UAC response could not be determined.", Owner));
}
}
}
m_sipDialogue = new SIPDialogue(m_serverTransaction, Owner, AdminMemberId);
m_sipDialogue.CallDurationLimit = m_sipCallDescriptor.CallDurationLimit;
// Set switchboard dialogue values from the answered response or from dialplan set values.
//m_sipDialogue.SwitchboardCallerDescription = sipResponse.Header.SwitchboardCallerDescription;
m_sipDialogue.SwitchboardLineName = sipResponse.Header.SwitchboardLineName;
m_sipDialogue.CRMPersonName = sipResponse.Header.CRMPersonName;
m_sipDialogue.CRMCompanyName = sipResponse.Header.CRMCompanyName;
m_sipDialogue.CRMPictureURL = sipResponse.Header.CRMPictureURL;
if (m_sipCallDescriptor.SwitchboardHeaders != null)
{
//if (!m_sipCallDescriptor.SwitchboardHeaders.SwitchboardDialogueDescription.IsNullOrBlank())
//{
// m_sipDialogue.SwitchboardDescription = m_sipCallDescriptor.SwitchboardHeaders.SwitchboardDialogueDescription;
//}
m_sipDialogue.SwitchboardLineName = m_sipCallDescriptor.SwitchboardHeaders.SwitchboardLineName;
m_sipDialogue.SwitchboardOwner = m_sipCallDescriptor.SwitchboardHeaders.SwitchboardOwner;
}
}
FireCallAnswered(this, sipResponse);
}
}
catch (Exception excp)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.Error, "Exception ServerFinalResponseReceived. " + excp.Message, Owner));
}
}
private void ServerInformationResponseReceived(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "Information response " + sipResponse.StatusCode + " " + sipResponse.ReasonPhrase + " for " + m_serverTransaction.TransactionRequest.URI.ToString() + ".", Owner));
if (m_callCancelled)
{
// Call was cancelled in the interim.
Cancel();
}
else
{
if (sipResponse.Status == SIPResponseStatusCodesEnum.Ringing || sipResponse.Status == SIPResponseStatusCodesEnum.SessionProgress)
{
FireCallRinging(this, sipResponse);
}
else
{
FireCallTrying(this, sipResponse);
}
}
}
private void ServerTimedOut(SIPTransaction sipTransaction)
{
if (!m_callCancelled)
{
FireCallFailed(this, "Timeout, no response from server");
}
}
//private void ByeFinalResponseReceived(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse)
//{
// Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.DialPlan, "BYE response " + sipResponse.StatusCode + " " + sipResponse.ReasonPhrase + ".", Owner));
//}
private SIPRequest GetInviteRequest(SIPCallDescriptor sipCallDescriptor, string branchId, string callId, SIPEndPoint localSIPEndPoint, SIPRouteSet routeSet, string content, string contentType)
{
SIPRequest inviteRequest = new SIPRequest(SIPMethodsEnum.INVITE, sipCallDescriptor.Uri);
inviteRequest.LocalSIPEndPoint = localSIPEndPoint;
SIPHeader inviteHeader = new SIPHeader(sipCallDescriptor.GetFromHeader(), SIPToHeader.ParseToHeader(sipCallDescriptor.To), 1, callId);
inviteHeader.From.FromTag = CallProperties.CreateNewTag();
// For incoming calls forwarded via the dial plan the username needs to go into the Contact header.
inviteHeader.Contact = new List<SIPContactHeader>() { new SIPContactHeader(null, new SIPURI(inviteRequest.URI.Scheme, localSIPEndPoint)) };
inviteHeader.Contact[0].ContactURI.User = sipCallDescriptor.Username;
inviteHeader.CSeqMethod = SIPMethodsEnum.INVITE;
inviteHeader.UserAgent = m_userAgent;
inviteHeader.Routes = routeSet;
inviteRequest.Header = inviteHeader;
if (!sipCallDescriptor.ProxySendFrom.IsNullOrBlank())
{
inviteHeader.ProxySendFrom = sipCallDescriptor.ProxySendFrom;
}
SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint, branchId);
inviteRequest.Header.Vias.PushViaHeader(viaHeader);
inviteRequest.Body = content;
inviteRequest.Header.ContentLength = (inviteRequest.Body != null) ? inviteRequest.Body.Length : 0;
inviteRequest.Header.ContentType = contentType;
// Add custom switchboard headers.
if (CallDescriptor.SwitchboardHeaders != null)
{
inviteHeader.SwitchboardOriginalCallID = CallDescriptor.SwitchboardHeaders.SwitchboardOriginalCallID;
//inviteHeader.SwitchboardCallerDescription = CallDescriptor.SwitchboardHeaders.SwitchboardCallerDescription;
inviteHeader.SwitchboardLineName = CallDescriptor.SwitchboardHeaders.SwitchboardLineName;
//inviteHeader.SwitchboardOwner = CallDescriptor.SwitchboardHeaders.SwitchboardOwner;
//inviteHeader.SwitchboardOriginalFrom = CallDescriptor.SwitchboardHeaders.SwitchboardOriginalFrom;
}
// Add custom CRM headers.
if (CallDescriptor.CRMHeaders != null)
{
inviteHeader.CRMPersonName = CallDescriptor.CRMHeaders.PersonName;
inviteHeader.CRMCompanyName = CallDescriptor.CRMHeaders.CompanyName;
inviteHeader.CRMPictureURL = CallDescriptor.CRMHeaders.AvatarURL;
}
try
{
if (sipCallDescriptor.CustomHeaders != null && sipCallDescriptor.CustomHeaders.Count > 0)
{
foreach (string customHeader in sipCallDescriptor.CustomHeaders)
{
if (customHeader.IsNullOrBlank())
{
continue;
}
else if (customHeader.Trim().StartsWith(SIPHeaders.SIP_HEADER_USERAGENT))
{
inviteRequest.Header.UserAgent = customHeader.Substring(customHeader.IndexOf(":") + 1).Trim();
}
else
{
inviteRequest.Header.UnknownHeaders.Add(customHeader);
}
}
}
}
catch (Exception excp)
{
logger.Error("Exception Parsing CustomHeader for GetInviteRequest. " + excp.Message + sipCallDescriptor.CustomHeaders);
}
return inviteRequest;
}
private SIPRequest GetCancelRequest(SIPRequest inviteRequest)
{
SIPRequest cancelRequest = new SIPRequest(SIPMethodsEnum.CANCEL, inviteRequest.URI);
cancelRequest.LocalSIPEndPoint = inviteRequest.LocalSIPEndPoint;
SIPHeader inviteHeader = inviteRequest.Header;
SIPHeader cancelHeader = new SIPHeader(inviteHeader.From, inviteHeader.To, inviteHeader.CSeq, inviteHeader.CallId);
cancelRequest.Header = cancelHeader;
cancelHeader.CSeqMethod = SIPMethodsEnum.CANCEL;
cancelHeader.Routes = inviteHeader.Routes;
cancelHeader.ProxySendFrom = inviteHeader.ProxySendFrom;
cancelHeader.Vias = inviteHeader.Vias;
return cancelRequest;
}
private SIPRequest GetByeRequest(SIPResponse inviteResponse, SIPURI byeURI, SIPEndPoint localSIPEndPoint)
{
SIPRequest byeRequest = new SIPRequest(SIPMethodsEnum.BYE, byeURI);
byeRequest.LocalSIPEndPoint = localSIPEndPoint;
SIPFromHeader byeFromHeader = inviteResponse.Header.From;
SIPToHeader byeToHeader = inviteResponse.Header.To;
int cseq = inviteResponse.Header.CSeq + 1;
SIPHeader byeHeader = new SIPHeader(byeFromHeader, byeToHeader, cseq, inviteResponse.Header.CallId);
byeHeader.CSeqMethod = SIPMethodsEnum.BYE;
byeHeader.ProxySendFrom = m_serverTransaction.TransactionRequest.Header.ProxySendFrom;
byeRequest.Header = byeHeader;
byeRequest.Header.Routes = (inviteResponse.Header.RecordRoutes != null) ? inviteResponse.Header.RecordRoutes.Reversed() : null;
SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint, CallProperties.CreateBranchId());
byeRequest.Header.Vias.PushViaHeader(viaHeader);
return byeRequest;
}
private SIPRequest GetUpdateRequest(SIPRequest inviteRequest, CRMHeaders crmHeaders)
{
SIPRequest updateRequest = new SIPRequest(SIPMethodsEnum.UPDATE, inviteRequest.URI);
updateRequest.LocalSIPEndPoint = inviteRequest.LocalSIPEndPoint;
SIPHeader inviteHeader = inviteRequest.Header;
SIPHeader updateHeader = new SIPHeader(inviteHeader.From, inviteHeader.To, inviteHeader.CSeq + 1, inviteHeader.CallId);
inviteRequest.Header.CSeq++;
updateRequest.Header = updateHeader;
updateHeader.CSeqMethod = SIPMethodsEnum.UPDATE;
updateHeader.Routes = inviteHeader.Routes;
updateHeader.ProxySendFrom = inviteHeader.ProxySendFrom;
SIPViaHeader viaHeader = new SIPViaHeader(inviteRequest.LocalSIPEndPoint, CallProperties.CreateBranchId());
updateHeader.Vias.PushViaHeader(viaHeader);
// Add custom CRM headers.
if (crmHeaders != null)
{
updateHeader.CRMPersonName = crmHeaders.PersonName;
updateHeader.CRMCompanyName = crmHeaders.CompanyName;
updateHeader.CRMPictureURL = crmHeaders.AvatarURL;
}
return updateRequest;
}
private void TransactionTraceMessage(SIPTransaction sipTransaction, string message)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentClient, SIPMonitorEventTypesEnum.SIPTransaction, message, Owner));
}
private void FireCallTrying(SIPClientUserAgent uac, SIPResponse tryingResponse)
{
if (CallTrying != null)
{
CallTrying(uac, tryingResponse);
}
}
private void FireCallRinging(SIPClientUserAgent uac, SIPResponse ringingResponse)
{
if (CallRinging != null)
{
CallRinging(uac, ringingResponse);
}
}
private void FireCallAnswered(SIPClientUserAgent uac, SIPResponse answeredResponse)
{
if (CallAnswered != null)
{
CallAnswered(uac, answeredResponse);
}
}
private void FireCallFailed(SIPClientUserAgent uac, string errorMessage)
{
if (CallFailed != null)
{
CallFailed(uac, errorMessage);
}
}
}
}
| |
// 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;
using System.Collections.Generic;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// The HttpRequest query string collection
/// </summary>
public class QueryCollection : IQueryCollection
{
/// <summary>
/// Gets an empty <see cref="QueryCollection"/>.
/// </summary>
public static readonly QueryCollection Empty = new QueryCollection();
private static readonly string[] EmptyKeys = Array.Empty<string>();
// Pre-box
private static readonly IEnumerator<KeyValuePair<string, StringValues>> EmptyIEnumeratorType = default(Enumerator);
private static readonly IEnumerator EmptyIEnumerator = default(Enumerator);
private Dictionary<string, StringValues>? Store { get; }
/// <summary>
/// Initializes a new instance of <see cref="QueryCollection"/>.
/// </summary>
public QueryCollection()
{
}
/// <summary>
/// Initializes a new instance of <see cref="QueryCollection"/>.
/// </summary>
/// <param name="store">The backing store.</param>
public QueryCollection(Dictionary<string, StringValues> store)
{
Store = store;
}
/// <summary>
/// Creates a shallow copy of the specified <paramref name="store"/>.
/// </summary>
/// <param name="store">The <see cref="QueryCollection"/> to clone.</param>
public QueryCollection(QueryCollection store)
{
Store = store.Store;
}
/// <summary>
/// Initializes a new instance of <see cref="QueryCollection"/>.
/// </summary>
/// <param name="capacity">The initial number of query items that this instance can contain.</param>
public QueryCollection(int capacity)
{
Store = new Dictionary<string, StringValues>(capacity, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Gets the associated set of values from the collection.
/// </summary>
/// <param name="key">The key name.</param>
/// <returns>the associated value from the collection as a StringValues or StringValues.Empty if the key is not present.</returns>
public StringValues this[string key]
{
get
{
if (Store == null)
{
return StringValues.Empty;
}
if (TryGetValue(key, out var value))
{
return value;
}
return StringValues.Empty;
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="QueryCollection" />;.
/// </summary>
/// <returns>The number of elements contained in the <see cref="QueryCollection" />.</returns>
public int Count
{
get
{
if (Store == null)
{
return 0;
}
return Store.Count;
}
}
/// <summary>
/// Gets the collection of query names in this instance.
/// </summary>
public ICollection<string> Keys
{
get
{
if (Store == null)
{
return EmptyKeys;
}
return Store.Keys;
}
}
/// <summary>
/// Determines whether the <see cref="QueryCollection" /> contains a specific key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>true if the <see cref="QueryCollection" /> contains a specific key; otherwise, false.</returns>
public bool ContainsKey(string key)
{
if (Store == null)
{
return false;
}
return Store.ContainsKey(key);
}
/// <summary>
/// Retrieves a value from the collection.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>true if the <see cref="QueryCollection" /> contains the key; otherwise, false.</returns>
public bool TryGetValue(string key, out StringValues value)
{
if (Store == null)
{
value = default(StringValues);
return false;
}
return Store.TryGetValue(key, out value);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="Enumerator" /> object that can be used to iterate through the collection.</returns>
public Enumerator GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
// Non-boxed Enumerator
return default;
}
return new Enumerator(Store.GetEnumerator());
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}" /> object that can be used to iterate through the collection.</returns>
IEnumerator<KeyValuePair<string, StringValues>> IEnumerable<KeyValuePair<string, StringValues>>.GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
// Non-boxed Enumerator
return EmptyIEnumeratorType;
}
return Store.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
// Non-boxed Enumerator
return EmptyIEnumerator;
}
return Store.GetEnumerator();
}
/// <summary>
/// Enumerates a <see cref="QueryCollection"/>.
/// </summary>
public struct Enumerator : IEnumerator<KeyValuePair<string, StringValues>>
{
// Do NOT make this readonly, or MoveNext will not work
private Dictionary<string, StringValues>.Enumerator _dictionaryEnumerator;
private readonly bool _notEmpty;
internal Enumerator(Dictionary<string, StringValues>.Enumerator dictionaryEnumerator)
{
_dictionaryEnumerator = dictionaryEnumerator;
_notEmpty = true;
}
/// <summary>
/// Advances the enumerator to the next element of the <see cref="HeaderDictionary"/>.
/// </summary>
/// <returns><see langword="true"/> if the enumerator was successfully advanced to the next element;
/// <see langword="false"/> if the enumerator has passed the end of the collection.</returns>
public bool MoveNext()
{
if (_notEmpty)
{
return _dictionaryEnumerator.MoveNext();
}
return false;
}
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
public KeyValuePair<string, StringValues> Current
{
get
{
if (_notEmpty)
{
return _dictionaryEnumerator.Current;
}
return default(KeyValuePair<string, StringValues>);
}
}
/// <inheritdoc />
public void Dispose()
{
}
object IEnumerator.Current
{
get
{
return Current;
}
}
void IEnumerator.Reset()
{
if (_notEmpty)
{
((IEnumerator)_dictionaryEnumerator).Reset();
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.NotificationHubs
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// NamespacesOperations operations.
/// </summary>
public partial interface INamespacesOperations
{
/// <summary>
/// Checks the availability of the given service namespace across all
/// Azure subscriptions. This is useful because the domain name is
/// created based on the service namespace name.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" />
/// </summary>
/// <param name='parameters'>
/// The namespace name.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(CheckAvailabilityParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates/Updates a service namespace. Once created, this
/// namespace's resource manifest is immutable. This operation is
/// idempotent.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Patches the existing namespace
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to patch a Namespace Resource.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> PatchWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespacePatchParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated notificationHubs under the namespace.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated notificationHubs under the namespace.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns the description for the specified namespace.
/// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets an authorization rule for a namespace by name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. If resourceGroupName value is null
/// the method lists all the namespaces within subscription
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the available namespaces within the subscription
/// irrespective of the resourceGroups.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the Primary and Secondary ConnectionStrings to the namespace
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified
/// authorizationRule.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Regenerates the Primary/Secondary Keys to the Namespace
/// Authorization Rule
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified
/// authorizationRule.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the Namespace Authorization Rule
/// Key.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the available namespaces within the subscription
/// irrespective of the resourceGroups.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the authorization rules for a namespace.
/// </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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using MICore;
using Microsoft.DebugEngineHost;
namespace Microsoft.MIDebugEngine
{
internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback
{
private readonly IDebugEventCallback2 _eventCallback;
private readonly AD7Engine _engine;
public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback)
{
_engine = engine;
_eventCallback = HostMarshal.GetThreadSafeEventCallback(ad7Callback);
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread)
{
uint attributes;
Guid riidEvent = new Guid(iidEvent);
EngineUtils.RequireOk(eventObject.GetAttributes(out attributes));
EngineUtils.RequireOk(_eventCallback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes));
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread)
{
IDebugProgram2 program = _engine;
if (!_engine.ProgramCreateEventSent)
{
// Any events before programe create shouldn't include the program
program = null;
}
Send(eventObject, iidEvent, program, thread);
}
public void OnError(string message)
{
SendMessage(message, OutputMessage.Severity.Error, isAsync: true);
}
/// <summary>
/// Sends an error to the user, blocking until the user dismisses the error
/// </summary>
/// <param name="message">string to display to the user</param>
public void OnErrorImmediate(string message)
{
SendMessage(message, OutputMessage.Severity.Error, isAsync: false);
}
public void OnWarning(string message)
{
SendMessage(message, OutputMessage.Severity.Warning, isAsync: true);
}
public void OnModuleLoad(DebuggedModule debuggedModule)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event
// for the exe.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */);
debuggedModule.Client = ad7Module;
// The sample engine does not support binding breakpoints as modules load since the primary exe is the only module
// symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded.
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnModuleUnload(DebuggedModule debuggedModule)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Module ad7Module = (AD7Module)debuggedModule.Client;
Debug.Assert(ad7Module != null);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */);
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnOutputString(string outputString)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString);
Send(eventObject, AD7OutputDebugStringEvent.IID, null);
}
public void OnOutputMessage(OutputMessage outputMessage)
{
try
{
if (outputMessage.ErrorCode == 0)
{
var eventObject = new AD7MessageEvent(outputMessage, isAsync: true);
Send(eventObject, AD7MessageEvent.IID, null);
}
else
{
var eventObject = new AD7ErrorEvent(outputMessage, isAsync: true);
Send(eventObject, AD7ErrorEvent.IID, null);
}
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
public void OnProcessExit(uint exitCode)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
try
{
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
catch (InvalidOperationException)
{
// If debugging has already stopped, this can throw
}
}
public void OnEntryPoint(DebuggedThread thread)
{
AD7EntryPointEvent eventObject = new AD7EntryPointEvent();
Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client);
}
public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client;
Debug.Assert(ad7Thread != null);
AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode);
Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread);
}
public void OnThreadStart(DebuggedThread debuggedThread)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event
// for the main thread of the application.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent();
Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client);
}
public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count];
int i = 0;
foreach (object objCurrentBreakpoint in clients)
{
boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint;
i++;
}
// An engine that supports more advanced breakpoint features such as hit counts, conditions and filters
// should notify each bound breakpoint that it has been hit and evaluate conditions here.
// The sample engine does not support these features.
AD7BoundBreakpointsEnum boundBreakpointsEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpointsEnum);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7BreakpointEvent.IID, ad7Thread);
}
// Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting.
public void OnException(DebuggedThread thread, string name, string description, uint code, Guid? exceptionCategory = null, ExceptionBreakpointState state = ExceptionBreakpointState.None)
{
AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code, exceptionCategory, state);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7ExceptionEvent.IID, ad7Thread);
}
public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null)
{
AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(_engine, var, prop);
Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client);
}
public void OnStepComplete(DebuggedThread thread)
{
// Step complete is sent when a step has finished
AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent();
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread);
}
public void OnAsyncBreakComplete(DebuggedThread thread)
{
// This will get called when the engine receives the breakpoint event that is created when the user
// hits the pause button in vs.
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent();
Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread);
}
public void OnLoadComplete(DebuggedThread thread)
{
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent();
Send(eventObject, AD7LoadCompleteEvent.IID, ad7Thread);
}
public void OnProgramDestroy(uint exitCode)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
// Engines notify the debugger about the results of a symbol serach by sending an instance
// of IDebugSymbolSearchEvent2
public void OnSymbolSearch(DebuggedModule module, string status, uint dwStatusFlags)
{
enum_MODULE_INFO_FLAGS statusFlags = (enum_MODULE_INFO_FLAGS)dwStatusFlags;
string statusString = ((statusFlags & enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED) != 0 ? "Symbols Loaded - " : "No symbols loaded") + status;
AD7Module ad7Module = new AD7Module(module, _engine.DebuggedProcess);
AD7SymbolSearchEvent eventObject = new AD7SymbolSearchEvent(ad7Module, statusString, statusFlags);
Send(eventObject, AD7SymbolSearchEvent.IID, null);
}
// Engines notify the debugger that a breakpoint has bound through the breakpoint bound event.
public void OnBreakpointBound(object objBoundBreakpoint)
{
AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint;
IDebugPendingBreakpoint2 pendingBreakpoint;
((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint);
AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint);
Send(eventObject, AD7BreakpointBoundEvent.IID, null);
}
// Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event
public void OnBreakpointError(AD7ErrorBreakpoint bperr)
{
AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr);
Send(eventObject, AD7BreakpointErrorEvent.IID, null);
}
// Engines notify the SDM that a bound breakpoint change resulted in an error
public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason);
Send(eventObject, AD7BreakpointUnboundEvent.IID, null);
}
public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2);
Send(eventObject, AD7CustomDebugEvent.IID, null);
}
public void OnStopComplete(DebuggedThread thread)
{
var eventObject = new AD7StopCompleteEvent();
Send(eventObject, AD7StopCompleteEvent.IID, (AD7Thread)thread.Client);
}
private void SendMessage(string message, OutputMessage.Severity severity, bool isAsync)
{
try
{
// IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine.
// The sample engine doesn't take advantage of this.
AD7MessageEvent eventObject = new AD7MessageEvent(new OutputMessage(message, enum_MESSAGETYPE.MT_MESSAGEBOX, severity), isAsync);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using hw.Helper;
using JetBrains.Annotations;
namespace Reni.Helper
{
static class Extension
{
[PublicAPI]
internal static IEnumerable<TTarget> GetNodesFromTopToBottom<TTarget>
(this ITree<TTarget> target, Func<TTarget, bool> predicate = null)
where TTarget : ITree<TTarget>
{
if(target == null)
yield break;
var index = 0;
while(index < target.DirectChildCount)
{
var node = target.GetDirectChild(index);
if(predicate == null || predicate(node))
yield return node;
else if(node != null)
foreach(var result in node.GetNodesFromTopToBottom(predicate))
yield return result;
index++;
}
}
[PublicAPI]
internal static IEnumerable<TTarget> GetNodesFromLeftToRight<TTarget>(this ITree<TTarget> target)
where TTarget : ITree<TTarget>
{
if(target == null)
yield break;
var index = 0;
while(index < target.LeftDirectChildCount)
{
var node = target.GetDirectChild(index);
if(node != null)
foreach(var child in node.GetNodesFromLeftToRight())
yield return child;
index++;
}
yield return (TTarget)target;
while(index < target.DirectChildCount)
{
var node = target.GetDirectChild(index);
if(node != null)
foreach(var child in node.GetNodesFromLeftToRight())
yield return child;
index++;
}
}
[PublicAPI]
internal static int[] GetPath<TTarget>(this TTarget container, Func<TTarget, bool> isMatch)
where TTarget : ITree<TTarget>
{
if(container == null)
return null;
if(isMatch(container))
return new int[0];
return container
.DirectChildCount
.Select(container.GetDirectChild)
.Select((node, index) => GetSubPath(node, index, isMatch))
.FirstOrDefault(path => path != null);
}
[PublicAPI]
internal static IEnumerable<int[]> GetPaths<TTarget>(this TTarget container, Func<TTarget, bool> isMatch)
where TTarget : ITree<TTarget>
{
if(container == null)
return new int[0][];
if(isMatch(container))
return new[] {new int[0]};
return container
.DirectChildCount
.Select(container.GetDirectChild)
.SelectMany((node, index) => GetSubPaths(node, index, isMatch))
.Where(path => path != null);
}
static int[] GetSubPath<TTarget>(TTarget container, int index, Func<TTarget, bool> isMatch)
where TTarget : ITree<TTarget>
{
var subPath = GetPath(container, isMatch);
return subPath == null? null : T(index).Concat(subPath).ToArray();
}
static IEnumerable<int[]> GetSubPaths<TTarget>(TTarget container, int index, Func<TTarget, bool> isMatch)
where TTarget : ITree<TTarget>
{
var subPath = GetPaths(container, isMatch);
return subPath.Select(subPath => T(index).Concat(subPath).ToArray());
}
[PublicAPI]
internal static IEnumerable<TTarget> GetNodesFromRightToLeft<TTarget>(this ITree<TTarget> target)
where TTarget : ITree<TTarget>
{
if(target == null)
yield break;
var index = target.DirectChildCount;
while(index > target.LeftDirectChildCount)
{
index--;
var node = target.GetDirectChild(index);
if(node == null)
continue;
foreach(var child in node.GetNodesFromRightToLeft())
yield return child;
}
yield return (TTarget)target;
while(index > 0)
{
index--;
var node = target.GetDirectChild(index);
if(node == null)
continue;
foreach(var child in node.GetNodesFromRightToLeft())
yield return child;
}
}
static TTarget[] SubBackChain<TTarget>(this TTarget target, TTarget recent)
where TTarget : class, ITree<TTarget>
{
if(target == recent)
return new TTarget[0];
return target.DirectChildCount
.Select(target.GetDirectChild)
.Where(child => child != null)
.Select(child => child.BackChain(recent).ToArray())
.FirstOrDefault(result => result.Any());
}
internal static IEnumerable<TTarget> BackChain<TTarget>(this TTarget target, TTarget recent)
where TTarget : class, ITree<TTarget>
{
var subChain = target.SubBackChain(recent);
if(subChain == null)
yield break;
foreach(var items in subChain)
yield return items;
yield return target;
}
static TValue[] T<TValue>(params TValue[] value) => value;
[PublicAPI]
internal static IEnumerable<TResult> GetNodesFromLeftToRight<TAspect, TResult>
(this TResult target, Func<TResult, TAspect> getAspect)
where TAspect : ITree<TResult>
{
var aspect = getAspect(target);
var index = 0;
var right = new List<TResult>();
while(true)
{
if(index == aspect.LeftDirectChildCount)
right.Add(target);
if(index == aspect.DirectChildCount)
return right;
var node = aspect.GetDirectChild(index);
if(node != null)
right.AddRange(node.GetNodesFromLeftToRight(getAspect));
index++;
}
}
[PublicAPI]
internal static IEnumerable<TResult> GetNodesFromRightToLeft<TAspect, TResult>
(this TResult target, Func<TResult, TAspect> getAspect)
where TAspect : ITree<TResult>
{
var aspect = getAspect(target);
var index = aspect.DirectChildCount;
while(true)
{
if(index == aspect.LeftDirectChildCount)
yield return target;
if(index == 0)
yield break;
index--;
var node = aspect.GetDirectChild(index);
if(node != null)
foreach(var child in node.GetNodesFromRightToLeft(getAspect))
yield return child;
}
}
}
}
| |
// <copyright file="Path.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Security;
using JetBrains.Annotations;
using FS = System.IO;
// ReSharper disable once CheckNamespace
namespace IX.System.IO
{
/// <summary>
/// A class for implementing <see cref="IX.System.IO.IPath" /> with <see cref="FS.Path" />.
/// </summary>
/// <seealso cref="IX.System.IO.IPath" />
/// <seealso cref="FS.Path" />
[PublicAPI]
public class Path : IPath
{
/// <summary>
/// Gets a platform-specific character used to separate directory levels in a path string that reflects a hierarchical
/// file system organization.
/// </summary>
public char DirectorySeparatorChar => FS.Path.DirectorySeparatorChar;
/// <summary>
/// Gets a platform-specific alternate character used to separate directory levels in a path string that reflects a
/// hierarchical file system organization.
/// </summary>
public char AltDirectorySeparatorChar => FS.Path.AltDirectorySeparatorChar;
/// <summary>
/// Gets a platform-specific volume separator character.
/// </summary>
public char VolumeSeparatorChar => FS.Path.VolumeSeparatorChar;
/// <summary>
/// Gets a platform-specific separator character used to separate path strings in environment variables.
/// </summary>
public char PathSeparator => FS.Path.PathSeparator;
/// <summary>
/// Changes the extension of a path string.
/// </summary>
/// <param name="path">
/// The path information to modify. The path cannot contain any of the characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </param>
/// <param name="extension">
/// The new extension (with or without a leading period). Specify <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic) to remove an existing extension from path.
/// </param>
/// <returns>The modified path information.</returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters
/// defined in <see cref="GetInvalidPathChars" />.
/// </exception>
/// <remarks>
/// <para>
/// On Windows-based desktop platforms, if path is <see langword="null" /> or an empty string (""), the path
/// information is returned unmodified.
/// </para>
/// <para>
/// If extension is <see langword="null" />, the returned string contains the specified path with its extension
/// removed. If path has no extension, and extension is not <see langword="null" />, the returned path string
/// contains extension appended to the end of path.
/// </para>
/// </remarks>
public string ChangeExtension(
string path,
string extension) => FS.Path.ChangeExtension(
path,
extension);
/// <summary>
/// Combines an array of strings into a path.
/// </summary>
/// <param name="paths">An array of parts of the path.</param>
/// <returns>The combined paths.</returns>
/// <exception cref="ArgumentException">
/// One of the strings in the array contains one or more of the invalid characters
/// defined in <see cref="GetInvalidPathChars" />.
/// </exception>
/// <exception cref="ArgumentNullException">One of the strings in the array is <see langword="null" />.</exception>
public string Combine(params string[] paths) => FS.Path.Combine(paths);
/// <summary>
/// Returns the directory information for the specified path string.
/// </summary>
/// <param name="path">The path of a file or directory.</param>
/// <returns>
/// Directory information for path, or <see langword="null" /> if path denotes a root directory or is
/// <see langword="null" />. Returns <see cref="string.Empty" /> if path does not contain directory information.
/// </returns>
/// <exception cref="ArgumentException">
/// The <paramref name="path" /> contains invalid characters, is empty, or contains
/// only white spaces.
/// </exception>
/// <exception cref="FS.PathTooLongException">
/// In the .NET for Windows Store apps or the Portable Class Library, catch the
/// base class exception, <see cref="FS.IOException" />, instead.The path parameter is longer than the system-defined
/// maximum length.
/// </exception>
// ReSharper disable once AssignNullToNotNullAttribute
public string GetDirectoryName([CanBeNull] string path) => FS.Path.GetDirectoryName(path);
/// <summary>
/// Returns the extension of the specified path string.
/// </summary>
/// <param name="path">The path string from which to get the extension.</param>
/// <returns>
/// The extension of the specified path (including the period "."), or <see langword="null" />, or
/// <see cref="string.Empty" />. If path is <see langword="null" />, the method returns <see langword="null" />. If
/// path does not have extension information, the method returns <see cref="string.Empty" />.
/// </returns>
public string GetExtension(string path) => FS.Path.GetExtension(path);
/// <summary>
/// Returns the file name and extension of the specified path string.
/// </summary>
/// <param name="path">The path string from which to obtain the file name and extension.</param>
/// <returns>
/// The characters after the last directory character in path. If the last character of path is a directory or
/// volume separator character, this method returns <see cref="string.Empty" />. If path is <see langword="null" />,
/// this method returns <see langword="null" />.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public string GetFileName(string path) => FS.Path.GetFileName(path);
/// <summary>
/// Returns the file name of the specified path string without the extension.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// The string returned by <see cref="GetFileName(string)" /> , minus the last period (.) and all characters
/// following it.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public string GetFileNameWithoutExtension(string path) => FS.Path.GetFileNameWithoutExtension(path);
/// <summary>
/// Returns the absolute path for the specified path string.
/// </summary>
/// <param name="path">The file or directory for which to obtain absolute path information.</param>
/// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> is a zero-length string, contains only white space, or
/// contains one or more of the invalid characters defined in <see cref="GetInvalidPathChars" />. -or- The system could
/// not retrieve the absolute path.
/// </exception>
/// <exception cref="SecurityException">The caller does not have the required permissions.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null" />.</exception>
/// <exception cref="NotSupportedException">
/// <paramref name="path" /> contains a colon (":") that is not part of a
/// volume identifier (for example, "c:\").
/// </exception>
/// <exception cref="FS.PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum
/// length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be
/// less than 260 characters.
/// </exception>
public string GetFullPath(string path) => FS.Path.GetFullPath(path);
/// <summary>
/// Gets an array containing the characters that are not allowed in file names.
/// </summary>
/// <returns>An array containing the characters that are not allowed in file names.</returns>
public char[] GetInvalidFileNameChars() => FS.Path.GetInvalidFileNameChars();
/// <summary>
/// Gets an array containing the characters that are not allowed in path names.
/// </summary>
/// <returns>An array containing the characters that are not allowed in path names.</returns>
public char[] GetInvalidPathChars() => FS.Path.GetInvalidPathChars();
/// <summary>
/// Gets the root directory information of the specified path.
/// </summary>
/// <param name="path">The path from which to obtain root directory information.</param>
/// <returns>
/// The root directory of path, such as "C:\", or <see langword="null" /> if <paramref name="path" /> is
/// <see langword="null" />, or an empty string if <paramref name="path" /> does not contain root directory
/// information.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />. -or- <see cref="string.Empty" /> was passed to <paramref name="path" />.
/// </exception>
public string GetPathRoot(string path) => FS.Path.GetPathRoot(path);
/// <summary>
/// Returns a random folder name or file name.
/// </summary>
/// <returns>A random folder name or file name.</returns>
public string GetRandomFileName() => FS.Path.GetRandomFileName();
/// <summary>
/// Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.
/// </summary>
/// <returns>The full path of the temporary file.</returns>
/// <exception cref="FS.IOException">
/// An I/O error occurs, such as no unique temporary file name is available. -or- This
/// method was unable to create a temporary file.
/// </exception>
public string GetTempFileName() => FS.Path.GetTempFileName();
/// <summary>
/// Returns the path of the current user's temporary folder.
/// </summary>
/// <returns>The path to the temporary folder, ending with a backslash.</returns>
/// <exception cref="SecurityException">The caller does not have the required permissions.</exception>
public string GetTempPath() => FS.Path.GetTempPath();
/// <summary>
/// Determines whether a path includes a file name extension.
/// </summary>
/// <param name="path">The path to search for an extension.</param>
/// <returns>
/// <see langword="true" /> if the characters that follow the last directory separator (\\ or /) or volume
/// separator (:) in the path include a period (.) followed by one or more characters; otherwise,
/// <see langword="false" />.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public bool HasExtension(string path) => FS.Path.HasExtension(path);
/// <summary>
/// Gets a value indicating whether the specified path string contains a root.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns><see langword="true" /> if path contains a root; otherwise, <see langword="false" />.</returns>
/// <exception cref="ArgumentException">
/// <paramref name="path" /> contains one or more of the invalid characters defined in
/// <see cref="GetInvalidPathChars" />.
/// </exception>
public bool IsPathRooted(string path) => FS.Path.IsPathRooted(path);
}
}
| |
namespace XenAdmin.Dialogs
{
partial class AddServerDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AddServerDialog));
this.AddButton = new System.Windows.Forms.Button();
this.CancelButton2 = new System.Windows.Forms.Button();
this.ServerNameLabel = new System.Windows.Forms.Label();
this.UsernameLabel = new System.Windows.Forms.Label();
this.PasswordLabel = new System.Windows.Forms.Label();
this.UsernameTextBox = new System.Windows.Forms.TextBox();
this.PasswordTextBox = new System.Windows.Forms.TextBox();
this.ServerNameComboBox = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanelCreds = new System.Windows.Forms.TableLayoutPanel();
this.labelError = new System.Windows.Forms.Label();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.comboBoxClouds = new System.Windows.Forms.ComboBox();
this.labelInstructions = new System.Windows.Forms.Label();
this.tableLayoutPanelType = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox1.SuspendLayout();
this.tableLayoutPanelCreds.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
this.tableLayoutPanelType.SuspendLayout();
this.SuspendLayout();
//
// AddButton
//
resources.ApplyResources(this.AddButton, "AddButton");
this.AddButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.AddButton.Name = "AddButton";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// CancelButton2
//
resources.ApplyResources(this.CancelButton2, "CancelButton2");
this.CancelButton2.CausesValidation = false;
this.CancelButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton2.Name = "CancelButton2";
this.CancelButton2.UseVisualStyleBackColor = true;
this.CancelButton2.Click += new System.EventHandler(this.CancelButton2_Click);
this.CancelButton2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CancelButton2_KeyDown);
//
// ServerNameLabel
//
resources.ApplyResources(this.ServerNameLabel, "ServerNameLabel");
this.ServerNameLabel.Name = "ServerNameLabel";
//
// UsernameLabel
//
resources.ApplyResources(this.UsernameLabel, "UsernameLabel");
this.UsernameLabel.Name = "UsernameLabel";
//
// PasswordLabel
//
resources.ApplyResources(this.PasswordLabel, "PasswordLabel");
this.PasswordLabel.Name = "PasswordLabel";
//
// UsernameTextBox
//
resources.ApplyResources(this.UsernameTextBox, "UsernameTextBox");
this.UsernameTextBox.Name = "UsernameTextBox";
this.UsernameTextBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged);
//
// PasswordTextBox
//
resources.ApplyResources(this.PasswordTextBox, "PasswordTextBox");
this.PasswordTextBox.Name = "PasswordTextBox";
this.PasswordTextBox.UseSystemPasswordChar = true;
this.PasswordTextBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged);
//
// ServerNameComboBox
//
resources.ApplyResources(this.ServerNameComboBox, "ServerNameComboBox");
this.ServerNameComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.ServerNameComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.tableLayoutPanelType.SetColumnSpan(this.ServerNameComboBox, 2);
this.ServerNameComboBox.Name = "ServerNameComboBox";
this.ServerNameComboBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged);
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.tableLayoutPanelType.SetColumnSpan(this.groupBox1, 3);
this.groupBox1.Controls.Add(this.tableLayoutPanelCreds);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// tableLayoutPanelCreds
//
resources.ApplyResources(this.tableLayoutPanelCreds, "tableLayoutPanelCreds");
this.tableLayoutPanelCreds.Controls.Add(this.UsernameLabel, 0, 0);
this.tableLayoutPanelCreds.Controls.Add(this.PasswordLabel, 0, 1);
this.tableLayoutPanelCreds.Controls.Add(this.PasswordTextBox, 1, 1);
this.tableLayoutPanelCreds.Controls.Add(this.UsernameTextBox, 1, 0);
this.tableLayoutPanelCreds.Controls.Add(this.labelError, 1, 2);
this.tableLayoutPanelCreds.Controls.Add(this.pictureBoxError, 0, 2);
this.tableLayoutPanelCreds.Name = "tableLayoutPanelCreds";
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.Name = "labelError";
this.labelError.TextChanged += new System.EventHandler(this.labelError_TextChanged);
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Image = global::XenAdmin.Properties.Resources._000_error_h32bit_16;
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// flowLayoutPanel1
//
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.tableLayoutPanelType.SetColumnSpan(this.flowLayoutPanel1, 3);
this.flowLayoutPanel1.Controls.Add(this.CancelButton2);
this.flowLayoutPanel1.Controls.Add(this.AddButton);
this.flowLayoutPanel1.Controls.Add(this.comboBoxClouds);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// comboBoxClouds
//
this.comboBoxClouds.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.comboBoxClouds, "comboBoxClouds");
this.comboBoxClouds.FormattingEnabled = true;
this.comboBoxClouds.Name = "comboBoxClouds";
//
// labelInstructions
//
resources.ApplyResources(this.labelInstructions, "labelInstructions");
this.tableLayoutPanelType.SetColumnSpan(this.labelInstructions, 3);
this.labelInstructions.Name = "labelInstructions";
//
// tableLayoutPanelType
//
resources.ApplyResources(this.tableLayoutPanelType, "tableLayoutPanelType");
this.tableLayoutPanelType.Controls.Add(this.ServerNameComboBox, 1, 2);
this.tableLayoutPanelType.Controls.Add(this.groupBox1, 0, 3);
this.tableLayoutPanelType.Controls.Add(this.ServerNameLabel, 0, 2);
this.tableLayoutPanelType.Controls.Add(this.labelInstructions, 0, 0);
this.tableLayoutPanelType.Controls.Add(this.flowLayoutPanel1, 0, 4);
this.tableLayoutPanelType.Name = "tableLayoutPanelType";
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// AddServerDialog
//
this.AcceptButton = this.AddButton;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.CancelButton2;
this.Controls.Add(this.tableLayoutPanelType);
this.Name = "AddServerDialog";
this.Load += new System.EventHandler(this.AddServerDialog_Load);
this.Shown += new System.EventHandler(this.AddServerDialog_Shown);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tableLayoutPanelCreds.ResumeLayout(false);
this.tableLayoutPanelCreds.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanelType.ResumeLayout(false);
this.tableLayoutPanelType.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
protected System.Windows.Forms.Label ServerNameLabel;
protected System.Windows.Forms.Label UsernameLabel;
protected System.Windows.Forms.Label PasswordLabel;
protected System.Windows.Forms.TextBox UsernameTextBox;
protected System.Windows.Forms.TextBox PasswordTextBox;
protected System.Windows.Forms.ComboBox ServerNameComboBox;
protected System.Windows.Forms.Button CancelButton2;
protected System.Windows.Forms.Button AddButton;
protected System.Windows.Forms.GroupBox groupBox1;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelCreds;
protected System.Windows.Forms.PictureBox pictureBoxError;
protected System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
protected System.Windows.Forms.Label labelError;
protected System.Windows.Forms.Label labelInstructions;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
protected System.Windows.Forms.RadioButton XenServerRadioButton;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelType;
private System.Windows.Forms.ComboBox comboBoxClouds;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Teleport
{
/// <summary>
/// The Mixed Reality Toolkit's implementation of the <see cref="Microsoft.MixedReality.Toolkit.Teleport.IMixedRealityTeleportSystem"/>.
/// </summary>
public class MixedRealityTeleportSystem : BaseCoreSystem, IMixedRealityTeleportSystem
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param>
[System.Obsolete("This constructor is obsolete (registrar parameter is no longer required) and will be removed in a future version of the Microsoft Mixed Reality Toolkit.")]
public MixedRealityTeleportSystem(
IMixedRealityServiceRegistrar registrar) : base(registrar, null) // Teleport system does not use a profile
{
Registrar = registrar;
}
/// <summary>
/// Constructor.
/// </summary>
public MixedRealityTeleportSystem() : base(null) { } // Teleport system does not use a profile
private TeleportEventData teleportEventData;
private bool isTeleporting = false;
private bool isProcessingTeleportRequest = false;
private Vector3 targetPosition = Vector3.zero;
private Vector3 targetRotation = Vector3.zero;
/// <summary>
/// Used to clean up event system when shutting down, if this system created one.
/// </summary>
private GameObject eventSystemReference = null;
#region IMixedRealityService Implementation
/// <inheritdoc/>
public override string Name { get; protected set; } = "Mixed Reality Teleport System";
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
InitializeInternal();
}
private void InitializeInternal()
{
#if UNITY_EDITOR
if (!UnityEditor.EditorApplication.isPlaying)
{
var eventSystems = Object.FindObjectsOfType<EventSystem>();
if (eventSystems.Length == 0)
{
if (!IsInputSystemEnabled)
{
eventSystemReference = new GameObject("Event System");
eventSystemReference.AddComponent<EventSystem>();
}
else
{
Debug.Log("The input system didn't properly add an event system to your scene. Please make sure the input system's priority is set higher than the teleport system.");
}
}
else if (eventSystems.Length > 1)
{
Debug.Log("Too many event systems in the scene. The Teleport System requires only one.");
}
}
#endif // UNITY_EDITOR
teleportEventData = new TeleportEventData(EventSystem.current);
}
/// <inheritdoc />
public override void Destroy()
{
base.Destroy();
if (eventSystemReference != null)
{
if (!Application.isPlaying)
{
Object.DestroyImmediate(eventSystemReference);
}
else
{
Object.Destroy(eventSystemReference);
}
}
}
#endregion IMixedRealityService Implementation
#region IEventSystemManager Implementation
private static readonly ProfilerMarker HandleEventPerfMarker = new ProfilerMarker("[MRTK] MixedRealityTeleportSystem.HandleEvent");
/// <inheritdoc />
public override void HandleEvent<T>(BaseEventData eventData, ExecuteEvents.EventFunction<T> eventHandler)
{
using (HandleEventPerfMarker.Auto())
{
Debug.Assert(eventData != null);
var teleportData = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
Debug.Assert(teleportData != null);
Debug.Assert(!teleportData.used);
// Process all the event listeners
base.HandleEvent(teleportData, eventHandler);
}
}
/// <summary>
/// Register a <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> to listen to teleport events.
/// </summary>
public override void Register(GameObject listener) => base.Register(listener);
/// <summary>
/// Unregister a <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> from listening to teleport events.
/// </summary>
public override void Unregister(GameObject listener) => base.Unregister(listener);
#endregion IEventSystemManager Implementation
#region IMixedRealityTeleportSystem Implementation
/// <summary>
/// Is an input system registered?
/// </summary>
private bool IsInputSystemEnabled => CoreServices.InputSystem != null;
private float teleportDuration = 0.25f;
/// <inheritdoc />
public float TeleportDuration
{
get => teleportDuration;
set
{
if (isProcessingTeleportRequest)
{
Debug.LogWarning("Couldn't change teleport duration. Teleport in progress.");
return;
}
teleportDuration = value;
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportRequestHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportRequest(casted);
};
private static readonly ProfilerMarker RaiseTeleportRequestPerfMarker = new ProfilerMarker("[MRTK] MixedRealityTeleportSystem.RaiseTeleportRequest");
/// <inheritdoc />
public void RaiseTeleportRequest(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
using (RaiseTeleportRequestPerfMarker.Auto())
{
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportRequestHandler);
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportStartedHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportStarted(casted);
};
private static readonly ProfilerMarker RaiseTeleportStartedPerfMarker = new ProfilerMarker("[MRTK] MixedRealityTeleportSystem.RaiseTeleportStarted");
/// <inheritdoc />
public void RaiseTeleportStarted(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
if (isTeleporting)
{
Debug.LogError("Teleportation already in progress");
return;
}
using (RaiseTeleportStartedPerfMarker.Auto())
{
isTeleporting = true;
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportStartedHandler);
ProcessTeleportationRequest(teleportEventData);
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportCompletedHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportCompleted(casted);
};
private static readonly ProfilerMarker RaiseTeleportCompletePerfMarker = new ProfilerMarker("[MRTK] MixedRealityTeleportSystem.RaiseTeleportComplete");
/// <summary>
/// Raise a teleportation completed event.
/// </summary>
/// <param name="pointer">The pointer that raised the event.</param>
/// <param name="hotSpot">The teleport target</param>
private void RaiseTeleportComplete(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
if (!isTeleporting)
{
Debug.LogError("No Active Teleportation in progress.");
return;
}
using (RaiseTeleportCompletePerfMarker.Auto())
{
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportCompletedHandler);
isTeleporting = false;
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportCanceledHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportCanceled(casted);
};
private static readonly ProfilerMarker RaiseTeleportCanceledPerfMarker = new ProfilerMarker("[MRTK] MixedRealityTeleportSystem.RaiseTeleportHandled");
/// <inheritdoc />
public void RaiseTeleportCanceled(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
using (RaiseTeleportCanceledPerfMarker.Auto())
{
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportCanceledHandler);
}
}
#endregion IMixedRealityTeleportSystem Implementation
private static readonly ProfilerMarker ProcessTeleportationRequestPerfMarker = new ProfilerMarker("[MRTK] MixedRealityTeleportSystem.ProcessTeleportationRequest");
private void ProcessTeleportationRequest(TeleportEventData eventData)
{
using (ProcessTeleportationRequestPerfMarker.Auto())
{
isProcessingTeleportRequest = true;
targetRotation = Vector3.zero;
var teleportPointer = eventData.Pointer as IMixedRealityTeleportPointer;
if (teleportPointer != null)
{
targetRotation.y = teleportPointer.PointerOrientation;
}
targetPosition = eventData.Pointer.Result.Details.Point;
if (eventData.HotSpot != null)
{
targetPosition = eventData.HotSpot.Position;
if (eventData.HotSpot.OverrideTargetOrientation)
{
targetRotation.y = eventData.HotSpot.TargetOrientation;
}
}
float height = targetPosition.y;
targetPosition -= CameraCache.Main.transform.position - MixedRealityPlayspace.Position;
targetPosition.y = height;
MixedRealityPlayspace.Position = targetPosition;
MixedRealityPlayspace.RotateAround(
CameraCache.Main.transform.position,
Vector3.up,
targetRotation.y - CameraCache.Main.transform.eulerAngles.y);
isProcessingTeleportRequest = false;
// Raise complete event using the pointer and hot spot provided.
RaiseTeleportComplete(eventData.Pointer, eventData.HotSpot);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using HandlebarsDotNet.Collections;
using HandlebarsDotNet.Polyfills;
using HandlebarsDotNet.Pools;
using HandlebarsDotNet.StringUtils;
using HandlebarsDotNet.Extensions;
namespace HandlebarsDotNet.PathStructure
{
public enum PathType
{
None,
Empty,
Variable,
Inversion,
BlockHelper,
BlockClose
}
/// <summary>
/// Represents path expression
/// </summary>
public sealed partial class PathInfo : IEquatable<PathInfo>
{
internal readonly bool IsValidHelperLiteral;
internal readonly bool HasValue;
internal readonly bool IsThis;
internal readonly bool IsPureThis;
internal readonly bool IsInversion;
internal readonly bool IsBlockHelper;
internal readonly bool IsBlockClose;
private readonly int _hashCode;
private readonly int _trimmedHashCode;
private readonly int _trimmedInvariantHashCode;
public static readonly PathInfo Empty = new PathInfo(PathType.Empty, "null", false, ArrayEx.Empty<PathSegment>());
private PathInfo(
PathType pathType,
string path,
bool isValidHelperLiteral,
PathSegment[] segments)
{
IsValidHelperLiteral = isValidHelperLiteral;
HasValue = pathType != PathType.Empty;
Path = path;
_hashCode = (Path.GetHashCode() * 397) ^ HasValue.GetHashCode();
if(!HasValue) return;
IsVariable = pathType == PathType.Variable;
IsInversion = pathType == PathType.Inversion;
IsBlockHelper = pathType == PathType.BlockHelper;
IsBlockClose = pathType == PathType.BlockClose;
var plainSegments = segments.Where(o => !o.IsParent && o.IsNotEmpty).ToArray();
IsThis = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == "." || plainSegments.Any(o => o.IsThis);
IsPureThis = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == ".";
Segments = segments;
using var container = StringBuilderPool.Shared.Use();
var builder = container.Value;
var segmentsLastIndex = Segments.Length - 1;
for (var segmentIndex = 0; segmentIndex <= segmentsLastIndex; segmentIndex++)
{
var segment = Segments[segmentIndex];
var pathChainLastIndex = segment.PathChain.Length - 1;
var pathChain = segment.PathChain;
for (var pathChainIndex = 0; pathChainIndex <= pathChainLastIndex; pathChainIndex++)
{
builder.Append(pathChain[pathChainIndex].TrimmedValue);
if (pathChainIndex != pathChainLastIndex) builder.Append('.');
}
if (segmentIndex != segmentsLastIndex) builder.Append('/');
}
TrimmedPath = builder.ToString();
_trimmedHashCode = TrimmedPath.GetHashCode();
_trimmedInvariantHashCode = TrimmedPath.ToLowerInvariant().GetHashCode();
}
/// <summary>
/// Indicates whether <see cref="PathInfo"/> is part of <c>@</c> variable
/// </summary>
public readonly bool IsVariable;
public readonly PathSegment[] Segments;
public readonly string Path;
public readonly string TrimmedPath;
/// <inheritdoc />
public bool Equals(PathInfo other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return HasValue == other.HasValue && string.Equals(Path, other.Path, StringComparison.Ordinal);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj is PathInfo pathInfo) return Equals(pathInfo);
return false;
}
/// <inheritdoc />
public override int GetHashCode() => _hashCode;
/// <summary>
/// Returns string representation of current <see cref="PathInfo"/>
/// </summary>
public override string ToString() => Path;
/// <inheritdoc cref="ToString"/>
public static implicit operator string(PathInfo pathInfo) => pathInfo.Path;
public static implicit operator PathInfo(string path) => PathInfoStore.Current?.GetOrAdd(path) ?? Parse(path);
public static PathInfo Parse(string path)
{
if (path == "null") return Empty;
var originalPath = path;
var pathType = GetPathType(path);
var pathSubstring = new Substring(path);
var isValidHelperLiteral = true;
var isVariable = pathType == PathType.Variable;
var isInversion = pathType == PathType.Inversion;
var isBlockHelper = pathType == PathType.BlockHelper;
if (isVariable || isBlockHelper || isInversion)
{
isValidHelperLiteral = isBlockHelper || isInversion;
pathSubstring = new Substring(pathSubstring, 1);
}
var segments = new List<PathSegment>();
var pathParts = Substring.Split(pathSubstring, '/');
var extendedEnumerator = ExtendedEnumerator<Substring>.Create(pathParts);
using var container = StringBuilderPool.Shared.Use();
var buffer = container.Value;
while (extendedEnumerator.MoveNext())
{
var segment = extendedEnumerator.Current.Value;
if (buffer.Length != 0)
{
buffer.Append('/');
buffer.Append(in segment);
if(Substring.LastIndexOf(segment, ']', out var index)
&& !Substring.LastIndexOf(segment, '[', index, out _))
{
var chainSegment = GetPathChain(buffer.ToString());
if (chainSegment.Length > 1) isValidHelperLiteral = false;
segments.Add(new PathSegment(segment, chainSegment));
buffer.Length = 0;
continue;
}
}
if(Substring.LastIndexOf(segment, '[', out var startIndex)
&& !Substring.LastIndexOf(segment, ']', startIndex, out _))
{
buffer.Append(in segment);
continue;
}
switch (segment.Length)
{
case 2 when segment[0] == '.' && segment[1] == '.':
isValidHelperLiteral = false;
segments.Add(new PathSegment(segment, ArrayEx.Empty<ChainSegment>()));
continue;
case 1 when segment[0] == '.':
isValidHelperLiteral = false;
segments.Add(new PathSegment(segment, ArrayEx.Empty<ChainSegment>()));
continue;
}
var chainSegments = GetPathChain(segment);
if (chainSegments.Length > 1 && pathType != PathType.BlockHelper) isValidHelperLiteral = false;
segments.Add(new PathSegment(segment, chainSegments));
}
if (isValidHelperLiteral && segments.Count > 1) isValidHelperLiteral = false;
return new PathInfo(pathType, originalPath, isValidHelperLiteral, segments.ToArray());
}
private static ChainSegment[] GetPathChain(Substring segmentString)
{
var insideEscapeBlock = false;
var pathChainParts = Substring.Split(segmentString, '.', StringSplitOptions.RemoveEmptyEntries);
var extendedEnumerator = ExtendedEnumerator<Substring>.Create(pathChainParts);
if (!extendedEnumerator.Any && segmentString == ".") return new[] { ChainSegment.This };
var chainSegments = new List<ChainSegment>();
while (extendedEnumerator.MoveNext())
{
var next = extendedEnumerator.Current.Value;
if (insideEscapeBlock)
{
if (Substring.EndsWith(next, ']'))
{
insideEscapeBlock = false;
}
chainSegments[chainSegments.Count - 1] = ChainSegment.Create($"{chainSegments[chainSegments.Count - 1]}.{next.ToString()}");
continue;
}
if (Substring.StartsWith(next, '['))
{
insideEscapeBlock = true;
}
if (Substring.EndsWith(next,']'))
{
insideEscapeBlock = false;
}
chainSegments.Add(ChainSegment.Create(next.ToString()));
}
return chainSegments.ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static PathType GetPathType(string path)
{
return path[0] switch
{
'@' => PathType.Variable,
'^' => PathType.Inversion,
'#' => PathType.BlockHelper,
'/' => PathType.BlockClose,
_ => PathType.None
};
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// BillingCodeType
/// </summary>
[DataContract]
public partial class BillingCodeType : IEquatable<BillingCodeType>
{
/// <summary>
/// Initializes a new instance of the <see cref="BillingCodeType" /> class.
/// </summary>
[JsonConstructorAttribute]
protected BillingCodeType() { }
/// <summary>
/// Initializes a new instance of the <see cref="BillingCodeType" /> class.
/// </summary>
/// <param name="Name">Name (required).</param>
/// <param name="Description">Description.</param>
/// <param name="BillingCode">BillingCode.</param>
/// <param name="IsActive">IsActive (default to false).</param>
public BillingCodeType(string Name = null, string Description = null, string BillingCode = null, bool? IsActive = null)
{
// to ensure "Name" is required (not null)
if (Name == null)
{
throw new InvalidDataException("Name is a required property for BillingCodeType and cannot be null");
}
else
{
this.Name = Name;
}
this.Description = Description;
this.BillingCode = BillingCode;
// use default value if no "IsActive" provided
if (IsActive == null)
{
this.IsActive = false;
}
else
{
this.IsActive = IsActive;
}
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets ClientId
/// </summary>
[DataMember(Name="clientId", EmitDefaultValue=false)]
public int? ClientId { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets BillingCode
/// </summary>
[DataMember(Name="billingCode", EmitDefaultValue=false)]
public string BillingCode { get; set; }
/// <summary>
/// Gets or Sets IsActive
/// </summary>
[DataMember(Name="isActive", EmitDefaultValue=false)]
public bool? IsActive { 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 BillingCodeType {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ClientId: ").Append(ClientId).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" BillingCode: ").Append(BillingCode).Append("\n");
sb.Append(" IsActive: ").Append(IsActive).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BillingCodeType);
}
/// <summary>
/// Returns true if BillingCodeType instances are equal
/// </summary>
/// <param name="other">Instance of BillingCodeType to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BillingCodeType other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.ClientId == other.ClientId ||
this.ClientId != null &&
this.ClientId.Equals(other.ClientId)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.BillingCode == other.BillingCode ||
this.BillingCode != null &&
this.BillingCode.Equals(other.BillingCode)
) &&
(
this.IsActive == other.IsActive ||
this.IsActive != null &&
this.IsActive.Equals(other.IsActive)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.ClientId != null)
hash = hash * 59 + this.ClientId.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.BillingCode != null)
hash = hash * 59 + this.BillingCode.GetHashCode();
if (this.IsActive != null)
hash = hash * 59 + this.IsActive.GetHashCode();
return hash;
}
}
}
}
| |
using AutoMapper;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
[Cmdlet(
VerbsCommon.Set,
ProfileNouns.VirtualMachineDscExtension,
SupportsShouldProcess = true,
DefaultParameterSetName = AzureBlobDscExtensionParamSet)]
[OutputType(typeof(PSAzureOperationResponse))]
public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension";
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the virtual machine.")]
[ResourceGroupCompleter()]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.Powershell.DSC'")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// The name of the configuration archive that was previously uploaded by
/// Publish-AzureRmVMDSCConfiguration. This parameter must specify only the name
/// of the file, without any path.
/// A null value or empty string indicate that the VM extension should install DSC,
/// but not start any configuration
/// </summary>
[Alias("ConfigurationArchiveBlob")]
[Parameter(
Mandatory = true,
Position = 5,
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureRmVMDSCConfiguration")]
[AllowEmptyString]
[AllowNull]
public string ArchiveBlobName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName.
/// </summary>
[Alias("StorageAccountName")]
[Parameter(
Mandatory = true,
Position = 4,
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")]
[ValidateNotNullOrEmpty]
public String ArchiveStorageAccountName { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " +
"This param is optional if storage account and virtual machine both exists in the same resource group name, " +
"specified by ResourceGroupName param.")]
[ValidateNotNullOrEmpty]
public string ArchiveResourceGroupName { get; set; }
/// <summary>
/// The DNS endpoint suffix for all storage services, e.g. "core.windows.net".
/// </summary>
[Alias("StorageEndpointSuffix")]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The Storage Endpoint Suffix.")]
[ValidateNotNullOrEmpty]
public string ArchiveStorageEndpointSuffix { get; set; }
/// <summary>
/// Name of the Azure Storage Container where the configuration script is located.
/// </summary>
[Alias("ContainerName")]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")]
[ValidateNotNullOrEmpty]
public string ArchiveContainerName { get; set; }
/// <summary>
/// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations
/// contained within the file specified by ArchiveBlobName.
///
/// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if
/// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite".
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")]
[ValidateNotNullOrEmpty]
public string ConfigurationName { get; set; }
/// <summary>
/// A hashtable specifying the arguments to the ConfigurationFunction. The keys
/// correspond to the parameter names and the values to the parameter values.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")]
[ValidateNotNullOrEmpty]
public Hashtable ConfigurationArgument { get; set; }
/// <summary>
/// Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")]
[ValidateNotNullOrEmpty]
public string ConfigurationData { get; set; }
/// <summary>
/// The specific version of the DSC extension that Set-AzureRmVMDSCExtension will
/// apply the settings to.
/// </summary>
[Alias("HandlerVersion")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The version of the DSC extension that Set-AzureRmVMDSCExtension will apply the settings to. " +
"Allowed format N.N")]
[ValidateNotNullOrEmpty]
public string Version { get; set; }
/// <summary>
/// By default Set-AzureRmVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them.
/// </summary>
[Parameter(
HelpMessage = "Use this parameter to overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Location of the resource.")]
[LocationCompleter("Microsoft.Storage/storageAccounts")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
/// <summary>
/// We install the extension handler version specified by the version param. By default extension handler is not autoupdated.
/// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available.
/// </summary>
[Parameter(
HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")]
public SwitchParameter AutoUpdate { get; set; }
/// <summary>
/// Specifies the version of the Windows Management Framework (WMF) to install
/// on the VM.
///
/// The DSC Azure Extension depends on DSC features that are only available in
/// the WMF updates. This parameter specifies which version of the update to
/// install on the VM. The possible values are "4.0","5.0" ,"5.1" and "latest".
///
/// A value of "4.0" will install WMF 4.0 Update packages
/// (https://support.microsoft.com/en-us/kb/3119938) on Windows 8.1 or Windows Server
/// 2012 R2, or
/// (https://support.microsoft.com/en-us/kb/3109118) on Windows Server 2008 R2
/// and on other versions of Windows if newer version is not already installed.
///
/// A value of "5.0" will install the latest release of WMF 5.0
/// (https://www.microsoft.com/en-us/download/details.aspx?id=50395).
///
/// A value of "5.1" will install the WMF 5.1
/// (https://www.microsoft.com/en-us/download/details.aspx?id=54616).
///
/// A value of "latest" will install the latest WMF, currently WMF 5.1
///
/// The default value is "latest"
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateSetAttribute(new[] {"4.0", "5.0", "5.1", "latest"})]
public string WmfVersion { get; set; }
/// <summary>
/// The Extension Data Collection state
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
HelpMessage = "Enables or Disables Data Collection in the extension. It is enabled if it is not specified. " +
"The value is persisted in the extension between calls.")
]
[ValidateSet("Enable", "Disable")]
[AllowNull]
public string DataCollection { get; set; }
//Private Variables
private const string VersionRegexExpr = @"^(([0-9])\.)\d+$";
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ValidateParameters();
CreateConfiguration();
}
//Private Methods
private void ValidateParameters()
{
if (string.IsNullOrEmpty(ArchiveBlobName))
{
if (ConfigurationName != null || ConfigurationArgument != null
|| ConfigurationData != null)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters);
}
if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters);
}
}
else
{
if (string.Compare(
Path.GetFileName(ArchiveBlobName),
ArchiveBlobName,
StringComparison.InvariantCultureIgnoreCase) != 0)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath);
}
if (ConfigurationData != null)
{
ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData);
if (!File.Exists(ConfigurationData))
{
this.ThrowInvalidArgumentError(
Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile,
ConfigurationData);
}
if (string.Compare(
Path.GetExtension(ConfigurationData),
".psd1",
StringComparison.InvariantCultureIgnoreCase) != 0)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile);
}
}
if (ArchiveResourceGroupName == null)
{
ArchiveResourceGroupName = ResourceGroupName;
}
_storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName);
if (ConfigurationName == null)
{
ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName);
}
if (ArchiveContainerName == null)
{
ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (ArchiveStorageEndpointSuffix == null)
{
ArchiveStorageEndpointSuffix =
DefaultProfile.DefaultContext.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
if (!(Regex.Match(Version, VersionRegexExpr).Success))
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion);
}
}
}
private void CreateConfiguration()
{
var publicSettings = new DscExtensionPublicSettings();
var privateSettings = new DscExtensionPrivateSettings();
if (!string.IsNullOrEmpty(ArchiveBlobName))
{
ConfigurationUris configurationUris = UploadConfigurationDataToBlob();
publicSettings.SasToken = configurationUris.SasToken;
publicSettings.ModulesUrl = configurationUris.ModulesUrl;
Hashtable privacySetting = new Hashtable();
privacySetting.Add("DataCollection", DataCollection);
publicSettings.Privacy = privacySetting;
publicSettings.ConfigurationFunction = string.Format(
CultureInfo.InvariantCulture,
"{0}\\{1}",
Path.GetFileNameWithoutExtension(ArchiveBlobName),
ConfigurationName);
Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings =
DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument);
publicSettings.Properties = settings.Item1;
privateSettings.Items = settings.Item2;
privateSettings.DataBlobUri = configurationUris.DataBlobUri;
if (!string.IsNullOrEmpty(WmfVersion))
{
publicSettings.WmfVersion = WmfVersion;
}
}
if (string.IsNullOrEmpty(this.Location))
{
this.Location = GetLocationFromVm(this.ResourceGroupName, this.VMName);
}
var parameters = new VirtualMachineExtension
{
Location = this.Location,
Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace,
VirtualMachineExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName,
TypeHandlerVersion = Version,
// Define the public and private property bags that will be passed to the extension.
Settings = publicSettings,
//PrivateConfuguration contains sensitive data in a plain text
ProtectedSettings = privateSettings,
AutoUpgradeMinorVersion = AutoUpdate.IsPresent
};
//Add retry logic due to CRP service restart known issue CRP bug: 3564713
var count = 1;
Rest.Azure.AzureOperationResponse<VirtualMachineExtension> op = null;
while (true)
{
try
{
op = VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync(
ResourceGroupName,
VMName,
Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName,
parameters).GetAwaiter().GetResult();
break;
}
catch (Rest.Azure.CloudException ex)
{
var errorReturned = JsonConvert.DeserializeObject<PSComputeLongRunningOperation>(
ex.Response.Content);
if ("Failed".Equals(errorReturned.Status)
&& errorReturned.Error != null && "InternalExecutionError".Equals(errorReturned.Error.Code))
{
count++;
if (count <= 2)
{
continue;
}
}
ThrowTerminatingError(new ErrorRecord(ex, "InvalidResult", ErrorCategory.InvalidResult, null));
}
}
var result = ComputeAutoMapperProfile.Mapper.Map<PSAzureOperationResponse>(op);
WriteObject(result);
}
/// <summary>
/// Uploading configuration data to blob storage.
/// </summary>
/// <returns>ConfigurationUris collection that represent artifacts of uploading</returns>
private ConfigurationUris UploadConfigurationDataToBlob()
{
//
// Get a reference to the container in blob storage
//
var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true);
var blobClient = storageAccount.CreateCloudBlobClient();
var containerReference = blobClient.GetContainerReference(ArchiveContainerName);
//
// Get a reference to the configuration blob and create a SAS token to access it
//
var blobAccessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime =
DateTime.UtcNow.AddHours(1),
Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete
};
var configurationBlobName = ArchiveBlobName;
var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName);
var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy);
//
// Upload the configuration data to blob storage and get a SAS token
//
string configurationDataBlobUri = null;
if (ConfigurationData != null)
{
var guid = Guid.NewGuid();
// there may be multiple VMs using the same configuration
var configurationDataBlobName = string.Format(
CultureInfo.InvariantCulture,
"{0}-{1}.psd1",
ConfigurationName,
guid);
var configurationDataBlobReference =
containerReference.GetBlockBlobReference(configurationDataBlobName);
ConfirmAction(
true,
string.Empty,
string.Format(
CultureInfo.CurrentUICulture,
Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscUploadToBlobStorageAction,
ConfigurationData),
configurationDataBlobReference.Uri.AbsoluteUri,
() =>
{
if (!Force && configurationDataBlobReference.ExistsAsync().ConfigureAwait(false).GetAwaiter().GetResult())
{
ThrowTerminatingError(
new ErrorRecord(
new UnauthorizedAccessException(
string.Format(
CultureInfo.CurrentUICulture,
Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageBlobAlreadyExists,
configurationDataBlobName)),
"StorageBlobAlreadyExists",
ErrorCategory.PermissionDenied,
null));
}
configurationDataBlobReference.UploadFromFileAsync(ConfigurationData).ConfigureAwait(false).GetAwaiter().GetResult();
var configurationDataBlobSasToken =
configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy);
configurationDataBlobUri =
configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri
+ configurationDataBlobSasToken;
});
}
return new ConfigurationUris
{
ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri,
SasToken = configurationBlobSasToken,
DataBlobUri = configurationDataBlobUri
};
}
/// <summary>
/// Class represent info about uploaded Configuration.
/// </summary>
private class ConfigurationUris
{
public string SasToken { get; set; }
public string DataBlobUri { get; set; }
public string ModulesUrl { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
using Shouldly;
using Xunit;
namespace TestStack.BDDfy.Tests.Scanner.FluentScanner
{
public class BaseClass
{
protected int InheritedInput1 = 1;
protected string InheritedInput2 = "2";
protected int[] InheritedArrayInput1
{
get
{
return new[] { 3, 4 };
}
}
protected string[] InheritedArrayInput2
{
get
{
return new[] { "5", "6" };
}
}
}
public class ExpressionExtensionsTests : BaseClass
{
private class ContainerType
{
public int Target { get; set; }
public string Target2 { get; set; }
public ContainerType SubContainer { get; set; }
public override string ToString()
{
return Target2;
}
}
class ClassUnderTest
{
public void MethodWithoutArguments()
{
}
public void MethodWithInputs(int input1, string input2)
{
}
public void MethodWithArrayInputs(int[] input1, string[] input2)
{
}
public void MethodWithInputs(ContainerType subContainer)
{
}
public void MethodWithNullableArg(decimal? nullableInput)
{
}
public Bar Foo { get; set; }
public class Bar
{
public void Baz()
{
}
}
}
List<object> GetArgumentValues(Expression<Action<ClassUnderTest>> action, ClassUnderTest instance)
{
return action.ExtractArguments(instance).Select(o => o.Value).ToList();
}
List<StepArgument> GetArguments(Expression<Action<ClassUnderTest>> action, ClassUnderTest instance)
{
return action.ExtractArguments(instance).ToList();
}
int _input1 = 1;
string _input2 = "2";
const string ConstInput2 = "2";
int[] _arrayInput1 = { 1, 2 };
public string[] _arrayInput2 = { "3", "4" };
public int[] ArrayInput1
{
get
{
return _arrayInput1;
}
}
string[] ArrayInput2
{
get
{
return _arrayInput2;
}
}
int Input1 { get { return _input1; } }
public string Input2 { get { return _input2; } }
int GetInput1(int someInput)
{
return someInput + 10;
}
string GetInput2(string someInput)
{
return someInput + " Input 2";
}
ContainerType container = new ContainerType();
[Fact]
public void NoArguments()
{
var arguments = GetArgumentValues(x => x.MethodWithoutArguments(), new ClassUnderTest());
arguments.Count.ShouldBe(0);
}
void AssertReturnedArguments(List<object> arguments, params object[] expectedArgs)
{
arguments.Count.ShouldBe(expectedArgs.Length);
for (int i = 0; i < expectedArgs.Length; i++)
{
arguments[i].ShouldBe(expectedArgs[i]);
}
}
[Fact]
public void InputArgumentsPassedInline()
{
var arguments = GetArgumentValues(x => x.MethodWithInputs(1, "2"), new ClassUnderTest());
AssertReturnedArguments(arguments, 1, "2");
}
[Fact]
public void InputArgumentsProvidedUsingVariables()
{
int input1 = 1;
const string input2 = "2";
var arguments = GetArgumentValues(x => x.MethodWithInputs(input1, input2), new ClassUnderTest());
AssertReturnedArguments(arguments, input1, input2);
}
[Fact]
public void InputArgumentsProvidedUsingFields()
{
var arguments = GetArgumentValues(x => x.MethodWithInputs(_input1, ConstInput2), new ClassUnderTest());
AssertReturnedArguments(arguments, _input1, ConstInput2);
}
[Fact]
public void InputArgumentsProvidedWhenCastIsInvolved()
{
// For some reason default(decimal) will cause a different expression when passing to a nullable method than
// if we have input1 = 1m; No idea why...
var input1 = default(decimal);
var arguments = GetArguments(x => x.MethodWithNullableArg(input1), new ClassUnderTest());
input1 = 1;
AssertReturnedArguments(arguments.Select(a => a.Value).ToList(), input1);
}
[Fact]
public void InputArgWithImplicitCast()
{
int input1 = 1;
var arguments = GetArgumentValues(x => x.MethodWithNullableArg(input1), new ClassUnderTest());
AssertReturnedArguments(arguments, input1);
}
[Fact]
public void InputArgumentsProvidedUsingProperty()
{
var arguments = GetArgumentValues(x => x.MethodWithInputs(Input1, Input2), new ClassUnderTest());
AssertReturnedArguments(arguments, Input1, Input2);
}
[Fact]
public void InputArgumentsProvidedUsingInheritedFields()
{
var arguments = GetArgumentValues(x => x.MethodWithInputs(InheritedInput1, InheritedInput2), new ClassUnderTest());
AssertReturnedArguments(arguments, InheritedInput1, InheritedInput2);
}
[Fact]
public void InputArgumentsProvidedUsingMethodCallDoesNotThrow()
{
Should.NotThrow(() => GetArgumentValues(x => x.MethodWithInputs(GetInput1(10), GetInput2("Test")), new ClassUnderTest()));
}
[Fact]
public void ArrayInputsArgumentsProvidedInline()
{
var arguments = GetArgumentValues(x => x.MethodWithArrayInputs(new[] { 1, 2 }, new[] { "3", "4" }), new ClassUnderTest());
AssertReturnedArguments(arguments, new[] { 1, 2 }, new[] { "3", "4" });
}
[Fact]
public void ArrayInputArgumentsProvidedUsingVariables()
{
var input1 = new[] { 1, 2 };
var input2 = new[] { "3", "4" };
var arguments = GetArgumentValues(x => x.MethodWithArrayInputs(input1, input2), new ClassUnderTest());
AssertReturnedArguments(arguments, input1, input2);
}
[Fact]
public void ArrayInputArgumentsProvidedUsingFields()
{
var arguments = GetArgumentValues(x => x.MethodWithArrayInputs(_arrayInput1, _arrayInput2), new ClassUnderTest());
AssertReturnedArguments(arguments, _arrayInput1, _arrayInput2);
}
[Fact]
public void ArrayInputArgumentsProvidedUsingProperty()
{
var arguments = GetArgumentValues(x => x.MethodWithArrayInputs(ArrayInput1, ArrayInput2), new ClassUnderTest());
AssertReturnedArguments(arguments, ArrayInput1, ArrayInput2);
}
[Fact]
public void ComplexArgument()
{
container.Target = 1;
container.SubContainer = new ContainerType { Target2 = "Foo" };
var arguments = GetArgumentValues(x => x.MethodWithInputs(container.Target, container.SubContainer.Target2), new ClassUnderTest());
AssertReturnedArguments(arguments, 1, "Foo");
}
[Fact]
public void ComplexArgumentMethodCall()
{
container.Target = 1;
container.SubContainer = new ContainerType { Target2 = "Foo" };
var arguments = GetArgumentValues(x => x.MethodWithInputs(container.Target, container.SubContainer.ToString()), new ClassUnderTest());
AssertReturnedArguments(arguments, 1, "Foo");
}
[Fact]
public void ComplexArgument2()
{
container.SubContainer = new ContainerType { Target2 = "Foo" };
var arguments = GetArgumentValues(x => x.MethodWithInputs(container.SubContainer), new ClassUnderTest());
AssertReturnedArguments(arguments, container.SubContainer);
}
[Fact]
public void ComplexArgumentWhenContainerIsNull()
{
ContainerType nullContainer = null;
var arguments = GetArgumentValues(x => x.MethodWithInputs(nullContainer.SubContainer), new ClassUnderTest());
AssertReturnedArguments(arguments, new object[] { null });
}
[Fact]
public void MethodCallValue()
{
var arguments = GetArgumentValues(x => x.MethodWithInputs(GetNumberThree(), GetFooString()), new ClassUnderTest());
AssertReturnedArguments(arguments, new object[] { 3, "Foo" });
}
[Fact]
public void DeepPropertyCall()
{
var arguments = GetArgumentValues(x => x.Foo.Baz(), new ClassUnderTest());
arguments.ShouldBeEmpty();
}
private string GetFooString()
{
return "Foo";
}
private int GetNumberThree()
{
return 3;
}
[Fact]
public void ArrayInputArgumentsProvidedUsingInheritedProperty()
{
var arguments = GetArgumentValues(x => x.MethodWithArrayInputs(InheritedArrayInput1, InheritedArrayInput2), new ClassUnderTest());
AssertReturnedArguments(arguments, InheritedArrayInput1, InheritedArrayInput2);
}
[Fact]
public void StaticField()
{
Should.NotThrow(() => GetArgumentValues(x => x.MethodWithInputs(GetInput1(10), GetInput2(string.Empty)), new ClassUnderTest()));
}
}
}
| |
//
// JsonSerializer.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2008 Novell, Inc. http://novell.com/
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Nancy.Json
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Nancy.Extensions;
internal sealed class JsonSerializer
{
internal static readonly long InitialJavaScriptDateTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
static readonly DateTime MinimumJavaScriptDate = new DateTime(100, 1, 1, 0, 0, 0, DateTimeKind.Utc);
static readonly MethodInfo serializeGenericDictionary = typeof(JsonSerializer).GetMethod("SerializeGenericDictionary", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary <object, bool> objectCache;
JavaScriptSerializer serializer;
JavaScriptTypeResolver typeResolver;
int recursionLimit;
int maxJsonLength;
int recursionDepth;
bool retainCasing;
bool iso8601DateFormat;
Dictionary <Type, MethodInfo> serializeGenericDictionaryMethods;
public JsonSerializer (JavaScriptSerializer serializer)
{
if (serializer == null)
throw new ArgumentNullException ("serializer");
this.serializer = serializer;
typeResolver = serializer.TypeResolver;
recursionLimit = serializer.RecursionLimit;
maxJsonLength = serializer.MaxJsonLength;
retainCasing = serializer.RetainCasing;
iso8601DateFormat = serializer.ISO8601DateFormat;
}
public void Serialize (object obj, StringBuilder output)
{
if (output == null)
throw new ArgumentNullException ("output");
DoSerialize (obj, output);
}
public void Serialize (object obj, TextWriter output)
{
if (output == null)
throw new ArgumentNullException ("output");
StringBuilder sb = new StringBuilder ();
DoSerialize (obj, sb);
output.Write (sb.ToString ());
}
void DoSerialize (object obj, StringBuilder output)
{
recursionDepth = 0;
objectCache = new Dictionary <object, bool> ();
SerializeValue (obj, output);
}
void SerializeValue (object obj, StringBuilder output)
{
recursionDepth++;
SerializeValueImpl (obj, output);
recursionDepth--;
}
void SerializeValueImpl (object obj, StringBuilder output)
{
if (recursionDepth > recursionLimit)
throw new ArgumentException ("Recursion limit has been exceeded while serializing object of type '{0}'", obj != null ? obj.GetType ().ToString () : "[null]");
if (obj == null || DBNull.Value.Equals (obj)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
#if !__MonoCS__
if (obj.GetType().Name == "RuntimeType")
{
obj = obj.ToString();
}
#else
if (obj.GetType().Name == "MonoType")
{
obj = obj.ToString();
}
#endif
Type valueType = obj.GetType ();
JavaScriptConverter jsc = serializer.GetConverter (valueType);
if (jsc != null) {
IDictionary <string, object> result = jsc.Serialize (obj, serializer);
if (result == null) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (valueType);
if (!string.IsNullOrEmpty(typeId))
result [JavaScriptSerializer.SerializedTypeNameKey] = typeId;
}
SerializeValue (result, output);
return;
}
JavaScriptPrimitiveConverter jscp = serializer.GetPrimitiveConverter (valueType);
if (jscp != null) {
obj = jscp.Serialize (obj, serializer);
if (obj == null || DBNull.Value.Equals (obj)) {
// Recurse in order that there be one place in the code that handles null values.
SerializeValueImpl (obj, output);
return;
}
valueType = obj.GetType ();
}
TypeCode typeCode = Type.GetTypeCode (valueType);
switch (typeCode) {
case TypeCode.String:
WriteValue (output, (string)obj);
return;
case TypeCode.Char:
WriteValue (output, (char)obj);
return;
case TypeCode.Boolean:
WriteValue (output, (bool)obj);
return;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
if (valueType.IsEnum) {
WriteEnumValue (output, obj, typeCode);
return;
}
goto case TypeCode.Decimal;
case TypeCode.Single:
WriteValue (output, (float)obj);
return;
case TypeCode.Double:
WriteValue (output, (double)obj);
return;
case TypeCode.Decimal:
WriteValue (output, obj as IConvertible);
return;
case TypeCode.DateTime:
WriteValue (output, (DateTime)obj);
return;
}
if (typeof (Uri).IsAssignableFrom (valueType)) {
WriteValue (output, (Uri)obj);
return;
}
if (typeof (Guid).IsAssignableFrom (valueType)) {
WriteValue (output, (Guid)obj);
return;
}
if (valueType == typeof(DateTimeOffset))
{
WriteValue(output, (DateTimeOffset)obj);
return;
}
if (typeof (DynamicDictionaryValue).IsAssignableFrom(valueType))
{
var o = (DynamicDictionaryValue) obj;
SerializeValue(o.Value, output);
return;
}
IConvertible convertible = obj as IConvertible;
if (convertible != null) {
WriteValue (output, convertible);
return;
}
try {
if (objectCache.ContainsKey (obj))
throw new InvalidOperationException ("Circular reference detected.");
objectCache.Add (obj, true);
Type closedIDict = GetClosedIDictionaryBase(valueType);
if (closedIDict != null) {
if (serializeGenericDictionaryMethods == null)
serializeGenericDictionaryMethods = new Dictionary <Type, MethodInfo> ();
MethodInfo mi;
if (!serializeGenericDictionaryMethods.TryGetValue (closedIDict, out mi)) {
Type[] types = closedIDict.GetGenericArguments ();
mi = serializeGenericDictionary.MakeGenericMethod (types [0], types [1]);
serializeGenericDictionaryMethods.Add (closedIDict, mi);
}
mi.Invoke (this, new object[] {output, obj});
return;
}
IDictionary dict = obj as IDictionary;
if (dict != null) {
SerializeDictionary (output, dict);
return;
}
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null) {
SerializeEnumerable (output, enumerable);
return;
}
SerializeArbitraryObject (output, obj, valueType);
} finally {
objectCache.Remove (obj);
}
}
Type GetClosedIDictionaryBase(Type t) {
if(t.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (t.GetGenericTypeDefinition ()))
return t;
foreach(Type iface in t.GetInterfaces()) {
if(iface.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (iface.GetGenericTypeDefinition ()))
return iface;
}
return null;
}
bool ShouldIgnoreMember (MemberInfo mi, out MethodInfo getMethod)
{
getMethod = null;
if (mi == null)
return true;
if (mi.GetCustomAttributes(true).Any(a => a.GetType().Name == "ScriptIgnoreAttribute"))
return true;
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return false;
PropertyInfo pi = mi as PropertyInfo;
if (pi == null)
return true;
getMethod = pi.GetGetMethod ();
if (getMethod == null || getMethod.GetParameters ().Length > 0) {
getMethod = null;
return true;
}
return false;
}
object GetMemberValue (object obj, MemberInfo mi)
{
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (obj);
MethodInfo method = mi as MethodInfo;
if (method == null)
throw new InvalidOperationException ("Member is not a method (internal error).");
object ret;
try {
ret = method.Invoke (obj, null);
} catch (TargetInvocationException niex) {
if (niex.InnerException is NotImplementedException) {
Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!");
Console.WriteLine (niex);
Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!");
return null;
}
throw;
}
return ret;
}
void SerializeArbitraryObject (StringBuilder output, object obj, Type type)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (type);
if (!string.IsNullOrEmpty (typeId))
{
WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId);
first = false;
}
}
SerializeMembers <FieldInfo> (type.GetFields (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
SerializeMembers <PropertyInfo> (type.GetProperties (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeMembers <T> (T[] members, object obj, StringBuilder output, ref bool first) where T: MemberInfo
{
MemberInfo member;
MethodInfo getMethod;
foreach (T mi in members)
{
if (ShouldIgnoreMember (mi as MemberInfo, out getMethod))
continue;
if (getMethod != null)
member = getMethod;
else
member = mi;
WriteDictionaryEntry (output, first, mi.Name, GetMemberValue (obj, member));
if (first)
first = false;
}
}
void SerializeEnumerable (StringBuilder output, IEnumerable enumerable)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "[");
bool first = true;
foreach (object value in enumerable) {
if (!first)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
SerializeValue (value, output);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "]");
}
void SerializeDictionary (StringBuilder output, IDictionary dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (DictionaryEntry entry in dict) {
WriteDictionaryEntry (output, first, entry.Key as string, entry.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (KeyValuePair <TKey, TValue> kvp in dict)
{
var key = typeof(TKey) == typeof(Guid) ? kvp.Key.ToString() : kvp.Key as string;
WriteDictionaryEntry (output, first, key, kvp.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value)
{
if (key == null)
throw new InvalidOperationException ("Only dictionaries with keys convertible to string, or guid keys are supported.");
if (!skipComma)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
key = retainCasing ? key : key.ToCamelCase();
WriteValue(output, key);
StringBuilderExtensions.AppendCount (output, maxJsonLength, ':');
SerializeValue (value, output);
}
void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode)
{
switch (typeCode) {
case TypeCode.SByte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (sbyte)value);
return;
case TypeCode.Int16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (short)value);
return;
case TypeCode.UInt16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ushort)value);
return;
case TypeCode.Int32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (int)value);
return;
case TypeCode.Byte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (byte)value);
return;
case TypeCode.UInt32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (uint)value);
return;
case TypeCode.Int64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (long)value);
return;
case TypeCode.UInt64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ulong)value);
return;
default:
throw new InvalidOperationException (string.Format("Invalid type code for enum: {0}", typeCode));
}
}
void WriteValue (StringBuilder output, float value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r",Json.DefaultNumberFormatInfo));
}
void WriteValue (StringBuilder output, double value)
{
StringBuilderExtensions.AppendCount(output, maxJsonLength, value.ToString("r",Json.DefaultNumberFormatInfo));
}
void WriteValue (StringBuilder output, Guid value)
{
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, Uri value)
{
WriteValue (output, value.GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped));
}
void WriteValue (StringBuilder output, DateTime value)
{
if (this.iso8601DateFormat)
{
if (value.Kind == DateTimeKind.Unspecified)
{
// To avoid confusion, treat "Unspecified" datetimes as Local -- just like the WCF datetime format does as well.
value = new DateTime(value.Ticks, DateTimeKind.Local);
}
StringBuilderExtensions.AppendCount(output, maxJsonLength, string.Concat("\"", value.ToString("o", CultureInfo.InvariantCulture), "\""));
}
else
{
DateTime time = value.ToUniversalTime();
string suffix = "";
if (value.Kind != DateTimeKind.Utc)
{
TimeSpan localTZOffset;
if (value >= time)
{
localTZOffset = value - time;
suffix = "+";
}
else
{
localTZOffset = time - value;
suffix = "-";
}
suffix += localTZOffset.ToString("hhmm");
}
if (time < MinimumJavaScriptDate)
time = MinimumJavaScriptDate;
long ticks = (time.Ticks - InitialJavaScriptDateTicks)/(long)10000;
StringBuilderExtensions.AppendCount(output, maxJsonLength, "\"\\/Date(" + ticks + suffix + ")\\/\"");
}
}
void WriteValue(StringBuilder output, DateTimeOffset value)
{
StringBuilderExtensions.AppendCount(output, maxJsonLength, string.Concat("\"", value.ToString("o", CultureInfo.InvariantCulture), "\""));
}
void WriteValue (StringBuilder output, IConvertible value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString (CultureInfo.InvariantCulture));
}
void WriteValue (StringBuilder output, bool value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value ? "true" : "false");
}
void WriteValue (StringBuilder output, char value)
{
if (value == '\0') {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, string value)
{
if (string.IsNullOrEmpty (value)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\"");
return;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
char c;
for (int i = 0; i < value.Length; i++) {
c = value [i];
switch (c) {
case '\t':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\t");
break;
case '\n':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\n");
break;
case '\r':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\r");
break;
case '\f':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\f");
break;
case '\b':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\b");
break;
case '<':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003c");
break;
case '>':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003e");
break;
case '"':
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\\\"");
break;
case '\'':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u0027");
break;
case '\\':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\\");
break;
default:
if (c > '\u001f')
StringBuilderExtensions.AppendCount (output, maxJsonLength, c);
else {
output.Append("\\u00");
int intVal = (int) c;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) ('0' + (intVal >> 4)));
intVal &= 0xf;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
}
break;
}
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* 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 = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// ConnectSalesforceField
/// </summary>
[DataContract]
public partial class ConnectSalesforceField : IEquatable<ConnectSalesforceField>, IValidatableObject
{
public ConnectSalesforceField()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectSalesforceField" /> class.
/// </summary>
/// <param name="DsAttribute">DsAttribute.</param>
/// <param name="DsLink">DsLink.</param>
/// <param name="DsNode">DsNode.</param>
/// <param name="Id">Id.</param>
/// <param name="SfField">SfField.</param>
/// <param name="SfFieldName">SfFieldName.</param>
/// <param name="SfFolder">SfFolder.</param>
/// <param name="SfLockedValue">SfLockedValue.</param>
public ConnectSalesforceField(string DsAttribute = default(string), string DsLink = default(string), string DsNode = default(string), string Id = default(string), string SfField = default(string), string SfFieldName = default(string), string SfFolder = default(string), string SfLockedValue = default(string))
{
this.DsAttribute = DsAttribute;
this.DsLink = DsLink;
this.DsNode = DsNode;
this.Id = Id;
this.SfField = SfField;
this.SfFieldName = SfFieldName;
this.SfFolder = SfFolder;
this.SfLockedValue = SfLockedValue;
}
/// <summary>
/// Gets or Sets DsAttribute
/// </summary>
[DataMember(Name="dsAttribute", EmitDefaultValue=false)]
public string DsAttribute { get; set; }
/// <summary>
/// Gets or Sets DsLink
/// </summary>
[DataMember(Name="dsLink", EmitDefaultValue=false)]
public string DsLink { get; set; }
/// <summary>
/// Gets or Sets DsNode
/// </summary>
[DataMember(Name="dsNode", EmitDefaultValue=false)]
public string DsNode { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets SfField
/// </summary>
[DataMember(Name="sfField", EmitDefaultValue=false)]
public string SfField { get; set; }
/// <summary>
/// Gets or Sets SfFieldName
/// </summary>
[DataMember(Name="sfFieldName", EmitDefaultValue=false)]
public string SfFieldName { get; set; }
/// <summary>
/// Gets or Sets SfFolder
/// </summary>
[DataMember(Name="sfFolder", EmitDefaultValue=false)]
public string SfFolder { get; set; }
/// <summary>
/// Gets or Sets SfLockedValue
/// </summary>
[DataMember(Name="sfLockedValue", EmitDefaultValue=false)]
public string SfLockedValue { 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 ConnectSalesforceField {\n");
sb.Append(" DsAttribute: ").Append(DsAttribute).Append("\n");
sb.Append(" DsLink: ").Append(DsLink).Append("\n");
sb.Append(" DsNode: ").Append(DsNode).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" SfField: ").Append(SfField).Append("\n");
sb.Append(" SfFieldName: ").Append(SfFieldName).Append("\n");
sb.Append(" SfFolder: ").Append(SfFolder).Append("\n");
sb.Append(" SfLockedValue: ").Append(SfLockedValue).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ConnectSalesforceField);
}
/// <summary>
/// Returns true if ConnectSalesforceField instances are equal
/// </summary>
/// <param name="other">Instance of ConnectSalesforceField to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ConnectSalesforceField other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.DsAttribute == other.DsAttribute ||
this.DsAttribute != null &&
this.DsAttribute.Equals(other.DsAttribute)
) &&
(
this.DsLink == other.DsLink ||
this.DsLink != null &&
this.DsLink.Equals(other.DsLink)
) &&
(
this.DsNode == other.DsNode ||
this.DsNode != null &&
this.DsNode.Equals(other.DsNode)
) &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.SfField == other.SfField ||
this.SfField != null &&
this.SfField.Equals(other.SfField)
) &&
(
this.SfFieldName == other.SfFieldName ||
this.SfFieldName != null &&
this.SfFieldName.Equals(other.SfFieldName)
) &&
(
this.SfFolder == other.SfFolder ||
this.SfFolder != null &&
this.SfFolder.Equals(other.SfFolder)
) &&
(
this.SfLockedValue == other.SfLockedValue ||
this.SfLockedValue != null &&
this.SfLockedValue.Equals(other.SfLockedValue)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.DsAttribute != null)
hash = hash * 59 + this.DsAttribute.GetHashCode();
if (this.DsLink != null)
hash = hash * 59 + this.DsLink.GetHashCode();
if (this.DsNode != null)
hash = hash * 59 + this.DsNode.GetHashCode();
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.SfField != null)
hash = hash * 59 + this.SfField.GetHashCode();
if (this.SfFieldName != null)
hash = hash * 59 + this.SfFieldName.GetHashCode();
if (this.SfFolder != null)
hash = hash * 59 + this.SfFolder.GetHashCode();
if (this.SfLockedValue != null)
hash = hash * 59 + this.SfLockedValue.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// An message for the attention of the administrator
/// First published in XenServer 5.0.
/// </summary>
public partial class Message : XenObject<Message>
{
#region Constructors
public Message()
{
}
public Message(string uuid,
string name,
long priority,
cls cls,
string obj_uuid,
DateTime timestamp,
string body)
{
this.uuid = uuid;
this.name = name;
this.priority = priority;
this.cls = cls;
this.obj_uuid = obj_uuid;
this.timestamp = timestamp;
this.body = body;
}
/// <summary>
/// Creates a new Message from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Message(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Message from a Proxy_Message.
/// </summary>
/// <param name="proxy"></param>
public Message(Proxy_Message proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Message.
/// </summary>
public override void UpdateFrom(Message record)
{
uuid = record.uuid;
name = record.name;
priority = record.priority;
cls = record.cls;
obj_uuid = record.obj_uuid;
timestamp = record.timestamp;
body = record.body;
}
internal void UpdateFrom(Proxy_Message proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name = proxy.name == null ? null : proxy.name;
priority = proxy.priority == null ? 0 : long.Parse(proxy.priority);
cls = proxy.cls == null ? (cls) 0 : (cls)Helper.EnumParseDefault(typeof(cls), (string)proxy.cls);
obj_uuid = proxy.obj_uuid == null ? null : proxy.obj_uuid;
timestamp = proxy.timestamp;
body = proxy.body == null ? null : proxy.body;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Message
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name"))
name = Marshalling.ParseString(table, "name");
if (table.ContainsKey("priority"))
priority = Marshalling.ParseLong(table, "priority");
if (table.ContainsKey("cls"))
cls = (cls)Helper.EnumParseDefault(typeof(cls), Marshalling.ParseString(table, "cls"));
if (table.ContainsKey("obj_uuid"))
obj_uuid = Marshalling.ParseString(table, "obj_uuid");
if (table.ContainsKey("timestamp"))
timestamp = Marshalling.ParseDateTime(table, "timestamp");
if (table.ContainsKey("body"))
body = Marshalling.ParseString(table, "body");
}
public Proxy_Message ToProxy()
{
Proxy_Message result_ = new Proxy_Message();
result_.uuid = uuid ?? "";
result_.name = name ?? "";
result_.priority = priority.ToString();
result_.cls = cls_helper.ToString(cls);
result_.obj_uuid = obj_uuid ?? "";
result_.timestamp = timestamp;
result_.body = body ?? "";
return result_;
}
public bool DeepEquals(Message other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name, other._name) &&
Helper.AreEqual2(this._priority, other._priority) &&
Helper.AreEqual2(this._cls, other._cls) &&
Helper.AreEqual2(this._obj_uuid, other._obj_uuid) &&
Helper.AreEqual2(this._timestamp, other._timestamp) &&
Helper.AreEqual2(this._body, other._body);
}
public override string SaveChanges(Session session, string opaqueRef, Message server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_name">The name of the message</param>
/// <param name="_priority">The priority of the message</param>
/// <param name="_cls">The class of object this message is associated with</param>
/// <param name="_obj_uuid">The uuid of the object this message is associated with</param>
/// <param name="_body">The body of the message</param>
public static XenRef<Message> create(Session session, string _name, long _priority, cls _cls, string _obj_uuid, string _body)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_create(session.opaque_ref, _name, _priority, _cls, _obj_uuid, _body);
else
return XenRef<Message>.Create(session.XmlRpcProxy.message_create(session.opaque_ref, _name ?? "", _priority.ToString(), cls_helper.ToString(_cls), _obj_uuid ?? "", _body ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_message">The opaque_ref of the given message</param>
public static void destroy(Session session, string _message)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.message_destroy(session.opaque_ref, _message);
else
session.XmlRpcProxy.message_destroy(session.opaque_ref, _message ?? "").parse();
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_cls">The class of object</param>
/// <param name="_obj_uuid">The uuid of the object</param>
/// <param name="_since">The cutoff time</param>
public static Dictionary<XenRef<Message>, Message> get(Session session, cls _cls, string _obj_uuid, DateTime _since)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_get(session.opaque_ref, _cls, _obj_uuid, _since);
else
return XenRef<Message>.Create<Proxy_Message>(session.XmlRpcProxy.message_get(session.opaque_ref, cls_helper.ToString(_cls), _obj_uuid ?? "", _since).parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Message>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_get_all(session.opaque_ref);
else
return XenRef<Message>.Create(session.XmlRpcProxy.message_get_all(session.opaque_ref).parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_since">The cutoff time</param>
public static Dictionary<XenRef<Message>, Message> get_since(Session session, DateTime _since)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_get_since(session.opaque_ref, _since);
else
return XenRef<Message>.Create<Proxy_Message>(session.XmlRpcProxy.message_get_since(session.opaque_ref, _since).parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_message">The opaque_ref of the given message</param>
public static Message get_record(Session session, string _message)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_get_record(session.opaque_ref, _message);
else
return new Message(session.XmlRpcProxy.message_get_record(session.opaque_ref, _message ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">The uuid of the message</param>
public static XenRef<Message> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Message>.Create(session.XmlRpcProxy.message_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Message>, Message> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.message_get_all_records(session.opaque_ref);
else
return XenRef<Message>.Create<Proxy_Message>(session.XmlRpcProxy.message_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// The name of the message
/// </summary>
public virtual string name
{
get { return _name; }
set
{
if (!Helper.AreEqual(value, _name))
{
_name = value;
NotifyPropertyChanged("name");
}
}
}
private string _name = "";
/// <summary>
/// The message priority, 0 being low priority
/// </summary>
public virtual long priority
{
get { return _priority; }
set
{
if (!Helper.AreEqual(value, _priority))
{
_priority = value;
NotifyPropertyChanged("priority");
}
}
}
private long _priority;
/// <summary>
/// The class of the object this message is associated with
/// </summary>
[JsonConverter(typeof(clsConverter))]
public virtual cls cls
{
get { return _cls; }
set
{
if (!Helper.AreEqual(value, _cls))
{
_cls = value;
NotifyPropertyChanged("cls");
}
}
}
private cls _cls;
/// <summary>
/// The uuid of the object this message is associated with
/// </summary>
public virtual string obj_uuid
{
get { return _obj_uuid; }
set
{
if (!Helper.AreEqual(value, _obj_uuid))
{
_obj_uuid = value;
NotifyPropertyChanged("obj_uuid");
}
}
}
private string _obj_uuid = "";
/// <summary>
/// The time at which the message was created
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime timestamp
{
get { return _timestamp; }
set
{
if (!Helper.AreEqual(value, _timestamp))
{
_timestamp = value;
NotifyPropertyChanged("timestamp");
}
}
}
private DateTime _timestamp;
/// <summary>
/// The body of the message
/// </summary>
public virtual string body
{
get { return _body; }
set
{
if (!Helper.AreEqual(value, _body))
{
_body = value;
NotifyPropertyChanged("body");
}
}
}
private string _body = "";
}
}
| |
/*
* 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 elastictranscoder-2012-09-25.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.ElasticTranscoder.Model;
namespace Amazon.ElasticTranscoder
{
/// <summary>
/// Interface for accessing ElasticTranscoder
///
/// AWS Elastic Transcoder Service
/// <para>
/// The AWS Elastic Transcoder Service.
/// </para>
/// </summary>
public partial interface IAmazonElasticTranscoder : IDisposable
{
#region CancelJob
/// <summary>
/// The CancelJob operation cancels an unfinished job.
///
/// <note>You can only cancel a job that has a status of <code>Submitted</code>. To prevent
/// a pipeline from starting to process a job while you're getting the job identifier,
/// use <a>UpdatePipelineStatus</a> to temporarily pause the pipeline.</note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CancelJob service method.</param>
///
/// <returns>The response from the CancelJob service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceInUseException">
/// The resource you are attempting to change is in use. For example, you are attempting
/// to delete a pipeline that is currently in use.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
CancelJobResponse CancelJob(CancelJobRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CancelJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CancelJob operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CancelJobResponse> CancelJobAsync(CancelJobRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateJob
/// <summary>
/// When you create a job, Elastic Transcoder returns JSON data that includes the values
/// that you specified plus information about the job that is created.
///
///
/// <para>
/// If you have specified more than one output for your jobs (for example, one output
/// for the Kindle Fire and another output for the Apple iPhone 4s), you currently must
/// use the Elastic Transcoder API to list the jobs (as opposed to the AWS Console).
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateJob service method.</param>
///
/// <returns>The response from the CreateJob service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.LimitExceededException">
/// Too many operations for a given AWS account. For example, the number of pipelines
/// exceeds the maximum allowed.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
CreateJobResponse CreateJob(CreateJobRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateJob operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateJobResponse> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreatePipeline
/// <summary>
/// The CreatePipeline operation creates a pipeline with settings that you specify.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePipeline service method.</param>
///
/// <returns>The response from the CreatePipeline service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.LimitExceededException">
/// Too many operations for a given AWS account. For example, the number of pipelines
/// exceeds the maximum allowed.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
CreatePipelineResponse CreatePipeline(CreatePipelineRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreatePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreatePipeline operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreatePipelineResponse> CreatePipelineAsync(CreatePipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreatePreset
/// <summary>
/// The CreatePreset operation creates a preset with settings that you specify.
///
/// <important>Elastic Transcoder checks the CreatePreset settings to ensure that they
/// meet Elastic Transcoder requirements and to determine whether they comply with H.264
/// standards. If your settings are not valid for Elastic Transcoder, Elastic Transcoder
/// returns an HTTP 400 response (<code>ValidationException</code>) and does not create
/// the preset. If the settings are valid for Elastic Transcoder but aren't strictly compliant
/// with the H.264 standard, Elastic Transcoder creates the preset and returns a warning
/// message in the response. This helps you determine whether your settings comply with
/// the H.264 standard while giving you greater flexibility with respect to the video
/// that Elastic Transcoder produces.</important>
/// <para>
/// Elastic Transcoder uses the H.264 video-compression format. For more information,
/// see the International Telecommunication Union publication <i>Recommendation ITU-T
/// H.264: Advanced video coding for generic audiovisual services</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePreset service method.</param>
///
/// <returns>The response from the CreatePreset service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.LimitExceededException">
/// Too many operations for a given AWS account. For example, the number of pipelines
/// exceeds the maximum allowed.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
CreatePresetResponse CreatePreset(CreatePresetRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreatePreset operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreatePreset operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreatePresetResponse> CreatePresetAsync(CreatePresetRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeletePipeline
/// <summary>
/// The DeletePipeline operation removes a pipeline.
///
///
/// <para>
/// You can only delete a pipeline that has never been used or that is not currently
/// in use (doesn't contain any active jobs). If the pipeline is currently in use, <code>DeletePipeline</code>
/// returns an error.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePipeline service method.</param>
///
/// <returns>The response from the DeletePipeline service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceInUseException">
/// The resource you are attempting to change is in use. For example, you are attempting
/// to delete a pipeline that is currently in use.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
DeletePipelineResponse DeletePipeline(DeletePipelineRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeletePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeletePipeline operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeletePipelineResponse> DeletePipelineAsync(DeletePipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeletePreset
/// <summary>
/// The DeletePreset operation removes a preset that you've added in an AWS region.
///
/// <note>
/// <para>
/// You can't delete the default presets that are included with Elastic Transcoder.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePreset service method.</param>
///
/// <returns>The response from the DeletePreset service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
DeletePresetResponse DeletePreset(DeletePresetRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeletePreset operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeletePreset operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeletePresetResponse> DeletePresetAsync(DeletePresetRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListJobsByPipeline
/// <summary>
/// The ListJobsByPipeline operation gets a list of the jobs currently in a pipeline.
///
///
/// <para>
/// Elastic Transcoder returns all of the jobs currently in the specified pipeline. The
/// response body contains one element for each job that satisfies the search criteria.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListJobsByPipeline service method.</param>
///
/// <returns>The response from the ListJobsByPipeline service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ListJobsByPipelineResponse ListJobsByPipeline(ListJobsByPipelineRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListJobsByPipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListJobsByPipeline operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListJobsByPipelineResponse> ListJobsByPipelineAsync(ListJobsByPipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListJobsByStatus
/// <summary>
/// The ListJobsByStatus operation gets a list of jobs that have a specified status. The
/// response body contains one element for each job that satisfies the search criteria.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListJobsByStatus service method.</param>
///
/// <returns>The response from the ListJobsByStatus service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ListJobsByStatusResponse ListJobsByStatus(ListJobsByStatusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListJobsByStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListJobsByStatus operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListJobsByStatusResponse> ListJobsByStatusAsync(ListJobsByStatusRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPipelines
/// <summary>
/// The ListPipelines operation gets a list of the pipelines associated with the current
/// AWS account.
/// </summary>
///
/// <returns>The response from the ListPipelines service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ListPipelinesResponse ListPipelines();
/// <summary>
/// The ListPipelines operation gets a list of the pipelines associated with the current
/// AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPipelines service method.</param>
///
/// <returns>The response from the ListPipelines service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ListPipelinesResponse ListPipelines(ListPipelinesRequest request);
/// <summary>
/// The ListPipelines operation gets a list of the pipelines associated with the current
/// AWS account.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListPipelines service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
Task<ListPipelinesResponse> ListPipelinesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the ListPipelines operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListPipelines operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListPipelinesResponse> ListPipelinesAsync(ListPipelinesRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPresets
/// <summary>
/// The ListPresets operation gets a list of the default presets included with Elastic
/// Transcoder and the presets that you've added in an AWS region.
/// </summary>
///
/// <returns>The response from the ListPresets service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ListPresetsResponse ListPresets();
/// <summary>
/// The ListPresets operation gets a list of the default presets included with Elastic
/// Transcoder and the presets that you've added in an AWS region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPresets service method.</param>
///
/// <returns>The response from the ListPresets service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ListPresetsResponse ListPresets(ListPresetsRequest request);
/// <summary>
/// The ListPresets operation gets a list of the default presets included with Elastic
/// Transcoder and the presets that you've added in an AWS region.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListPresets service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
Task<ListPresetsResponse> ListPresetsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the ListPresets operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListPresets operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListPresetsResponse> ListPresetsAsync(ListPresetsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ReadJob
/// <summary>
/// The ReadJob operation returns detailed information about a job.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ReadJob service method.</param>
///
/// <returns>The response from the ReadJob service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ReadJobResponse ReadJob(ReadJobRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ReadJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ReadJob operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ReadJobResponse> ReadJobAsync(ReadJobRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ReadPipeline
/// <summary>
/// The ReadPipeline operation gets detailed information about a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ReadPipeline service method.</param>
///
/// <returns>The response from the ReadPipeline service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ReadPipelineResponse ReadPipeline(ReadPipelineRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ReadPipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ReadPipeline operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ReadPipelineResponse> ReadPipelineAsync(ReadPipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ReadPreset
/// <summary>
/// The ReadPreset operation gets detailed information about a preset.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ReadPreset service method.</param>
///
/// <returns>The response from the ReadPreset service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
ReadPresetResponse ReadPreset(ReadPresetRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ReadPreset operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ReadPreset operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ReadPresetResponse> ReadPresetAsync(ReadPresetRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region TestRole
/// <summary>
/// The TestRole operation tests the IAM role used to create the pipeline.
///
///
/// <para>
/// The <code>TestRole</code> action lets you determine whether the IAM role you are using
/// has sufficient permissions to let Elastic Transcoder perform tasks associated with
/// the transcoding process. The action attempts to assume the specified IAM role, checks
/// read access to the input and output buckets, and tries to send a test notification
/// to Amazon SNS topics that you specify.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestRole service method.</param>
///
/// <returns>The response from the TestRole service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
TestRoleResponse TestRole(TestRoleRequest request);
/// <summary>
/// Initiates the asynchronous execution of the TestRole operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TestRole operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<TestRoleResponse> TestRoleAsync(TestRoleRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdatePipeline
/// <summary>
/// Use the <code>UpdatePipeline</code> operation to update settings for a pipeline.
/// <important>When you change pipeline settings, your changes take effect immediately.
/// Jobs that you have already submitted and that Elastic Transcoder has not started to
/// process are affected in addition to jobs that you submit after you change settings.
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdatePipeline service method.</param>
///
/// <returns>The response from the UpdatePipeline service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceInUseException">
/// The resource you are attempting to change is in use. For example, you are attempting
/// to delete a pipeline that is currently in use.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
UpdatePipelineResponse UpdatePipeline(UpdatePipelineRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdatePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdatePipeline operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdatePipelineResponse> UpdatePipelineAsync(UpdatePipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdatePipelineNotifications
/// <summary>
/// With the UpdatePipelineNotifications operation, you can update Amazon Simple Notification
/// Service (Amazon SNS) notifications for a pipeline.
///
///
/// <para>
/// When you update notifications for a pipeline, Elastic Transcoder returns the values
/// that you specified in the request.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdatePipelineNotifications service method.</param>
///
/// <returns>The response from the UpdatePipelineNotifications service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceInUseException">
/// The resource you are attempting to change is in use. For example, you are attempting
/// to delete a pipeline that is currently in use.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
UpdatePipelineNotificationsResponse UpdatePipelineNotifications(UpdatePipelineNotificationsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdatePipelineNotifications operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdatePipelineNotifications operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdatePipelineNotificationsResponse> UpdatePipelineNotificationsAsync(UpdatePipelineNotificationsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdatePipelineStatus
/// <summary>
/// The UpdatePipelineStatus operation pauses or reactivates a pipeline, so that the pipeline
/// stops or restarts the processing of jobs.
///
///
/// <para>
/// Changing the pipeline status is useful if you want to cancel one or more jobs. You
/// can't cancel jobs after Elastic Transcoder has started processing them; if you pause
/// the pipeline to which you submitted the jobs, you have more time to get the job IDs
/// for the jobs that you want to cancel, and to send a <a>CancelJob</a> request.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdatePipelineStatus service method.</param>
///
/// <returns>The response from the UpdatePipelineStatus service method, as returned by ElasticTranscoder.</returns>
/// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException">
/// General authentication failure. The request was not signed correctly.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException">
///
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException">
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the
/// request.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceInUseException">
/// The resource you are attempting to change is in use. For example, you are attempting
/// to delete a pipeline that is currently in use.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ResourceNotFoundException">
/// The requested resource does not exist or is not available. For example, the pipeline
/// to which you're trying to add a job doesn't exist or is still being created.
/// </exception>
/// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException">
/// One or more required parameter values were not provided in the request.
/// </exception>
UpdatePipelineStatusResponse UpdatePipelineStatus(UpdatePipelineStatusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdatePipelineStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdatePipelineStatus operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdatePipelineStatusResponse> UpdatePipelineStatusAsync(UpdatePipelineStatusRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
using System.Numerics;
namespace Neo.SmartContract.Framework.Services.Neo
{
public static class Storage
{
/// <summary>
/// Returns current StorageContext
/// </summary>
public static extern StorageContext CurrentContext
{
[Syscall("System.Storage.GetContext")]
get;
}
/// <summary>
/// Returns current read only StorageContext
/// </summary>
public static extern StorageContext CurrentReadOnlyContext
{
[Syscall("System.Storage.GetReadOnlyContext")]
get;
}
/// <summary>
/// Returns the byte[] value corresponding to given byte[] key for Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Get")]
public static extern byte[] Get(StorageContext context, byte[] key);
/// <summary>
/// Returns the byte[] value corresponding to given string key for Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Get")]
public static extern byte[] Get(StorageContext context, string key);
/// <summary>
/// Writes byte[] value on byte[] key for given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Put")]
public static extern void Put(StorageContext context, byte[] key, byte[] value);
/// <summary>
/// Writes BigInteger value on byte[] key for given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Put")]
public static extern void Put(StorageContext context, byte[] key, BigInteger value);
/// <summary>
/// Writes string value on byte[] key for given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Put")]
public static extern void Put(StorageContext context, byte[] key, string value);
/// <summary>
/// Writes byte[] value on string key for given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Put")]
public static extern void Put(StorageContext context, string key, byte[] value);
/// <summary>
/// Writes BigInteger value on string key for given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Put")]
public static extern void Put(StorageContext context, string key, BigInteger value);
/// <summary>
/// Writes string value on string key for given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Put")]
public static extern void Put(StorageContext context, string key, string value);
/// <summary>
/// Deletes byte[] key from given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Delete")]
public static extern void Delete(StorageContext context, byte[] key);
/// <summary>
/// Deletes string key from given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Delete")]
public static extern void Delete(StorageContext context, string key);
/// <summary>
/// Returns a byte[] to byte[] iterator for a byte[] prefix on a given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Find")]
public static extern Iterator<byte[], byte[]> Find(StorageContext context, byte[] prefix);
/// <summary>
/// Returns a string to byte[] iterator for a string prefix on a given Storage context (faster: generates opcode directly)
/// </summary>
[Syscall("System.Storage.Find")]
public static extern Iterator<string, byte[]> Find(StorageContext context, string prefix);
/// <summary>
/// Returns the byte[] value corresponding to given byte[] key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Get")]
public static extern byte[] Get(byte[] key);
/// <summary>
/// Returns the byte[] value corresponding to given string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Get")]
public static extern byte[] Get(string key);
/// <summary>
/// Writes byte[] value on byte[] key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Put")]
public static extern void Put(byte[] key, byte[] value);
/// <summary>
/// Writes BigInteger value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.PutEx")]
public static extern void PutEx(byte[] key, byte[] value, StorageFlags flags);
/// <summary>
/// Writes BigInteger value on byte[] key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Put")]
public static extern void Put(byte[] key, BigInteger value);
/// <summary>
/// Writes BigInteger value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.PutEx")]
public static extern void PutEx(byte[] key, BigInteger value, StorageFlags flags);
/// <summary>
/// Writes string value on byte[] key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Put")]
public static extern void Put(byte[] key, string value);
/// <summary>
/// Writes BigInteger value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.PutEx")]
public static extern void PutEx(byte[] key, string value, StorageFlags flags);
/// <summary>
/// Writes byte[] value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Put")]
public static extern void Put(string key, byte[] value);
/// <summary>
/// Writes BigInteger value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.PutEx")]
public static extern void PutEx(string key, byte[] value, StorageFlags flags);
/// <summary>
/// Writes BigInteger value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Put")]
public static extern void Put(string key, BigInteger value);
/// <summary>
/// Writes BigInteger value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.PutEx")]
public static extern void PutEx(string key, BigInteger value, StorageFlags flags);
/// <summary>
/// Writes string value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Put")]
public static extern void Put(string key, string value);
/// <summary>
/// Writes string value on string key for current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.PutEx")]
public static extern void PutEx(string key, string value, StorageFlags flags);
/// <summary>
/// Deletes byte[] key from current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Delete")]
public static extern void Delete(byte[] key);
/// <summary>
/// Deletes string key from given Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Delete")]
public static extern void Delete(string key);
/// <summary>
/// Returns a byte[] to byte[] iterator for a byte[] prefix on current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Find")]
public static extern Iterator<byte[], byte[]> Find(byte[] prefix);
/// <summary>
/// Returns a string to byte[] iterator for a string prefix on current Storage context
/// </summary>
[Syscall("System.Storage.GetContext")]
[Syscall("System.Storage.Find")]
public static extern Iterator<string, byte[]> Find(string prefix);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Specialized;
using System.Text;
namespace System.Runtime
{
//copied from System.Web.HttpUtility code (renamed here) to remove dependency on System.Web.dll
internal static class UrlUtility
{
private static Encoding s_asciiEncoding;
private static Encoding AsciiEncoding
{
get
{
if (s_asciiEncoding == null)
{
s_asciiEncoding = Encoding.GetEncoding("ascii");
}
return s_asciiEncoding;
}
}
// Query string parsing support
public static NameValueCollection ParseQueryString(string query)
{
return ParseQueryString(query, Encoding.UTF8);
}
public static NameValueCollection ParseQueryString(string query, Encoding encoding)
{
if (query == null)
{
throw Fx.Exception.ArgumentNull("query");
}
if (encoding == null)
{
throw Fx.Exception.ArgumentNull("encoding");
}
if (query.Length > 0 && query[0] == '?')
{
query = query.Substring(1);
}
return new HttpValueCollection(query, encoding);
}
public static string UrlEncode(string str)
{
if (str == null)
{
return null;
}
return UrlEncode(str, Encoding.UTF8);
}
// URL encodes a path portion of a URL string and returns the encoded string.
public static string UrlPathEncode(string str)
{
if (str == null)
{
return null;
}
// recurse in case there is a query string
int i = str.IndexOf('?');
if (i >= 0)
{
return UrlPathEncode(str.Substring(0, i)) + str.Substring(i);
}
// encode DBCS characters and spaces only
return UrlEncodeSpaces(UrlEncodeNonAscii(str, Encoding.UTF8));
}
public static string UrlEncode(string str, Encoding encoding)
{
if (str == null)
{
return null;
}
var bytes = UrlEncodeToBytes(str, encoding);
return AsciiEncoding.GetString(bytes, 0, bytes.Length);
}
public static string UrlEncodeUnicode(string str)
{
if (str == null)
{
return null;
}
return UrlEncodeUnicodeStringToStringInternal(str, false);
}
private static string UrlEncodeUnicodeStringToStringInternal(string s, bool ignoreAscii)
{
int l = s.Length;
StringBuilder sb = new StringBuilder(l);
for (int i = 0; i < l; i++)
{
char ch = s[i];
if ((ch & 0xff80) == 0)
{ // 7 bit?
if (ignoreAscii || IsSafe(ch))
{
sb.Append(ch);
}
else if (ch == ' ')
{
sb.Append('+');
}
else
{
sb.Append('%');
sb.Append(IntToHex((ch >> 4) & 0xf));
sb.Append(IntToHex((ch) & 0xf));
}
}
else
{ // arbitrary Unicode?
sb.Append("%u");
sb.Append(IntToHex((ch >> 12) & 0xf));
sb.Append(IntToHex((ch >> 8) & 0xf));
sb.Append(IntToHex((ch >> 4) & 0xf));
sb.Append(IntToHex((ch) & 0xf));
}
}
return sb.ToString();
}
// Helper to encode the non-ASCII url characters only
private static string UrlEncodeNonAscii(string str, Encoding e)
{
if (string.IsNullOrEmpty(str))
{
return str;
}
if (e == null)
{
e = Encoding.UTF8;
}
byte[] bytes = e.GetBytes(str);
bytes = UrlEncodeBytesToBytesInternalNonAscii(bytes, 0, bytes.Length, false);
return AsciiEncoding.GetString(bytes, 0, bytes.Length);
}
// Helper to encode spaces only
private static string UrlEncodeSpaces(string str)
{
if (str != null && str.IndexOf(' ') >= 0)
{
str = str.Replace(" ", "%20");
}
return str;
}
public static byte[] UrlEncodeToBytes(string str, Encoding e)
{
if (str == null)
{
return null;
}
byte[] bytes = e.GetBytes(str);
return UrlEncodeBytesToBytesInternal(bytes, 0, bytes.Length, false);
}
public static string UrlDecode(string str, Encoding e)
{
if (str == null)
{
return null;
}
return UrlDecodeStringFromStringInternal(str, e);
}
// Implementation for encoding
private static byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
{
int cSpaces = 0;
int cUnsafe = 0;
// count them first
for (int i = 0; i < count; i++)
{
char ch = (char)bytes[offset + i];
if (ch == ' ')
{
cSpaces++;
}
else if (!IsSafe(ch))
{
cUnsafe++;
}
}
// nothing to expand?
if (!alwaysCreateReturnValue && cSpaces == 0 && cUnsafe == 0)
{
return bytes;
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + cUnsafe * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[offset + i];
char ch = (char)b;
if (IsSafe(ch))
{
expandedBytes[pos++] = b;
}
else if (ch == ' ')
{
expandedBytes[pos++] = (byte)'+';
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)IntToHex(b & 0x0f);
}
}
return expandedBytes;
}
private static bool IsNonAsciiByte(byte b)
{
return (b >= 0x7F || b < 0x20);
}
private static byte[] UrlEncodeBytesToBytesInternalNonAscii(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
{
int cNonAscii = 0;
// count them first
for (int i = 0; i < count; i++)
{
if (IsNonAsciiByte(bytes[offset + i]))
{
cNonAscii++;
}
}
// nothing to expand?
if (!alwaysCreateReturnValue && cNonAscii == 0)
{
return bytes;
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + cNonAscii * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[offset + i];
if (IsNonAsciiByte(b))
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)IntToHex(b & 0x0f);
}
else
{
expandedBytes[pos++] = b;
}
}
return expandedBytes;
}
private static string UrlDecodeStringFromStringInternal(string s, Encoding e)
{
int count = s.Length;
UrlDecoder helper = new UrlDecoder(count, e);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++)
{
char ch = s[pos];
if (ch == '+')
{
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
if (s[pos + 1] == 'u' && pos < count - 5)
{
int h1 = HexToInt(s[pos + 2]);
int h2 = HexToInt(s[pos + 3]);
int h3 = HexToInt(s[pos + 4]);
int h4 = HexToInt(s[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HexToInt(s[pos + 1]);
int h2 = HexToInt(s[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
{
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
}
else
{
helper.AddChar(ch);
}
}
return helper.GetString();
}
// Private helpers for URL encoding/decoding
private static int HexToInt(char h)
{
return (h >= '0' && h <= '9') ? h - '0' :
(h >= 'a' && h <= 'f') ? h - 'a' + 10 :
(h >= 'A' && h <= 'F') ? h - 'A' + 10 :
-1;
}
private static char IntToHex(int n)
{
//WCF CHANGE: CHANGED FROM Debug.Assert() to Fx.Assert()
Fx.Assert(n < 0x10, "n < 0x10");
if (n <= 9)
{
return (char)(n + (int)'0');
}
else
{
return (char)(n - 10 + (int)'a');
}
}
// Set of safe chars, from RFC 1738.4 minus '+'
internal static bool IsSafe(char ch)
{
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
{
return true;
}
switch (ch)
{
case '-':
case '_':
case '.':
case '!':
case '*':
case '\'':
case '(':
case ')':
return true;
}
return false;
}
// Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes
internal class UrlDecoder
{
private int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private Encoding _encoding;
private void FlushBytes()
{
if (_numBytes > 0)
{
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
{
FlushBytes();
}
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
// if there are no pending bytes treat 7 bit bytes as characters
// this optimization is temp disable as it doesn't work for some encodings
//if (_numBytes == 0 && ((b & 0x80) == 0)) {
// AddChar((char)b);
//}
//else
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[_bufferSize];
}
_byteBuffer[_numBytes++] = b;
}
}
internal string GetString()
{
if (_numBytes > 0)
{
FlushBytes();
}
if (_numChars > 0)
{
return new String(_charBuffer, 0, _numChars);
}
else
{
return string.Empty;
}
}
}
internal class HttpValueCollection : NameValueCollection
{
internal HttpValueCollection(string str, Encoding encoding)
: base(StringComparer.OrdinalIgnoreCase)
{
if (!string.IsNullOrEmpty(str))
{
FillFromString(str, true, encoding);
}
IsReadOnly = false;
}
internal void FillFromString(string s, bool urlencoded, Encoding encoding)
{
int l = (s != null) ? s.Length : 0;
int i = 0;
while (i < l)
{
// find next & while noting first = on the way (and if there are more)
int si = i;
int ti = -1;
while (i < l)
{
char ch = s[i];
if (ch == '=')
{
if (ti < 0)
{
ti = i;
}
}
else if (ch == '&')
{
break;
}
i++;
}
// extract the name / value pair
string name = null;
string value = null;
if (ti >= 0)
{
name = s.Substring(si, ti - si);
value = s.Substring(ti + 1, i - ti - 1);
}
else
{
value = s.Substring(si, i - si);
}
// add name / value pair to the collection
if (urlencoded)
{
base.Add(
UrlUtility.UrlDecode(name, encoding),
UrlUtility.UrlDecode(value, encoding));
}
else
{
base.Add(name, value);
}
// trailing '&'
if (i == l - 1 && s[i] == '&')
{
base.Add(null, string.Empty);
}
i++;
}
}
public override string ToString()
{
return ToString(true, null);
}
private string ToString(bool urlencoded, IDictionary excludeKeys)
{
int n = Count;
if (n == 0)
{
return string.Empty;
}
StringBuilder s = new StringBuilder();
string key, keyPrefix, item;
for (int i = 0; i < n; i++)
{
key = GetKey(i);
if (excludeKeys != null && key != null && excludeKeys[key] != null)
{
continue;
}
if (urlencoded)
{
key = UrlUtility.UrlEncodeUnicode(key);
}
keyPrefix = (!string.IsNullOrEmpty(key)) ? (key + "=") : string.Empty;
ArrayList values = (ArrayList)BaseGet(i);
int numValues = (values != null) ? values.Count : 0;
if (s.Length > 0)
{
s.Append('&');
}
if (numValues == 1)
{
s.Append(keyPrefix);
item = (string)values[0];
if (urlencoded)
{
item = UrlUtility.UrlEncodeUnicode(item);
}
s.Append(item);
}
else if (numValues == 0)
{
s.Append(keyPrefix);
}
else
{
for (int j = 0; j < numValues; j++)
{
if (j > 0)
{
s.Append('&');
}
s.Append(keyPrefix);
item = (string)values[j];
if (urlencoded)
{
item = UrlUtility.UrlEncodeUnicode(item);
}
s.Append(item);
}
}
}
return s.ToString();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
namespace System.Numerics.Tests
{
public static class Util
{
private static Random s_random = new Random();
public static void SetRandomSeed(int seed)
{
s_random = new Random(seed);
}
/// <summary>
/// Generates random floats between 0 and 100.
/// </summary>
/// <param name="numValues">The number of values to generate</param>
/// <returns>An array containing the random floats</returns>
public static float[] GenerateRandomFloats(int numValues)
{
float[] values = new float[numValues];
for (int g = 0; g < numValues; g++)
{
values[g] = (float)(s_random.NextDouble() * 99 + 1);
}
return values;
}
/// <summary>
/// Generates random ints between 0 and 99, inclusive.
/// </summary>
/// <param name="numValues">The number of values to generate</param>
/// <returns>An array containing the random ints</returns>
public static int[] GenerateRandomInts(int numValues)
{
int[] values = new int[numValues];
for (int g = 0; g < numValues; g++)
{
values[g] = s_random.Next(1, 100);
}
return values;
}
/// <summary>
/// Generates random doubles between 0 and 100.
/// </summary>
/// <param name="numValues">The number of values to generate</param>
/// <returns>An array containing the random doubles</returns>
public static double[] GenerateRandomDoubles(int numValues)
{
double[] values = new double[numValues];
for (int g = 0; g < numValues; g++)
{
values[g] = s_random.NextDouble() * 99 + 1;
}
return values;
}
/// <summary>
/// Generates random doubles between 1 and 100.
/// </summary>
/// <param name="numValues">The number of values to generate</param>
/// <returns>An array containing the random doubles</returns>
public static long[] GenerateRandomLongs(int numValues)
{
long[] values = new long[numValues];
for (int g = 0; g < numValues; g++)
{
values[g] = s_random.Next(1, 100) * (long.MaxValue / int.MaxValue);
}
return values;
}
public static T[] GenerateRandomValues<T>(int numValues, int min = 1, int max = 100) where T : struct
{
T[] values = new T[numValues];
for (int g = 0; g < numValues; g++)
{
values[g] = GenerateSingleValue<T>(min, max);
}
return values;
}
public static T GenerateSingleValue<T>(int min = 1, int max = 100) where T : struct
{
var randomRange = s_random.Next(min, max);
T value = unchecked((T)(dynamic)randomRange);
return value;
}
public static T Abs<T>(T value) where T : struct
{
Type[] unsignedTypes = new[] { typeof(Byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) };
if (unsignedTypes.Contains(typeof(T)))
{
return value;
}
dynamic dyn = (dynamic)value;
var abs = Math.Abs(dyn);
T ret = (T)abs;
return ret;
}
public static T Sqrt<T>(T value) where T : struct
{
return unchecked((T)(dynamic)(Math.Sqrt((dynamic)value)));
}
public static T Multiply<T>(T left, T right) where T : struct
{
return unchecked((T)((dynamic)left * right));
}
public static T Divide<T>(T left, T right) where T : struct
{
return (T)((dynamic)left / right);
}
public static T Add<T>(T left, T right) where T : struct
{
return unchecked((T)((dynamic)left + right));
}
public static T Subtract<T>(T left, T right) where T : struct
{
return unchecked((T)((dynamic)left - right));
}
public static T Xor<T>(T left, T right) where T : struct
{
return (T)((dynamic)left ^ right);
}
public static T AndNot<T>(T left, T right) where T : struct
{
return (T)((dynamic)left & ~(dynamic)right);
}
public static T OnesComplement<T>(T left) where T : struct
{
return unchecked((T)(~(dynamic)left));
}
public static float Clamp(float value, float min, float max)
{
return value > max ? max : value < min ? min : value;
}
public static T Zero<T>() where T : struct
{
return (T)(dynamic)0;
}
public static T One<T>() where T : struct
{
return (T)(dynamic)1;
}
public static bool GreaterThan<T>(T left, T right) where T : struct
{
var result = (dynamic)left > right;
return (bool)result;
}
public static bool GreaterThanOrEqual<T>(T left, T right) where T : struct
{
var result = (dynamic)left >= right;
return (bool)result;
}
public static bool LessThan<T>(T left, T right) where T : struct
{
var result = (dynamic)left < right;
return (bool)result;
}
public static bool LessThanOrEqual<T>(T left, T right) where T : struct
{
var result = (dynamic)left <= right;
return (bool)result;
}
public static bool AnyEqual<T>(T[] left, T[] right) where T : struct
{
for (int g = 0; g < left.Length; g++)
{
if (((IEquatable<T>)left[g]).Equals(right[g]))
{
return true;
}
}
return false;
}
public static bool AllEqual<T>(T[] left, T[] right) where T : struct
{
for (int g = 0; g < left.Length; g++)
{
if (!((IEquatable<T>)left[g]).Equals(right[g]))
{
return false;
}
}
return true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolymorphicrecursiveOperations operations.
/// </summary>
internal partial class PolymorphicrecursiveOperations : IServiceOperations<AzureCompositeModel>, IPolymorphicrecursiveOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphicrecursiveOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal PolymorphicrecursiveOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.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<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "fishtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "fishtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </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> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.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("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Baseline.Dates;
using Marten.Events.Daemon.HighWater;
using Marten.Events.Daemon.Progress;
using Marten.Events.Daemon.Resiliency;
using Marten.Events.Projections;
using Marten.Exceptions;
using Marten.Services;
using Microsoft.Extensions.Logging;
namespace Marten.Events.Daemon
{
/// <summary>
/// The main class for running asynchronous projections
/// </summary>
internal class ProjectionDaemon: IProjectionDaemon
{
private readonly Dictionary<string, ShardAgent> _agents = new();
private CancellationTokenSource _cancellation;
private readonly HighWaterAgent _highWater;
private readonly ILogger _logger;
private readonly DocumentStore _store;
private INodeCoordinator _coordinator;
public ProjectionDaemon(DocumentStore store, IHighWaterDetector detector, ILogger logger)
{
_cancellation = new CancellationTokenSource();
_store = store;
_logger = logger;
Tracker = new ShardStateTracker(logger);
_highWater = new HighWaterAgent(detector, Tracker, logger, store.Events.Daemon, _cancellation.Token);
Settings = store.Events.Daemon;
}
public ProjectionDaemon(DocumentStore store, ILogger logger) : this(store, new HighWaterDetector(new AutoOpenSingleQueryRunner(store.Tenancy.Default), store.Events), logger)
{
}
public Task UseCoordinator(INodeCoordinator coordinator)
{
_coordinator = coordinator;
return _coordinator.Start(this, _cancellation.Token);
}
public DaemonSettings Settings { get; }
public ShardStateTracker Tracker { get; }
public bool IsRunning => _highWater.IsRunning;
public async Task StartDaemon()
{
_store.Tenancy.Default.EnsureStorageExists(typeof(IEvent));
await _highWater.Start();
}
public Task WaitForNonStaleData(TimeSpan timeout)
{
var completion = new TaskCompletionSource<bool>();
var timeoutCancellation = new CancellationTokenSource(timeout);
Task.Run(async () =>
{
var statistics = await _store.Advanced.FetchEventStoreStatistics(timeoutCancellation.Token);
timeoutCancellation.Token.Register(() =>
{
completion.TrySetException(new TimeoutException(
$"The active projection shards did not reach sequence {statistics.EventSequenceNumber} in time"));
});
if (CurrentShards().All(x => x.Position >= statistics.EventSequenceNumber))
{
completion.SetResult(true);
return;
}
while (!timeoutCancellation.IsCancellationRequested)
{
await Task.Delay(100.Milliseconds(), timeoutCancellation.Token);
if (CurrentShards().All(x => x.Position >= statistics.EventSequenceNumber))
{
completion.SetResult(true);
return;
}
}
}, timeoutCancellation.Token);
return completion.Task;
}
public async Task StartAllShards()
{
if (!_highWater.IsRunning)
{
await StartDaemon();
}
var shards = _store.Events.Projections.AllShards();
foreach (var shard in shards) await StartShard(shard, CancellationToken.None);
}
public async Task StartShard(string shardName, CancellationToken token)
{
if (!_highWater.IsRunning)
{
await StartDaemon();
}
// Latch it so it doesn't double start
if (_agents.ContainsKey(shardName)) return;
if (_store.Events.Projections.TryFindAsyncShard(shardName, out var shard)) await StartShard(shard, token);
}
public async Task StartShard(AsyncProjectionShard shard, CancellationToken cancellationToken)
{
// Don't duplicate the shard
if (_agents.ContainsKey(shard.Name.Identity)) return;
var parameters = new ActionParameters(async () =>
{
try
{
var agent = new ShardAgent(_store, shard, _logger, cancellationToken);
var position = await agent.Start(this);
Tracker.Publish(new ShardState(shard.Name, position) {Action = ShardAction.Started});
_agents[shard.Name.Identity] = agent;
}
catch (Exception e)
{
throw new ShardStartException(shard.Name, e);
}
}, cancellationToken);
parameters.LogAction = (logger, ex) =>
{
logger.LogError(ex, "Error when trying to start projection shard '{ShardName}'", shard.Name.Identity);
};
await TryAction(parameters);
}
public async Task StopShard(string shardName, Exception ex = null)
{
if (_agents.TryGetValue(shardName, out var agent))
{
if (agent.IsStopping()) return;
var parameters = new ActionParameters(agent, async () =>
{
try
{
await agent.Stop(ex);
_agents.Remove(shardName);
}
catch (Exception e)
{
throw new ShardStopException(agent.ShardName, e);
}
}, _cancellation.Token)
{
LogAction = (logger, exception) =>
{
logger.LogError(exception, "Error when trying to stop projection shard '{ShardName}'",
shardName);
}
};
await TryAction(parameters);
}
}
private bool _isStopping = false;
public async Task StopAll()
{
// This avoids issues around whether it was signaled here
// first or through the coordinator first
if (_isStopping) return;
_isStopping = true;
if (_coordinator != null)
{
await _coordinator.Stop();
}
_cancellation.Cancel();
await _highWater.Stop();
foreach (var agent in _agents.Values)
{
try
{
if (agent.IsStopping()) continue;
await agent.Stop();
}
catch (Exception e)
{
_logger.LogError(e, "Error trying to stop shard '{ShardName}'", agent.ShardName.Identity);
}
}
_agents.Clear();
// Need to restart this so that the daemon could
// be restarted later
_cancellation = new CancellationTokenSource();
}
public void Dispose()
{
_coordinator?.Dispose();
Tracker?.As<IDisposable>().Dispose();
_cancellation?.Dispose();
_highWater?.Dispose();
}
public Task RebuildProjection<TView>(CancellationToken token)
{
return RebuildProjection(typeof(TView).Name, token);
}
public Task RebuildProjection(string projectionName, CancellationToken token)
{
if (!_store.Events.Projections.TryFindProjection(projectionName, out var projection))
throw new ArgumentOutOfRangeException(nameof(projectionName),
$"No registered projection matches the name '{projectionName}'. Available names are {_store.Events.Projections.AllProjectionNames().Join(", ")}");
return RebuildProjection(projection, token);
}
public ShardAgent[] CurrentShards()
{
return _agents.Values.ToArray();
}
private async Task RebuildProjection(ProjectionSource source, CancellationToken token)
{
_logger.LogInformation("Starting to rebuild Projection {ProjectionName}", source.ProjectionName);
var running = _agents.Values.Where(x => x.ShardName.ProjectionName == source.ProjectionName).ToArray();
foreach (var agent in running)
{
await agent.Stop();
_agents.Remove(agent.ShardName.Identity);
}
if (token.IsCancellationRequested) return;
if (Tracker.HighWaterMark == 0) await _highWater.CheckNow();
if (token.IsCancellationRequested) return;
var shards = source.AsyncProjectionShards(_store);
// Teardown the current state
await using (var session = _store.LightweightSession())
{
source.Options.Teardown(session);
foreach (var shard in shards)
session.QueueOperation(new DeleteProjectionProgress(_store.Events, shard.Name.Identity));
await session.SaveChangesAsync(token);
}
if (token.IsCancellationRequested) return;
var waiters = shards.Select(async x =>
{
await StartShard(x, token);
return Tracker.WaitForShardState(x.Name, Tracker.HighWaterMark, 5.Minutes());
}).Select(x => x.Unwrap()).ToArray();
await waitForAllShardsToComplete(token, waiters);
foreach (var shard in shards) await StopShard(shard.Name.Identity);
}
private static async Task waitForAllShardsToComplete(CancellationToken token, Task[] waiters)
{
var completion = Task.WhenAll(waiters);
var tcs = new TaskCompletionSource<bool>();
// ReSharper disable once MethodSupportsCancellation
token.Register(() => tcs.SetCanceled());
await Task.WhenAny(tcs.Task, completion);
}
internal async Task TryAction(ActionParameters parameters)
{
if (parameters.Delay != default) await Task.Delay(parameters.Delay, parameters.Cancellation);
if (parameters.Cancellation.IsCancellationRequested) return;
try
{
await parameters.Action();
}
catch (Exception ex)
{
// Get out of here and do nothing if this is just a result of a Task being
// cancelled
if (ex is TaskCanceledException)
{
// Unless this is a parent action of a group action that failed and bailed out w/ a
// TaskCanceledException that is
if (parameters.Group?.Exception is ApplyEventException apply && parameters.GroupActionMode == GroupActionMode.Parent)
{
ex = apply;
}
else
{
return;
}
}
// IF you're using a group, you're using the group's cancellation, and it's going to be
// cancelled already
if (parameters.Group == null && parameters.Cancellation.IsCancellationRequested) return;
parameters.Group?.Abort(ex);
parameters.LogAction(_logger, ex);
var continuation = Settings.DetermineContinuation(ex, parameters.Attempts);
switch (continuation)
{
case RetryLater r:
parameters.IncrementAttempts(r.Delay);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Retrying in {Milliseconds}", r.Delay.TotalMilliseconds);
}
await TryAction(parameters);
break;
case Resiliency.StopShard:
if (parameters.Shard != null) await StopShard(parameters.Shard.ShardName.Identity, ex);
break;
case StopAllShards:
var tasks = _agents.Keys.ToArray().Select(name =>
{
return Task.Run(async () =>
{
await StopShard(name, ex);
}, _cancellation.Token);
});
await Task.WhenAll(tasks);
Tracker.Publish(
new ShardState(ShardName.All, Tracker.HighWaterMark)
{
Action = ShardAction.Stopped, Exception = ex
});
break;
case PauseShard pause:
if (parameters.Shard != null) await parameters.Shard.Pause(pause.Delay);
break;
case PauseAllShards pauseAll:
var tasks2 = _agents.Values.ToArray().Select(agent =>
{
return Task.Run(async () =>
{
await agent.Pause(pauseAll.Delay);
}, _cancellation.Token);
});
await Task.WhenAll(tasks2);
break;
case SkipEvent skip:
if (parameters.GroupActionMode == GroupActionMode.Child)
{
// Don't do anything, this has to be retried from the parent
// task
return;
}
parameters.ApplySkip(skip);
_logger.LogInformation("Skipping event #{Sequence} ({EventType}) in shard '{ShardName}'",
skip.Event.Sequence, skip.Event.EventType.GetFullName(), parameters.Shard.Name);
await WriteSkippedEvent(skip.Event, parameters.Shard.Name, ex as ApplyEventException);
await TryAction(parameters);
break;
case DoNothing:
// Don't do anything.
break;
}
}
}
internal async Task WriteSkippedEvent(IEvent @event, ShardName shardName, ApplyEventException exception)
{
try
{
var deadLetterEvent = new DeadLetterEvent(@event, shardName, exception);
await using (var session = _store.LightweightSession())
{
session.Store(deadLetterEvent);
await session.SaveChangesAsync();
}
}
catch (Exception e)
{
_logger.LogError(e, "Failed to write dead letter event {Event} to shard {ShardName}", @event,
shardName);
}
}
public AgentStatus StatusFor(string shardName)
{
return _agents.TryGetValue(shardName, out var agent)
? agent.Status
: AgentStatus.Stopped;
}
public Task WaitForShardToStop(string shardName, TimeSpan? timeout = null)
{
if (StatusFor(shardName) == AgentStatus.Stopped) return Task.CompletedTask;
bool IsStopped(ShardState s)
{
return s.ShardName.EqualsIgnoreCase(shardName) && s.Action == ShardAction.Stopped;
}
return Tracker.WaitForShardCondition(IsStopped, $"{shardName} is Stopped", timeout);
}
}
}
| |
using System.Globalization;
using System.Runtime.InteropServices;
using FluentAssertions;
using TestUtilities;
using Xunit;
namespace Meziantou.Framework.Tests;
public class DefaultConverterTests_StringTo
{
[Flags]
private enum SampleEnum
{
None = 0x0,
Option1 = 0x1,
Option2 = 0x2,
Option3 = 0x4,
}
[Fact]
public void TryConvert_StringToInt32_ValidValue()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("42", cultureInfo, out int value);
converted.Should().BeTrue();
value.Should().Be(42);
}
[Fact]
public void TryConvert_StringToInt32_EmptyString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("", cultureInfo, out int _);
converted.Should().BeFalse();
}
[Fact]
public void TryConvert_StringToNullableInt32_ValidInteger()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("42", cultureInfo, out int? value);
converted.Should().BeTrue();
value.Should().Be(42);
}
[Fact]
public void TryConvert_StringToNullableInt32_EmptyString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("", cultureInfo, out int? value);
converted.Should().BeTrue();
value.Should().BeNull();
}
[Fact]
public void TryConvert_StringToEnum_ValueAsString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("2", cultureInfo, out SampleEnum value);
converted.Should().BeTrue();
value.Should().Be(SampleEnum.Option2);
}
[Fact]
public void TryConvert_StringToEnum_CommaSeparatedString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("Option1, Option2", cultureInfo, out SampleEnum value);
converted.Should().BeTrue();
value.Should().Be(SampleEnum.Option1 | SampleEnum.Option2);
}
[Fact]
public void TryConvert_StringToEnum_CommaSeparatedStringAndInt()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("Option1, 2", cultureInfo, out SampleEnum value);
converted.Should().BeTrue();
value.Should().Be(SampleEnum.Option1 | SampleEnum.Option2);
}
[Fact]
public void TryConvert_StringToNullableLong()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("3000000000", cultureInfo, out long? value);
converted.Should().BeTrue();
value.Should().Be(3000000000L);
}
[Fact]
public void TryConvert_StringToCultureInfo_CultureAsString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("fr-FR", cultureInfo, out CultureInfo value);
converted.Should().BeTrue();
value.Name.Should().Be("fr-FR");
}
[Fact]
public void TryConvert_StringToCultureInfo_NeutralCultureAsString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("es", cultureInfo, out CultureInfo value);
converted.Should().BeTrue();
value.Name.Should().Be("es");
}
[RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
public void TryConvert_StringToCultureInfo_LcidAsString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("1033", cultureInfo, out CultureInfo value);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
converted.Should().BeTrue();
value.Name.Should().Be("en-US");
}
else
{
converted.Should().BeFalse();
}
}
[RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
public void TryConvert_StringToCultureInfo_InvalidCulture()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("dfgnksdfklgfg", cultureInfo, out CultureInfo _);
converted.Should().BeFalse();
}
[Fact]
public void TryConvert_StringToCultureInfo_EmptyString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("", cultureInfo, out CultureInfo value);
converted.Should().BeTrue();
value.Should().Be(CultureInfo.InvariantCulture);
}
[Fact]
public void TryConvert_StringToCultureInfo_NullValue()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
string inputValue = null;
var converted = converter.TryChangeType<CultureInfo>(inputValue, cultureInfo, out var value);
converted.Should().BeTrue();
value.Should().BeNull();
}
[Fact]
public void TryConvert_StringToUri_EmptyString()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("", cultureInfo, out Uri value);
converted.Should().BeTrue();
value.Should().BeNull();
}
[Fact]
public void TryConvert_StringToUri_RelativeUri()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("test.png", cultureInfo, out Uri value);
converted.Should().BeTrue();
value.Should().Be(new Uri("test.png", UriKind.Relative));
}
[Fact]
public void TryConvert_StringToUri_AbsoluteUri()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("https://meziantou.net", cultureInfo, out Uri value);
converted.Should().BeTrue();
value.Should().Be(new Uri("https://meziantou.net", UriKind.Absolute));
}
[Fact]
public void TryConvert_StringToTimeSpan()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("12:30", cultureInfo, out TimeSpan value);
converted.Should().BeTrue();
value.Should().Be(new TimeSpan(12, 30, 0));
}
[Fact]
public void TryConvert_StringToGuid()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("2d8a54aa-569b-404f-933b-693918885dba", cultureInfo, out Guid value);
converted.Should().BeTrue();
value.Should().Be(new Guid("2d8a54aa-569b-404f-933b-693918885dba"));
}
[Fact]
public void TryConvert_StringToDecimal()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("42.24", cultureInfo, out decimal value);
converted.Should().BeTrue();
value.Should().Be(42.24m);
}
[Fact]
public void TryConvert_StringToByteArray_Base16_Prefixed()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("0x0AFF", cultureInfo, out byte[] value);
converted.Should().BeTrue();
value.Should().Equal(new byte[] { 0x0A, 0xFF });
}
[Fact]
public void TryConvert_StringToByteArray_Base64()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("AQIDBA==", cultureInfo, out byte[] value);
converted.Should().BeTrue();
value.Should().Equal(new byte[] { 1, 2, 3, 4 });
}
[Fact]
public void TryConvert_StringToByteArray_Base64_Invalid()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("AQIDBA=", cultureInfo, out byte[] _);
converted.Should().BeFalse();
}
[Fact]
public void TryConvert_StringToDateTime()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("2018/06/24 14:21:01", cultureInfo, out DateTime value);
converted.Should().BeTrue();
value.Should().Be(new DateTime(2018, 06, 24, 14, 21, 01));
}
[Fact]
public void TryConvert_StringToDateTimeOffset()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("2018/06/24 14:21:01+0230", cultureInfo, out DateTimeOffset value);
converted.Should().BeTrue();
value.Should().Be(new DateTimeOffset(2018, 06, 24, 14, 21, 01, new TimeSpan(2, 30, 0)));
}
[Fact]
public void TryConvert_StringToByteArray_Base16()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("0d0102", cultureInfo, out byte[] value);
converted.Should().BeTrue();
value.Should().Equal(new byte[] { 0x0d, 0x01, 0x02 });
}
[Fact]
public void TryConvert_StringToByteArray_Base16Prefixed()
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType("0x0d01", cultureInfo, out byte[] value);
converted.Should().BeTrue();
value.Should().Equal(new byte[] { 0x0d, 0x01 });
}
[Theory]
[InlineData("True")]
[InlineData("true")]
[InlineData("t")]
[InlineData("yes")]
[InlineData("y")]
public void TryConvert_StringToBoolean_TrueValue(string text)
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType(text, cultureInfo, out bool value);
converted.Should().BeTrue();
value.Should().BeTrue();
}
[Theory]
[InlineData("False")]
[InlineData("false")]
[InlineData("f")]
[InlineData("No")]
[InlineData("n")]
public void TryConvert_StringToBoolean_FalseValue(string text)
{
var converter = new DefaultConverter();
var cultureInfo = CultureInfo.InvariantCulture;
var converted = converter.TryChangeType(text, cultureInfo, out bool value);
converted.Should().BeTrue();
value.Should().BeFalse();
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System.Collections.Generic;
namespace NPOI.HPSF
{
using System;
using System.IO;
using System.Collections;
using NPOI.Util;
using NPOI.POIFS.FileSystem;
/// <summary>
/// Adds writing support To the {@link PropertySet} class.
/// Please be aware that this class' functionality will be merged into the
/// {@link PropertySet} class at a later time, so the API will Change.
/// @author Rainer Klute
/// <a href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
/// @since 2003-02-19
/// </summary>
[Serializable]
public class MutablePropertySet : PropertySet
{
/// <summary>
/// Initializes a new instance of the <see cref="MutablePropertySet"/> class.
/// Its primary task is To initialize the immutable field with their proper
/// values. It also Sets fields that might Change To reasonable defaults.
/// </summary>
public MutablePropertySet()
{
/* Initialize the "byteOrder" field. */
byteOrder = LittleEndian.GetUShort(BYTE_ORDER_ASSERTION);
/* Initialize the "format" field. */
format = LittleEndian.GetUShort(FORMAT_ASSERTION);
/* Initialize "osVersion" field as if the property has been Created on
* a Win32 platform, whether this is the case or not. */
osVersion = (OS_WIN32 << 16) | 0x0A04;
/* Initailize the "classID" field. */
classID = new ClassID();
/* Initialize the sections. Since property Set must have at least
* one section it is Added right here. */
sections = new List<Section>();
sections.Add(new MutableSection());
}
/// <summary>
/// Initializes a new instance of the <see cref="MutablePropertySet"/> class.
/// All nested elements, i.e.<c>Section</c>s and <c>Property</c> instances, will be their
/// mutable counterparts in the new <c>MutablePropertySet</c>.
/// </summary>
/// <param name="ps">The property Set To copy</param>
public MutablePropertySet(PropertySet ps)
{
byteOrder = ps.ByteOrder;
format = ps.Format;
osVersion = ps.OSVersion;
ClassID=ps.ClassID;
ClearSections();
if (sections == null)
sections = new List<Section>();
foreach (Section section in ps.Sections)
{
MutableSection s = new MutableSection(section);
AddSection(s);
}
}
/**
* The Length of the property Set stream header.
*/
private int OFFSET_HEADER =
BYTE_ORDER_ASSERTION.Length + /* Byte order */
FORMAT_ASSERTION.Length + /* Format */
LittleEndianConsts.INT_SIZE + /* OS version */
ClassID.LENGTH + /* Class ID */
LittleEndianConsts.INT_SIZE; /* Section count */
/// <summary>
/// Gets or sets the "byteOrder" property.
/// </summary>
/// <value>the byteOrder value To Set</value>
public override int ByteOrder
{
get { return this.byteOrder; }
set { this.byteOrder = value; }
}
/// <summary>
/// Gets or sets the "format" property.
/// </summary>
/// <value>the format value To Set</value>
public override int Format
{
set { this.format = value; }
get { return this.format; }
}
/// <summary>
/// Gets or sets the "osVersion" property
/// </summary>
/// <value>the osVersion value To Set.</value>
public override int OSVersion
{
set { this.osVersion = value; }
get { return this.osVersion; }
}
/// <summary>
/// Gets or sets the property Set stream's low-level "class ID"
/// </summary>
/// <value>The property Set stream's low-level "class ID" field.</value>
public override ClassID ClassID
{
set { this.classID = value; }
get { return this.classID; }
}
/// <summary>
/// Removes all sections from this property Set.
/// </summary>
public virtual void ClearSections()
{
sections=null;
}
/// <summary>
/// Adds a section To this property Set.
/// </summary>
/// <param name="section">section The {@link Section} To Add. It will be Appended
/// after any sections that are alReady present in the property Set
/// and thus become the last section.</param>
public virtual void AddSection(Section section)
{
if (sections == null)
sections = new List<Section>();
sections.Add(section);
}
/// <summary>
/// Writes the property Set To an output stream.
/// </summary>
/// <param name="out1">the output stream To Write the section To</param>
public virtual void Write(Stream out1)
{
/* Write the number of sections in this property Set stream. */
int nrSections = sections.Count;
int length = 0;
/* Write the property Set's header. */
length += TypeWriter.WriteToStream(out1, (short)ByteOrder);
length += TypeWriter.WriteToStream(out1, (short)Format);
length += TypeWriter.WriteToStream(out1, OSVersion);
length += TypeWriter.WriteToStream(out1, ClassID);
length += TypeWriter.WriteToStream(out1, nrSections);
int offset = OFFSET_HEADER;
/* Write the section list, i.e. the references To the sections. Each
* entry in the section list consist of the section's class ID and the
* section's offset relative To the beginning of the stream. */
offset += nrSections * (ClassID.Length + LittleEndianConsts.INT_SIZE);
int sectionsBegin = offset;
for (IEnumerator i = sections.GetEnumerator(); i.MoveNext(); )
{
MutableSection s = (MutableSection)i.Current;
ClassID formatID = s.FormatID;
if (formatID == null)
throw new NoFormatIDException();
length += TypeWriter.WriteToStream(out1, s.FormatID);
length += TypeWriter.WriteUIntToStream(out1, (uint)offset);
offset += s.Size;
}
/* Write the sections themselves. */
offset = sectionsBegin;
for (IEnumerator i = sections.GetEnumerator(); i.MoveNext(); )
{
MutableSection s = (MutableSection)i.Current;
offset += s.Write(out1);
}
/* Indicate that we're done */
out1.Close();
}
/// <summary>
/// Returns the contents of this property set stream as an input stream.
/// The latter can be used for example to write the property set into a POIFS
/// document. The input stream represents a snapshot of the property set.
/// If the latter is modified while the input stream is still being
/// read, the modifications will not be reflected in the input stream but in
/// the {@link MutablePropertySet} only.
/// </summary>
/// <returns>the contents of this property set stream</returns>
public virtual Stream ToInputStream()
{
using (MemoryStream psStream = new MemoryStream())
{
try
{
Write(psStream);
psStream.Flush();
}
finally
{
psStream.Close();
}
byte[] streamData = psStream.ToArray();
return new MemoryStream(streamData);
}
}
/// <summary>
/// Writes a property Set To a document in a POI filesystem directory
/// </summary>
/// <param name="dir">The directory in the POI filesystem To Write the document To.</param>
/// <param name="name">The document's name. If there is alReady a document with the
/// same name in the directory the latter will be overwritten.</param>
public virtual void Write(DirectoryEntry dir, String name)
{
/* If there is alReady an entry with the same name, Remove it. */
try
{
Entry e = dir.GetEntry(name);
e.Delete();
}
catch (FileNotFoundException)
{
/* Entry not found, no need To Remove it. */
}
/* Create the new entry. */
dir.CreateDocument(name, ToInputStream());
}
}
}
| |
//#define FBV7_API_ENABLED
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if FBV7_API_ENABLED
using Facebook.Unity;
#endif
public class SP_FB_API_v7 : SP_FB_API {
private const string PUBLISH_PERMISSION_STRING = "publish_actions";
private string _UserId = string.Empty;
private string _AccessToken = string.Empty;
//--------------------------------------
// API Methods
//--------------------------------------
public void Init() {
#if FBV7_API_ENABLED
FB.Init(OnInitComplete, OnHideUnity);
#endif
}
public void Login(params string[] scopes) {
#if FBV7_API_ENABLED
List<string> scopesList = new List<string>(scopes);
if (scopesList.Contains(PUBLISH_PERMISSION_STRING))
{
scopesList.Remove(PUBLISH_PERMISSION_STRING);
if (FB.IsLoggedIn)
{
if (scopesList.Count > 0)
{
Debug.Log("Logging with read permission");
FB.LogInWithReadPermissions(scopesList, ReadPermissionCallback);
}
else
{
Debug.Log("Logging with write permission");
List<string> publishList = new List<string>();
publishList.Add(PUBLISH_PERMISSION_STRING);
FB.LogInWithPublishPermissions(publishList, LoginCallback);
}
}
else
{
FB.LogInWithReadPermissions(scopesList, ReadPermissionCallback);
}
}
else
{
FB.LogInWithReadPermissions(scopesList, LoginCallback);
}
#endif
}
#if FBV7_API_ENABLED
private void ReadPermissionCallback(ILoginResult result)
{
LoginCallback(result);
if (FB.IsLoggedIn)
{
Debug.Log("ReadPermissionCallback:Logging with write permission");
List<string> publishList = new List<string>();
publishList.Add(PUBLISH_PERMISSION_STRING);
FB.LogInWithPublishPermissions(publishList, LoginCallback);
}
}
#endif
public void Logout() {
#if FBV7_API_ENABLED
_UserId = string.Empty;
_AccessToken = string.Empty;
FB.LogOut();
#endif
}
public void API(string query, FB_HttpMethod method, SPFacebook.FB_Delegate callback) {
#if FBV7_API_ENABLED
new FB_GrapRequest_V7(query, ConvertHttpMethod(method), callback);
#endif
}
public void API(string query, FB_HttpMethod method, SPFacebook.FB_Delegate callback, WWWForm form) {
#if FBV7_API_ENABLED
new FB_GrapRequest_V7(query, ConvertHttpMethod(method), callback, form);
#endif
}
public void AppRequest(string message, FB_RequestActionType actionType, string objectId, string[] to, string data = "", string title = "") {
#if FBV7_API_ENABLED
FB.AppRequest(message, ConvertActionType(actionType), objectId, to, data, title, AppRequestCallback);
#endif
}
public void AppRequest(string message, FB_RequestActionType actionType, string objectId, List<object> filters = null, string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "") {
#if FBV7_API_ENABLED
FB.AppRequest(message, ConvertActionType(actionType), objectId, filters, excludeIds, maxRecipients, data, title, AppRequestCallback);
#endif
}
public void AppRequest(string message, string[] to = null, List<object> filters = null, string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "") {
#if FBV7_API_ENABLED
FB.AppRequest(message, to, filters, excludeIds, maxRecipients, data, title, AppRequestCallback);
#endif
}
public void FeedShare (string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string actionName = "", string actionLink = "", string reference = "") {
#if FBV7_API_ENABLED
System.Uri linkUri = null;
if (!string.IsNullOrEmpty(link))
linkUri = new System.Uri(link);
System.Uri pictureUri = null;
if (!string.IsNullOrEmpty(picture))
pictureUri = new System.Uri(picture);
FB.FeedShare(
toId: toId,
link: linkUri,
linkName: linkName,
linkCaption: linkCaption,
linkDescription: linkDescription,
picture: pictureUri,
mediaSource: reference,
callback: PostCallback
);
#endif
}
public void AppInvite(string appLink, string imgLink) {
#if FBV7_API_ENABLED
FB.Mobile.AppInvite(new System.Uri(appLink), new System.Uri(imgLink), AppInviteResult);
#endif
}
#if FBV7_API_ENABLED
private void AppInviteResult(IAppInviteResult result) {
FB_AppInviteResult res = new FB_AppInviteResult(result.Cancelled, result.RawResult, result.Error, result.ResultDictionary);
SPFacebook.Instance.AppInviteResultCallback(res);
}
#endif
//--------------------------------------
// Get / Set
//--------------------------------------
public bool IsLoggedIn {
get {
#if FBV7_API_ENABLED
return FB.IsLoggedIn;
#else
return false;
#endif
}
}
public string UserId {
get {
return _UserId;
}
}
public string AccessToken {
get {
return _AccessToken;
}
}
public string AppId {
get {
#if FBV7_API_ENABLED
return FB.AppId;
#else
return "";
#endif
}
}
public static bool IsAPIEnabled {
get {
#if FBV7_API_ENABLED
return true;
#else
return false;
#endif
}
}
//--------------------------------------
// Handlers
//--------------------------------------
#if FBV7_API_ENABLED
private void AppRequestCallback(IAppRequestResult result) {
FB_AppRequestResult res = new FB_AppRequestResult(result.RawResult, result.Error);
SPFacebook.Instance.AppRequestCallback(res);
}
private void LoginCallback(ILoginResult result) {
FB_LoginResult res;
if (result == null) {
res = new FB_LoginResult(string.Empty, "Null Response", false);
} else {
res = new FB_LoginResult(result.RawResult, result.Error, result.Cancelled);
}
if(res.IsSucceeded && !result.Cancelled && result.AccessToken != null) {
_UserId = result.AccessToken.UserId;
_AccessToken = result.AccessToken.TokenString;
res.SetCredential(_UserId, _AccessToken);
}
SPFacebook.Instance.LoginCallback(res);
}
private void OnInitComplete() {
if (Facebook.Unity.AccessToken.CurrentAccessToken != null) {
_AccessToken = Facebook.Unity.AccessToken.CurrentAccessToken.TokenString;
_UserId = Facebook.Unity.AccessToken.CurrentAccessToken.UserId;
}
SPFacebook.Instance.OnInitComplete();
}
private void OnHideUnity(bool isGameShown) {
SPFacebook.Instance.OnHideUnity(isGameShown);
}
private void PostCallback(IShareResult result) {
FB_PostResult res = new FB_PostResult(result.RawResult, result.Error);
SPFacebook.Instance.PostCallback(res);
}
//--------------------------------------
// Utils
//--------------------------------------
private HttpMethod ConvertHttpMethod(FB_HttpMethod method) {
switch(method) {
case FB_HttpMethod.GET:
return HttpMethod.GET;
case FB_HttpMethod.POST:
return HttpMethod.POST;
case FB_HttpMethod.DELETE:
return HttpMethod.DELETE;
}
return HttpMethod.GET;
}
private OGActionType ConvertActionType(FB_RequestActionType actionType) {
switch(actionType) {
case FB_RequestActionType.AskFor:
return OGActionType.ASKFOR;
case FB_RequestActionType.Send:
return OGActionType.SEND;
case FB_RequestActionType.Turn:
return OGActionType.TURN;
}
return OGActionType.ASKFOR;
}
#endif
}
| |
// 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.
//
// C# translation of Whetstone Double Precision Benchmark
using Microsoft.Xunit.Performance;
using System;
using System.Runtime.CompilerServices;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
namespace Benchstone.BenchF
{
public static class Whetsto
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 50000;
#endif
private static int s_j, s_k, s_l;
private static double s_t, s_t2;
public static volatile int Volatile_out;
private static void Escape(int n, int j, int k, double x1, double x2, double x3, double x4)
{
Volatile_out = n;
Volatile_out = j;
Volatile_out = k;
Volatile_out = (int)x1;
Volatile_out = (int)x2;
Volatile_out = (int)x3;
Volatile_out = (int)x4;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool Bench()
{
double[] e1 = new double[4];
double x1, x2, x3, x4, x, y, z, t1;
int i, n1, n2, n3, n4, n6, n7, n8, n9, n10, n11;
s_t = 0.499975;
t1 = 0.50025;
s_t2 = 2.0;
n1 = 0 * Iterations;
n2 = 12 * Iterations;
n3 = 14 * Iterations;
n4 = 345 * Iterations;
n6 = 210 * Iterations;
n7 = 32 * Iterations;
n8 = 899 * Iterations;
n9 = 616 * Iterations;
n10 = 0 * Iterations;
n11 = 93 * Iterations;
x1 = 1.0;
x2 = x3 = x4 = -1.0;
for (i = 1; i <= n1; i += 1)
{
x1 = (x1 + x2 + x3 - x4) * s_t;
x2 = (x1 + x2 - x3 - x4) * s_t;
x3 = (x1 - x2 + x3 + x4) * s_t;
x4 = (-x1 + x2 + x3 + x4) * s_t;
}
Escape(n1, n1, n1, x1, x2, x3, x4);
/* MODULE 2: array elements */
e1[0] = 1.0;
e1[1] = e1[2] = e1[3] = -1.0;
for (i = 1; i <= n2; i += 1)
{
e1[0] = (e1[0] + e1[1] + e1[2] - e1[3]) * s_t;
e1[1] = (e1[0] + e1[1] - e1[2] + e1[3]) * s_t;
e1[2] = (e1[0] - e1[1] + e1[2] + e1[3]) * s_t;
e1[3] = (-e1[0] + e1[1] + e1[2] + e1[3]) * s_t;
}
Escape(n2, n3, n2, e1[0], e1[1], e1[2], e1[3]);
/* MODULE 3: array as parameter */
for (i = 1; i <= n3; i += 1)
{
PA(e1);
}
Escape(n3, n2, n2, e1[0], e1[1], e1[2], e1[3]);
/* MODULE 4: conditional jumps */
s_j = 1;
for (i = 1; i <= n4; i += 1)
{
if (s_j == 1)
{
s_j = 2;
}
else
{
s_j = 3;
}
if (s_j > 2)
{
s_j = 0;
}
else
{
s_j = 1;
}
if (s_j < 1)
{
s_j = 1;
}
else
{
s_j = 0;
}
}
Escape(n4, s_j, s_j, x1, x2, x3, x4);
/* MODULE 5: omitted */
/* MODULE 6: integer Math */
s_j = 1;
s_k = 2;
s_l = 3;
for (i = 1; i <= n6; i += 1)
{
s_j = s_j * (s_k - s_j) * (s_l - s_k);
s_k = s_l * s_k - (s_l - s_j) * s_k;
s_l = (s_l - s_k) * (s_k + s_j);
e1[s_l - 2] = s_j + s_k + s_l;
e1[s_k - 2] = s_j * s_k * s_l;
}
Escape(n6, s_j, s_k, e1[0], e1[1], e1[2], e1[3]);
/* MODULE 7: trig. functions */
x = y = 0.5;
for (i = 1; i <= n7; i += 1)
{
x = s_t * System.Math.Atan(s_t2 * System.Math.Sin(x) * System.Math.Cos(x) / (System.Math.Cos(x + y) + System.Math.Cos(x - y) - 1.0));
y = s_t * System.Math.Atan(s_t2 * System.Math.Sin(y) * System.Math.Cos(y) / (System.Math.Cos(x + y) + System.Math.Cos(x - y) - 1.0));
}
Escape(n7, s_j, s_k, x, x, y, y);
/* MODULE 8: procedure calls */
x = y = z = 1.0;
for (i = 1; i <= n8; i += 1)
{
P3(x, y, out z);
}
Escape(n8, s_j, s_k, x, y, z, z);
/* MODULE9: array references */
s_j = 1;
s_k = 2;
s_l = 3;
e1[0] = 1.0;
e1[1] = 2.0;
e1[2] = 3.0;
for (i = 1; i <= n9; i += 1)
{
P0(e1);
}
Escape(n9, s_j, s_k, e1[0], e1[1], e1[2], e1[3]);
/* MODULE10: integer System.Math */
s_j = 2;
s_k = 3;
for (i = 1; i <= n10; i += 1)
{
s_j = s_j + s_k;
s_k = s_j + s_k;
s_j = s_k - s_j;
s_k = s_k - s_j - s_j;
}
Escape(n10, s_j, s_k, x1, x2, x3, x4);
/* MODULE11: standard functions */
x = 0.75;
for (i = 1; i <= n11; i += 1)
{
x = System.Math.Sqrt(System.Math.Exp(System.Math.Log(x) / t1));
}
Escape(n11, s_j, s_k, x, x, x, x);
return true;
}
private static void PA(double[] e)
{
int j;
j = 0;
lab:
e[0] = (e[0] + e[1] + e[2] - e[3]) * s_t;
e[1] = (e[0] + e[1] - e[2] + e[3]) * s_t;
e[2] = (e[0] - e[1] + e[2] + e[3]) * s_t;
e[3] = (-e[0] + e[1] + e[2] + e[3]) / s_t2;
j += 1;
if (j < 6)
{
goto lab;
}
}
private static void P3(double x, double y, out double z)
{
x = s_t * (x + y);
y = s_t * (x + y);
z = (x + y) / s_t2;
}
private static void P0(double[] e1)
{
e1[s_j] = e1[s_k];
e1[s_k] = e1[s_l];
e1[s_l] = e1[s_j];
}
[Benchmark]
public static void Test()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Bench();
}
}
}
private static bool TestBase()
{
bool result = Bench();
return result;
}
public static int Main()
{
bool result = TestBase();
return (result ? 100 : -1);
}
}
}
| |
namespace EmpMan.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Addrecruitmenttables : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.RecruitmentInterviews",
c => new
{
ID = c.Int(nullable: false, identity: true),
RecruitmentID = c.String(maxLength: 128),
RecruitmentStaffID = c.String(maxLength: 128),
Name = c.String(maxLength: 256),
ShortName = c.String(maxLength: 256),
RegInterviewEmpID = c.Int(),
IsInterviewed = c.Boolean(),
IsStaffCancel = c.Boolean(),
ScheduleInterviewDate = c.DateTime(),
ActualInterviewDate = c.DateTime(),
ScheduleInterviewRoom = c.String(),
ActualInterviewRoom = c.String(),
InterviewContent = c.String(),
InterviewComment = c.String(),
InterviewResult = c.String(),
IsFinished = c.Boolean(),
ReportDate = c.DateTime(),
IsTrainingIntroduction = c.Boolean(),
IsSendSMS = c.Boolean(),
SMSCount = c.Int(),
SMSContent = c.String(),
RowVersion = c.Binary(),
DisplayOrder = c.Int(),
AccountData = c.String(maxLength: 256),
Note = c.String(),
AccessDataLevel = c.Int(),
CreatedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 256),
UpdatedDate = c.DateTime(),
UpdatedBy = c.String(maxLength: 256),
MetaKeyword = c.String(maxLength: 256),
MetaDescription = c.String(maxLength: 256),
Status = c.Boolean(nullable: false),
DataStatus = c.Int(),
UserAgent = c.String(),
UserHostAddress = c.String(),
UserHostName = c.String(),
RequestDate = c.DateTime(),
RequestBy = c.String(),
ApprovedDate = c.DateTime(),
ApprovedBy = c.String(),
ApprovedStatus = c.Int(),
})
.PrimaryKey(t => t.ID);
CreateTable(
"dbo.Recruitments",
c => new
{
ID = c.String(nullable: false, maxLength: 128),
No = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 256),
ShortName = c.String(maxLength: 256),
RecruitmentTypeMasterID = c.Int(),
RecruitmentTypeMasterDetailID = c.Int(),
CvCompanyFolderPath = c.String(),
CvDeptFolderPath = c.String(),
CvCount = c.Int(),
SendMailFromEmpID = c.Int(),
SendMailToEmpID = c.Int(),
AnsRecruitDeptDeadlineDate = c.DateTime(),
AnsLocalDeadlineDate = c.DateTime(),
IsNotification = c.Boolean(),
ExpireDate = c.DateTime(),
Content = c.String(),
IsFinished = c.Boolean(),
RowVersion = c.Binary(),
DisplayOrder = c.Int(),
AccountData = c.String(maxLength: 256),
Note = c.String(),
AccessDataLevel = c.Int(),
CreatedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 256),
UpdatedDate = c.DateTime(),
UpdatedBy = c.String(maxLength: 256),
MetaKeyword = c.String(maxLength: 256),
MetaDescription = c.String(maxLength: 256),
Status = c.Boolean(nullable: false),
DataStatus = c.Int(),
UserAgent = c.String(),
UserHostAddress = c.String(),
UserHostName = c.String(),
RequestDate = c.DateTime(),
RequestBy = c.String(),
ApprovedDate = c.DateTime(),
ApprovedBy = c.String(),
ApprovedStatus = c.Int(),
})
.PrimaryKey(t => t.ID);
CreateTable(
"dbo.RecruitmentStaffs",
c => new
{
ID = c.Int(nullable: false, identity: true),
RecruitmentID = c.String(maxLength: 128),
RecruitmentStaffID = c.String(maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
ShortName = c.String(maxLength: 256),
RecruitmentTypeMasterID = c.Int(),
RecruitmentTypeMasterDetailID = c.Int(),
RequestInCompanyDate = c.DateTime(),
InterviewResult = c.String(),
RequestInterviewDate = c.DateTime(),
InterViewTime = c.DateTime(),
ExamRound1 = c.String(),
ExamResult = c.String(),
CompanyCvNo = c.Int(),
Pharse = c.Int(),
FullName = c.String(),
BirthDay = c.DateTime(),
Gender = c.Boolean(),
National = c.String(),
IdentNo = c.String(),
PhoneNumber = c.String(),
Email = c.String(),
KiboSalary = c.Decimal(precision: 18, scale: 2),
EducationLevel = c.String(),
CollectName = c.String(),
ProfessionalKbn = c.String(),
EducationType = c.String(),
Grade = c.String(),
IsCertificated = c.Boolean(),
DebtSubjectCount = c.Int(),
DebtSubjectReason = c.String(),
CertificatedDateTime = c.String(),
JapaneseLevel = c.String(),
EnglishLevel = c.String(),
OtherSkill = c.String(),
MarriedStatus = c.String(),
Objective = c.String(),
CvNote = c.String(),
Comment1 = c.String(),
Comment2 = c.String(),
CvCreateDate = c.DateTime(),
CvUpdateDate = c.DateTime(),
CvSendCount = c.Int(),
CvSendList = c.String(),
StartWorkingDate = c.DateTime(),
AdddressPlace = c.String(),
BornPlace = c.String(),
Hobby = c.String(),
IsTestRound1ByPass = c.String(),
GradeTestRound1 = c.Decimal(precision: 18, scale: 2),
EngGradeTestRound1 = c.Decimal(precision: 18, scale: 2),
ProfessionalKbnGradeTestRound1 = c.Decimal(precision: 18, scale: 2),
GradeTestRound2 = c.Decimal(precision: 18, scale: 2),
CvStatus = c.String(),
EmpType = c.String(),
TrainingClassConditionTalkDate = c.DateTime(),
WorkingConditionTalkDate = c.DateTime(),
Avatar = c.String(),
IsSendSMS = c.Boolean(),
SMSCount = c.Int(),
SMSContent = c.String(),
IsTrainingIntroduction = c.Boolean(),
DeptReceived = c.Int(),
TeamReceived = c.Int(),
TrialStartDate = c.DateTime(),
SupportEmpID = c.Int(),
GhostPC = c.String(maxLength: 256),
ItMailNotificationDate = c.DateTime(),
ResourceDeptMailNotificationDate = c.DateTime(),
SystemEmpID = c.Int(),
RowVersion = c.Binary(),
DisplayOrder = c.Int(),
AccountData = c.String(maxLength: 256),
Note = c.String(),
AccessDataLevel = c.Int(),
CreatedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 256),
UpdatedDate = c.DateTime(),
UpdatedBy = c.String(maxLength: 256),
MetaKeyword = c.String(maxLength: 256),
MetaDescription = c.String(maxLength: 256),
Status = c.Boolean(nullable: false),
DataStatus = c.Int(),
UserAgent = c.String(),
UserHostAddress = c.String(),
UserHostName = c.String(),
RequestDate = c.DateTime(),
RequestBy = c.String(),
ApprovedDate = c.DateTime(),
ApprovedBy = c.String(),
ApprovedStatus = c.Int(),
})
.PrimaryKey(t => t.ID);
}
public override void Down()
{
DropTable("dbo.RecruitmentStaffs");
DropTable("dbo.Recruitments");
DropTable("dbo.RecruitmentInterviews");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
namespace Shared.Datastructures
{
//TODO: Commentaar toevoegen aan methoden
/// <summary>
/// Een implementatie van een heap
/// </summary>
/// <typeparam name="T"></typeparam>
public class Heap<T> : IList<T> where T : IComparable<T>
{
/// <summary>
/// lijst representatie van de heap
/// </summary>
List<T> data;
/// <summary>
/// Default constructor voor een lege heap
/// </summary>
public Heap()
{
data = new List<T>();
}
/// <summary>
/// Default constructor voor een lege heap met een capaciteit
/// </summary>
/// <param name="capacity"> Capaciteit van de heap</param>
public Heap(int capacity)
{
data = new List<T>(capacity);
}
/// <summary>
/// Constructor die een heap maakt met een collection
/// </summary>
/// <param name="collection"></param>
public Heap(IEnumerable<T> collection)
{
data = new List<T>(collection);
for (int i = 1 + data.Count / 2; i >= 0; i--)
siftDown(i);
}
/// <summary>
/// Het aantal elementen in de heap
/// </summary>
public int Count
{
get { return data.Count; }
}
#region standard methods
/// <summary>
/// Maak de heap leag
/// </summary>
public void Clear()
{
data.Clear();
}
/// <summary>
/// Vraag een enumerator voor de heap op
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
return data.GetEnumerator();
}
#endregion
/// <summary>
/// Bevat de heap een element
/// </summary>
/// <param name="item"> het element waarvoor gezocht wordt</param>
/// <returns></returns>
public bool Contains(T item)
{
return Contains(item, 0);
}
/// <summary>
/// Doet een geoptimaliseerde search naar item vanaf index
/// </summary>
/// <param name="item"> het element waarvoor gezocht wordt </param>
/// <param name="index"> de startindex </param>
/// <returns></returns>
bool Contains(T item, int index)
{
int c = data[index].CompareTo(item);
if (c > 0)
return false;
if (c == 0)
return true;
return Contains(item, (index << 1) + 1) || Contains(item, (index << 1) + 2);
}
/// <summary>
/// Bevat de heap een element die aan het predicaat voldoet
/// </summary>
/// <param name="match"> Het predikaat waaraan voldaan moet worden</param>
/// <returns></returns>
public bool Contains(Predicate<T> match)
{
foreach (T item in data)
{
if (match(item))
return true;
}
return false;
}
/// <summary>
/// Kijkt of de heap een element bevat dat aan het predikaat voldoet
/// en, als dit het geval is, dat element in result zet
/// </summary>
/// <param name="match"> Het predikaat waaraan voldaan moet worden </param>
/// <param name="result"> Het element </param>
/// <returns> </returns>
public bool TryFind(Predicate<T> match, out T result)
{
foreach (T item in data)
{
if (match(item))
{
result = item;
return true;
}
}
result = default(T);
return false;
}
/// <summary>
/// Herorden de heap
/// </summary>
/// <param name="index"></param>
public void ReSort(int index)
{
siftUp(index);
}
/// <summary>
/// Haal het kleinste element uit de heap
/// </summary>
/// <returns> Het kleinste element in de heap </returns>
public T RemoveMin()
{
T min = data[0];
int index = data.Count - 1;
data[0] = data[index];
data.RemoveAt(index);
siftDown(0);
return min;
}
/// <summary>
/// Doet een heap siftdown operatie
/// </summary>
/// <param name="index"></param>
void siftDown(int index)
{
int child0 = (index << 1) + 1;
if (child0 >= data.Count)
return;
int child1 = child0 + 1;
int c0 = data[index].CompareTo(data[child0]);
if (child1 >= data.Count)
{
if (c0 > 0)
swap(index, child0);
}
else
{
if (c0 > 0 || data[index].CompareTo(data[child1]) > 0)
{
int cc = data[child0].CompareTo(data[child1]);
if (cc > 0)
{
swap(index, child1);
siftDown(child1);
}
else
{
swap(index, child0);
siftDown(child0);
}
}
}
}
/// <summary>
/// Swapt 2 elementen in de heap
/// </summary>
/// <param name="i0"> element 1 </param>
/// <param name="i1"> element 2</param>
void swap(int i0, int i1)
{
T temp = data[i0];
data[i0] = data[i1];
data[i1] = temp;
}
/// <summary>
/// Voegt een elment toe aan de heap
/// </summary>
/// <param name="item"> het toe te voegen element</param>
public void Add(T item)
{
data.Add(item);
if (data.Count == 1)
return;
siftUp(data.Count - 1);
return;
}
/// <summary>
/// Doet een siftup operatie
/// </summary>
/// <param name="index"></param>
void siftUp(int index)
{
int index2 = (index - 1) >> 1;
while (data[index].CompareTo(data[index2]) < 0)
{
swap(index2, index);
index = index2;
index2 = (index - 1) >> 1;
if (index2 < 0)
return;
}
}
#region IEnumerable Members
/// <summary>
/// Vraag een enumerator voor de heap op
/// </summary>
/// <returns> Een enumerator voor de heap</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Kopieert een array in de heap vanaf een index
/// </summary>
/// <param name="array"> Het array dat gekopieerd wordt </param>
/// <param name="arrayIndex"> De index waar het array naar gekopieerd wordt</param>
public void CopyTo(T[] array, int arrayIndex)
{
for (int i = 0; i < data.Count && i < array.Length; i++)
{
array[i + arrayIndex] = data[i];
}
}
/// <summary>
/// Een heap is niet read-only
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Verwijdert een element uit de heap.
/// Returnt false als het element niet in de heap is
/// </summary>
/// <param name="item"> Het te verwijderen element </param>
/// <returns></returns>
public bool Remove(T item)
{
int index = data.IndexOf(item);
if (index < 0)
return false;
data[index] = data[data.Count - 1];
data.RemoveAt(data.Count - 1);
siftDown(index);
return true;
}
#endregion
/// <summary>
/// Verwijdert een element uit de heap op een index
/// </summary>
/// <param name="index"> De index die verwijderd wordt</param>
public void RemoveAt(int index)
{
data[index] = data[data.Count - 1];
data.RemoveAt(data.Count - 1);
siftDown(index);
}
/// <summary>
/// Vraagt de index op van een element in de heap
/// </summary>
/// <param name="item"> Het element </param>
/// <returns> de index van het element</returns>
public int IndexOf(T item)
{
return IndexOf(item, 0);
}
/// <summary>
/// Geoptimaliseerde search naar de index van een element
/// </summary>
/// <param name="item"> Het element </param>
/// <param name="index"> zoekindex </param>
/// <returns> De index van het element </returns>
int IndexOf(T item, int index)
{
int c = data[index].CompareTo(item);
if (c > 0)
return -1;
if (c == 0)
return index;
int i1 = IndexOf(item, (index << 1) + 1);
if (i1 >= 0)
return i1;
i1 = IndexOf(item, (index << 1) + 2);
if (i1 >= 0)
return i1;
return -1;
}
/// <summary>
/// Verander de waarde van een element op een index
/// </summary>
/// <param name="index"> De index </param>
/// <param name="newValue"> De nieuwe waarde </param>
public void ModifyValue(int index, T newValue)
{
T old = data[index];
data[index] = newValue;
int cmp = old.CompareTo(newValue);
if (cmp == 0)
return;
if (cmp > 0)
siftUp(index);
else
siftDown(index);
}
#region IList<T> Members
/// <summary>
/// !!WAARSCHUWING!!
/// Insert het element niet op de gegeven index, maar gedraagt als
/// een Add operatie
/// </summary>
/// <param name="index"> Wordt genegeerd</param>
/// <param name="item"> Het element dat toegevoegd wordt</param>
public void Insert(int index, T item)
{
Add(item);
}
/// <summary>
/// Het element op een index
/// </summary>
/// <param name="index"> De index van het element </param>
/// <returns> Het element </returns>
public T this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
#endregion
/// <summary>
/// Testing
/// </summary>
public static void Test()
{
Heap<int> testheap = new Heap<int>(new int[] { 7, 6, 5, 4, 3, 2, 1, 0 });
for (int i = 0; i < 8; i++)
{
int value = testheap.RemoveMin();
if (value != i)
throw new Exception("Heap failed");
}
for (int i = 0; i < 10; i++)
{
testheap.Add(i);
}
for (int i = 0; i < 10; i++)
{
int value = testheap.RemoveMin();
if (value != i)
throw new Exception("Heap failed");
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using NTemplate;
using WebOnDiet.Framework.Adapters;
using WebOnDiet.Framework.Configuration;
using WebOnDiet.Framework.Container;
using WebOnDiet.Framework.Handlers;
using WebOnDiet.Framework.Routes;
namespace WebOnDiet.Framework
{
public interface IWebOnDietApplication
{
void Configure(IConfiguration configuration);
}
public class WebOnDietHttpHandlerFactory : IHttpHandlerFactory
{
private static IConfiguration Configuration;
readonly static RoutesCollection Routes = new RoutesCollection();
public static Kernel Container { get; private set; }
private static bool initialized;
static WebOnDietHttpHandlerFactory()
{
Initialize();
}
internal static void Initialize()
{
if (initialized) return;
initialized = true;
Action<IConfiguration> configure = x => { };
if (HttpContext.Current != null)
{
var x = AppDomain.CurrentDomain.SetupInformation.CachePath;
var dir = HttpContext.Current.Server.MapPath("~/bin");
Configuration = new AspNetAppConfiguration();
var dllFiles = (from f in Directory.GetFiles(dir, "*.dll", SearchOption.TopDirectoryOnly)
select f)
.ToDictionary(f => Path.GetFileName(f).ToUpper());
var target = Path.Combine(x, "manual");
if (Directory.Exists(target))
Directory.Delete(target, true);
Directory.CreateDirectory(target);
foreach (var assemblyFilename in Directory.GetFiles(x, "*.dll", SearchOption.AllDirectories))
{
if (dllFiles.ContainsKey(Path.GetFileName(assemblyFilename).ToUpper()))
{
Configuration.AddRoutesAssembly(Assembly.LoadFile(assemblyFilename));
dllFiles.Remove(Path.GetFileName(assemblyFilename).ToUpper());
}
}
foreach (var missing in dllFiles.Values)
{
var targetDll = Path.Combine(target, Path.GetFileName(missing));
File.Copy(missing, targetDll);
Configuration.AddRoutesAssembly(Assembly.LoadFile(targetDll));
}
var currentApp = HttpContext.Current.ApplicationInstance as IWebOnDietApplication;
if (currentApp != null)
{
configure = currentApp.Configure;
Configuration.AddRoutesAssembly(currentApp.GetType().BaseType.Assembly);
}
}
else
{
if (Embedded.Server.CurrentContext != null)
{
Configuration = new AspNetAppConfiguration();
configure = Embedded.Server.Current.Configure;
}
else
throw new Exception("No hosting found");
}
configure(Configuration);
var routedMethods = (from assembly in Configuration.RouteAssemblies
from type in assembly.GetExportedTypes()
where type.IsInterface == false
&& type.IsAbstract == false
from method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
from attr in method.GetCustomAttributes(true)
let routeAttribute = attr as IRouteAttribute
where routeAttribute != null
orderby routeAttribute.Precedence descending
select new { RouteAttribute = routeAttribute, Method = method }).ToArray();
var routes = from r in routedMethods
let route = r.RouteAttribute.Route.IndexOf(':') > 0
? (IRoute)new PatternRoute(r.RouteAttribute.Route) { Target = new TargetMethod(r.Method) }
: (IRoute)new ExactMatchRoute(r.RouteAttribute.Route) { Target = new TargetMethod(r.Method) }
select route;
Routes.AddRange(routes);
var routeClasses = routedMethods.Select(m => m.Method.DeclaringType).Distinct().ToArray();
Container = new Kernel();
foreach (var routeClass in routeClasses)
{
Container.Register(routeClass, routeClass);
}
var templateEngine = new NTemplateEngine(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath);
templateEngine.Initialize();
wod.TemplateEngine = templateEngine;
wod.Render = new Renderer(templateEngine);
}
public System.Web.IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
var abstractContext = new HttpContextAdapter(context);
context.SetCurrentContext(abstractContext);
return GetHandler(abstractContext, requestType, url, pathTranslated);
}
public void ReleaseHandler(System.Web.IHttpHandler handler)
{
}
public IHttpHandler GetHandler(IHttpContext context, string requestType, string url, string pathTranslated)
{
var appPath = (context.Request.ApplicationPath ?? string.Empty).TrimEnd('/');
var appRelativeUrl = context.Request.Path;
if (appPath.Length > 0)
appRelativeUrl = url != appPath
? url.Substring(appPath.Length)
: "/";
if (appRelativeUrl == string.Empty) appRelativeUrl = "/";
if (appRelativeUrl != "/") appRelativeUrl = appRelativeUrl.TrimEnd('/');
RouteMatch routeMatch;
try
{
routeMatch = GetRoutedMethod(appRelativeUrl);
}
catch (Exception ex)
{
throw;
}
if (routeMatch != null)
{
routeMatch.Context = context;
return new RoutedRequestHandler(routeMatch);
}
NotFoundHandler.SetLookedUpResource(context, appRelativeUrl);
return NotFoundHandler.Instance;
}
static RouteMatch GetRoutedMethod(string appRelativeUrl)
{
return Routes.Match(appRelativeUrl);
}
public void ReleaseHandler(IHttpHandler handler)
{
}
}
public interface IHttpHandler : System.Web.IHttpHandler
{
void ProcessRequest(IHttpContext context);
}
public interface IHttpContext
{
IRequest Request { get; }
IResponse Response { get; }
IDictionary Items { get; }
}
public interface IRequest
{
string ApplicationPath { get; }
string Path { get; }
Uri Url { get; }
NameValueCollection Form { get; }
NameValueCollection QueryString { get; }
}
public interface IResponse
{
void Write(string value);
void Clear();
int StatusCode { get; set; }
string ContentType { get; set; }
void RedirectPermanent(string target, bool endResponse);
void Redirect(string target, bool endResponse);
void Flush();
}
public static class HttpContextExtensions
{
private const string CURRENT_CONTEXT_KEY = "CURRENT_CONTEXT_KEY";
public static IHttpContext GetCurrentContext(this HttpContext context)
{
return (IHttpContext)context.Items[CURRENT_CONTEXT_KEY];
}
public static void SetCurrentContext(this HttpContext context, IHttpContext abstractContext)
{
context.Items[CURRENT_CONTEXT_KEY] = abstractContext;
}
}
}
| |
using System;
using System.Collections.Generic;
using ExcelDna.Integration;
namespace AsyncFunctions
{
// This class defines a few test functions that can be used to explore the automatic array resizing.
public static class ResizeTestFunctions
{
// Just returns an array of the given size
public static object[,] dnaMakeArray(int rows, int columns)
{
object[,] result = new object[rows, columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i, j] = i + j;
}
}
return result;
}
public static double[,] dnaMakeArrayDoubles(int rows, int columns)
{
double[,] result = new double[rows, columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i, j] = i + (j / 1000.0);
}
}
return result;
}
public static object dnaMakeMixedArrayAndResize(int rows, int columns)
{
object[,] result = new object[rows, columns];
for (int j = 0; j < columns; j++)
{
result[0, j] = "Col " + j;
}
for (int i = 1; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i, j] = i + (j * 0.1);
}
}
return ArrayResizer.dnaResize(result);
}
// Makes an array, but automatically resizes the result
public static object dnaMakeArrayAndResize(int rows, int columns, string unused, string unusedtoo)
{
object[,] result = dnaMakeArray(rows, columns);
return ArrayResizer.dnaResize(result);
// Can also call Resize via Excel - so if the Resize add-in is not part of this code, it should still work
// (though calling direct is better for large arrays - it prevents extra marshaling).
// return XlCall.Excel(XlCall.xlUDF, "Resize", result);
}
public static double[,] dnaMakeArrayAndResizeDoubles(int rows, int columns)
{
double[,] result = dnaMakeArrayDoubles(rows, columns);
return ArrayResizer.dnaResizeDoubles(result);
}
}
public class ArrayResizer
{
// This function will run in the UDF context.
// Needs extra protection to allow multithreaded use.
public static object dnaResize(object[,] array)
{
var caller = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;
if (caller == null)
{
return array;
}
int rows = array.GetLength(0);
int columns = array.GetLength(1);
if (rows == 0 || columns == 0)
return array;
// For dynamic-array aware Excel we don't do anything if the caller is a single cell
// Excel will expand in this case
if (UtilityFunctions.dnaSupportsDynamicArrays() &&
caller.RowFirst == caller.RowLast &&
caller.ColumnFirst == caller.ColumnLast)
{
return array;
}
if ((caller.RowLast - caller.RowFirst + 1 == rows) &&
(caller.ColumnLast - caller.ColumnFirst + 1 == columns))
{
// Size is already OK - just return result
return array;
}
var rowLast = caller.RowFirst + rows - 1;
var columnLast = caller.ColumnFirst + columns - 1;
// Check for the sheet limits
if (rowLast > ExcelDnaUtil.ExcelLimits.MaxRows - 1 ||
columnLast > ExcelDnaUtil.ExcelLimits.MaxColumns - 1)
{
// Can't resize - goes beyond the end of the sheet - just return #VALUE
// (Can't give message here, or change cells)
return ExcelError.ExcelErrorValue;
}
// TODO: Add some kind of guard for ever-changing result?
ExcelAsyncUtil.QueueAsMacro(() =>
{
// Create a reference of the right size
var target = new ExcelReference(caller.RowFirst, rowLast, caller.ColumnFirst, columnLast, caller.SheetId);
DoResize(target); // Will trigger a recalc by writing formula
});
// Return the whole array even if we plan to resize - to prevent flashing #N/A
return array;
}
public static double[,] dnaResizeDoubles(double[,] array)
{
var caller = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;
if (caller == null)
{
return array;
}
int rows = array.GetLength(0);
int columns = array.GetLength(1);
if (rows == 0 || columns == 0)
{
return array;
}
// For dynamic-array aware Excel we don't do anything if the caller is a single cell
// Excel will expand in this case
if (UtilityFunctions.dnaSupportsDynamicArrays() &&
caller.RowFirst == caller.RowLast &&
caller.ColumnFirst == caller.ColumnLast)
{
return array;
}
if ((caller.RowLast - caller.RowFirst + 1 == rows) &&
(caller.ColumnLast - caller.ColumnFirst + 1 == columns))
{
// Size is already OK - just return result
return array;
}
var rowLast = caller.RowFirst + rows - 1;
var columnLast = caller.ColumnFirst + columns - 1;
if (rowLast > ExcelDnaUtil.ExcelLimits.MaxRows - 1 ||
columnLast > ExcelDnaUtil.ExcelLimits.MaxColumns - 1)
{
// Can't resize - goes beyond the end of the sheet - just return null (for #NUM!)
// (Can't give message here, or change cells)
return null;
}
// TODO: Add guard for ever-changing result?
ExcelAsyncUtil.QueueAsMacro(() =>
{
// Create a reference of the right size
var target = new ExcelReference(caller.RowFirst, rowLast, caller.ColumnFirst, columnLast, caller.SheetId);
DoResize(target); // Will trigger a recalc by writing formula
});
// Return what we have - to prevent flashing #N/A
return array;
}
static void DoResize(ExcelReference target)
{
// Get the current state for reset later
using (new ExcelEchoOffHelper())
using (new ExcelCalculationManualHelper())
{
ExcelReference firstCell = new ExcelReference(target.RowFirst, target.RowFirst, target.ColumnFirst, target.ColumnFirst, target.SheetId);
// Get the formula in the first cell of the target
string formula = (string)XlCall.Excel(XlCall.xlfGetCell, 41, firstCell);
bool isFormulaArray = (bool)XlCall.Excel(XlCall.xlfGetCell, 49, firstCell);
if (isFormulaArray)
{
// Select the sheet and firstCell - needed because we want to use SelectSpecial.
using (new ExcelSelectionHelper(firstCell))
{
// Extend the selection to the whole array and clear
XlCall.Excel(XlCall.xlcSelectSpecial, 6);
ExcelReference oldArray = (ExcelReference)XlCall.Excel(XlCall.xlfSelection);
oldArray.SetValue(ExcelEmpty.Value);
}
}
// Get the formula and convert to R1C1 mode
bool isR1C1Mode = (bool)XlCall.Excel(XlCall.xlfGetWorkspace, 4);
string formulaR1C1 = formula;
if (!isR1C1Mode)
{
object formulaR1C1Obj;
XlCall.XlReturn formulaR1C1Return = XlCall.TryExcel(XlCall.xlfFormulaConvert, out formulaR1C1Obj, formula, true, false, ExcelMissing.Value, firstCell);
if (formulaR1C1Return != XlCall.XlReturn.XlReturnSuccess || formulaR1C1Obj is ExcelError)
{
string firstCellAddress = (string)XlCall.Excel(XlCall.xlfReftext, firstCell, true);
XlCall.Excel(XlCall.xlcAlert, "Cannot resize array formula at " + firstCellAddress + " - formula might be too long when converted to R1C1 format.");
firstCell.SetValue("'" + formula);
return;
}
formulaR1C1 = (string)formulaR1C1Obj;
}
// Must be R1C1-style references
object ignoredResult;
//Debug.Print("Resizing START: " + target.RowLast);
XlCall.XlReturn formulaArrayReturn = XlCall.TryExcel(XlCall.xlcFormulaArray, out ignoredResult, formulaR1C1, target);
//Debug.Print("Resizing FINISH");
// TODO: Find some dummy macro to clear the undo stack
if (formulaArrayReturn != XlCall.XlReturn.XlReturnSuccess)
{
string firstCellAddress = (string)XlCall.Excel(XlCall.xlfReftext, firstCell, true);
XlCall.Excel(XlCall.xlcAlert, "Cannot resize array formula at " + firstCellAddress + " - result might overlap another array.");
// Might have failed due to array in the way.
firstCell.SetValue("'" + formula);
}
}
}
}
// RIIA-style helpers to deal with Excel selections
// Don't use if you agree with Eric Lippert here: http://stackoverflow.com/a/1757344/44264
public class ExcelEchoOffHelper : XlCall, IDisposable
{
object oldEcho;
public ExcelEchoOffHelper()
{
oldEcho = XlCall.Excel(XlCall.xlfGetWorkspace, 40);
XlCall.Excel(XlCall.xlcEcho, false);
}
public void Dispose()
{
XlCall.Excel(XlCall.xlcEcho, oldEcho);
}
}
public class ExcelCalculationManualHelper : XlCall, IDisposable
{
object oldCalculationMode;
public ExcelCalculationManualHelper()
{
oldCalculationMode = XlCall.Excel(XlCall.xlfGetDocument, 14);
XlCall.Excel(XlCall.xlcOptionsCalculation, 3);
}
public void Dispose()
{
XlCall.Excel(XlCall.xlcOptionsCalculation, oldCalculationMode);
}
}
// Select an ExcelReference (perhaps on another sheet) allowing changes to be made there.
// On clean-up, resets all the selections and the active sheet.
// Should not be used if the work you are going to do will switch sheets, amke new sheets etc.
public class ExcelSelectionHelper : XlCall, IDisposable
{
object oldSelectionOnActiveSheet;
object oldActiveCellOnActiveSheet;
object oldSelectionOnRefSheet;
object oldActiveCellOnRefSheet;
public ExcelSelectionHelper(ExcelReference refToSelect)
{
// Remember old selection state on the active sheet
oldSelectionOnActiveSheet = XlCall.Excel(XlCall.xlfSelection);
oldActiveCellOnActiveSheet = XlCall.Excel(XlCall.xlfActiveCell);
// Switch to the sheet we want to select
string refSheet = (string)XlCall.Excel(XlCall.xlSheetNm, refToSelect);
XlCall.Excel(XlCall.xlcWorkbookSelect, new object[] { refSheet });
// record selection and active cell on the sheet we want to select
oldSelectionOnRefSheet = XlCall.Excel(XlCall.xlfSelection);
oldActiveCellOnRefSheet = XlCall.Excel(XlCall.xlfActiveCell);
// make the selection
XlCall.Excel(XlCall.xlcFormulaGoto, refToSelect);
}
public void Dispose()
{
// Reset the selection on the target sheet
XlCall.Excel(XlCall.xlcSelect, oldSelectionOnRefSheet, oldActiveCellOnRefSheet);
// Reset the sheet originally selected
string oldActiveSheet = (string)XlCall.Excel(XlCall.xlSheetNm, oldSelectionOnActiveSheet);
XlCall.Excel(XlCall.xlcWorkbookSelect, new object[] { oldActiveSheet });
// Reset the selection in the active sheet (some bugs make this change sometimes too)
XlCall.Excel(XlCall.xlcSelect, oldSelectionOnActiveSheet, oldActiveCellOnActiveSheet);
}
}
public static class UtilityFunctions
{
static bool? _supportsDynamicArrays;
[ExcelFunction(IsHidden = true)]
public static bool dnaSupportsDynamicArrays()
{
if (!_supportsDynamicArrays.HasValue)
{
try
{
var result = XlCall.Excel(614, new object[] { 1 }, new object[] { true });
_supportsDynamicArrays = true;
}
catch
{
_supportsDynamicArrays = false;
}
}
return _supportsDynamicArrays.Value;
}
}
}
| |
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
public enum CameraModes { Follow, Isometric, Free }
private Transform cameraTransform;
private Transform dummyTarget;
public Transform CameraTarget;
public float FollowDistance = 30.0f;
public float MaxFollowDistance = 100.0f;
public float MinFollowDistance = 2.0f;
public float ElevationAngle = 30.0f;
public float MaxElevationAngle = 85.0f;
public float MinElevationAngle = 0f;
public float OrbitalAngle = 0f;
public CameraModes CameraMode = CameraModes.Follow;
public bool MovementSmoothing = true;
public bool RotationSmoothing = false;
private bool previousSmoothing;
public float MovementSmoothingValue = 25f;
public float RotationSmoothingValue = 5.0f;
public float MoveSensitivity = 2.0f;
private Vector3 currentVelocity;
private Vector3 desiredPosition;
private float mouseX;
private float mouseY;
private Vector3 moveVector;
private float mouseWheel;
// Controls for Touches on Mobile devices
private float prev_ZoomDelta;
private const string event_SmoothingValue = "Slider - Smoothing Value";
private const string event_FollowDistance = "Slider - Camera Zoom";
void Awake()
{
if (QualitySettings.vSyncCount > 0)
Application.targetFrameRate = 60;
else
Application.targetFrameRate = -1;
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
Input.simulateMouseWithTouches = false;
cameraTransform = transform;
previousSmoothing = MovementSmoothing;
}
// Use this for initialization
void Start ()
{
if (CameraTarget == null)
{
// If we don't have a target (assigned by the player, create a dummy in the center of the scene).
dummyTarget = new GameObject("Camera Target").transform;
CameraTarget = dummyTarget;
}
}
// Update is called once per frame
void LateUpdate ()
{
GetPlayerInput();
// Check if we still have a valid target
if (CameraTarget != null)
{
if (CameraMode == CameraModes.Isometric)
{
desiredPosition = CameraTarget.position + Quaternion.Euler(ElevationAngle, OrbitalAngle, 0f) * new Vector3(0, 0, -FollowDistance);
}
else if (CameraMode == CameraModes.Follow)
{
desiredPosition = CameraTarget.position + CameraTarget.TransformDirection(Quaternion.Euler(ElevationAngle, OrbitalAngle, 0f) * (new Vector3(0, 0, -FollowDistance)));
}
else
{
// Free Camera implementation
}
if (MovementSmoothing == true)
{
// Using Smoothing
cameraTransform.position = Vector3.SmoothDamp(cameraTransform.position, desiredPosition, ref currentVelocity, MovementSmoothingValue * Time.fixedDeltaTime);
//cameraTransform.position = Vector3.Lerp(cameraTransform.position, desiredPosition, Time.deltaTime * 5.0f);
}
else
{
// Not using Smoothing
cameraTransform.position = desiredPosition;
}
if (RotationSmoothing == true)
cameraTransform.rotation = Quaternion.Lerp(cameraTransform.rotation, Quaternion.LookRotation(CameraTarget.position - cameraTransform.position), RotationSmoothingValue * Time.deltaTime);
else
{
cameraTransform.LookAt(CameraTarget);
}
}
}
void GetPlayerInput()
{
moveVector = Vector3.zero;
// Check Mouse Wheel Input prior to Shift Key so we can apply multiplier on Shift for Scrolling
mouseWheel = Input.GetAxis("Mouse ScrollWheel");
float touchCount = Input.touchCount;
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || touchCount > 0)
{
mouseWheel *= 10;
if (Input.GetKeyDown(KeyCode.I))
CameraMode = CameraModes.Isometric;
if (Input.GetKeyDown(KeyCode.F))
CameraMode = CameraModes.Follow;
if (Input.GetKeyDown(KeyCode.S))
MovementSmoothing = !MovementSmoothing;
// Check for right mouse button to change camera follow and elevation angle
if (Input.GetMouseButton(1))
{
mouseY = Input.GetAxis("Mouse Y");
mouseX = Input.GetAxis("Mouse X");
if (mouseY > 0.01f || mouseY < -0.01f)
{
ElevationAngle -= mouseY * MoveSensitivity;
// Limit Elevation angle between min & max values.
ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
}
if (mouseX > 0.01f || mouseX < -0.01f)
{
OrbitalAngle += mouseX * MoveSensitivity;
if (OrbitalAngle > 360)
OrbitalAngle -= 360;
if (OrbitalAngle < 0)
OrbitalAngle += 360;
}
}
// Get Input from Mobile Device
if (touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 deltaPosition = Input.GetTouch(0).deltaPosition;
// Handle elevation changes
if (deltaPosition.y > 0.01f || deltaPosition.y < -0.01f)
{
ElevationAngle -= deltaPosition.y * 0.1f;
// Limit Elevation angle between min & max values.
ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
}
// Handle left & right
if (deltaPosition.x > 0.01f || deltaPosition.x < -0.01f)
{
OrbitalAngle += deltaPosition.x * 0.1f;
if (OrbitalAngle > 360)
OrbitalAngle -= 360;
if (OrbitalAngle < 0)
OrbitalAngle += 360;
}
}
// Check for left mouse button to select a new CameraTarget or to reset Follow position
if (Input.GetMouseButton(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 300, 1 << 10 | 1 << 11 | 1 << 12 | 1 << 14))
{
if (hit.transform == CameraTarget)
{
// Reset Follow Position
OrbitalAngle = 0;
}
else
{
CameraTarget = hit.transform;
OrbitalAngle = 0;
MovementSmoothing = previousSmoothing;
}
}
}
if (Input.GetMouseButton(2))
{
if (dummyTarget == null)
{
// We need a Dummy Target to anchor the Camera
dummyTarget = new GameObject("Camera Target").transform;
dummyTarget.position = CameraTarget.position;
dummyTarget.rotation = CameraTarget.rotation;
CameraTarget = dummyTarget;
previousSmoothing = MovementSmoothing;
MovementSmoothing = false;
}
else if (dummyTarget != CameraTarget)
{
// Move DummyTarget to CameraTarget
dummyTarget.position = CameraTarget.position;
dummyTarget.rotation = CameraTarget.rotation;
CameraTarget = dummyTarget;
previousSmoothing = MovementSmoothing;
MovementSmoothing = false;
}
mouseY = Input.GetAxis("Mouse Y");
mouseX = Input.GetAxis("Mouse X");
moveVector = cameraTransform.TransformDirection(mouseX, mouseY, 0);
dummyTarget.Translate(-moveVector, Space.World);
}
}
// Check Pinching to Zoom in - out on Mobile device
if (touchCount == 2)
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
float prevTouchDelta = (touch0PrevPos - touch1PrevPos).magnitude;
float touchDelta = (touch0.position - touch1.position).magnitude;
float zoomDelta = prevTouchDelta - touchDelta;
if (zoomDelta > 0.01f || zoomDelta < -0.01f)
{
FollowDistance += zoomDelta * 0.25f;
// Limit FollowDistance between min & max values.
FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
}
}
// Check MouseWheel to Zoom in-out
if (mouseWheel < -0.01f || mouseWheel > 0.01f)
{
FollowDistance -= mouseWheel * 5.0f;
// Limit FollowDistance between min & max values.
FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using log4net.Util;
using log4net.Layout;
using log4net.Core;
namespace log4net.Appender
{
/// <summary>
/// Appender that logs to a database.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="AdoNetAppender"/> appends logging events to a table within a
/// database. The appender can be configured to specify the connection
/// string by setting the <see cref="ConnectionString"/> property.
/// The connection type (provider) can be specified by setting the <see cref="ConnectionType"/>
/// property. For more information on database connection strings for
/// your specific database see <a href="http://www.connectionstrings.com/">http://www.connectionstrings.com/</a>.
/// </para>
/// <para>
/// Records are written into the database either using a prepared
/// statement or a stored procedure. The <see cref="CommandType"/> property
/// is set to <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify a prepared statement
/// or to <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify a stored
/// procedure.
/// </para>
/// <para>
/// The prepared statement text or the name of the stored procedure
/// must be set in the <see cref="CommandText"/> property.
/// </para>
/// <para>
/// The prepared statement or stored procedure can take a number
/// of parameters. Parameters are added using the <see cref="AddParameter"/>
/// method. This adds a single <see cref="AdoNetAppenderParameter"/> to the
/// ordered list of parameters. The <see cref="AdoNetAppenderParameter"/>
/// type may be subclassed if required to provide database specific
/// functionality. The <see cref="AdoNetAppenderParameter"/> specifies
/// the parameter name, database type, size, and how the value should
/// be generated using a <see cref="ILayout"/>.
/// </para>
/// </remarks>
/// <example>
/// An example of a SQL Server table that could be logged to:
/// <code lang="SQL">
/// CREATE TABLE [dbo].[Log] (
/// [ID] [int] IDENTITY (1, 1) NOT NULL ,
/// [Date] [datetime] NOT NULL ,
/// [Thread] [varchar] (255) NOT NULL ,
/// [Level] [varchar] (20) NOT NULL ,
/// [Logger] [varchar] (255) NOT NULL ,
/// [Message] [varchar] (4000) NOT NULL
/// ) ON [PRIMARY]
/// </code>
/// </example>
/// <example>
/// An example configuration to log to the above table:
/// <code lang="XML" escaped="true">
/// <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender" >
/// <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
/// <connectionString value="data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa" />
/// <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
/// <parameter>
/// <parameterName value="@log_date" />
/// <dbType value="DateTime" />
/// <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
/// </parameter>
/// <parameter>
/// <parameterName value="@thread" />
/// <dbType value="String" />
/// <size value="255" />
/// <layout type="log4net.Layout.PatternLayout" value="%thread" />
/// </parameter>
/// <parameter>
/// <parameterName value="@log_level" />
/// <dbType value="String" />
/// <size value="50" />
/// <layout type="log4net.Layout.PatternLayout" value="%level" />
/// </parameter>
/// <parameter>
/// <parameterName value="@logger" />
/// <dbType value="String" />
/// <size value="255" />
/// <layout type="log4net.Layout.PatternLayout" value="%logger" />
/// </parameter>
/// <parameter>
/// <parameterName value="@message" />
/// <dbType value="String" />
/// <size value="4000" />
/// <layout type="log4net.Layout.PatternLayout" value="%message" />
/// </parameter>
/// </appender>
/// </code>
/// </example>
/// <author>Julian Biddle</author>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Lance Nehring</author>
public class AdoNetAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AdoNetAppender" /> class.
/// </summary>
/// <remarks>
/// Public default constructor to initialize a new instance of this class.
/// </remarks>
public AdoNetAppender()
{
m_connectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
m_useTransactions = true;
m_commandType = System.Data.CommandType.Text;
m_parameters = new ArrayList();
m_reconnectOnError = false;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the database connection string that is used to connect to
/// the database.
/// </summary>
/// <value>
/// The database connection string used to connect to the database.
/// </value>
/// <remarks>
/// <para>
/// The connections string is specific to the connection type.
/// See <see cref="ConnectionType"/> for more information.
/// </para>
/// </remarks>
/// <example>Connection string for MS Access via ODBC:
/// <code>"DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb"</code>
/// </example>
/// <example>Another connection string for MS Access via ODBC:
/// <code>"Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;"</code>
/// </example>
/// <example>Connection string for MS Access via OLE DB:
/// <code>"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;"</code>
/// </example>
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
/// <summary>
/// The appSettings key from App.Config that contains the connection string.
/// </summary>
public string AppSettingsKey
{
get { return m_appSettingsKey; }
set { m_appSettingsKey = value; }
}
/// <summary>
/// The connectionStrings key from App.Config that contains the connection string.
/// </summary>
/// <remarks>
/// This property requires at least .NET 2.0.
/// </remarks>
public string ConnectionStringName
{
get { return m_connectionStringName; }
set { m_connectionStringName = value; }
}
/// <summary>
/// Gets or sets the type name of the <see cref="IDbConnection"/> connection
/// that should be created.
/// </summary>
/// <value>
/// The type name of the <see cref="IDbConnection"/> connection.
/// </value>
/// <remarks>
/// <para>
/// The type name of the ADO.NET provider to use.
/// </para>
/// <para>
/// The default is to use the OLE DB provider.
/// </para>
/// </remarks>
/// <example>Use the OLE DB Provider. This is the default value.
/// <code>System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
/// </example>
/// <example>Use the MS SQL Server Provider.
/// <code>System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
/// </example>
/// <example>Use the ODBC Provider.
/// <code>Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral</code>
/// This is an optional package that you can download from
/// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a>
/// search for <b>ODBC .NET Data Provider</b>.
/// </example>
/// <example>Use the Oracle Provider.
/// <code>System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
/// This is an optional package that you can download from
/// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a>
/// search for <b>.NET Managed Provider for Oracle</b>.
/// </example>
public string ConnectionType
{
get { return m_connectionType; }
set { m_connectionType = value; }
}
/// <summary>
/// Gets or sets the command text that is used to insert logging events
/// into the database.
/// </summary>
/// <value>
/// The command text used to insert logging events into the database.
/// </value>
/// <remarks>
/// <para>
/// Either the text of the prepared statement or the
/// name of the stored procedure to execute to write into
/// the database.
/// </para>
/// <para>
/// The <see cref="CommandType"/> property determines if
/// this text is a prepared statement or a stored procedure.
/// </para>
/// </remarks>
public string CommandText
{
get { return m_commandText; }
set { m_commandText = value; }
}
/// <summary>
/// Gets or sets the command type to execute.
/// </summary>
/// <value>
/// The command type to execute.
/// </value>
/// <remarks>
/// <para>
/// This value may be either <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify
/// that the <see cref="CommandText"/> is a prepared statement to execute,
/// or <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify that the
/// <see cref="CommandText"/> property is the name of a stored procedure
/// to execute.
/// </para>
/// <para>
/// The default value is <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>).
/// </para>
/// </remarks>
public CommandType CommandType
{
get { return m_commandType; }
set { m_commandType = value; }
}
/// <summary>
/// Should transactions be used to insert logging events in the database.
/// </summary>
/// <value>
/// <c>true</c> if transactions should be used to insert logging events in
/// the database, otherwise <c>false</c>. The default value is <c>true</c>.
/// </value>
/// <remarks>
/// <para>
/// Gets or sets a value that indicates whether transactions should be used
/// to insert logging events in the database.
/// </para>
/// <para>
/// When set a single transaction will be used to insert the buffered events
/// into the database. Otherwise each event will be inserted without using
/// an explicit transaction.
/// </para>
/// </remarks>
public bool UseTransactions
{
get { return m_useTransactions; }
set { m_useTransactions = value; }
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to call the NetSend method.
/// </value>
/// <remarks>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
/// <summary>
/// Should this appender try to reconnect to the database on error.
/// </summary>
/// <value>
/// <c>true</c> if the appender should try to reconnect to the database after an
/// error has occurred, otherwise <c>false</c>. The default value is <c>false</c>,
/// i.e. not to try to reconnect.
/// </value>
/// <remarks>
/// <para>
/// The default behaviour is for the appender not to try to reconnect to the
/// database if an error occurs. Subsequent logging events are discarded.
/// </para>
/// <para>
/// To force the appender to attempt to reconnect to the database set this
/// property to <c>true</c>.
/// </para>
/// <note>
/// When the appender attempts to connect to the database there may be a
/// delay of up to the connection timeout specified in the connection string.
/// This delay will block the calling application's thread.
/// Until the connection can be reestablished this potential delay may occur multiple times.
/// </note>
/// </remarks>
public bool ReconnectOnError
{
get { return m_reconnectOnError; }
set { m_reconnectOnError = value; }
}
#endregion // Public Instance Properties
#region Protected Instance Properties
/// <summary>
/// Gets or sets the underlying <see cref="IDbConnection" />.
/// </summary>
/// <value>
/// The underlying <see cref="IDbConnection" />.
/// </value>
/// <remarks>
/// <see cref="AdoNetAppender" /> creates a <see cref="IDbConnection" /> to insert
/// logging events into a database. Classes deriving from <see cref="AdoNetAppender" />
/// can use this property to get or set this <see cref="IDbConnection" />. Use the
/// underlying <see cref="IDbConnection" /> returned from <see cref="Connection" /> if
/// you require access beyond that which <see cref="AdoNetAppender" /> provides.
/// </remarks>
protected IDbConnection Connection
{
get { return m_dbConnection; }
set { m_dbConnection = value; }
}
#endregion // Protected Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
base.ActivateOptions();
// Are we using a command object
m_usePreparedCommand = (m_commandText != null && m_commandText.Length > 0);
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
InitializeDatabaseConnection();
InitializeDatabaseCommand();
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// Override the parent method to close the database
/// </summary>
/// <remarks>
/// <para>
/// Closes the database command and database connection.
/// </para>
/// </remarks>
override protected void OnClose()
{
base.OnClose();
DisposeCommand(false);
DiposeConnection();
}
#endregion
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Inserts the events into the database.
/// </summary>
/// <param name="events">The events to insert into the database.</param>
/// <remarks>
/// <para>
/// Insert all the events specified in the <paramref name="events"/>
/// array into the database.
/// </para>
/// </remarks>
override protected void SendBuffer(LoggingEvent[] events)
{
if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open))
{
LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((m_dbConnection==null)?SystemInfo.NullText:m_dbConnection.State.ToString()) );
InitializeDatabaseConnection();
InitializeDatabaseCommand();
}
// Check that the connection exists and is open
if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Open)
{
if (m_useTransactions)
{
// Create transaction
// NJC - Do this on 2 lines because it can confuse the debugger
IDbTransaction dbTran = null;
try
{
dbTran = m_dbConnection.BeginTransaction();
SendBuffer(dbTran, events);
// commit transaction
dbTran.Commit();
}
catch(Exception ex)
{
// rollback the transaction
if (dbTran != null)
{
try
{
dbTran.Rollback();
}
catch(Exception)
{
// Ignore exception
}
}
// Can't insert into the database. That's a bad thing
ErrorHandler.Error("Exception while writing to database", ex);
}
}
else
{
// Send without transaction
SendBuffer(null, events);
}
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Public Instance Methods
/// <summary>
/// Adds a parameter to the command.
/// </summary>
/// <param name="parameter">The parameter to add to the command.</param>
/// <remarks>
/// <para>
/// Adds a parameter to the ordered list of command parameters.
/// </para>
/// </remarks>
public void AddParameter(AdoNetAppenderParameter parameter)
{
m_parameters.Add(parameter);
}
#endregion // Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Writes the events to the database using the transaction specified.
/// </summary>
/// <param name="dbTran">The transaction that the events will be executed under.</param>
/// <param name="events">The array of events to insert into the database.</param>
/// <remarks>
/// <para>
/// The transaction argument can be <c>null</c> if the appender has been
/// configured not to use transactions. See <see cref="UseTransactions"/>
/// property for more information.
/// </para>
/// </remarks>
virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
{
if (m_usePreparedCommand)
{
// Send buffer using the prepared command object
if (m_dbCommand != null)
{
if (dbTran != null)
{
m_dbCommand.Transaction = dbTran;
}
// run for all events
foreach(LoggingEvent e in events)
{
// Set the parameter values
foreach(AdoNetAppenderParameter param in m_parameters)
{
param.FormatValue(m_dbCommand, e);
}
// Execute the query
m_dbCommand.ExecuteNonQuery();
}
}
}
else
{
// create a new command
using(IDbCommand dbCmd = m_dbConnection.CreateCommand())
{
if (dbTran != null)
{
dbCmd.Transaction = dbTran;
}
// run for all events
foreach(LoggingEvent e in events)
{
// Get the command text from the Layout
string logStatement = GetLogStatement(e);
LogLog.Debug(declaringType, "LogStatement ["+logStatement+"]");
dbCmd.CommandText = logStatement;
dbCmd.ExecuteNonQuery();
}
}
}
}
/// <summary>
/// Formats the log message into database statement text.
/// </summary>
/// <param name="logEvent">The event being logged.</param>
/// <remarks>
/// This method can be overridden by subclasses to provide
/// more control over the format of the database statement.
/// </remarks>
/// <returns>
/// Text that can be passed to a <see cref="System.Data.IDbCommand"/>.
/// </returns>
virtual protected string GetLogStatement(LoggingEvent logEvent)
{
if (Layout == null)
{
ErrorHandler.Error("AdoNetAppender: No Layout specified.");
return "";
}
else
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
Layout.Format(writer, logEvent);
return writer.ToString();
}
}
/// <summary>
/// Creates an <see cref="IDbConnection"/> instance used to connect to the database.
/// </summary>
/// <remarks>
/// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary).
/// </remarks>
/// <param name="connectionType">The <see cref="Type"/> of the <see cref="IDbConnection"/> object.</param>
/// <param name="connectionString">The connectionString output from the ResolveConnectionString method.</param>
/// <returns>An <see cref="IDbConnection"/> instance with a valid connection string.</returns>
virtual protected IDbConnection CreateConnection(Type connectionType, string connectionString)
{
IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType);
connection.ConnectionString = connectionString;
return connection;
}
/// <summary>
/// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey
/// property.
/// </summary>
/// <remarks>
/// ConnectiongStringName is only supported on .NET 2.0 and higher.
/// </remarks>
/// <param name="connectionStringContext">Additional information describing the connection string.</param>
/// <returns>A connection string used to connect to the database.</returns>
virtual protected string ResolveConnectionString(out string connectionStringContext)
{
if (m_connectionString != null && m_connectionString.Length > 0)
{
connectionStringContext = "ConnectionString";
return m_connectionString;
}
if (!String.IsNullOrEmpty(m_connectionStringName))
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[m_connectionStringName];
if (settings != null)
{
connectionStringContext = "ConnectionStringName";
return settings.ConnectionString;
}
else
{
throw new LogException("Unable to find [" + m_connectionStringName + "] ConfigurationManager.ConnectionStrings item");
}
}
if (m_appSettingsKey != null && m_appSettingsKey.Length > 0)
{
connectionStringContext = "AppSettingsKey";
string appSettingsConnectionString = SystemInfo.GetAppSetting(m_appSettingsKey);
if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0)
{
throw new LogException("Unable to find [" + m_appSettingsKey + "] AppSettings key.");
}
return appSettingsConnectionString;
}
connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings.";
return string.Empty;
}
/// <summary>
/// Retrieves the class type of the ADO.NET provider.
/// </summary>
/// <remarks>
/// <para>
/// Gets the Type of the ADO.NET provider to use to connect to the
/// database. This method resolves the type specified in the
/// <see cref="ConnectionType"/> property.
/// </para>
/// <para>
/// Subclasses can override this method to return a different type
/// if necessary.
/// </para>
/// </remarks>
/// <returns>The <see cref="Type"/> of the ADO.NET provider</returns>
virtual protected Type ResolveConnectionType()
{
try
{
return SystemInfo.GetTypeFromString(m_connectionType, true, false);
}
catch(Exception ex)
{
ErrorHandler.Error("Failed to load connection type ["+m_connectionType+"]", ex);
throw;
}
}
#endregion // Protected Instance Methods
#region Private Instance Methods
/// <summary>
/// Prepares the database command and initialize the parameters.
/// </summary>
private void InitializeDatabaseCommand()
{
if (m_dbConnection != null && m_usePreparedCommand)
{
try
{
DisposeCommand(false);
// Create the command object
m_dbCommand = m_dbConnection.CreateCommand();
// Set the command string
m_dbCommand.CommandText = m_commandText;
// Set the command type
m_dbCommand.CommandType = m_commandType;
}
catch (Exception e)
{
ErrorHandler.Error("Could not create database command [" + m_commandText + "]", e);
DisposeCommand(true);
}
if (m_dbCommand != null)
{
try
{
foreach (AdoNetAppenderParameter param in m_parameters)
{
try
{
param.Prepare(m_dbCommand);
}
catch (Exception e)
{
ErrorHandler.Error("Could not add database command parameter [" + param.ParameterName + "]", e);
throw;
}
}
}
catch
{
DisposeCommand(true);
}
}
if (m_dbCommand != null)
{
try
{
// Prepare the command statement.
m_dbCommand.Prepare();
}
catch (Exception e)
{
ErrorHandler.Error("Could not prepare database command [" + m_commandText + "]", e);
DisposeCommand(true);
}
}
}
}
/// <summary>
/// Connects to the database.
/// </summary>
private void InitializeDatabaseConnection()
{
string connectionStringContext = "Unable to determine connection string context.";
string resolvedConnectionString = string.Empty;
try
{
DisposeCommand(true);
DiposeConnection();
// Set the connection string
resolvedConnectionString = ResolveConnectionString(out connectionStringContext);
m_dbConnection = CreateConnection(ResolveConnectionType(), resolvedConnectionString);
using (SecurityContext.Impersonate(this))
{
// Open the database connection
m_dbConnection.Open();
}
}
catch (Exception e)
{
// Sadly, your connection string is bad.
ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e);
m_dbConnection = null;
}
}
/// <summary>
/// Cleanup the existing command.
/// </summary>
/// <param name="ignoreException">
/// If true, a message will be written using LogLog.Warn if an exception is encountered when calling Dispose.
/// </param>
private void DisposeCommand(bool ignoreException)
{
// Cleanup any existing command or connection
if (m_dbCommand != null)
{
try
{
m_dbCommand.Dispose();
}
catch (Exception ex)
{
if (!ignoreException)
{
LogLog.Warn(declaringType, "Exception while disposing cached command object", ex);
}
}
m_dbCommand = null;
}
}
/// <summary>
/// Cleanup the existing connection.
/// </summary>
/// <remarks>
/// Calls the IDbConnection's <see cref="IDbConnection.Close"/> method.
/// </remarks>
private void DiposeConnection()
{
if (m_dbConnection != null)
{
try
{
m_dbConnection.Close();
}
catch (Exception ex)
{
LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex);
}
m_dbConnection = null;
}
}
#endregion // Private Instance Methods
#region Protected Instance Fields
/// <summary>
/// Flag to indicate if we are using a command object
/// </summary>
/// <remarks>
/// <para>
/// Set to <c>true</c> when the appender is to use a prepared
/// statement or stored procedure to insert into the database.
/// </para>
/// </remarks>
protected bool m_usePreparedCommand;
/// <summary>
/// The list of <see cref="AdoNetAppenderParameter"/> objects.
/// </summary>
/// <remarks>
/// <para>
/// The list of <see cref="AdoNetAppenderParameter"/> objects.
/// </para>
/// </remarks>
protected ArrayList m_parameters;
#endregion // Protected Instance Fields
#region Private Instance Fields
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
/// <summary>
/// The <see cref="IDbConnection" /> that will be used
/// to insert logging events into a database.
/// </summary>
private IDbConnection m_dbConnection;
/// <summary>
/// The database command.
/// </summary>
private IDbCommand m_dbCommand;
/// <summary>
/// Database connection string.
/// </summary>
private string m_connectionString;
/// <summary>
/// The appSettings key from App.Config that contains the connection string.
/// </summary>
private string m_appSettingsKey;
/// <summary>
/// The connectionStrings key from App.Config that contains the connection string.
/// </summary>
private string m_connectionStringName;
/// <summary>
/// String type name of the <see cref="IDbConnection"/> type name.
/// </summary>
private string m_connectionType;
/// <summary>
/// The text of the command.
/// </summary>
private string m_commandText;
/// <summary>
/// The command type.
/// </summary>
private CommandType m_commandType;
/// <summary>
/// Indicates whether to use transactions when writing to the database.
/// </summary>
private bool m_useTransactions;
/// <summary>
/// Indicates whether to use transactions when writing to the database.
/// </summary>
private bool m_reconnectOnError;
#endregion // Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the AdoNetAppender class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(AdoNetAppender);
#endregion Private Static Fields
}
/// <summary>
/// Parameter type used by the <see cref="AdoNetAppender"/>.
/// </summary>
/// <remarks>
/// <para>
/// This class provides the basic database parameter properties
/// as defined by the <see cref="System.Data.IDbDataParameter"/> interface.
/// </para>
/// <para>This type can be subclassed to provide database specific
/// functionality. The two methods that are called externally are
/// <see cref="Prepare"/> and <see cref="FormatValue"/>.
/// </para>
/// </remarks>
public class AdoNetAppenderParameter
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AdoNetAppenderParameter" /> class.
/// </summary>
/// <remarks>
/// Default constructor for the AdoNetAppenderParameter class.
/// </remarks>
public AdoNetAppenderParameter()
{
m_precision = 0;
m_scale = 0;
m_size = 0;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the name of this parameter.
/// </summary>
/// <value>
/// The name of this parameter.
/// </value>
/// <remarks>
/// <para>
/// The name of this parameter. The parameter name
/// must match up to a named parameter to the SQL stored procedure
/// or prepared statement.
/// </para>
/// </remarks>
public string ParameterName
{
get { return m_parameterName; }
set { m_parameterName = value; }
}
/// <summary>
/// Gets or sets the database type for this parameter.
/// </summary>
/// <value>
/// The database type for this parameter.
/// </value>
/// <remarks>
/// <para>
/// The database type for this parameter. This property should
/// be set to the database type from the <see cref="DbType"/>
/// enumeration. See <see cref="IDataParameter.DbType"/>.
/// </para>
/// <para>
/// This property is optional. If not specified the ADO.NET provider
/// will attempt to infer the type from the value.
/// </para>
/// </remarks>
/// <seealso cref="IDataParameter.DbType" />
public DbType DbType
{
get { return m_dbType; }
set
{
m_dbType = value;
m_inferType = false;
}
}
/// <summary>
/// Gets or sets the precision for this parameter.
/// </summary>
/// <value>
/// The precision for this parameter.
/// </value>
/// <remarks>
/// <para>
/// The maximum number of digits used to represent the Value.
/// </para>
/// <para>
/// This property is optional. If not specified the ADO.NET provider
/// will attempt to infer the precision from the value.
/// </para>
/// </remarks>
/// <seealso cref="IDbDataParameter.Precision" />
public byte Precision
{
get { return m_precision; }
set { m_precision = value; }
}
/// <summary>
/// Gets or sets the scale for this parameter.
/// </summary>
/// <value>
/// The scale for this parameter.
/// </value>
/// <remarks>
/// <para>
/// The number of decimal places to which Value is resolved.
/// </para>
/// <para>
/// This property is optional. If not specified the ADO.NET provider
/// will attempt to infer the scale from the value.
/// </para>
/// </remarks>
/// <seealso cref="IDbDataParameter.Scale" />
public byte Scale
{
get { return m_scale; }
set { m_scale = value; }
}
/// <summary>
/// Gets or sets the size for this parameter.
/// </summary>
/// <value>
/// The size for this parameter.
/// </value>
/// <remarks>
/// <para>
/// The maximum size, in bytes, of the data within the column.
/// </para>
/// <para>
/// This property is optional. If not specified the ADO.NET provider
/// will attempt to infer the size from the value.
/// </para>
/// <para>
/// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case.
/// </para>
/// </remarks>
/// <seealso cref="IDbDataParameter.Size" />
public int Size
{
get { return m_size; }
set { m_size = value; }
}
/// <summary>
/// Gets or sets the <see cref="IRawLayout"/> to use to
/// render the logging event into an object for this
/// parameter.
/// </summary>
/// <value>
/// The <see cref="IRawLayout"/> used to render the
/// logging event into an object for this parameter.
/// </value>
/// <remarks>
/// <para>
/// The <see cref="IRawLayout"/> that renders the value for this
/// parameter.
/// </para>
/// <para>
/// The <see cref="RawLayoutConverter"/> can be used to adapt
/// any <see cref="ILayout"/> into a <see cref="IRawLayout"/>
/// for use in the property.
/// </para>
/// </remarks>
public IRawLayout Layout
{
get { return m_layout; }
set { m_layout = value; }
}
#endregion // Public Instance Properties
#region Public Instance Methods
/// <summary>
/// Prepare the specified database command object.
/// </summary>
/// <param name="command">The command to prepare.</param>
/// <remarks>
/// <para>
/// Prepares the database command object by adding
/// this parameter to its collection of parameters.
/// </para>
/// </remarks>
virtual public void Prepare(IDbCommand command)
{
// Create a new parameter
IDbDataParameter param = command.CreateParameter();
// Set the parameter properties
param.ParameterName = m_parameterName;
if (!m_inferType)
{
param.DbType = m_dbType;
}
if (m_precision != 0)
{
param.Precision = m_precision;
}
if (m_scale != 0)
{
param.Scale = m_scale;
}
if (m_size != 0)
{
param.Size = m_size;
}
// Add the parameter to the collection of params
command.Parameters.Add(param);
}
/// <summary>
/// Renders the logging event and set the parameter value in the command.
/// </summary>
/// <param name="command">The command containing the parameter.</param>
/// <param name="loggingEvent">The event to be rendered.</param>
/// <remarks>
/// <para>
/// Renders the logging event using this parameters layout
/// object. Sets the value of the parameter on the command object.
/// </para>
/// </remarks>
virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent)
{
// Lookup the parameter
IDbDataParameter param = (IDbDataParameter)command.Parameters[m_parameterName];
// Format the value
object formattedValue = Layout.Format(loggingEvent);
// If the value is null then convert to a DBNull
if (formattedValue == null)
{
formattedValue = DBNull.Value;
}
param.Value = formattedValue;
}
#endregion // Public Instance Methods
#region Private Instance Fields
/// <summary>
/// The name of this parameter.
/// </summary>
private string m_parameterName;
/// <summary>
/// The database type for this parameter.
/// </summary>
private DbType m_dbType;
/// <summary>
/// Flag to infer type rather than use the DbType
/// </summary>
private bool m_inferType = true;
/// <summary>
/// The precision for this parameter.
/// </summary>
private byte m_precision;
/// <summary>
/// The scale for this parameter.
/// </summary>
private byte m_scale;
/// <summary>
/// The size for this parameter.
/// </summary>
private int m_size;
/// <summary>
/// The <see cref="IRawLayout"/> to use to render the
/// logging event into an object for this parameter.
/// </summary>
private IRawLayout m_layout;
#endregion // Private Instance Fields
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using Validation;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner Builder class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedSet<T>
{
/// <summary>
/// A sorted set that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted set instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// While <see cref="ImmutableSortedSet<T>.Union"/> and other bulk change methods
/// already provide fast bulk change operations on the collection, this class allows
/// multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedSet<>.Builder.DebuggerProxy))]
public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection
{
/// <summary>
/// The root of the binary tree that stores the collection. Contents are typically not entirely frozen.
/// </summary>
private ImmutableSortedSet<T>.Node root = ImmutableSortedSet<T>.Node.EmptyNode;
/// <summary>
/// The comparer to use for sorting the set.
/// </summary>
private IComparer<T> comparer = Comparer<T>.Default;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedSet<T> immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="set">A set to act as the basis for a new set.</param>
internal Builder(ImmutableSortedSet<T> set)
{
Requires.NotNull(set, "set");
this.root = set.root;
this.comparer = set.KeyComparer;
this.immutable = set;
}
#region ISet<T> Properties
/// <summary>
/// Gets the number of elements in this set.
/// </summary>
public int Count
{
get { return this.Root.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
/// <remarks>
/// No index setter is offered because the element being replaced may not sort
/// to the same position in the sorted collection as the replacing element.
/// </remarks>
public T this[int index]
{
get { return this.root[index]; }
}
/// <summary>
/// Gets the maximum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The maximum value in the set.</value>
public T Max
{
get { return this.root.Max; }
}
/// <summary>
/// Gets the minimum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The minimum value in the set.</value>
public T Min
{
get { return this.root.Min; }
}
/// <summary>
/// Gets or sets the System.Collections.Generic.IComparer<T> object that is used to determine equality for the values in the System.Collections.Generic.SortedSet<T>.
/// </summary>
/// <value>The comparer that is used to determine equality for the values in the set.</value>
/// <remarks>
/// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped,
/// leaving only one of each matching pair in the collection.
/// </remarks>
public IComparer<T> KeyComparer
{
get
{
return this.comparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.comparer)
{
var newRoot = Node.EmptyNode;
foreach (T item in this)
{
bool mutated;
newRoot = newRoot.Add(item, value, out mutated);
}
this.immutable = null;
this.comparer = value;
this.Root = newRoot;
}
}
}
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return this.version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return this.root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
this.version++;
if (this.root != value)
{
this.root = value;
// Clear any cached value for the immutable view since it is now invalidated.
this.immutable = null;
}
}
}
#region ISet<T> Methods
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
/// <returns>true if the element is added to the set; false if the element is already in the set.</returns>
public bool Add(T item)
{
bool mutated;
this.Root = this.Root.Add(item, this.comparer, out mutated);
return mutated;
}
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">The collection of items to remove from the set.</param>
public void ExceptWith(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Remove(item, this.comparer, out mutated);
}
}
/// <summary>
/// Modifies the current set so that it contains only elements that are also in a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void IntersectWith(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
var result = ImmutableSortedSet<T>.Node.EmptyNode;
foreach (T item in other)
{
if (this.Contains(item))
{
bool mutated;
result = result.Add(item, this.comparer, out mutated);
}
}
this.Root = result;
}
/// <summary>
/// Determines whether the current set is a proper (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of other; otherwise, false.</returns>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a proper (strict) superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSupersetOf(other);
}
/// <summary>
/// Determines whether the current set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
public bool IsSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSupersetOf(other);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
public bool Overlaps(IEnumerable<T> other)
{
return this.ToImmutable().Overlaps(other);
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is equal to other; otherwise, false.</returns>
public bool SetEquals(IEnumerable<T> other)
{
return this.ToImmutable().SetEquals(other);
}
/// <summary>
/// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void SymmetricExceptWith(IEnumerable<T> other)
{
this.Root = this.ToImmutable().SymmetricExcept(other).root;
}
/// <summary>
/// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void UnionWith(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Add(item, this.comparer, out mutated);
}
}
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
void ICollection<T>.Add(T item)
{
this.Add(item);
}
/// <summary>
/// Removes all elements from this set.
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedSet<T>.Node.EmptyNode;
}
/// <summary>
/// Determines whether the set contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the set.</param>
/// <returns>true if item is found in the set; false otherwise.</returns>
public bool Contains(T item)
{
return this.Root.Contains(item, this.comparer);
}
/// <summary>
/// See <see cref="ICollection<T>"/>
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
this.root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the set.
/// </summary>
/// <param name="item">The object to remove from the set.</param>
/// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns>
public bool Remove(T item)
{
bool mutated;
this.Root = this.Root.Remove(item, this.comparer, out mutated);
return mutated;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
public ImmutableSortedSet<T>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.Root.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an System.Collections.Generic.IEnumerable<T> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the System.Collections.Generic.SortedSet<T>
/// in reverse order.
/// </returns>
[Pure]
public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(this.root);
}
/// <summary>
/// Creates an immutable sorted set based on the contents of this instance.
/// </summary>
/// <returns>An immutable set.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedSet<T> ToImmutable()
{
// Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (this.immutable == null)
{
this.immutable = ImmutableSortedSet<T>.Wrap(this.Root, this.comparer);
}
return this.immutable;
}
#region ICollection members
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
/// <exception cref="System.NotImplementedException"></exception>
void ICollection.CopyTo(Array array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns>
/// <exception cref="System.NotImplementedException"></exception>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.</returns>
/// <exception cref="System.NotImplementedException"></exception>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (this.syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref this.syncRoot, new Object(), null);
}
return this.syncRoot;
}
}
#endregion
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
[ExcludeFromCodeCoverage]
private class DebuggerProxy
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableSortedSet<T>.Node set;
/// <summary>
/// The simple view of the collection.
/// </summary>
private T[] contents;
/// <summary>
/// Initializes a new instance of the <see cref="DebuggerProxy"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public DebuggerProxy(ImmutableSortedSet<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
this.set = builder.Root;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Contents
{
get
{
if (this.contents == null)
{
this.contents = this.set.ToArray(this.set.Count);
}
return this.contents;
}
}
}
}
}
}
| |
//
// FolderExport.cs
//
// Author:
// Lorenzo Milesi <maxxer@yetopen.it>
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008 Lorenzo Milesi
// Copyright (C) 2008-2009 Stephane Delcroix
//
// 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.
//
/*
* Copyright (C) 2005 Alessandro Gervaso <gervystar@gervystar.net>
*
* 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., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301
*/
//This should be used to export the selected pics to an original gallery
//located on a GIO location.
using System;
using System.IO;
using Hyena;
using Mono.Unix;
using FSpot.Core;
using FSpot.Filters;
using FSpot.Settings;
using FSpot.Widgets;
using FSpot.Utils;
using FSpot.UI.Dialog;
namespace FSpot.Exporters.Folder
{
public class FolderExport : FSpot.Extensions.IExporter
{
IBrowsableCollection selection;
#pragma warning disable 649
[GtkBeans.Builder.Object] Gtk.Dialog dialog;
[GtkBeans.Builder.Object] Gtk.ScrolledWindow thumb_scrolledwindow;
[GtkBeans.Builder.Object] Gtk.Entry name_entry;
[GtkBeans.Builder.Object] Gtk.Entry description_entry;
[GtkBeans.Builder.Object] Gtk.CheckButton scale_check;
[GtkBeans.Builder.Object] Gtk.CheckButton export_tags_check;
[GtkBeans.Builder.Object] Gtk.CheckButton export_tag_icons_check;
[GtkBeans.Builder.Object] Gtk.CheckButton open_check;
[GtkBeans.Builder.Object] Gtk.RadioButton static_radio;
[GtkBeans.Builder.Object] Gtk.RadioButton original_radio;
[GtkBeans.Builder.Object] Gtk.RadioButton plain_radio;
[GtkBeans.Builder.Object] Gtk.SpinButton size_spin;
[GtkBeans.Builder.Object] Gtk.HBox chooser_hbox;
#pragma warning restore 649
public const string EXPORT_SERVICE = "folder/";
public const string SCALE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "scale";
public const string SIZE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "size";
public const string OPEN_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "browser";
public const string EXPORT_TAGS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "export_tags";
public const string EXPORT_TAG_ICONS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "export_tag_icons";
public const string METHOD_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "method";
public const string URI_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "uri";
public const string SHARPEN_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "sharpen";
public const string INCLUDE_TARBALLS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "include_tarballs";
private GtkBeans.Builder builder;
private string dialog_name = "folder_export_dialog";
GLib.File dest;
Gtk.FileChooserButton uri_chooser;
bool open;
bool scale;
bool exportTags;
bool exportTagIcons;
int size;
string description;
string gallery_name = Catalog.GetString("Gallery");
// FIXME: this needs to be a real temp directory
string gallery_path = Path.Combine (Path.GetTempPath (), "f-spot-original-" + System.DateTime.Now.Ticks.ToString ());
ThreadProgressDialog progress_dialog;
System.Threading.Thread command_thread;
public FolderExport () {}
public void Run (IBrowsableCollection selection)
{
this.selection = selection;
var view = new TrayView (selection);
view.DisplayDates = false;
view.DisplayTags = false;
builder = new GtkBeans.Builder (null, "folder_export.ui", null);
builder.Autoconnect (this);
Dialog.Modal = false;
Dialog.TransientFor = null;
thumb_scrolledwindow.Add (view);
HandleSizeActive (null, null);
name_entry.Text = gallery_name;
string uri_path = System.IO.Path.Combine (FSpot.Settings.Global.HomeDirectory, "Desktop");
if (!System.IO.Directory.Exists (uri_path))
uri_path = FSpot.Settings.Global.HomeDirectory;
uri_chooser = new Gtk.FileChooserButton (Catalog.GetString ("Select Export Folder"),
Gtk.FileChooserAction.SelectFolder);
uri_chooser.LocalOnly = false;
if (!string.IsNullOrEmpty (Preferences.Get<string> (URI_KEY)))
uri_chooser.SetCurrentFolderUri (Preferences.Get<string> (URI_KEY));
else
uri_chooser.SetFilename (uri_path);
chooser_hbox.PackStart (uri_chooser);
Dialog.ShowAll ();
Dialog.Response += HandleResponse;
LoadPreference (SCALE_KEY);
LoadPreference (SIZE_KEY);
LoadPreference (OPEN_KEY);
LoadPreference (EXPORT_TAGS_KEY);
LoadPreference (EXPORT_TAG_ICONS_KEY);
LoadPreference (METHOD_KEY);
}
public void HandleSizeActive (object sender, System.EventArgs args)
{
size_spin.Sensitive = scale_check.Active;
}
public void HandleStandaloneActive (object sender, System.EventArgs args)
{
export_tags_check.Sensitive = static_radio.Active;
HandleExportTagsActive (sender, args);
}
public void HandleExportTagsActive (object sender, System.EventArgs args)
{
export_tag_icons_check.Sensitive = export_tags_check.Active && static_radio.Active;
}
public void Upload ()
{
// FIXME: use mkstemp
try {
ThreadAssist.ProxyToMain (Dialog.Hide);
GLib.File source = GLib.FileFactory.NewForPath (Path.Combine (gallery_path, gallery_name));
GLib.File target = GLib.FileFactory.NewForPath (Path.Combine (dest.Path, source.Basename));
if (dest.IsNative)
gallery_path = dest.Path;
progress_dialog.Message = Catalog.GetString ("Building Gallery");
progress_dialog.Fraction = 0.0;
FolderGallery gallery;
if (static_radio.Active) {
gallery = new HtmlGallery (selection, gallery_path, gallery_name);
} else if (original_radio.Active) {
gallery = new OriginalGallery (selection, gallery_path, gallery_name);
} else {
gallery = new FolderGallery (selection, gallery_path, gallery_name);
}
if (scale) {
Log.DebugFormat ("Resize Photos to {0}.", size);
gallery.SetScale (size);
} else {
Log.Debug ("Exporting full size.");
}
if (exportTags)
gallery.ExportTags = true;
if (exportTagIcons)
gallery.ExportTagIcons = true;
gallery.Description = description;
gallery.GenerateLayout ();
FilterSet filter_set = new FilterSet ();
if (scale)
filter_set.Add (new ResizeFilter ((uint) size));
filter_set.Add (new ChmodFilter ());
filter_set.Add (new UniqueNameFilter (new SafeUri (gallery_path)));
for (int photo_index = 0; photo_index < selection.Count; photo_index++)
{
try {
progress_dialog.Message = string.Format (Catalog.GetString ("Exporting \"{0}\"..."), selection[photo_index].Name);
progress_dialog.Fraction = photo_index / (double) selection.Count;
gallery.ProcessImage (photo_index, filter_set);
progress_dialog.ProgressText = string.Format (Catalog.GetString ("{0} of {1}"), (photo_index + 1), selection.Count);
}
catch (Exception e) {
Log.Error (e.ToString ());
progress_dialog.Message = string.Format (Catalog.GetString ("Error Copying \"{0}\" to Gallery:{2}{1}"),
selection[photo_index].Name, e.Message, Environment.NewLine);
progress_dialog.ProgressText = Catalog.GetString ("Error");
if (progress_dialog.PerformRetrySkip ())
photo_index--;
}
}
// create the zip tarballs for original
if (gallery is OriginalGallery) {
bool include_tarballs;
try {
include_tarballs = Preferences.Get<bool> (INCLUDE_TARBALLS_KEY);
} catch (NullReferenceException){
include_tarballs = true;
Preferences.Set (INCLUDE_TARBALLS_KEY, true);
}
if (include_tarballs)
(gallery as OriginalGallery).CreateZip ();
}
// we've created the structure, now if the destination was local (native) we are done
// otherwise we xfer
if (!dest.IsNative) {
Log.DebugFormat ("Transferring \"{0}\" to \"{1}\"", source.Path, target.Path);
progress_dialog.Message = string.Format (Catalog.GetString ("Transferring to \"{0}\""), target.Path);
progress_dialog.ProgressText = Catalog.GetString ("Transferring...");
source.CopyRecursive (target, GLib.FileCopyFlags.Overwrite, new GLib.Cancellable (), Progress);
}
// No need to check result here as if result is not true, an Exception will be thrown before
progress_dialog.Message = Catalog.GetString ("Export Complete.");
progress_dialog.Fraction = 1.0;
progress_dialog.ProgressText = Catalog.GetString ("Exporting Photos Completed.");
progress_dialog.ButtonLabel = Gtk.Stock.Ok;
if (open) {
Log.DebugFormat (string.Format ("Open URI \"{0}\"", target.Uri.ToString ()));
ThreadAssist.ProxyToMain (() => { GtkBeans.Global.ShowUri (Dialog.Screen, target.Uri.ToString () ); });
}
// Save these settings for next time
Preferences.Set (SCALE_KEY, scale);
Preferences.Set (SIZE_KEY, size);
Preferences.Set (OPEN_KEY, open);
Preferences.Set (EXPORT_TAGS_KEY, exportTags);
Preferences.Set (EXPORT_TAG_ICONS_KEY, exportTagIcons);
Preferences.Set (METHOD_KEY, static_radio.Active ? "static" : original_radio.Active ? "original" : "folder" );
Preferences.Set (URI_KEY, uri_chooser.Uri);
} catch (System.Exception e) {
Log.Error (e.ToString ());
progress_dialog.Message = e.ToString ();
progress_dialog.ProgressText = Catalog.GetString ("Error Transferring");
} finally {
// if the destination isn't local then we want to remove the temp directory we
// created.
if (!dest.IsNative)
System.IO.Directory.Delete (gallery_path, true);
ThreadAssist.ProxyToMain (() => { Dialog.Destroy(); });
}
}
private void Progress (long current_num_bytes, long total_num_bytes)
{
if (total_num_bytes > 0)
progress_dialog.Fraction = current_num_bytes / (double)total_num_bytes;
}
private void HandleResponse (object sender, Gtk.ResponseArgs args)
{
if (args.ResponseId != Gtk.ResponseType.Ok) {
// FIXME this is to work around a bug in gtk+ where
// the filesystem events are still listened to when
// a FileChooserButton is destroyed but not finalized
// and an event comes in that wants to update the child widgets.
Dialog.Destroy ();
uri_chooser.Dispose ();
uri_chooser = null;
return;
}
dest = GLib.FileFactory.NewForUri (uri_chooser.Uri);
open = open_check.Active;
scale = scale_check.Active;
exportTags = export_tags_check.Active;
exportTagIcons = export_tag_icons_check.Active;
gallery_name = name_entry.Text;
if (description_entry != null)
description = description_entry.Text;
if (scale)
size = size_spin.ValueAsInt;
command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (Upload));
command_thread.Name = Catalog.GetString ("Exporting Photos");
progress_dialog = new ThreadProgressDialog (command_thread, 1);
progress_dialog.Start ();
}
void LoadPreference (string key)
{
switch (key) {
case SCALE_KEY:
if (scale_check.Active != Preferences.Get<bool> (key))
scale_check.Active = Preferences.Get<bool> (key);
break;
case SIZE_KEY:
int size;
if (Preferences.TryGet<int> (key, out size))
size_spin.Value = (double) size;
else
size_spin.Value = 400;
break;
case OPEN_KEY:
if (open_check.Active != Preferences.Get<bool> (key))
open_check.Active = Preferences.Get<bool> (key);
break;
case EXPORT_TAGS_KEY:
if (export_tags_check.Active != Preferences.Get<bool> (key))
export_tags_check.Active = Preferences.Get<bool> (key);
break;
case EXPORT_TAG_ICONS_KEY:
if (export_tag_icons_check.Active != Preferences.Get<bool> (key))
export_tag_icons_check.Active = Preferences.Get<bool> (key);
break;
case METHOD_KEY:
static_radio.Active = (Preferences.Get<string> (key) == "static");
original_radio.Active = (Preferences.Get<string> (key) == "original");
plain_radio.Active = (Preferences.Get<string> (key) == "folder");
break;
}
}
private Gtk.Dialog Dialog {
get {
if (dialog == null)
dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name));
return dialog;
}
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// C = angle2 - angle1 - referenceAngle
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
/// <summary>
/// A weld joint essentially glues two bodies together. A weld joint may
/// distort somewhat because the island constraint solver is approximate.
/// </summary>
public class WeldJoint : Joint
{
public Vector2 LocalAnchorA;
public Vector2 LocalAnchorB;
private Vector3 _impulse;
private Mat33 _mass;
/// <summary>
/// You need to specify a local anchor point
/// where they are attached and the relative body angle. The position
/// of the anchor point is important for computing the reaction torque.
/// You can change the anchor points relative to bodyA or bodyB by changing LocalAnchorA
/// and/or LocalAnchorB.
/// </summary>
/// <param name="bodyA">The first body</param>
/// <param name="bodyB">The second body</param>
/// <param name="localAnchorA">The first body anchor.</param>
/// <param name="localAnchorB">The second body anchor.</param>
public WeldJoint(Body bodyA, Body bodyB, Vector2 localAnchorA, Vector2 localAnchorB)
: base(bodyA, bodyB)
{
JointType = JointType.Weld;
LocalAnchorA = localAnchorA;
LocalAnchorB = localAnchorB;
ReferenceAngle = BodyB.Rotation - BodyA.Rotation;
}
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
/// <summary>
/// The body2 angle minus body1 angle in the reference state (radians).
/// </summary>
public float ReferenceAngle { get; private set; }
public override Vector2 GetReactionForce(float inv_dt)
{
return inv_dt*new Vector2(_impulse.X, _impulse.Y);
}
public override float GetReactionTorque(float inv_dt)
{
return inv_dt*_impulse.Z;
}
internal override void InitVelocityConstraints(ref TimeStep step)
{
Body bA = BodyA;
Body bB = BodyB;
Transform xfA, xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
// Compute the effective mass matrix.
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
_mass.Col1.X = mA + mB + rA.Y*rA.Y*iA + rB.Y*rB.Y*iB;
_mass.Col2.X = -rA.Y*rA.X*iA - rB.Y*rB.X*iB;
_mass.Col3.X = -rA.Y*iA - rB.Y*iB;
_mass.Col1.Y = _mass.Col2.X;
_mass.Col2.Y = mA + mB + rA.X*rA.X*iA + rB.X*rB.X*iB;
_mass.Col3.Y = rA.X*iA + rB.X*iB;
_mass.Col1.Z = _mass.Col3.X;
_mass.Col2.Z = _mass.Col3.Y;
_mass.Col3.Z = iA + iB;
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_impulse *= step.dtRatio;
Vector2 P = new Vector2(_impulse.X, _impulse.Y);
bA.LinearVelocityInternal -= mA*P;
bA.AngularVelocityInternal -= iA*(MathUtils.Cross(rA, P) + _impulse.Z);
bB.LinearVelocityInternal += mB*P;
bB.AngularVelocityInternal += iB*(MathUtils.Cross(rB, P) + _impulse.Z);
}
else
{
_impulse = Vector3.Zero;
}
}
internal override void SolveVelocityConstraints(ref TimeStep step)
{
Body bA = BodyA;
Body bB = BodyB;
Vector2 vA = bA.LinearVelocityInternal;
float wA = bA.AngularVelocityInternal;
Vector2 vB = bB.LinearVelocityInternal;
float wB = bB.AngularVelocityInternal;
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
Transform xfA, xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
// Solve point-to-point constraint
Vector2 Cdot1 = vB + MathUtils.Cross(wB, rB) - vA - MathUtils.Cross(wA, rA);
float Cdot2 = wB - wA;
Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2);
Vector3 impulse = _mass.Solve33(-Cdot);
_impulse += impulse;
Vector2 P = new Vector2(impulse.X, impulse.Y);
vA -= mA*P;
wA -= iA*(MathUtils.Cross(rA, P) + impulse.Z);
vB += mB*P;
wB += iB*(MathUtils.Cross(rB, P) + impulse.Z);
bA.LinearVelocityInternal = vA;
bA.AngularVelocityInternal = wA;
bB.LinearVelocityInternal = vB;
bB.AngularVelocityInternal = wB;
}
internal override bool SolvePositionConstraints()
{
Body bA = BodyA;
Body bB = BodyB;
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
Transform xfA;
Transform xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
Vector2 C1 = bB.Sweep.C + rB - bA.Sweep.C - rA;
float C2 = bB.Sweep.A - bA.Sweep.A - ReferenceAngle;
// Handle large detachment.
const float k_allowedStretch = 10.0f*Settings.LinearSlop;
float positionError = C1.Length();
float angularError = Math.Abs(C2);
if (positionError > k_allowedStretch)
{
iA *= 1.0f;
iB *= 1.0f;
}
_mass.Col1.X = mA + mB + rA.Y*rA.Y*iA + rB.Y*rB.Y*iB;
_mass.Col2.X = -rA.Y*rA.X*iA - rB.Y*rB.X*iB;
_mass.Col3.X = -rA.Y*iA - rB.Y*iB;
_mass.Col1.Y = _mass.Col2.X;
_mass.Col2.Y = mA + mB + rA.X*rA.X*iA + rB.X*rB.X*iB;
_mass.Col3.Y = rA.X*iA + rB.X*iB;
_mass.Col1.Z = _mass.Col3.X;
_mass.Col2.Z = _mass.Col3.Y;
_mass.Col3.Z = iA + iB;
Vector3 C = new Vector3(C1.X, C1.Y, C2);
Vector3 impulse = _mass.Solve33(-C);
Vector2 P = new Vector2(impulse.X, impulse.Y);
bA.Sweep.C -= mA*P;
bA.Sweep.A -= iA*(MathUtils.Cross(rA, P) + impulse.Z);
bB.Sweep.C += mB*P;
bB.Sweep.A += iB*(MathUtils.Cross(rB, P) + impulse.Z);
bA.SynchronizeTransform();
bB.SynchronizeTransform();
return positionError <= Settings.LinearSlop && angularError <= Settings.AngularSlop;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WorksheetConfiguration.cs" company="Patrick Magee">
// The MIT License (MIT)
//
// Copyright (c) 2014 Patrick Magee
//
// 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.
// </copyright>
// <summary>
// The worksheet configuration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace EPPlus.ComponentModel.Export
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;
using EPPlus.ComponentModel.Common;
using OfficeOpenXml;
using OfficeOpenXml.Table;
/// <summary>
/// The worksheet configuration.
/// </summary>
public class WorksheetConfiguration : IWorksheetConfiguration
{
#region Fields
/// <summary>
/// The ExportService.
/// </summary>
private readonly IExportService exportService;
/// <summary>
/// Tables must have a unique table name.
/// This stores the number of tables for each type, so that the next table name
/// can store the index of that type.
/// </summary>
/// <example>
/// table_type_1, table_type_2
/// </example>
private readonly IDictionary<Type, int> typeCount;
/// <summary>
/// The pluraliser for tables
/// </summary>
private readonly PluralizationService pluralizationService;
/// <summary>
/// The table configurations.
/// </summary>
private readonly List<ITableConfiguration> tableConfigurations;
/// <summary>
/// The worksheet.
/// </summary>
private readonly ExcelWorksheet worksheet;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="WorksheetConfiguration"/> class.
/// </summary>
/// <param name="exportService">
/// The ExportService.
/// </param>
/// <param name="worksheet">
/// The worksheet.
/// </param>
/// <exception cref="ArgumentNullException">
/// </exception>
public WorksheetConfiguration(IExportService exportService, ExcelWorksheet worksheet) : this()
{
if (exportService == null)
{
throw new ArgumentNullException("exportService");
}
if (worksheet == null)
{
throw new ArgumentNullException("worksheet");
}
this.exportService = exportService;
this.worksheet = worksheet;
}
/// <summary>
/// Prevents a default instance of the <see cref="WorksheetConfiguration"/> class from being created.
/// </summary>
private WorksheetConfiguration()
{
this.pluralizationService = PluralizationService.CreateService(CultureInfo.CurrentCulture);
this.tableConfigurations = new List<ITableConfiguration>();
this.typeCount = new Dictionary<Type, int>();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the ExportService.
/// </summary>
public IExportService ExportService
{
get
{
return this.exportService;
}
}
/// <summary>
/// Gets the table configurations.
/// </summary>
public IEnumerable<ITableConfiguration> TableConfigurations
{
get
{
return this.tableConfigurations;
}
}
/// <summary>
/// Gets the worksheet name.
/// </summary>
public string WorksheetName
{
get
{
return this.worksheet.Name;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// The add table for export.
/// </summary>
/// <param name="collection">
/// The collection.
/// </param>
/// <param name="tableName">
/// The table name.
/// </param>
/// <typeparam name="T">
/// </typeparam>
/// <returns>
/// The <see cref="ITableConfiguration"/>.
/// </returns>
public ITableConfiguration<T> AddTableForExport<T>(IEnumerable<T> collection, string tableName = null)
{
var key = this.GetKey(tableName ?? string.Empty, typeof(T));
var rangeToFill = this.GetRangeToFill();
var dataTable = collection.ToDataTable(key);
rangeToFill.LoadFromDataTable(dataTable, PrintHeaders: true, TableStyle: TableStyles.Dark1);
var table = worksheet.Tables[key];
return this.CreateTableConfiguration<T>(table);
}
#endregion
#region Methods
/// <summary>
/// The create table configuration.
/// </summary>
/// <param name="table">
/// The table.
/// </param>
/// <typeparam name="T">
/// </typeparam>
/// <returns>
/// The <see cref="ITableConfiguration"/>.
/// </returns>
private ITableConfiguration<T> CreateTableConfiguration<T>(ExcelTable table)
{
ITableConfiguration<T> configuration = new TableConfiguration<T>(this, table);
this.tableConfigurations.Add(configuration);
return configuration;
}
/// <summary>
/// It gets the correct ExcelRange to fill from by inserting new rows at the end of the current range.
/// This ensures there is an empty row between new tables being inserted into the spreadsheet.
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <returns>
/// The <see cref="ExcelRange"/> that is to be filled from a collection or datatable.
/// </returns>
private ExcelRange GetRangeToFill()
{
var isEmpty = this.worksheet.Dimension == null;
return this.worksheet.Cells[isEmpty ? 1 : this.worksheet.Dimension.End.Row + 2, 1];
}
/// <summary>
/// The get key.
/// </summary>
/// <param name="tableName">
/// The table name.
/// </param>
/// <typeparam name="T">
/// </typeparam>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// </exception>
public string GetKey(string tableName, Type type)
{
if (tableName == null)
{
throw new ArgumentNullException("tableName");
}
var count = 1;
if (!typeCount.ContainsKey(type))
{
typeCount[type] = 1;
}
else
{
count = typeCount[type] + 1;
typeCount[type] = count;
}
tableName = tableName.Replace(" ", "_");
var sheetName = WorksheetName.Replace(" ", "_");
var plural = pluralizationService.Pluralize(type.Name);
return string.Format("{0}_{1}_{2}_{3}", sheetName, tableName, plural, count).Replace("__", "_");
}
#endregion
}
}
| |
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
// For more info on events, see https://msdn.microsoft.com/en-us/library/bb161367.aspx
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Cosmos.VS.DebugEngine.AD7.Impl
{
#region Event base classes
class AD7AsynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7StoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7SynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7SynchronousStoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
#endregion
sealed class AD7StepCompletedEvent : IDebugEvent2, IDebugStepCompleteEvent2
{
public const string IID = "0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D";
public static void Send(AD7Engine engine)
{
var xEvent = new AD7StepCompletedEvent();
engine.Callback.Send(xEvent, IID, engine.mProcess.Thread);
}
#region IDebugEvent2 Members
public int GetAttributes(out uint pdwAttrib)
{
pdwAttrib = (uint)(enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP);
return VSConstants.S_OK;
}
#endregion
}
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2
{
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 m_engine;
AD7EngineCreateEvent(AD7Engine engine)
{
m_engine = engine;
}
public static void Send(AD7Engine engine)
{
var eventObject = new AD7EngineCreateEvent(engine);
engine.Callback.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine)
{
engine = m_engine;
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
sealed class AD7ProgramCreateEvent : AD7AsynchronousEvent, IDebugProgramCreateEvent2
{
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine)
{
var eventObject = new AD7ProgramCreateEvent();
engine.Callback.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2
{
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
readonly AD7Module m_module;
readonly bool m_fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad)
{
m_module = module;
m_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad)
{
module = m_module;
if (m_fLoad)
{
//debugMessage = String.Concat("Loaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 1;
}
else
{
//debugMessage = String.Concat("Unloaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 0;
}
return VSConstants.S_OK;
}
internal static void Send(AD7Engine engine, AD7Module aModule, bool fLoad)
{
var eventObject = new AD7ModuleLoadEvent(aModule, fLoad);
engine.Callback.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2
{
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
readonly uint m_exitCode;
public AD7ProgramDestroyEvent(uint exitCode)
{
m_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2
{
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
internal static void Send(AD7Engine engine, IDebugThread2 aThread)
{
var eventObject = new AD7ThreadCreateEvent();
engine.Callback.Send(eventObject, IID, aThread);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2
{
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
readonly uint m_exitCode;
public AD7ThreadDestroyEvent(uint exitCode)
{
m_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = m_exitCode;
return VSConstants.S_OK;
}
internal static void Send(AD7Engine aEngine, IDebugThread2 aThread, uint aExitCode)
{
var xObj = new AD7ThreadDestroyEvent(aExitCode);
aEngine.Callback.Send(xObj, IID, aThread);
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent()
{
}
internal static void Send(AD7Engine aEngine, AD7Thread aThread)
{
var xMessage = new AD7LoadCompleteEvent();
aEngine.Callback.Send(xMessage, IID, aThread);
}
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2
{
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing.
sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2
{
public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e";
private string m_str;
public AD7OutputDebugStringEvent(string str)
{
m_str = str;
}
#region IDebugOutputStringEvent2 Members
int IDebugOutputStringEvent2.GetString(out string pbstrString)
{
pbstrString = m_str;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to indicate the results of searching for symbols for a module in the debuggee
sealed class AD7SymbolSearchEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2
{
public const string IID = "638F7C54-C160-4c7b-B2D0-E0337BC61F8C";
private AD7Module m_module;
private string m_searchInfo;
private enum_MODULE_INFO_FLAGS m_symbolFlags;
public AD7SymbolSearchEvent(AD7Module module, string searchInfo, enum_MODULE_INFO_FLAGS symbolFlags)
{
m_module = module;
m_searchInfo = searchInfo;
m_symbolFlags = symbolFlags;
}
#region IDebugSymbolSearchEvent2 Members
int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags)
{
pModule = m_module;
pbstrDebugMessage = m_searchInfo;
pdwModuleInfoFlags[0] = m_symbolFlags;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2
{
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint m_pendingBreakpoint;
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint)
{
m_pendingBreakpoint = pendingBreakpoint;
m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
var boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = m_boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return VSConstants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP)
{
ppPendingBP = m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
}
// This Event is sent when a breakpoint is hit in the debuggee
sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2
{
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
IEnumDebugBoundBreakpoints2 m_boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints)
{
m_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = m_boundBreakpoints;
return VSConstants.S_OK;
}
#endregion
}
sealed class AD7EntrypointEvent : AD7StoppingEvent, IDebugEntryPointEvent2
{
public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9";
public static void Send(AD7Engine aEngine)
{
aEngine.Callback.Send(new AD7EntrypointEvent(), IID, null);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Responses/DownloadRemoteConfigVersionResponse.proto
#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 POGOProtos.Networking.Responses {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/DownloadRemoteConfigVersionResponse.proto</summary>
public static partial class DownloadRemoteConfigVersionResponseReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Responses/DownloadRemoteConfigVersionResponse.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DownloadRemoteConfigVersionResponseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CklQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0Rvd25sb2FkUmVt",
"b3RlQ29uZmlnVmVyc2lvblJlc3BvbnNlLnByb3RvEh9QT0dPUHJvdG9zLk5l",
"dHdvcmtpbmcuUmVzcG9uc2VzIuwBCiNEb3dubG9hZFJlbW90ZUNvbmZpZ1Zl",
"cnNpb25SZXNwb25zZRJbCgZyZXN1bHQYASABKA4ySy5QT0dPUHJvdG9zLk5l",
"dHdvcmtpbmcuUmVzcG9uc2VzLkRvd25sb2FkUmVtb3RlQ29uZmlnVmVyc2lv",
"blJlc3BvbnNlLlJlc3VsdBIjChtpdGVtX3RlbXBsYXRlc190aW1lc3RhbXBf",
"bXMYAiABKAQSIQoZYXNzZXRfZGlnZXN0X3RpbWVzdGFtcF9tcxgDIAEoBCIg",
"CgZSZXN1bHQSCQoFVU5TRVQQABILCgdTVUNDRVNTEAFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse), global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse.Parser, new[]{ "Result", "ItemTemplatesTimestampMs", "AssetDigestTimestampMs" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse.Types.Result) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class DownloadRemoteConfigVersionResponse : pb::IMessage<DownloadRemoteConfigVersionResponse> {
private static readonly pb::MessageParser<DownloadRemoteConfigVersionResponse> _parser = new pb::MessageParser<DownloadRemoteConfigVersionResponse>(() => new DownloadRemoteConfigVersionResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DownloadRemoteConfigVersionResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DownloadRemoteConfigVersionResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DownloadRemoteConfigVersionResponse(DownloadRemoteConfigVersionResponse other) : this() {
result_ = other.result_;
itemTemplatesTimestampMs_ = other.itemTemplatesTimestampMs_;
assetDigestTimestampMs_ = other.assetDigestTimestampMs_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DownloadRemoteConfigVersionResponse Clone() {
return new DownloadRemoteConfigVersionResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse.Types.Result result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse.Types.Result Result {
get { return result_; }
set {
result_ = value;
}
}
/// <summary>Field number for the "item_templates_timestamp_ms" field.</summary>
public const int ItemTemplatesTimestampMsFieldNumber = 2;
private ulong itemTemplatesTimestampMs_;
/// <summary>
/// Latest available?
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong ItemTemplatesTimestampMs {
get { return itemTemplatesTimestampMs_; }
set {
itemTemplatesTimestampMs_ = value;
}
}
/// <summary>Field number for the "asset_digest_timestamp_ms" field.</summary>
public const int AssetDigestTimestampMsFieldNumber = 3;
private ulong assetDigestTimestampMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong AssetDigestTimestampMs {
get { return assetDigestTimestampMs_; }
set {
assetDigestTimestampMs_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DownloadRemoteConfigVersionResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DownloadRemoteConfigVersionResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
if (ItemTemplatesTimestampMs != other.ItemTemplatesTimestampMs) return false;
if (AssetDigestTimestampMs != other.AssetDigestTimestampMs) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
if (ItemTemplatesTimestampMs != 0UL) hash ^= ItemTemplatesTimestampMs.GetHashCode();
if (AssetDigestTimestampMs != 0UL) hash ^= AssetDigestTimestampMs.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
if (ItemTemplatesTimestampMs != 0UL) {
output.WriteRawTag(16);
output.WriteUInt64(ItemTemplatesTimestampMs);
}
if (AssetDigestTimestampMs != 0UL) {
output.WriteRawTag(24);
output.WriteUInt64(AssetDigestTimestampMs);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
if (ItemTemplatesTimestampMs != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ItemTemplatesTimestampMs);
}
if (AssetDigestTimestampMs != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(AssetDigestTimestampMs);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DownloadRemoteConfigVersionResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
if (other.ItemTemplatesTimestampMs != 0UL) {
ItemTemplatesTimestampMs = other.ItemTemplatesTimestampMs;
}
if (other.AssetDigestTimestampMs != 0UL) {
AssetDigestTimestampMs = other.AssetDigestTimestampMs;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse.Types.Result) input.ReadEnum();
break;
}
case 16: {
ItemTemplatesTimestampMs = input.ReadUInt64();
break;
}
case 24: {
AssetDigestTimestampMs = input.ReadUInt64();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the DownloadRemoteConfigVersionResponse message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum Result {
[pbr::OriginalName("UNSET")] Unset = 0,
[pbr::OriginalName("SUCCESS")] Success = 1,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
namespace MyMeta
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class Parameters : Collection, IParameters, IEnumerable, ICollection
{
public Parameters()
{
}
internal DataColumn f_Catalog = null;
internal DataColumn f_Schema = null;
internal DataColumn f_ProcedureName = null;
internal DataColumn f_ParameterName = null;
internal DataColumn f_Ordinal = null;
internal DataColumn f_Type = null;
internal DataColumn f_HasDefault = null;
internal DataColumn f_Default = null;
internal DataColumn f_IsNullable = null;
internal DataColumn f_DataType = null;
internal DataColumn f_CharMaxLength = null;
internal DataColumn f_CharOctetLength = null;
internal DataColumn f_NumericPrecision = null;
internal DataColumn f_NumericScale = null;
internal DataColumn f_Description = null;
internal DataColumn f_TypeName = null;
internal DataColumn f_FullTypeName = null;
internal DataColumn f_LocalTypeName = null;
private void BindToColumns(DataTable metaData)
{
if(false == _fieldsBound)
{
if(metaData.Columns.Contains("PROCEDURE_CATALOG")) f_Catalog = metaData.Columns["PROCEDURE_CATALOG"];
if(metaData.Columns.Contains("PROCEDURE_SCHEMA")) f_Schema = metaData.Columns["PROCEDURE_SCHEMA"];
if(metaData.Columns.Contains("PROCEDURE_NAME")) f_ProcedureName = metaData.Columns["PROCEDURE_NAME"];
if(metaData.Columns.Contains("PARAMETER_NAME")) f_ParameterName = metaData.Columns["PARAMETER_NAME"];
if(metaData.Columns.Contains("ORDINAL_POSITION")) f_Ordinal = metaData.Columns["ORDINAL_POSITION"];
if(metaData.Columns.Contains("PARAMETER_TYPE")) f_Type = metaData.Columns["PARAMETER_TYPE"];
if(metaData.Columns.Contains("PARAMETER_HASDEFAULT")) f_HasDefault = metaData.Columns["PARAMETER_HASDEFAULT"];
if(metaData.Columns.Contains("PARAMETER_DEFAULT")) f_Default = metaData.Columns["PARAMETER_DEFAULT"];
if(metaData.Columns.Contains("IS_NULLABLE")) f_IsNullable = metaData.Columns["IS_NULLABLE"];
if(metaData.Columns.Contains("DATA_TYPE")) f_DataType = metaData.Columns["DATA_TYPE"];
if(metaData.Columns.Contains("CHARACTER_MAXIMUM_LENGTH")) f_CharMaxLength = metaData.Columns["CHARACTER_MAXIMUM_LENGTH"];
if(metaData.Columns.Contains("CHARACTER_OCTET_LENGTH")) f_CharOctetLength = metaData.Columns["CHARACTER_OCTET_LENGTH"];
if(metaData.Columns.Contains("NUMERIC_PRECISION")) f_NumericPrecision = metaData.Columns["NUMERIC_PRECISION"];
if(metaData.Columns.Contains("NUMERIC_SCALE")) f_NumericScale = metaData.Columns["NUMERIC_SCALE"];
if(metaData.Columns.Contains("DESCRIPTION")) f_Description = metaData.Columns["DESCRIPTION"];
if(metaData.Columns.Contains("FULL_TYPE_NAME")) f_FullTypeName = metaData.Columns["FULL_TYPE_NAME"];
if(metaData.Columns.Contains("TYPE_NAME")) f_TypeName = metaData.Columns["TYPE_NAME"];
if(metaData.Columns.Contains("LOCAL_TYPE_NAME")) f_LocalTypeName = metaData.Columns["LOCAL_TYPE_NAME"];
}
}
virtual internal void LoadAll()
{
}
internal void PopulateArray(DataTable metaData)
{
BindToColumns(metaData);
Parameter param = null;
int count = metaData.Rows.Count;
for(int i = 0; i < count; i++)
{
param = (Parameter)this.dbRoot.ClassFactory.CreateParameter();
param.dbRoot = this.dbRoot;
param.Parameters = this;
param.Row = metaData.Rows[i];
this._array.Add(param);
}
}
internal void AddTable(Parameter param)
{
this._array.Add(param);
}
#region indexers
virtual public IParameter this[object index]
{
get
{
if(index.GetType() == Type.GetType("System.String"))
{
return GetByPhysicalName(index as String);
}
else
{
int idx = Convert.ToInt32(index);
return this._array[idx] as Parameter;
}
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
public Parameter GetByName(string name)
{
Parameter obj = null;
Parameter tmp = null;
int count = this._array.Count;
for(int i = 0; i < count; i++)
{
tmp = this._array[i] as Parameter;
if(this.CompareStrings(name,tmp.Name))
{
obj = tmp;
break;
}
}
return obj;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
public Parameter GetByPhysicalName(string name)
{
Parameter obj = null;
Parameter tmp = null;
int count = this._array.Count;
for(int i = 0; i < count; i++)
{
tmp = this._array[i] as Parameter;
if(this.CompareStrings(name,tmp.Name))
{
obj = tmp;
break;
}
}
return obj;
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
#region IEnumerable<IParameter> Members
public IEnumerator<IParameter> GetEnumerator() {
foreach (object item in _array)
yield return item as IParameter;
}
#endregion
#region XML User Data
#if ENTERPRISE
[ComVisible(false)]
#endif
override public string UserDataXPath
{
get
{
return Procedure.UserDataXPath + @"/Parameters";
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override internal bool GetXmlNode(out XmlNode node, bool forceCreate)
{
node = null;
bool success = false;
if(null == _xmlNode)
{
// Get the parent node
XmlNode parentNode = null;
if(this.Procedure.GetXmlNode(out parentNode, forceCreate))
{
// See if our user data already exists
string xPath = @"./Parameters";
if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate)
{
// Create it, and try again
this.CreateUserMetaData(parentNode);
GetUserData(xPath, parentNode, out _xmlNode);
}
}
}
if(null != _xmlNode)
{
node = _xmlNode;
success = true;
}
return success;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override public void CreateUserMetaData(XmlNode parentNode)
{
XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Parameters", null);
parentNode.AppendChild(myNode);
}
#endregion
#region IList Members
object System.Collections.IList.this[int index]
{
get { return this[index];}
set { }
}
#endregion
internal Procedure Procedure = null;
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
namespace MLifter.GenerateTestData
{
partial class Mainform
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Mainform));
this.groupBoxCopyLM = new System.Windows.Forms.GroupBox();
this.buttonSource = new System.Windows.Forms.Button();
this.labelSourceLM = new System.Windows.Forms.Label();
this.textBoxSource = new System.Windows.Forms.TextBox();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.buttonGenerate = new System.Windows.Forms.Button();
this.textBoxConnectionString = new System.Windows.Forms.TextBox();
this.listViewLMs = new System.Windows.Forms.ListView();
this.columnHeaderTitle = new System.Windows.Forms.ColumnHeader();
this.columnHeaderAuthor = new System.Windows.Forms.ColumnHeader();
this.columnHeaderNumber = new System.Windows.Forms.ColumnHeader();
this.checkBoxCopyLM = new System.Windows.Forms.CheckBox();
this.labelCurrentUser = new System.Windows.Forms.Label();
this.textBoxCurrentUser = new System.Windows.Forms.TextBox();
this.buttonChangeUser = new System.Windows.Forms.Button();
this.textBoxSessionNum = new System.Windows.Forms.TextBox();
this.labelSessionNum = new System.Windows.Forms.Label();
this.textBoxCardNum = new System.Windows.Forms.TextBox();
this.labelCardNum = new System.Windows.Forms.Label();
this.groupBoxDB = new System.Windows.Forms.GroupBox();
this.groupBoxCopyLM.SuspendLayout();
this.groupBoxDB.SuspendLayout();
this.SuspendLayout();
//
// groupBoxCopyLM
//
resources.ApplyResources(this.groupBoxCopyLM, "groupBoxCopyLM");
this.groupBoxCopyLM.Controls.Add(this.buttonSource);
this.groupBoxCopyLM.Controls.Add(this.labelSourceLM);
this.groupBoxCopyLM.Controls.Add(this.textBoxSource);
this.groupBoxCopyLM.Name = "groupBoxCopyLM";
this.groupBoxCopyLM.TabStop = false;
//
// buttonSource
//
resources.ApplyResources(this.buttonSource, "buttonSource");
this.buttonSource.Name = "buttonSource";
this.buttonSource.UseVisualStyleBackColor = true;
this.buttonSource.Click += new System.EventHandler(this.buttonSource_Click);
//
// labelSourceLM
//
resources.ApplyResources(this.labelSourceLM, "labelSourceLM");
this.labelSourceLM.Name = "labelSourceLM";
//
// textBoxSource
//
resources.ApplyResources(this.textBoxSource, "textBoxSource");
this.textBoxSource.Name = "textBoxSource";
//
// buttonGenerate
//
resources.ApplyResources(this.buttonGenerate, "buttonGenerate");
this.buttonGenerate.Name = "buttonGenerate";
this.buttonGenerate.UseVisualStyleBackColor = true;
this.buttonGenerate.Click += new System.EventHandler(this.buttonGenerate_Click);
//
// textBoxConnectionString
//
resources.ApplyResources(this.textBoxConnectionString, "textBoxConnectionString");
this.textBoxConnectionString.Name = "textBoxConnectionString";
this.textBoxConnectionString.TextChanged += new System.EventHandler(this.textBoxConnectionString_TextChanged);
//
// listViewLMs
//
resources.ApplyResources(this.listViewLMs, "listViewLMs");
this.listViewLMs.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderTitle,
this.columnHeaderAuthor,
this.columnHeaderNumber});
this.listViewLMs.GridLines = true;
this.listViewLMs.HideSelection = false;
this.listViewLMs.HoverSelection = true;
this.listViewLMs.MultiSelect = false;
this.listViewLMs.Name = "listViewLMs";
this.listViewLMs.UseCompatibleStateImageBehavior = false;
this.listViewLMs.View = System.Windows.Forms.View.Details;
//
// columnHeaderTitle
//
resources.ApplyResources(this.columnHeaderTitle, "columnHeaderTitle");
//
// columnHeaderAuthor
//
resources.ApplyResources(this.columnHeaderAuthor, "columnHeaderAuthor");
//
// columnHeaderNumber
//
resources.ApplyResources(this.columnHeaderNumber, "columnHeaderNumber");
//
// checkBoxCopyLM
//
resources.ApplyResources(this.checkBoxCopyLM, "checkBoxCopyLM");
this.checkBoxCopyLM.Name = "checkBoxCopyLM";
this.checkBoxCopyLM.UseVisualStyleBackColor = true;
this.checkBoxCopyLM.CheckedChanged += new System.EventHandler(this.checkBoxCopyLM_CheckedChanged);
//
// labelCurrentUser
//
resources.ApplyResources(this.labelCurrentUser, "labelCurrentUser");
this.labelCurrentUser.Name = "labelCurrentUser";
//
// textBoxCurrentUser
//
resources.ApplyResources(this.textBoxCurrentUser, "textBoxCurrentUser");
this.textBoxCurrentUser.Name = "textBoxCurrentUser";
this.textBoxCurrentUser.ReadOnly = true;
//
// buttonChangeUser
//
resources.ApplyResources(this.buttonChangeUser, "buttonChangeUser");
this.buttonChangeUser.Name = "buttonChangeUser";
this.buttonChangeUser.UseVisualStyleBackColor = true;
this.buttonChangeUser.Click += new System.EventHandler(this.buttonChangeUser_Click);
//
// textBoxSessionNum
//
resources.ApplyResources(this.textBoxSessionNum, "textBoxSessionNum");
this.textBoxSessionNum.Name = "textBoxSessionNum";
this.textBoxSessionNum.TextChanged += new System.EventHandler(this.textBoxSessionNum_TextChanged);
//
// labelSessionNum
//
resources.ApplyResources(this.labelSessionNum, "labelSessionNum");
this.labelSessionNum.Name = "labelSessionNum";
//
// textBoxCardNum
//
resources.ApplyResources(this.textBoxCardNum, "textBoxCardNum");
this.textBoxCardNum.Name = "textBoxCardNum";
this.textBoxCardNum.TextChanged += new System.EventHandler(this.textBoxCardNum_TextChanged);
//
// labelCardNum
//
resources.ApplyResources(this.labelCardNum, "labelCardNum");
this.labelCardNum.Name = "labelCardNum";
//
// groupBoxDB
//
resources.ApplyResources(this.groupBoxDB, "groupBoxDB");
this.groupBoxDB.Controls.Add(this.listViewLMs);
this.groupBoxDB.Controls.Add(this.textBoxConnectionString);
this.groupBoxDB.Name = "groupBoxDB";
this.groupBoxDB.TabStop = false;
//
// Mainform
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.groupBoxDB);
this.Controls.Add(this.textBoxCardNum);
this.Controls.Add(this.labelCardNum);
this.Controls.Add(this.textBoxSessionNum);
this.Controls.Add(this.labelSessionNum);
this.Controls.Add(this.buttonChangeUser);
this.Controls.Add(this.textBoxCurrentUser);
this.Controls.Add(this.labelCurrentUser);
this.Controls.Add(this.checkBoxCopyLM);
this.Controls.Add(this.buttonGenerate);
this.Controls.Add(this.groupBoxCopyLM);
this.HelpButton = true;
this.Name = "Mainform";
this.Load += new System.EventHandler(this.Mainform_Load);
this.groupBoxCopyLM.ResumeLayout(false);
this.groupBoxCopyLM.PerformLayout();
this.groupBoxDB.ResumeLayout(false);
this.groupBoxDB.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBoxCopyLM;
private System.Windows.Forms.Label labelSourceLM;
private System.Windows.Forms.TextBox textBoxSource;
private System.Windows.Forms.Button buttonSource;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.Button buttonGenerate;
private System.Windows.Forms.TextBox textBoxConnectionString;
private System.Windows.Forms.ListView listViewLMs;
private System.Windows.Forms.ColumnHeader columnHeaderTitle;
private System.Windows.Forms.ColumnHeader columnHeaderAuthor;
private System.Windows.Forms.ColumnHeader columnHeaderNumber;
private System.Windows.Forms.CheckBox checkBoxCopyLM;
private System.Windows.Forms.Label labelCurrentUser;
private System.Windows.Forms.TextBox textBoxCurrentUser;
private System.Windows.Forms.Button buttonChangeUser;
private System.Windows.Forms.TextBox textBoxSessionNum;
private System.Windows.Forms.Label labelSessionNum;
private System.Windows.Forms.TextBox textBoxCardNum;
private System.Windows.Forms.Label labelCardNum;
private System.Windows.Forms.GroupBox groupBoxDB;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public partial class ZipTest
{
[Fact]
public async Task CreateFromDirectoryNormal()
{
await TestCreateDirectory(zfolder("normal"), true);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
await TestCreateDirectory(zfolder("unicode"), true);
}
}
private async Task TestCreateDirectory(string folderName, Boolean testWithBaseDir)
{
string noBaseDir = GetTmpFilePath();
ZipFile.CreateFromDirectory(folderName, noBaseDir);
await IsZipSameAsDirAsync(noBaseDir, folderName, ZipArchiveMode.Read, true, true);
if (testWithBaseDir)
{
string withBaseDir = GetTmpFilePath();
ZipFile.CreateFromDirectory(folderName, withBaseDir, CompressionLevel.Optimal, true);
SameExceptForBaseDir(noBaseDir, withBaseDir, folderName);
}
}
private static void SameExceptForBaseDir(string zipNoBaseDir, string zipBaseDir, string baseDir)
{
//b has the base dir
using (ZipArchive a = ZipFile.Open(zipNoBaseDir, ZipArchiveMode.Read),
b = ZipFile.Open(zipBaseDir, ZipArchiveMode.Read))
{
var aCount = a.Entries.Count;
var bCount = b.Entries.Count;
Assert.Equal(aCount, bCount);
int bIdx = 0;
foreach (ZipArchiveEntry aEntry in a.Entries)
{
ZipArchiveEntry bEntry = b.Entries[bIdx++];
Assert.Equal(Path.GetFileName(baseDir) + "/" + aEntry.FullName, bEntry.FullName);
Assert.Equal(aEntry.Name, bEntry.Name);
Assert.Equal(aEntry.Length, bEntry.Length);
Assert.Equal(aEntry.CompressedLength, bEntry.CompressedLength);
using (Stream aStream = aEntry.Open(), bStream = bEntry.Open())
{
StreamsEqual(aStream, bStream);
}
}
}
}
[Fact]
public void ExtractToDirectoryNormal()
{
TestExtract(zfile("normal.zip"), zfolder("normal"));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
TestExtract(zfile("unicode.zip"), zfolder("unicode"));
}
TestExtract(zfile("empty.zip"), zfolder("empty"));
TestExtract(zfile("explicitdir1.zip"), zfolder("explicitdir"));
TestExtract(zfile("explicitdir2.zip"), zfolder("explicitdir"));
TestExtract(zfile("appended.zip"), zfolder("small"));
TestExtract(zfile("prepended.zip"), zfolder("small"));
TestExtract(zfile("noexplicitdir.zip"), zfolder("explicitdir"));
}
private void TestExtract(string zipFileName, string folderName)
{
string tempFolder = GetTmpDirPath(true);
ZipFile.ExtractToDirectory(zipFileName, tempFolder);
DirsEqual(tempFolder, folderName);
Assert.Throws<ArgumentNullException>(() => ZipFile.ExtractToDirectory(null, tempFolder));
}
#region "Extension Methods"
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CreateEntryFromFileTest(bool withCompressionLevel)
{
//add file
string testArchive = CreateTempCopyFile(zfile("normal.zip"));
using (ZipArchive archive = ZipFile.Open(testArchive, ZipArchiveMode.Update))
{
string entryName = "added.txt";
string sourceFilePath = zmodified(Path.Combine("addFile", entryName));
Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).CreateEntryFromFile(sourceFilePath, entryName));
Assert.Throws<ArgumentNullException>(() => archive.CreateEntryFromFile(null, entryName));
Assert.Throws<ArgumentNullException>(() => archive.CreateEntryFromFile(sourceFilePath, null));
ZipArchiveEntry e = withCompressionLevel ?
archive.CreateEntryFromFile(sourceFilePath, entryName) :
archive.CreateEntryFromFile(sourceFilePath, entryName, CompressionLevel.Fastest);
Assert.NotNull(e);
}
await IsZipSameAsDirAsync(testArchive, zmodified("addFile"), ZipArchiveMode.Read, true, true);
}
[Fact]
public void ExtractToFileTest()
{
using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read))
{
string file = GetTmpFilePath();
ZipArchiveEntry e = archive.GetEntry("first.txt");
Assert.Throws<ArgumentNullException>(() => ((ZipArchiveEntry)null).ExtractToFile(file));
Assert.Throws<ArgumentNullException>(() => e.ExtractToFile(null));
//extract when there is nothing there
e.ExtractToFile(file);
using (Stream fs = File.Open(file, FileMode.Open), es = e.Open())
{
StreamsEqual(fs, es);
}
Assert.Throws<IOException>(() => e.ExtractToFile(file, false));
//truncate file
using (Stream fs = File.Open(file, FileMode.Truncate)) { }
//now use overwrite mode
e.ExtractToFile(file, true);
using (Stream fs = File.Open(file, FileMode.Open), es = e.Open())
{
StreamsEqual(fs, es);
}
}
}
[Fact]
public void ExtractToDirectoryTest()
{
using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read))
{
string tempFolder = GetTmpDirPath(false);
Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).ExtractToDirectory(tempFolder));
Assert.Throws<ArgumentNullException>(() => archive.ExtractToDirectory(null));
archive.ExtractToDirectory(tempFolder);
DirsEqual(tempFolder, zfolder("normal"));
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
using (ZipArchive archive = ZipFile.OpenRead(zfile("unicode.zip")))
{
string tempFolder = GetTmpDirPath(false);
archive.ExtractToDirectory(tempFolder);
DirsEqual(tempFolder, zfolder("unicode"));
}
}
}
[Fact]
public void CreatedEmptyDirectoriesRoundtrip()
{
DirectoryInfo rootDir = new DirectoryInfo(GetTmpDirPath(create: true));
rootDir.CreateSubdirectory("empty1");
string archivePath = GetTmpFilePath();
ZipFile.CreateFromDirectory(
rootDir.FullName, archivePath,
CompressionLevel.Optimal, false, Encoding.UTF8);
using (ZipArchive archive = ZipFile.OpenRead(archivePath))
{
Assert.Equal(1, archive.Entries.Count);
Assert.True(archive.Entries[0].FullName.StartsWith("empty1"));
}
}
[Fact]
public void CreatedEmptyRootDirectoryRoundtrips()
{
DirectoryInfo emptyRoot = new DirectoryInfo(GetTmpDirPath(create: true));
string archivePath = GetTmpFilePath();
ZipFile.CreateFromDirectory(
emptyRoot.FullName, archivePath,
CompressionLevel.Optimal, true);
using (ZipArchive archive = ZipFile.OpenRead(archivePath))
{
Assert.Equal(1, archive.Entries.Count);
}
}
#endregion
}
}
| |
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SLua
{
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Reflection;
using UnityEditor;
using LuaInterface;
using System.Text;
using System.Text.RegularExpressions;
public class LuaCodeGen : MonoBehaviour
{
public const string Path = "Assets/Slua/LuaObject/";
public delegate void ExportGenericDelegate(Type t, string ns);
static bool autoRefresh = true;
static bool IsCompiling {
get {
if (EditorApplication.isCompiling) {
Debug.Log("Unity Editor is compiling, please wait.");
}
return EditorApplication.isCompiling;
}
}
[InitializeOnLoad]
public class Startup
{
static Startup()
{
bool ok = System.IO.Directory.Exists(Path);
if (!ok && EditorUtility.DisplayDialog("Slua", "Not found lua interface for Unity, generate it now?", "Generate", "No"))
{
GenerateAll();
}
}
}
[MenuItem("SLua/All/Make")]
static public void GenerateAll()
{
autoRefresh = false;
Generate();
GenerateUI();
Custom();
Generate3rdDll();
autoRefresh = true;
AssetDatabase.Refresh();
}
[MenuItem("SLua/Unity/Make UnityEngine")]
static public void Generate()
{
if (IsCompiling) {
return;
}
Assembly assembly = Assembly.Load("UnityEngine");
Type[] types = assembly.GetExportedTypes();
List<string> uselist;
List<string> noUseList;
CustomExport.OnGetNoUseList(out noUseList);
CustomExport.OnGetUseList(out uselist);
List<Type> exports = new List<Type>();
string path = Path + "Unity/";
foreach (Type t in types)
{
bool export = true;
// check type in uselist
if (uselist != null && uselist.Count > 0)
{
export = false;
foreach (string str in uselist)
{
if (t.FullName == str)
{
export = true;
break;
}
}
}
else
{
// check type not in nouselist
foreach (string str in noUseList)
{
if (t.FullName.Contains(str))
{
export = false;
break;
}
}
}
if (export)
{
if (Generate(t,path))
exports.Add(t);
}
}
GenerateBind(exports, "BindUnity", 0,path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate engine interface finished");
}
[MenuItem("SLua/Unity/Make UI (for Unity4.6+)")]
static public void GenerateUI()
{
if (IsCompiling) {
return;
}
List<string> noUseList = new List<string>
{
"CoroutineTween",
"GraphicRebuildTracker",
};
Assembly assembly = Assembly.Load("UnityEngine.UI");
Type[] types = assembly.GetExportedTypes();
List<Type> exports = new List<Type>();
string path = Path + "Unity/";
foreach (Type t in types)
{
bool export = true;
foreach (string str in noUseList)
{
if (t.FullName.Contains(str))
export = false;
}
if (export)
{
if (Generate(t, path))
exports.Add(t);
}
}
GenerateBind(exports, "BindUnityUI", 1,path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate UI interface finished");
}
[MenuItem("SLua/Unity/Clear Uinty UI")]
static public void ClearUnity()
{
clear(new string[] { Path + "Unity" });
Debug.Log("Clear Unity & UI complete.");
}
static public bool IsObsolete(MemberInfo t)
{
return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0;
}
[MenuItem("SLua/Custom/Make")]
static public void Custom()
{
if (IsCompiling) {
return;
}
List<Type> exports = new List<Type>();
string path = Path + "Custom/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
ExportGenericDelegate fun = (Type t, string ns) =>
{
if (Generate(t, ns, path))
exports.Add(t);
};
// export self-dll
Assembly assembly = Assembly.Load("Assembly-CSharp");
Type[] types = assembly.GetExportedTypes();
foreach (Type t in types)
{
if (t.GetCustomAttributes(typeof(CustomLuaClassAttribute), false).Length > 0)
{
fun(t, null);
}
}
CustomExport.OnAddCustomClass(fun);
GenerateBind(exports, "BindCustom", 3,path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate custom interface finished");
}
[MenuItem("SLua/3rdDll/Make")]
static public void Generate3rdDll()
{
if (IsCompiling) {
return;
}
List<Type> cust = new List<Type>();
Assembly assembly = Assembly.Load("Assembly-CSharp");
Type[] types = assembly.GetExportedTypes();
List<string> assemblyList = new List<string>();
CustomExport.OnAddCustomAssembly(ref assemblyList);
foreach (string assemblyItem in assemblyList)
{
assembly = Assembly.Load(assemblyItem);
types = assembly.GetExportedTypes();
foreach (Type t in types)
{
cust.Add(t);
}
}
if (cust.Count > 0)
{
List<Type> exports = new List<Type>();
string path = Path + "Dll/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
foreach (Type t in cust)
{
if (Generate(t,path))
exports.Add(t);
}
GenerateBind(exports, "BindDll", 2, path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate 3rdDll interface finished");
}
}
[MenuItem("SLua/3rdDll/Clear")]
static public void Clear3rdDll()
{
clear(new string[] { Path + "Dll" });
Debug.Log("Clear AssemblyDll complete.");
}
[MenuItem("SLua/Custom/Clear")]
static public void ClearCustom()
{
clear(new string[] { Path + "Custom" });
Debug.Log("Clear custom complete.");
}
[MenuItem("SLua/All/Clear")]
static public void ClearALL()
{
clear(new string[] { Path.Substring(0, Path.Length - 1) });
Debug.Log("Clear all complete.");
}
static void clear(string[] paths)
{
try
{
foreach (string path in paths)
{
System.IO.Directory.Delete(path, true);
}
}
catch
{
}
AssetDatabase.Refresh();
}
static bool Generate(Type t, string path)
{
return Generate(t, null, path);
}
static bool Generate(Type t, string ns, string path)
{
if (t.IsInterface)
return false;
CodeGenerator cg = new CodeGenerator();
cg.givenNamespace = ns;
cg.path = path;
return cg.Generate(t);
}
static void GenerateBind(List<Type> list, string name, int order,string path)
{
CodeGenerator cg = new CodeGenerator();
cg.path = path;
cg.GenerateBind(list, name, order);
}
}
class CodeGenerator
{
static List<string> memberFilter = new List<string>
{
"AnimationClip.averageDuration",
"AnimationClip.averageAngularSpeed",
"AnimationClip.averageSpeed",
"AnimationClip.apparentSpeed",
"AnimationClip.isLooping",
"AnimationClip.isAnimatorMotion",
"AnimationClip.isHumanMotion",
"AnimatorOverrideController.PerformOverrideClipListCleanup",
"Caching.SetNoBackupFlag",
"Caching.ResetNoBackupFlag",
"Light.areaSize",
"Security.GetChainOfTrustValue",
"Texture2D.alphaIsTransparency",
"WWW.movie",
"WebCamTexture.MarkNonReadable",
"WebCamTexture.isReadable",
// i don't why below 2 functions missed in iOS platform
"Graphic.OnRebuildRequested",
"Text.OnRebuildRequested",
// il2cpp not exixts
"Application.ExternalEval",
"GameObject.networkView",
"Component.networkView",
// unity5
"AnimatorControllerParameter.name",
"Input.IsJoystickPreconfigured",
"Resources.LoadAssetAtPath",
#if UNITY_4_6
"Motion.ValidateIfRetargetable",
"Motion.averageDuration",
"Motion.averageAngularSpeed",
"Motion.averageSpeed",
"Motion.apparentSpeed",
"Motion.isLooping",
"Motion.isAnimatorMotion",
"Motion.isHumanMotion",
#endif
};
HashSet<string> funcname = new HashSet<string>();
Dictionary<string, bool> directfunc = new Dictionary<string, bool>();
public string givenNamespace;
public string path;
class PropPair
{
public string get = "null";
public string set = "null";
public bool isInstance = true;
}
Dictionary<string, PropPair> propname = new Dictionary<string, PropPair>();
int indent = 0;
public void GenerateBind(List<Type> list, string name, int order)
{
HashSet<Type> exported = new HashSet<Type>();
string f = path + name + ".cs";
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
Write(file, "using System;");
Write(file, "namespace SLua {");
Write(file, "[LuaBinder({0})]", order);
Write(file, "public class {0} {{", name);
Write(file, "public static void Bind(IntPtr l) {");
foreach (Type t in list)
{
WriteBindType(file, t, list, exported);
}
Write(file, "}");
Write(file, "}");
Write(file, "}");
file.Close();
}
void WriteBindType(StreamWriter file, Type t, List<Type> exported, HashSet<Type> binded)
{
if (t == null || binded.Contains(t) || !exported.Contains(t))
return;
WriteBindType(file, t.BaseType, exported, binded);
Write(file, "{0}.reg(l);", ExportName(t), binded);
binded.Add(t);
}
public bool Generate(Type t)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!t.IsGenericTypeDefinition && (!IsObsolete(t) && t != typeof(YieldInstruction) && t != typeof(Coroutine))
|| (t.BaseType != null && t.BaseType == typeof(System.MulticastDelegate)))
{
if (t.IsEnum)
{
StreamWriter file = Begin(t);
WriteHead(t, file);
RegEnumFunction(t, file);
End(file);
}
else if (t.BaseType == typeof(System.MulticastDelegate))
{
string f;
if (t.IsGenericType)
{
if (t.ContainsGenericParameters)
return false;
f = path + string.Format("Lua{0}_{1}.cs", _Name(GenericBaseName(t)), _Name(GenericName(t)));
}
else
{
f = path + "LuaDelegate_" + _Name(t.FullName) + ".cs";
}
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
WriteDelegate(t, file);
file.Close();
return false;
}
else
{
funcname.Clear();
propname.Clear();
directfunc.Clear();
StreamWriter file = Begin(t);
WriteHead(t, file);
WriteConstructor(t, file);
WriteFunction(t, file);
WriteFunction(t, file, true);
WriteField(t, file);
RegFunction(t, file);
End(file);
if (t.BaseType != null && t.BaseType.Name == "UnityEvent`1")
{
string f = path + "LuaUnityEvent_" + _Name(GenericName(t.BaseType)) + ".cs";
file = new StreamWriter(f, false, Encoding.UTF8);
WriteEvent(t, file);
file.Close();
}
}
return true;
}
return false;
}
void WriteDelegate(Type t, StreamWriter file)
{
string temp = @"
using System;
using System.Collections.Generic;
using LuaInterface;
using UnityEngine;
namespace SLua
{
public partial class LuaDelegation : LuaObject
{
static internal int checkDelegate(IntPtr l,int p,out $FN ua) {
int op = extractFunction(l,p);
if(LuaDLL.lua_isnil(l,p)) {
ua=null;
return op;
}
else if (LuaDLL.lua_isuserdata(l, p)==1)
{
ua = ($FN)checkObj(l, p);
return op;
}
LuaDelegate ld;
checkType(l, -1, out ld);
if(ld.d!=null)
{
ua = ($FN)ld.d;
return op;
}
LuaDLL.lua_pop(l,1);
l = LuaState.get(l).L;
ua = ($ARGS) =>
{
int error = pushTry(l);
";
temp = temp.Replace("$TN", t.Name);
temp = temp.Replace("$FN", SimpleType(t));
MethodInfo mi = t.GetMethod("Invoke");
List<int> outindex = new List<int>();
List<int> refindex = new List<int>();
temp = temp.Replace("$ARGS", ArgsList(mi, ref outindex, ref refindex));
Write(file, temp);
this.indent = 4;
for (int n = 0; n < mi.GetParameters().Length; n++)
{
if (!outindex.Contains(n))
Write(file, "pushValue(l,a{0});", n + 1);
}
Write(file, "ld.pcall({0}, error);", mi.GetParameters().Length - outindex.Count);
if (mi.ReturnType != typeof(void))
WriteValueCheck(file, mi.ReturnType, 1, "ret", "error+");
foreach (int i in outindex)
{
string a = string.Format("a{0}", i + 1);
WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+");
}
foreach (int i in refindex)
{
string a = string.Format("a{0}", i + 1);
WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+");
}
Write(file, "LuaDLL.lua_settop(l, error-1);");
if (mi.ReturnType != typeof(void))
Write(file, "return ret;");
Write(file, "};");
Write(file, "ld.d=ua;");
Write(file, "return op;");
Write(file, "}");
Write(file, "}");
Write(file, "}");
}
string ArgsList(MethodInfo m, ref List<int> outindex, ref List<int> refindex)
{
string str = "";
ParameterInfo[] pars = m.GetParameters();
for (int n = 0; n < pars.Length; n++)
{
string t = SimpleType(pars[n].ParameterType);
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef && p.IsOut)
{
str += string.Format("out {0} a{1}", t, n + 1);
outindex.Add(n);
}
else if (p.ParameterType.IsByRef)
{
str += string.Format("ref {0} a{1}", t, n + 1);
refindex.Add(n);
}
else
str += string.Format("{0} a{1}", t, n + 1);
if (n < pars.Length - 1)
str += ",";
}
return str;
}
void tryMake(Type t)
{
if (t.BaseType == typeof(System.MulticastDelegate))
{
CodeGenerator cg = new CodeGenerator();
cg.path = this.path;
cg.Generate(t);
}
}
void WriteEvent(Type t, StreamWriter file)
{
string temp = @"
using System;
using System.Collections.Generic;
using LuaInterface;
using UnityEngine;
using UnityEngine.EventSystems;
namespace SLua
{
public class LuaUnityEvent_$CLS : LuaObject
{
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int AddListener(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
UnityEngine.Events.UnityAction<$GN> a1;
checkType(l, 2, out a1);
self.AddListener(a1);
return 0;
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int RemoveListener(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
UnityEngine.Events.UnityAction<$GN> a1;
checkType(l, 2, out a1);
self.RemoveListener(a1);
return 0;
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Invoke(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
$GN o;
checkType(l,2,out o);
self.Invoke(o);
return 0;
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
static public void reg(IntPtr l)
{
getTypeTable(l, typeof(LuaUnityEvent_$CLS).FullName);
addMember(l, AddListener);
addMember(l, RemoveListener);
addMember(l, Invoke);
createTypeMetatable(l, null, typeof(LuaUnityEvent_$CLS), typeof(UnityEngine.Events.UnityEventBase));
}
static bool checkType(IntPtr l,int p,out UnityEngine.Events.UnityAction<$GN> ua) {
LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION);
LuaDelegate ld;
checkType(l, p, out ld);
if (ld.d != null)
{
ua = (UnityEngine.Events.UnityAction<$GN>)ld.d;
return true;
}
l = LuaState.get(l).L;
ua = ($GN v) =>
{
int error = pushTry(l);
pushValue(l, v);
ld.pcall(1, error);
LuaDLL.lua_settop(l,error - 1);
};
ld.d = ua;
return true;
}
}
}";
temp = temp.Replace("$CLS", _Name(GenericName(t.BaseType)));
temp = temp.Replace("$FNAME", FullName(t));
temp = temp.Replace("$GN", GenericName(t.BaseType));
Write(file, temp);
}
void RegEnumFunction(Type t, StreamWriter file)
{
// Write export function
Write(file, "static public void reg(IntPtr l) {");
Write(file, "getEnumTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace);
FieldInfo[] fields = t.GetFields();
foreach (FieldInfo f in fields)
{
if (f.Name == "value__") continue;
Write(file, "addMember(l,{0},\"{1}\");", (int)f.GetValue(null), f.Name);
}
Write(file, "LuaDLL.lua_pop(l, 1);");
Write(file, "}");
}
StreamWriter Begin(Type t)
{
string clsname = ExportName(t);
string f = path + clsname + ".cs";
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
return file;
}
private void End(StreamWriter file)
{
Write(file, "}");
file.Flush();
file.Close();
}
private void WriteHead(Type t, StreamWriter file)
{
Write(file, "using UnityEngine;");
Write(file, "using System;");
Write(file, "using LuaInterface;");
Write(file, "using SLua;");
Write(file, "using System.Collections.Generic;");
Write(file, "public class {0} : LuaObject {{", ExportName(t));
}
private void WriteFunction(Type t, StreamWriter file, bool writeStatic = false)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.DeclaredOnly;
if (writeStatic)
bf |= BindingFlags.Static;
else
bf |= BindingFlags.Instance;
MethodInfo[] members = t.GetMethods(bf);
foreach (MethodInfo mi in members)
{
bool instanceFunc;
if (writeStatic && isPInvoke(mi, out instanceFunc))
{
directfunc.Add(t.FullName + "." + mi.Name, instanceFunc);
continue;
}
string fn = writeStatic ? staticName(mi.Name) : mi.Name;
if (mi.MemberType == MemberTypes.Method
&& !IsObsolete(mi)
&& !DontExport(mi)
&& !funcname.Contains(fn)
&& isUsefullMethod(mi)
&& !MemberInFilter(t, mi))
{
WriteFunctionDec(file, fn);
WriteFunctionImpl(file, mi, t, bf);
funcname.Add(fn);
}
}
}
bool isPInvoke(MethodInfo mi, out bool instanceFunc)
{
object[] attrs = mi.GetCustomAttributes(typeof(MonoPInvokeCallbackAttribute), false);
if (attrs.Length > 0)
{
instanceFunc = mi.GetCustomAttributes(typeof(StaticExportAttribute), false).Length == 0;
return true;
}
instanceFunc = true;
return false;
}
string staticName(string name)
{
if (name.StartsWith("op_"))
return name;
return name + "_s";
}
bool MemberInFilter(Type t, MemberInfo mi)
{
return memberFilter.Contains(t.Name + "." + mi.Name);
}
bool IsObsolete(MemberInfo mi)
{
return LuaCodeGen.IsObsolete(mi);
}
void RegFunction(Type t, StreamWriter file)
{
// Write export function
Write(file, "static public void reg(IntPtr l) {");
if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`"))
{
Write(file, "LuaUnityEvent_{1}.reg(l);", FullName(t), _Name((GenericName(t.BaseType))));
}
Write(file, "getTypeTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace);
foreach (string f in funcname)
{
Write(file, "addMember(l,{0});", f);
}
foreach (string f in directfunc.Keys)
{
bool instance = directfunc[f];
Write(file, "addMember(l,{0},{1});", f, instance ? "true" : "false");
}
foreach (string f in propname.Keys)
{
PropPair pp = propname[f];
Write(file, "addMember(l,\"{0}\",{1},{2},{3});", f, pp.get, pp.set, pp.isInstance ? "true" : "false");
}
if (t.BaseType != null && !CutBase(t.BaseType))
{
if (t.BaseType.Name.Contains("UnityEvent`1"))
Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof(LuaUnityEvent_{1}));", TypeDecl(t), _Name(GenericName(t.BaseType)), constructorOrNot(t));
else
Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof({1}));", TypeDecl(t), TypeDecl(t.BaseType), constructorOrNot(t));
}
else
Write(file, "createTypeMetatable(l,{1}, typeof({0}));", TypeDecl(t), constructorOrNot(t));
Write(file, "}");
}
string constructorOrNot(Type t)
{
ConstructorInfo[] cons = GetValidConstructor(t);
if (cons.Length > 0 || t.IsValueType)
return "constructor";
return "null";
}
bool CutBase(Type t)
{
if (t.FullName.StartsWith("System.Object"))
return true;
return false;
}
void WriteSet(StreamWriter file, Type t, string cls, string fn, bool isstatic = false)
{
if (t.BaseType == typeof(MulticastDelegate))
{
if (isstatic)
{
Write(file, "if(op==0) {0}.{1}=v;", cls, fn);
Write(file, "else if(op==1) {0}.{1}+=v;", cls, fn);
Write(file, "else if(op==2) {0}.{1}-=v;", cls, fn);
}
else
{
Write(file, "if(op==0) self.{0}=v;", fn);
Write(file, "else if(op==1) self.{0}+=v;", fn);
Write(file, "else if(op==2) self.{0}-=v;", fn);
}
}
else
{
if (isstatic)
{
Write(file, "{0}.{1}=v;", cls, fn);
}
else
{
Write(file, "self.{0}=v;", fn);
}
}
}
private void WriteField(Type t, StreamWriter file)
{
// Write field set/get
FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo fi in fields)
{
if (DontExport(fi) || IsObsolete(fi))
continue;
PropPair pp = new PropPair();
pp.isInstance = !fi.IsStatic;
if (fi.FieldType.BaseType != typeof(MulticastDelegate))
{
WriteFunctionAttr(file);
Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.IsStatic)
{
WritePushValue(fi.FieldType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name));
}
else
{
WriteCheckSelf(file, t);
WritePushValue(fi.FieldType, file, string.Format("self.{0}", fi.Name));
}
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
pp.get = "get_" + fi.Name;
}
if (!fi.IsLiteral && !fi.IsInitOnly)
{
WriteFunctionAttr(file);
Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.IsStatic)
{
Write(file, "{0} v;", TypeDecl(fi.FieldType));
WriteCheckType(file, fi.FieldType, 2);
WriteSet(file, fi.FieldType, TypeDecl(t), fi.Name, true);
}
else
{
WriteCheckSelf(file, t);
Write(file, "{0} v;", TypeDecl(fi.FieldType));
WriteCheckType(file, fi.FieldType, 2);
WriteSet(file, fi.FieldType, t.FullName, fi.Name);
}
if (t.IsValueType && !fi.IsStatic)
Write(file, "setBack(l,self);");
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
pp.set = "set_" + fi.Name;
}
propname.Add(fi.Name, pp);
tryMake(fi.FieldType);
}
//for this[]
List<PropertyInfo> getter = new List<PropertyInfo>();
List<PropertyInfo> setter = new List<PropertyInfo>();
// Write property set/get
PropertyInfo[] props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo fi in props)
{
//if (fi.Name == "Item" || IsObsolete(fi) || MemberInFilter(t,fi) || DontExport(fi))
if (IsObsolete(fi) || MemberInFilter(t, fi) || DontExport(fi))
continue;
if (fi.Name == "Item"
|| (t.Name == "String" && fi.Name == "Chars")) // for string[]
{
//for this[]
if (!fi.GetGetMethod().IsStatic && fi.GetIndexParameters().Length == 1)
{
if (fi.CanRead && !IsNotSupport(fi.PropertyType))
getter.Add(fi);
if (fi.CanWrite && fi.GetSetMethod() != null)
setter.Add(fi);
}
continue;
}
PropPair pp = new PropPair();
bool isInstance = true;
if (fi.CanRead && fi.GetGetMethod() != null)
{
if (!IsNotSupport(fi.PropertyType))
{
WriteFunctionAttr(file);
Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.GetGetMethod().IsStatic)
{
isInstance = false;
WritePushValue(fi.PropertyType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name));
}
else
{
WriteCheckSelf(file, t);
WritePushValue(fi.PropertyType, file, string.Format("self.{0}", fi.Name));
}
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
pp.get = "get_" + fi.Name;
}
}
if (fi.CanWrite && fi.GetSetMethod() != null)
{
WriteFunctionAttr(file);
Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.GetSetMethod().IsStatic)
{
WriteValueCheck(file, fi.PropertyType, 2);
WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name, true);
isInstance = false;
}
else
{
WriteCheckSelf(file, t);
WriteValueCheck(file, fi.PropertyType, 2);
WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name);
}
if (t.IsValueType)
Write(file, "setBack(l,self);");
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
pp.set = "set_" + fi.Name;
}
pp.isInstance = isInstance;
propname.Add(fi.Name, pp);
tryMake(fi.PropertyType);
}
//for this[]
WriteItemFunc(t, file, getter, setter);
}
void WriteItemFunc(Type t, StreamWriter file, List<PropertyInfo> getter, List<PropertyInfo> setter)
{
//Write property this[] set/get
if (getter.Count > 0)
{
//get
bool first_get = true;
WriteFunctionAttr(file);
Write(file, "static public int getItem(IntPtr l) {");
WriteTry(file);
WriteCheckSelf(file, t);
if (getter.Count == 1)
{
PropertyInfo _get = getter[0];
ParameterInfo[] infos = _get.GetIndexParameters();
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
Write(file, "var ret = self[v];");
WritePushValue(_get.PropertyType, file, "ret");
Write(file, "return 1;");
}
else
{
Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);");
for (int i = 0; i < getter.Count; i++)
{
PropertyInfo fii = getter[i];
ParameterInfo[] infos = fii.GetIndexParameters();
Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_get ? "if" : "else if", infos[0].ParameterType);
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
Write(file, "var ret = self[v];");
WritePushValue(fii.PropertyType, file, "ret");
Write(file, "return 1;");
Write(file, "}");
first_get = false;
}
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
Write(file, "return 0;");
}
WriteCatchExecption(file);
Write(file, "}");
funcname.Add("getItem");
}
if (setter.Count > 0)
{
bool first_set = true;
WriteFunctionAttr(file);
Write(file, "static public int setItem(IntPtr l) {");
WriteTry(file);
WriteCheckSelf(file, t);
if (setter.Count == 1)
{
PropertyInfo _set = setter[0];
ParameterInfo[] infos = _set.GetIndexParameters();
WriteValueCheck(file, infos[0].ParameterType, 2);
WriteValueCheck(file, _set.PropertyType, 3, "c");
Write(file, "self[v]=c;");
}
else
{
Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);");
for (int i = 0; i < setter.Count; i++)
{
PropertyInfo fii = setter[i];
if (t.BaseType != typeof(MulticastDelegate))
{
ParameterInfo[] infos = fii.GetIndexParameters();
Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_set ? "if" : "else if", infos[0].ParameterType);
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
WriteValueCheck(file, fii.PropertyType, 3, "c");
Write(file, "self[v]=c;");
Write(file, "return 0;");
Write(file, "}");
first_set = false;
}
if (t.IsValueType)
Write(file, "setBack(l,self);");
}
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
}
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
funcname.Add("setItem");
}
}
void WriteTry(StreamWriter file)
{
Write(file, "try {");
}
void WriteCatchExecption(StreamWriter file)
{
Write(file, "}");
Write(file, "catch(Exception e) {");
Write(file, "LuaDLL.luaL_error(l, e.ToString());");
Write(file, "return 0;");
Write(file, "}");
}
void WriteCheckType(StreamWriter file, Type t, int n, string v = "v", string nprefix = "")
{
if (t.IsEnum)
Write(file, "checkEnum(l,{2}{0},out {1});", n, v, nprefix);
else if (t.BaseType == typeof(System.MulticastDelegate))
Write(file, "int op=LuaDelegation.checkDelegate(l,{2}{0},out {1});", n, v, nprefix);
else
Write(file, "checkType(l,{2}{0},out {1});", n, v, nprefix);
}
void WriteValueCheck(StreamWriter file, Type t, int n, string v = "v", string nprefix = "")
{
Write(file, "{0} {1};", SimpleType(t), v);
WriteCheckType(file, t, n, v, nprefix);
}
private void WriteFunctionAttr(StreamWriter file)
{
Write(file, "[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]");
}
ConstructorInfo[] GetValidConstructor(Type t)
{
List<ConstructorInfo> ret = new List<ConstructorInfo>();
if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed)
return ret.ToArray();
if (t.BaseType != null && t.BaseType.Name == "MonoBehaviour")
return ret.ToArray();
ConstructorInfo[] cons = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
foreach (ConstructorInfo ci in cons)
{
if (!IsObsolete(ci) && !DontExport(ci) && !ContainUnsafe(ci))
ret.Add(ci);
}
return ret.ToArray();
}
bool ContainUnsafe(MethodBase mi)
{
foreach (ParameterInfo p in mi.GetParameters())
{
if (p.ParameterType.FullName.Contains("*"))
return true;
}
return false;
}
bool DontExport(MemberInfo mi)
{
return mi.GetCustomAttributes(typeof(DoNotToLuaAttribute), false).Length > 0;
}
private void WriteConstructor(Type t, StreamWriter file)
{
ConstructorInfo[] cons = GetValidConstructor(t);
if (cons.Length > 0)
{
WriteFunctionAttr(file);
Write(file, "static public int constructor(IntPtr l) {");
WriteTry(file);
if (cons.Length > 1)
Write(file, "int argc = LuaDLL.lua_gettop(l);");
Write(file, "{0} o;", TypeDecl(t));
bool first = true;
for (int n = 0; n < cons.Length; n++)
{
ConstructorInfo ci = cons[n];
ParameterInfo[] pars = ci.GetParameters();
if (cons.Length > 1)
{
if (isUniqueArgsCount(cons, ci))
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", ci.GetParameters().Length + 1);
else
Write(file, "{0}(matchType(l,argc,2{1})){{", first ? "if" : "else if", TypeDecl(pars));
}
for (int k = 0; k < pars.Length; k++)
{
ParameterInfo p = pars[k];
bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
CheckArgument(file, p.ParameterType, k, 2, p.IsOut, hasParams);
}
Write(file, "o=new {0}({1});", TypeDecl(t), FuncCall(ci));
if (t.Name == "String") // if export system.string, push string as ud not lua string
Write(file, "pushObject(l,o);");
else
Write(file, "pushValue(l,o);");
Write(file, "return 1;");
if (cons.Length == 1)
WriteCatchExecption(file);
Write(file, "}");
first = false;
}
if (cons.Length > 1)
{
Write(file, "LuaDLL.luaL_error(l,\"New object failed.\");");
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
}
}
else if (t.IsValueType) // default constructor
{
WriteFunctionAttr(file);
Write(file, "static public int constructor(IntPtr l) {");
WriteTry(file);
Write(file, "{0} o;", FullName(t));
Write(file, "o=new {0}();", FullName(t));
Write(file, "pushValue(l,o);");
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
}
}
bool IsNotSupport(Type t)
{
if (t.IsSubclassOf(typeof(Delegate)))
return true;
return false;
}
string[] prefix = new string[] { "System.Collections.Generic" };
string RemoveRef(string s, bool removearray = true)
{
if (s.EndsWith("&")) s = s.Substring(0, s.Length - 1);
if (s.EndsWith("[]") && removearray) s = s.Substring(0, s.Length - 2);
if (s.StartsWith(prefix[0])) s = s.Substring(prefix[0].Length + 1, s.Length - prefix[0].Length - 1);
s = s.Replace("+", ".");
if (s.Contains("`"))
{
string regstr = @"`\d";
Regex r = new Regex(regstr, RegexOptions.None);
s = r.Replace(s, "");
s = s.Replace("[", "<");
s = s.Replace("]", ">");
}
return s;
}
string GenericBaseName(Type t)
{
string n = t.FullName;
if (n.IndexOf('[') > 0)
{
n = n.Substring(0, n.IndexOf('['));
}
return n.Replace("+", ".");
}
string GenericName(Type t)
{
try
{
Type[] tt = t.GetGenericArguments();
string ret = "";
for (int n = 0; n < tt.Length; n++)
{
string dt = SimpleType(tt[n]);
ret += dt;
if (n < tt.Length - 1)
ret += "_";
}
return ret;
}
catch (Exception e)
{
Debug.Log(e.ToString());
return "";
}
}
string _Name(string n)
{
string ret = "";
for (int i = 0; i < n.Length; i++)
{
if (char.IsLetterOrDigit(n[i]))
ret += n[i];
else
ret += "_";
}
return ret;
}
string TypeDecl(ParameterInfo[] pars)
{
string ret = "";
for (int n = 0; n < pars.Length; n++)
{
ret += ",typeof(";
if (pars[n].IsOut)
ret += "LuaOut";
else
ret += SimpleType(pars[n].ParameterType);
ret += ")";
}
return ret;
}
bool isUsefullMethod(MethodInfo method)
{
if (method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
method.Name != "op_Implicit" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!IsObsolete(method) && !method.IsGenericMethod &&
//!method.Name.StartsWith("op_", StringComparison.Ordinal) &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal))
{
return true;
}
return false;
}
void WriteFunctionDec(StreamWriter file, string name)
{
WriteFunctionAttr(file);
Write(file, "static public int {0}(IntPtr l) {{", name);
}
MethodBase[] GetMethods(Type t, string name, BindingFlags bf)
{
List<MethodBase> methods = new List<MethodBase>();
MemberInfo[] cons = t.GetMember(name, bf);
foreach (MemberInfo m in cons)
{
if (m.MemberType == MemberTypes.Method
&& !IsObsolete(m)
&& !DontExport(m)
&& isUsefullMethod((MethodInfo)m))
methods.Add((MethodBase)m);
}
methods.Sort((a, b) =>
{
return a.GetParameters().Length - b.GetParameters().Length;
});
return methods.ToArray();
}
void WriteFunctionImpl(StreamWriter file, MethodInfo m, Type t, BindingFlags bf)
{
WriteTry(file);
MethodBase[] cons = GetMethods(t, m.Name, bf);
if (cons.Length == 1) // no override function
{
if (isUsefullMethod(m) && !m.ReturnType.ContainsGenericParameters && !m.ContainsGenericParameters) // don't support generic method
WriteFunctionCall(m, file, t);
else
{
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
Write(file, "return 0;");
}
}
else // 2 or more override function
{
Write(file, "int argc = LuaDLL.lua_gettop(l);");
bool first = true;
for (int n = 0; n < cons.Length; n++)
{
if (cons[n].MemberType == MemberTypes.Method)
{
MethodInfo mi = cons[n] as MethodInfo;
ParameterInfo[] pars = mi.GetParameters();
if (isUsefullMethod(mi)
&& !mi.ReturnType.ContainsGenericParameters
/*&& !ContainGeneric(pars)*/) // don't support generic method
{
if (isUniqueArgsCount(cons, mi))
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", mi.IsStatic ? mi.GetParameters().Length : mi.GetParameters().Length + 1);
else
Write(file, "{0}(matchType(l,argc,{1}{2})){{", first ? "if" : "else if", mi.IsStatic ? 1 : 2, TypeDecl(pars));
WriteFunctionCall(mi, file, t);
Write(file, "}");
first = false;
}
}
}
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
Write(file, "return 0;");
}
WriteCatchExecption(file);
Write(file, "}");
}
bool isUniqueArgsCount(MethodBase[] cons, MethodBase mi)
{
foreach (MethodBase member in cons)
{
MethodBase m = (MethodBase)member;
if (m != mi && mi.GetParameters().Length == m.GetParameters().Length)
return false;
}
return true;
}
bool ContainGeneric(ParameterInfo[] pars)
{
foreach (ParameterInfo p in pars)
{
if (p.ParameterType.IsGenericType || p.ParameterType.IsGenericParameter || p.ParameterType.IsGenericTypeDefinition)
return true;
}
return false;
}
void WriteCheckSelf(StreamWriter file, Type t)
{
if (t.IsValueType)
{
Write(file, "{0} self;", TypeDecl(t));
Write(file, "checkType(l,1,out self);");
}
else if (t==typeof(UnityEngine.Object) || t.IsSubclassOf(typeof(UnityEngine.Object)))
{
Write(file, "{0} self=({0})checkUOSelf(l);", TypeDecl(t));
}
else
Write(file, "{0} self=({0})checkSelf(l);", TypeDecl(t));
}
private void WriteFunctionCall(MethodInfo m, StreamWriter file, Type t)
{
bool hasref = false;
ParameterInfo[] pars = m.GetParameters();
int argIndex = 1;
if (!m.IsStatic)
{
WriteCheckSelf(file, t);
argIndex++;
}
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
string pn = p.ParameterType.Name;
if (pn.EndsWith("&"))
{
hasref = true;
}
bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
CheckArgument(file, p.ParameterType, n, argIndex, p.IsOut, hasParams);
}
string ret = "";
if (m.ReturnType != typeof(void))
{
ret = "var ret=";
}
if (m.IsStatic)
{
if (m.Name == "op_Multiply")
Write(file, "{0}a1*a2;", ret);
else if (m.Name == "op_Subtraction")
Write(file, "{0}a1-a2;", ret);
else if (m.Name == "op_Addition")
Write(file, "{0}a1+a2;", ret);
else if (m.Name == "op_Division")
Write(file, "{0}a1/a2;", ret);
else if (m.Name == "op_UnaryNegation")
Write(file, "{0}-a1;", ret);
else if (m.Name == "op_Equality")
Write(file, "{0}(a1==a2);", ret);
else if (m.Name == "op_Inequality")
Write(file, "{0}(a1!=a2);", ret);
else if (m.Name == "op_LessThan")
Write(file, "{0}(a1<a2);", ret);
else if (m.Name == "op_GreaterThan")
Write(file, "{0}(a2<a1);", ret);
else if (m.Name == "op_LessThanOrEqual")
Write(file, "{0}(a1<=a2);", ret);
else if (m.Name == "op_GreaterThanOrEqual")
Write(file, "{0}(a2<=a1);", ret);
else
Write(file, "{3}{2}.{0}({1});", m.Name, FuncCall(m), TypeDecl(t), ret);
}
else
Write(file, "{2}self.{0}({1});", m.Name, FuncCall(m), ret);
int retcount = 0;
if (m.ReturnType != typeof(void))
{
WritePushValue(m.ReturnType, file);
retcount = 1;
}
// push out/ref value for return value
if (hasref)
{
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef)
{
WritePushValue(p.ParameterType, file, string.Format("a{0}", n + 1));
retcount++;
}
}
}
if (t.IsValueType && m.ReturnType == typeof(void) && !m.IsStatic)
Write(file, "setBack(l,self);");
Write(file, "return {0};", retcount);
}
string SimpleType_(Type t)
{
string tn = t.Name;
switch (tn)
{
case "Single":
return "float";
case "String":
return "string";
case "Double":
return "double";
case "Boolean":
return "bool";
case "Int32":
return "int";
case "Object":
return FullName(t);
default:
tn = TypeDecl(t);
tn = tn.Replace("System.Collections.Generic.", "");
tn = tn.Replace("System.Object", "object");
return tn;
}
}
string SimpleType(Type t)
{
string ret = SimpleType_(t);
return ret;
}
void WritePushValue(Type t, StreamWriter file)
{
if (t.IsEnum)
Write(file, "pushEnum(l,(int)ret);");
else
Write(file, "pushValue(l,ret);");
}
void WritePushValue(Type t, StreamWriter file, string ret)
{
if (t.IsEnum)
Write(file, "pushEnum(l,(int){0});", ret);
else
Write(file, "pushValue(l,{0});", ret);
}
void Write(StreamWriter file, string fmt, params object[] args)
{
if (fmt.StartsWith("}")) indent--;
for (int n = 0; n < indent; n++)
file.Write("\t");
if (args.Length == 0)
file.WriteLine(fmt);
else
{
string line = string.Format(fmt, args);
file.WriteLine(line);
}
if (fmt.EndsWith("{")) indent++;
}
private void CheckArgument(StreamWriter file, Type t, int n, int argstart, bool isout, bool isparams)
{
Write(file, "{0} a{1};", TypeDecl(t), n + 1);
if (!isout)
{
if (t.IsEnum)
Write(file, "checkEnum(l,{0},out a{1});", n + argstart, n + 1);
else if (t.BaseType == typeof(System.MulticastDelegate))
{
tryMake(t);
Write(file, "LuaDelegation.checkDelegate(l,{0},out a{1});", n + argstart, n + 1);
}
else if (isparams)
Write(file, "checkParams(l,{0},out a{1});", n + argstart, n + 1);
else
Write(file, "checkType(l,{0},out a{1});", n + argstart, n + 1);
}
}
string FullName(string str)
{
if (str == null)
{
throw new NullReferenceException();
}
return RemoveRef(str.Replace("+", "."));
}
string TypeDecl(Type t)
{
if (t.IsGenericType)
{
string ret = GenericBaseName(t);
string gs = "";
gs += "<";
Type[] types = t.GetGenericArguments();
for (int n = 0; n < types.Length; n++)
{
gs += TypeDecl(types[n]);
if (n < types.Length - 1)
gs += ",";
}
gs += ">";
ret = Regex.Replace(ret, @"`\d", gs);
return ret;
}
if (t.IsArray)
{
return TypeDecl(t.GetElementType()) + "[]";
}
else
return RemoveRef(t.ToString(), false);
}
string ExportName(Type t)
{
if (t.IsGenericType)
{
return string.Format("Lua_{0}_{1}", _Name(GenericBaseName(t)), _Name(GenericName(t)));
}
else
{
string name = RemoveRef(t.FullName, true);
name = "Lua_" + name;
return name.Replace(".", "_");
}
}
string FullName(Type t)
{
if (t.FullName == null)
{
Debug.Log(t.Name);
return t.Name;
}
return FullName(t.FullName);
}
string FuncCall(MethodBase m)
{
string str = "";
ParameterInfo[] pars = m.GetParameters();
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef && p.IsOut)
str += string.Format("out a{0}", n + 1);
else if (p.ParameterType.IsByRef)
str += string.Format("ref a{0}", n + 1);
else
str += string.Format("a{0}", n + 1);
if (n < pars.Length - 1)
str += ",";
}
return str;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using System.Diagnostics;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Controls;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.Mshtml;
using mshtml;
namespace OpenLiveWriter.PostEditor.Tables
{
public class TableEditor
{
public static void InsertTable(IHtmlEditor htmlEditor, TableCreationParameters parameters)
{
InsertTable(htmlEditor, null, parameters);
}
public static void InsertTable(IHtmlEditor htmlEditor, IHtmlEditorComponentContext editorContext, TableCreationParameters parameters)
{
// note whether we are inserting into mshtml
bool insertingIntoMshtml = editorContext != null;
// build table html
StringBuilder tableHtml = new StringBuilder();
// clip the width if necessary (if inserting a table within another table cell)
if (insertingIntoMshtml)
{
IHTMLElement2 parentCellBlock = editorContext.Selection.SelectedMarkupRange.Start.GetParentElement(ElementFilters.BLOCK_OR_TABLE_CELL_ELEMENTS) as IHTMLElement2;
if (parentCellBlock is IHTMLTableCell)
{
int parentCellWidth = parentCellBlock.clientWidth != 0 ? parentCellBlock.clientWidth : parentCellBlock.scrollWidth;
parameters.Properties.Width = Math.Min(parentCellWidth, parameters.Properties.Width);
}
}
// table properties
TableProperties properties = parameters.Properties;
StringBuilder propertiesString = new StringBuilder();
if (properties.Width.Units != PixelPercentUnits.Undefined)
propertiesString.AppendFormat("width=\"{0}\"", properties.Width);
if (properties.BorderSize != String.Empty)
propertiesString.AppendFormat(" border=\"{0}\"", properties.BorderSize);
if (properties.CellPadding != String.Empty)
propertiesString.AppendFormat(" cellpadding=\"{0}\"", properties.CellPadding);
if (properties.CellSpacing != String.Empty)
propertiesString.AppendFormat(" cellspacing=\"{0}\"", properties.CellSpacing);
// begin table
tableHtml.AppendFormat("<table {0} unselectable=\"on\">\r\n", propertiesString.ToString());
tableHtml.Append("<tbody>\r\n");
// write cells
string columnWidth = String.Empty;
switch (parameters.Properties.Width.Units)
{
case PixelPercentUnits.Pixels:
int width = parameters.Properties.Width / parameters.Columns;
columnWidth = string.Format(" width=\"{0}\"", width);
break;
case PixelPercentUnits.Percentage:
columnWidth = string.Format(" width=\"{0}%\"", 100 / parameters.Columns);
break;
}
for (int r = 0; r < parameters.Rows; r++)
{
tableHtml.Append("<tr>\r\n");
for (int c = 0; c < parameters.Columns; c++)
{
// add default alignment and width to each cell
string valign = " valign=\"top\""; // (more natural/expected behavior than middle)
tableHtml.AppendFormat("<td {0}{1}></td>\r\n", valign, columnWidth);
}
tableHtml.Append("</tr>\r\n");
}
// end table
tableHtml.Append("</tbody>\r\n");
tableHtml.Append("</table>\r\n");
// if we have an mshml selection, save it before inserting (so we can locate the table after insert)
MarkupRange targetMarkupRange = null;
if (insertingIntoMshtml)
{
targetMarkupRange = editorContext.Selection.SelectedMarkupRange.Clone();
targetMarkupRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left;
targetMarkupRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
}
IDisposable insertionNotification = null;
if (insertingIntoMshtml)
{
insertionNotification = new HtmlEditorControl.InitialInsertionNotify((HtmlEditorControl)editorContext);
}
using (insertionNotification)
{
// insert the table
htmlEditor.InsertHtml(tableHtml.ToString(), false);
// select the first cell for editing if we have an mshtml selection
if (insertingIntoMshtml)
{
IHTMLElement[] cells = targetMarkupRange.GetElements(ElementFilters.TABLE_CELL_ELEMENT, true);
if (cells.Length > 0)
{
SelectCell(editorContext, cells[0] as IHTMLTableCell);
}
}
}
}
public static TableProperties GetTableProperties(IHtmlEditorComponentContext editorContext)
{
return GetTableProperties(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static TableProperties GetTableProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
return tableEditor.TableProperties;
}
public static void SetTableProperties(IHtmlEditorComponentContext editorContext, TableProperties tableProperties)
{
SetTableProperties(editorContext, editorContext.Selection.SelectedMarkupRange, tableProperties);
}
public static void SetTableProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange, TableProperties tableProperties)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.TableProperties = tableProperties;
}
public static void DeleteTable(IHtmlEditorComponentContext editorContext)
{
DeleteTable(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static void DeleteTable(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.DeleteTable();
}
public static RowProperties GetRowProperties(IHtmlEditorComponentContext editorContext)
{
return GetRowProperties(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static RowProperties GetRowProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
return tableEditor.RowProperties;
}
public static void SetRowProperties(IHtmlEditorComponentContext editorContext, RowProperties rowProperties)
{
SetRowProperties(editorContext, editorContext.Selection.SelectedMarkupRange, rowProperties);
}
public static void SetRowProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange, RowProperties rowProperties)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.RowProperties = rowProperties;
}
public static IHTMLTableRow InsertRowAbove(IHtmlEditorComponentContext editorContext)
{
return InsertRowAbove(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static IHTMLTableRow InsertRowAbove(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
return tableEditor.InsertRowAbove();
}
public static IHTMLTableRow InsertRowBelow(IHtmlEditorComponentContext editorContext)
{
return InsertRowBelow(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static IHTMLTableRow InsertRowBelow(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
return tableEditor.InsertRowBelow();
}
public static void MoveRowUp(IHtmlEditorComponentContext editorContext)
{
MarkupRange selectedMarkupRange = editorContext.Selection.SelectedMarkupRange;
using (new SelectionPreserver(selectedMarkupRange))
MoveRowUp(editorContext, selectedMarkupRange);
}
public static void MoveRowUp(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.MoveRowUp();
}
public static void MoveRowDown(IHtmlEditorComponentContext editorContext)
{
MarkupRange selectedMarkupRange = editorContext.Selection.SelectedMarkupRange;
using (new SelectionPreserver(selectedMarkupRange))
MoveRowDown(editorContext, selectedMarkupRange);
}
public static void MoveRowDown(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.MoveRowDown();
}
public static void DeleteRows(IHtmlEditorComponentContext editorContext)
{
DeleteRows(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static void DeleteRows(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.DeleteRows();
}
public static ColumnProperties GetColumnProperties(IHtmlEditorComponentContext editorContext)
{
return GetColumnProperties(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static ColumnProperties GetColumnProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
return tableEditor.ColumnProperties;
}
public static void SetColumnProperties(IHtmlEditorComponentContext editorContext, ColumnProperties columnProperties)
{
SetColumnProperties(editorContext, editorContext.Selection.SelectedMarkupRange, columnProperties);
}
public static void SetColumnProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange, ColumnProperties columnProperties)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.ColumnProperties = columnProperties;
}
public static void InsertColumnLeft(IHtmlEditorComponentContext editorContext)
{
InsertColumnLeft(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static void InsertColumnLeft(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.InsertColumnLeft();
}
public static void InsertColumnRight(IHtmlEditorComponentContext editorContext)
{
InsertColumnRight(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static void InsertColumnRight(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.InsertColumnRight();
}
public static void MoveColumnLeft(IHtmlEditorComponentContext editorContext)
{
MarkupRange selectedMarkupRange = editorContext.Selection.SelectedMarkupRange;
using (new SelectionPreserver(selectedMarkupRange))
MoveColumnLeft(editorContext, selectedMarkupRange);
}
public static void MoveColumnLeft(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.MoveColumnLeft();
}
public static void MoveColumnRight(IHtmlEditorComponentContext editorContext)
{
MarkupRange selectedMarkupRange = editorContext.Selection.SelectedMarkupRange;
using (new SelectionPreserver(selectedMarkupRange))
MoveColumnRight(editorContext, selectedMarkupRange);
}
public static void MoveColumnRight(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.MoveColumnRight();
}
public static void DeleteColumns(IHtmlEditorComponentContext editorContext)
{
DeleteColumns(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static void DeleteColumns(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.DeleteColumns();
}
public static CellProperties GetCellProperties(IHtmlEditorComponentContext editorContext)
{
return GetCellProperties(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static CellProperties GetCellProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
return tableEditor.CellProperties;
}
public static void SetCellProperties(IHtmlEditorComponentContext editorContext, CellProperties cellProperties)
{
SetCellProperties(editorContext, editorContext.Selection.SelectedMarkupRange, cellProperties);
}
public static void SetCellProperties(IHtmlEditorComponentContext editorContext, MarkupRange markupRange, CellProperties cellProperties)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.CellProperties = cellProperties;
}
public static void ClearCells(IHtmlEditorComponentContext editorContext)
{
ClearCells(editorContext, editorContext.Selection.SelectedMarkupRange);
}
public static void ClearCells(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
TableEditor tableEditor = new TableEditor(editorContext, markupRange);
tableEditor.ClearCells();
}
public static void InsertLineBreak(IHtmlEditorComponentContext editorContext)
{
TableEditor tableEditor = new TableEditor(editorContext);
tableEditor.InsertLineBreak();
}
public static void SelectNextCell(IHtmlEditorComponentContext editorContext)
{
TableEditor tableEditor = new TableEditor(editorContext);
tableEditor.SelectNextCell();
}
public static void SelectPreviousCell(IHtmlEditorComponentContext editorContext)
{
TableEditor tableEditor = new TableEditor(editorContext);
tableEditor.SelectPreviousCell();
}
public static void SelectCell(IHtmlEditorComponentContext editorContext, IHTMLTableCell cell)
{
TableEditor tableEditor = new TableEditor(editorContext);
tableEditor.SelectCell(cell);
}
public static void MakeEmptyCellsNbsp(IHtmlEditorComponentContext editorContext, IHTMLElement tableElement)
{
MarkupRange tableMarkupRange = editorContext.MarkupServices.CreateMarkupRange(tableElement, false);
TableEditor tableEditor = new TableEditor(editorContext, tableMarkupRange);
tableEditor.MakeEmptyCellsNbsp();
}
public static void MakeEmptyCellsNull(IHtmlEditorComponentContext editorContext, IHTMLElement tableElement)
{
MarkupRange tableMarkupRange = editorContext.MarkupServices.CreateMarkupRange(tableElement, false);
TableEditor tableEditor = new TableEditor(editorContext, tableMarkupRange);
tableEditor.MakeEmptyCellsNull();
}
#region Construction and Initialization
private TableEditor(IHtmlEditorComponentContext editorContext)
: this(editorContext, editorContext.Selection.SelectedMarkupRange)
{
}
private TableEditor(IHtmlEditorComponentContext editorContext, MarkupRange markupRange)
{
_editorContext = editorContext;
_markupRange = markupRange;
}
#endregion
#region Table Level Commands
private TableProperties TableProperties
{
get
{
TableProperties tableProperties = new TableProperties();
// read cell padding
if (TableSelection.Table.cellPadding != null)
tableProperties.CellPadding = TableSelection.Table.cellPadding.ToString();
else
tableProperties.CellPadding = String.Empty;
// read cell spacing
if (TableSelection.Table.cellSpacing != null)
tableProperties.CellSpacing = TableSelection.Table.cellSpacing.ToString();
else
tableProperties.CellSpacing = String.Empty;
// read border
if (TableSelection.Table.border != null)
tableProperties.BorderSize = TableSelection.Table.border.ToString();
else
tableProperties.BorderSize = String.Empty;
// read width
tableProperties.Width = TableHelper.GetTableWidth(TableSelection.Table);
// return
return tableProperties;
}
set
{
// save properties to table
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// cell padding
if (value.CellPadding != String.Empty)
TableSelection.Table.cellPadding = value.CellPadding;
else
(TableSelection.Table as IHTMLElement).removeAttribute("cellpadding", 0);
// cell spacing
if (value.CellSpacing != String.Empty)
TableSelection.Table.cellSpacing = value.CellSpacing;
else
(TableSelection.Table as IHTMLElement).removeAttribute("cellspacing", 0);
// border
if (value.BorderSize != String.Empty)
TableSelection.Table.border = value.BorderSize;
else
(TableSelection.Table as IHTMLElement).removeAttribute("border", 0);
// get the existing width, calculate the delta, then spread
// the delta across all of the columns
var existingWidth = TableHelper.GetTableWidth(TableSelection.Table);
if (existingWidth.Units == PixelPercentUnits.Pixels)
{
int changeInWidth = value.Width - existingWidth;
IHTMLTableRow firstRow = TableSelection.Table.rows.item(0, 0) as IHTMLTableRow;
if (firstRow.cells.length > 0)
{
int changePerColumn = changeInWidth / firstRow.cells.length;
int leftoverChange = changeInWidth % firstRow.cells.length;
foreach (IHTMLTableCell cell in firstRow.cells)
{
HTMLTableColumn column = new HTMLTableColumn(TableSelection.Table, cell);
column.Width = column.Width + changePerColumn + leftoverChange;
leftoverChange = 0; // allocate only once
}
}
}
// also set the width of the whole table to match the columns
TableSelection.Table.width = value.Width.ToString();
// update borders
TableHelper.UpdateDesignTimeBorders(TableSelection.Table);
// sync widths
TableHelper.SynchronizeCellAndTableWidthsForEditing(TableSelection.Table);
undoUnit.Commit();
}
}
}
public void DeleteTable()
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
HTMLElementHelper.RemoveElement(TableSelection.Table as IHTMLElement);
_editorContext.FireSelectionChanged();
undoUnit.Commit();
}
}
#endregion
#region Row Level Commands
private RowProperties RowProperties
{
get
{
IHTMLTableRow row = TableSelection.BeginRow;
RowProperties rowProperties = new RowProperties();
rowProperties.Height = TableHelper.GetRowHeight(row);
rowProperties.CellProperties.BackgroundColor = GetBackgroundColorForRow(row);
rowProperties.CellProperties.HorizontalAlignment = GetAlignmentForRow(row);
rowProperties.CellProperties.VerticalAlignment = GetVAlignmentForRow(row);
return rowProperties;
}
set
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
RowProperties existingRowProperties = RowProperties;
IHTMLTableRow row = TableSelection.BeginRow;
// height
if (value.Height > 0)
{
(row as IHTMLTableRow2).height = value.Height;
}
else
{
(row as IHTMLElement).removeAttribute("height", 0);
}
foreach (IHTMLTableCell cell in row.cells)
{
// background color
if (!value.CellProperties.BackgroundColor.IsMixed) // mixed means hands ooff
{
if (value.CellProperties.BackgroundColor.Color != Color.Empty)
{
cell.bgColor = ColorHelper.ColorToString(value.CellProperties.BackgroundColor.Color);
}
else
{
(cell as IHTMLElement).removeAttribute("bgcolor", 0);
}
}
// horizontal alignment
if (value.CellProperties.HorizontalAlignment != HorizontalAlignment.Mixed) // mixed means hands off
{
if (value.CellProperties.HorizontalAlignment != HorizontalAlignment.Left)
{
cell.align = TableHelper.GetHtmlAlignmentForAlignment(value.CellProperties.HorizontalAlignment);
}
else
{
(cell as IHTMLElement).removeAttribute("align", 0);
}
}
// vertical alignment
if (value.CellProperties.VerticalAlignment != VerticalAlignment.Mixed) // mixed means hands off
{
if (value.CellProperties.VerticalAlignment != VerticalAlignment.Middle)
{
cell.vAlign = TableHelper.GetHtmlAlignmentForVAlignment(value.CellProperties.VerticalAlignment);
}
else
{
(cell as IHTMLElement).removeAttribute("valign", 0);
}
}
}
undoUnit.Commit();
}
}
}
private IHTMLTableRow InsertRowAbove()
{
return InsertRow(false);
}
private IHTMLTableRow InsertRowBelow()
{
return InsertRow(true);
}
private void MoveRowUp()
{
// no-op if this is the first row or the selection spans more than one row
if ((TableSelection.BeginRow.rowIndex == 0) || !TableSelection.SingleRowSelected)
return;
using (_editorContext.DamageServices.CreateDamageTracker(_editorContext.MarkupServices.CreateMarkupRange(TableSelection.Table as IHTMLElement, true), false))
{
// determine the source row and target row
IHTMLTableRow sourceRow = TableSelection.BeginRow;
IHTMLTableRow targetRow = TableSelection.Table.rows.item(sourceRow.rowIndex - 1, sourceRow.rowIndex - 1) as IHTMLTableRow;
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// swap them
HTMLElementHelper.SwapElements(sourceRow as IHTMLElement, targetRow as IHTMLElement);
undoUnit.Commit();
}
}
}
private void MoveRowDown()
{
// no-op if this is the last row or the selection spans more than one row
if ((TableSelection.BeginRow.rowIndex >= (TableSelection.Table.rows.length - 1)) || !TableSelection.SingleRowSelected)
return;
using (_editorContext.DamageServices.CreateDamageTracker(_editorContext.MarkupServices.CreateMarkupRange(TableSelection.Table as IHTMLElement, true), false))
{
// determine the source row and target row
IHTMLTableRow sourceRow = TableSelection.BeginRow;
IHTMLTableRow targetRow = TableSelection.Table.rows.item(sourceRow.rowIndex + 1, sourceRow.rowIndex + 1) as IHTMLTableRow;
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// swap them
HTMLElementHelper.SwapElements(sourceRow as IHTMLElement, targetRow as IHTMLElement);
undoUnit.Commit();
}
}
}
private void DeleteRows()
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
int endRowIndex = TableSelection.EndRow.rowIndex;
int endColumnIndex = TableSelection.EndColumn.Index;
// collect up the rows to remove
ArrayList rowsToRemove = new ArrayList();
for (int i = TableSelection.BeginRow.rowIndex; i <= endRowIndex; i++)
rowsToRemove.Add(TableSelection.Table.rows.item(i, i));
// The selection gets into a very bad state if we allow HTMLElementHelper.RemoveElement below
// to remove the element(s) that are selected.
// To avoid this, we move the selection before deleting the rows.
MarkupRange newSelection;
if (endRowIndex == TableSelection.Table.rows.length - 1)
{
// Deleting bottom-most row. Move selection below the table
newSelection = _editorContext.MarkupServices.CreateMarkupRange(TableSelection.Table as IHTMLElement, true);
newSelection.Collapse(false);
}
else
{
// Move selection into next row
int nextRowIndex = endRowIndex + 1;
newSelection = _editorContext.MarkupServices.CreateMarkupRange((IHTMLElement)((IHTMLTableRow)TableSelection.Table.rows.item(nextRowIndex, nextRowIndex)).cells.item(endColumnIndex, endColumnIndex), false);
newSelection.Collapse(true);
}
newSelection.ToTextRange().select(); ;
// delete the rows
foreach (IHTMLElement row in rowsToRemove)
HTMLElementHelper.RemoveElement(row);
// delete the entire table if this action left it empty
DeleteTableIfEmpty();
// commit the changes
undoUnit.Commit();
}
}
#endregion
#region Column Oriented Commands
private ColumnProperties ColumnProperties
{
get
{
HTMLTableColumn tableColumn = TableSelection.BeginColumn;
ColumnProperties columnProperties = new ColumnProperties();
columnProperties.Width = tableColumn.Width;
columnProperties.CellProperties.BackgroundColor = tableColumn.BackgroundColor;
columnProperties.CellProperties.HorizontalAlignment = tableColumn.HorizontalAlignment;
columnProperties.CellProperties.VerticalAlignment = tableColumn.VerticalAlignment;
return columnProperties;
}
set
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
HTMLTableColumn tableColumn = TableSelection.BeginColumn;
tableColumn.Width = value.Width;
tableColumn.BackgroundColor = value.CellProperties.BackgroundColor;
tableColumn.HorizontalAlignment = value.CellProperties.HorizontalAlignment;
tableColumn.VerticalAlignment = value.CellProperties.VerticalAlignment;
TableHelper.SynchronizeCellAndTableWidthsForEditing(TableSelection.Table);
undoUnit.Commit();
}
}
}
private void InsertColumnLeft()
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
InsertAdjacentColumn(TableSelection.BeginColumn, false);
TableHelper.SynchronizeCellAndTableWidthsForEditing(TableSelection.Table);
undoUnit.Commit();
}
}
private void InsertColumnRight()
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
InsertAdjacentColumn(TableSelection.EndColumn, true);
TableHelper.SynchronizeCellAndTableWidthsForEditing(TableSelection.Table);
undoUnit.Commit();
}
}
private void MoveColumnLeft()
{
// no-op if this is the first column or the selection spans more than one column
if ((TableSelection.BeginColumn.Index == 0) || !TableSelection.SingleColumnSelected)
return;
// determine the source and target column indexes
int sourceIndex = TableSelection.BeginColumn.Index;
int targetIndex = sourceIndex - 1;
using (_editorContext.DamageServices.CreateDamageTracker(_editorContext.MarkupServices.CreateMarkupRange(TableSelection.Table as IHTMLElement, true), false))
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// swap the cells in the respective columns
foreach (IHTMLTableRow row in TableSelection.Table.rows)
{
if (row.cells.length > sourceIndex)
{
HTMLElementHelper.SwapElements(
row.cells.item(sourceIndex, sourceIndex) as IHTMLElement,
row.cells.item(targetIndex, targetIndex) as IHTMLElement);
}
}
undoUnit.Commit();
}
}
}
private void MoveColumnRight()
{
// no-op if this is the last column or the selection spans more than one column
if ((TableSelection.BeginColumn.Index >= (TableSelection.BeginRow.cells.length - 1)) || !TableSelection.SingleColumnSelected)
return;
// determine the source and target column indexes
int sourceIndex = TableSelection.BeginColumn.Index;
int targetIndex = sourceIndex + 1;
using (_editorContext.DamageServices.CreateDamageTracker(_editorContext.MarkupServices.CreateMarkupRange(TableSelection.Table as IHTMLElement, true), false))
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// swap the cells in the respective columns
foreach (IHTMLTableRow row in TableSelection.Table.rows)
{
if (row.cells.length > targetIndex)
{
HTMLElementHelper.SwapElements(
row.cells.item(sourceIndex, sourceIndex) as IHTMLElement,
row.cells.item(targetIndex, targetIndex) as IHTMLElement);
}
}
undoUnit.Commit();
}
}
}
private void DeleteColumns()
{
// index to delete
int endRowIndex = TableSelection.EndRow.rowIndex;
int beginColumnIndex = TableSelection.BeginColumn.Index;
int endColumnIndex = TableSelection.EndColumn.Index;
// accumulate a list of cells in the columns
ArrayList columnCells = new ArrayList();
foreach (IHTMLTableRow row in TableSelection.Table.rows)
{
// if the row contains a cell in this column
if (row.cells.length > beginColumnIndex)
{
for (int i = beginColumnIndex; i <= endColumnIndex; i++)
columnCells.Add(row.cells.item(i, i));
}
}
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// The selection gets into a very bad state if we allow HTMLElementHelper.RemoveElement below
// to remove the element(s) that are selected.
// To avoid this, we move the selection before deleting the columns.
MarkupRange newSelection;
if (endColumnIndex == ((IHTMLTableRow)TableSelection.Table.rows.item(endRowIndex, endRowIndex)).cells.length - 1)
{
// Deleting rightmost column. Move selection outside of table
newSelection = _editorContext.MarkupServices.CreateMarkupRange(TableSelection.Table as IHTMLElement, true);
newSelection.Collapse(false);
}
else
{
// Move selection into next column
int nextColumnIndex = endColumnIndex + 1;
newSelection = _editorContext.MarkupServices.CreateMarkupRange((IHTMLElement)TableSelection.EndRow.cells.item(nextColumnIndex, nextColumnIndex), false);
newSelection.Collapse(true);
}
newSelection.ToTextRange().select();
// delete each cell
foreach (IHTMLTableCell cell in columnCells)
HTMLElementHelper.RemoveElement(cell as IHTMLElement);
TableHelper.SynchronizeCellAndTableWidthsForEditing(TableSelection.Table);
DeleteTableIfEmpty();
undoUnit.Commit();
}
}
#endregion
#region Cell Editing Oriented Commands
private CellProperties CellProperties
{
get
{
CellProperties cellProperties = new CellProperties();
cellProperties.BackgroundColor = new CellColor(TableHelper.GetColorForHtmlColor(TableSelection.BeginCell.bgColor));
cellProperties.HorizontalAlignment = TableHelper.GetAlignmentForHtmlAlignment(TableSelection.BeginCell.align);
cellProperties.VerticalAlignment = TableHelper.GetVAlignmentForHtmlAlignment(TableSelection.BeginCell.vAlign);
return cellProperties;
}
set
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
if (!value.BackgroundColor.IsMixed)
{
if (value.BackgroundColor.Color != Color.Empty)
{
TableSelection.BeginCell.bgColor = ColorHelper.ColorToString(value.BackgroundColor.Color);
}
else
{
(TableSelection.BeginCell as IHTMLElement).removeAttribute("bgcolor", 0);
}
}
if (value.HorizontalAlignment != HorizontalAlignment.Mixed)
{
if (value.HorizontalAlignment != HorizontalAlignment.Left)
{
TableSelection.BeginCell.align = TableHelper.GetHtmlAlignmentForAlignment(value.HorizontalAlignment);
}
else
{
(TableSelection.BeginCell as IHTMLElement).removeAttribute("align", 0);
}
}
if (value.VerticalAlignment != VerticalAlignment.Mixed)
{
if (value.VerticalAlignment != VerticalAlignment.Middle)
{
TableSelection.BeginCell.vAlign = TableHelper.GetHtmlAlignmentForVAlignment(value.VerticalAlignment);
}
else
{
(TableSelection.BeginCell as IHTMLElement).removeAttribute("valign", 0);
}
}
undoUnit.Commit();
}
}
}
private void ClearCells()
{
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// clear the contents of the selected cells
foreach (IHTMLElement cellElement in TableSelection.SelectedCells)
{
cellElement.innerHTML = null;
}
// select the begin cell
SelectCell(TableSelection.BeginCell);
// commit
undoUnit.Commit();
}
}
/// <summary>
/// Routine to automatically add/remove/restore to empty cells so that
/// these empty cells do not "collapse" when published.
/// </summary>
private void MakeEmptyCellsNbsp()
{
IHTMLElement tableElement = TableSelection.Table as IHTMLElement;
if (tableElement != null)
{
// modify document but "merge" this edit with any previously undoable action
using (IUndoUnit undoUnit = _editorContext.CreateInvisibleUndoUnit())
{
MarkupRange tableMarkupRange = _editorContext.MarkupServices.CreateMarkupRange(tableElement);
foreach (IHTMLElement cellElement in tableMarkupRange.GetElements(ElementFilters.TABLE_CELL_ELEMENT, true))
{
if ((cellElement.innerHTML == null) || cellElement.innerHTML == String.Empty)
{
cellElement.innerHTML = EMPTY_CELL;
}
}
undoUnit.Commit();
}
}
}
private void MakeEmptyCellsNull()
{
IHTMLElement tableElement = TableSelection.Table as IHTMLElement;
if (tableElement != null)
{
// modify document but "merge" this edit with any previously undoable action
using (IUndoUnit undoUnit = _editorContext.CreateInvisibleUndoUnit())
{
MarkupRange tableMarkupRange = _editorContext.MarkupServices.CreateMarkupRange(tableElement);
foreach (IHTMLElement cellElement in tableMarkupRange.GetElements(ElementFilters.TABLE_CELL_ELEMENT, true))
{
string innerHTML = cellElement.innerHTML;
if ((innerHTML == EMPTY_CELL) || innerHTML == String.Empty)
{
cellElement.innerHTML = null;
}
}
undoUnit.Commit();
}
}
}
#endregion
#region Selection Mutating Operations
private void InsertLineBreak()
{
// modify document but "merge" this edit with any previously undoable action
using (IUndoUnit undoUnit = _editorContext.CreateInvisibleUndoUnit())
{
// alias MarkupServices
MshtmlMarkupServices markupServices = _editorContext.MarkupServices;
// create and insert a BR element
IHTMLElement brElement = markupServices.CreateElement(_ELEMENT_TAG_ID.TAGID_BR, null);
markupServices.InsertElement(brElement, MarkupRange.Start, MarkupRange.End);
// move the selection to be just after the BR
MarkupRange range = markupServices.CreateMarkupRange();
range.Start.MoveAdjacentToElement(brElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
range.End.MoveToPointer(range.Start);
range.ToTextRange().select();
// commit the edit
undoUnit.Commit();
}
}
private void SelectNextCell()
{
// determine the target cell (if the selection spans more than one cell then
// the target cell is the very first cell)
IHTMLElement targetCell = null;
if (!TableSelection.HasContiguousSelection)
{
MarkupPointer afterCurrentCellPointer = _editorContext.MarkupServices.CreateMarkupPointer(TableSelection.BeginCell as IHTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
MarkupPointer endOfTablePointer = _editorContext.MarkupServices.CreateMarkupPointer(TableSelection.Table as IHTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd);
targetCell = afterCurrentCellPointer.SeekElementRight(ElementFilters.TABLE_CELL_ELEMENT, endOfTablePointer);
}
else
{
targetCell = TableSelection.BeginCell as IHTMLElement;
}
// if there is no target cell then we need to insert a row and use its
// first cell as the target cell
if (targetCell == null)
{
IHTMLTableRow newRow = InsertRowBelow();
if (newRow != null)
{
// record the target cell
targetCell = newRow.cells.item(0, 0) as IHTMLElement;
}
}
// move the selection to the target cell and select the contents of the cell
if (targetCell != null)
{
SelectCell(targetCell as IHTMLTableCell);
}
}
private void SelectPreviousCell()
{
// determine the target cell (if the selection spans more than one cell then
// the target cell is the very first cell)
IHTMLElement targetCell = null;
if (!TableSelection.HasContiguousSelection)
{
MarkupPointer beforeCurrentCellPointer = _editorContext.MarkupServices.CreateMarkupPointer(TableSelection.BeginCell as IHTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
MarkupPointer beginningOfTablePointer = _editorContext.MarkupServices.CreateMarkupPointer(TableSelection.Table as IHTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
targetCell = beforeCurrentCellPointer.SeekElementLeft(ElementFilters.TABLE_CELL_ELEMENT, beginningOfTablePointer);
}
else
{
targetCell = TableSelection.BeginCell as IHTMLElement;
}
if (targetCell != null)
{
SelectCell(targetCell as IHTMLTableCell);
}
}
private void SelectCell(IHTMLTableCell cell)
{
IHTMLElement cellElement = cell as IHTMLElement;
// move the selection to the beginning of the cell
MarkupRange markupRange = _editorContext.MarkupServices.CreateMarkupRange(cellElement);
// if the cell is empty then collapse the selection
if (cellElement.innerHTML == null)
markupRange.End.MoveToPointer(markupRange.Start);
IHTMLTxtRange textRange = markupRange.ToTextRange();
textRange.select();
}
#endregion
#region Private Helpers
private MarkupRange MarkupRange
{
get
{
return _markupRange;
}
}
private TableSelection TableSelection
{
get
{
if (_tableSelection == null)
_tableSelection = new TableSelection(MarkupRange);
return _tableSelection;
}
}
private IHTMLTableRow InsertRow(bool below)
{
// determine the html element relative position and base row
IHTMLTableRow selectedRow = below ? TableSelection.EndRow : TableSelection.BeginRow;
// screen out no selected row
if (selectedRow == null)
return null;
using (IUndoUnit undoUnit = _editorContext.CreateUndoUnit())
{
// create a new row, copy the source row's attributes to it, and insert it
IHTMLTableRow newRow = TableSelection.Table.insertRow(below ? selectedRow.rowIndex + 1 : selectedRow.rowIndex) as IHTMLTableRow;
HTMLElementHelper.CopyAttributes(selectedRow as IHTMLElement, newRow as IHTMLElement);
// insert a like number of cells into the new row, cloning the attributes of the
// corresponding cells from the source row
for (int i = 0; i < selectedRow.cells.length; i++)
{
IHTMLTableCell newCell = InsertCell(newRow);
HTMLElementHelper.CopyAttributes(selectedRow.cells.item(i, i) as IHTMLElement, newCell as IHTMLElement);
}
// commit the changes
undoUnit.Commit();
// return the row for further manipulation
return newRow;
}
}
private CellColor GetBackgroundColorForRow(IHTMLTableRow row)
{
CellColor cellColor = new CellColor();
bool firstCellProcessed = false;
foreach (IHTMLTableCell cell in row.cells)
{
// for the first cell processed, note its color
if (!firstCellProcessed)
{
cellColor.Color = TableHelper.GetColorForHtmlColor(cell.bgColor);
firstCellProcessed = true;
}
// for subsequent cells, if any of them differ from the first cell
// then the background color is mixed
else
{
if (cellColor.Color != TableHelper.GetColorForHtmlColor(cell.bgColor))
{
cellColor.IsMixed = true;
break;
}
}
}
return cellColor;
}
private HorizontalAlignment GetAlignmentForRow(IHTMLTableRow row)
{
HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left;
bool firstCellProcessed = false;
foreach (IHTMLTableCell cell in row.cells)
{
// for the first cell processed, note its alignment
if (!firstCellProcessed)
{
horizontalAlignment = TableHelper.GetAlignmentForHtmlAlignment(cell.align);
firstCellProcessed = true;
}
// for subsequent cells, if any of them differ from the first cell
// then the alignment is mixed
else
{
if (horizontalAlignment != TableHelper.GetAlignmentForHtmlAlignment(cell.align))
{
horizontalAlignment = HorizontalAlignment.Mixed;
break;
}
}
}
return horizontalAlignment;
}
private VerticalAlignment GetVAlignmentForRow(IHTMLTableRow row)
{
VerticalAlignment verticalAlignment = VerticalAlignment.Middle;
bool firstCellProcessed = false;
foreach (IHTMLTableCell cell in row.cells)
{
// for the first cell processed, note its alignment
if (!firstCellProcessed)
{
verticalAlignment = TableHelper.GetVAlignmentForHtmlAlignment(cell.vAlign);
firstCellProcessed = true;
}
// for subsequent cells, if any of them differ from the first cell
// then the alignment is mixed
else
{
if (verticalAlignment != TableHelper.GetVAlignmentForHtmlAlignment(cell.vAlign))
{
verticalAlignment = VerticalAlignment.Mixed;
break;
}
}
}
return verticalAlignment;
}
private bool TableParentElementFilter(IHTMLElement e)
{
if (ElementFilters.BLOCK_ELEMENTS(e))
return true;
else if (e is IHTMLTableCell)
return true;
else
return false;
}
private IHTMLTableCell InsertCell(IHTMLTableRow row)
{
return InsertCell(row, -1);
}
private IHTMLTableCell InsertCell(IHTMLTableRow row, int index)
{
IHTMLElement cell = (IHTMLElement)row.insertCell(index);
return cell as IHTMLTableCell;
}
private void DeleteTableIfEmpty()
{
IHTMLElement tableElement = TableSelection.Table as IHTMLElement;
MarkupRange tableMarkupRange = _editorContext.MarkupServices.CreateMarkupRange(tableElement);
if (tableMarkupRange.GetElements(ElementFilters.TABLE_CELL_ELEMENT, true).Length == 0)
{
HTMLElementHelper.RemoveElement(tableElement);
_editorContext.FireSelectionChanged();
}
}
private void InsertAdjacentColumn(HTMLTableColumn column, bool after)
{
// set the specified alignment for each cell in the column
foreach (IHTMLTableRow row in TableSelection.Table.rows)
{
if (row.cells.length > column.Index)
{
// insert the cell
IHTMLTableCell newCell = InsertCell(row, after ? column.Index + 1 : column.Index);
// copy the attributes of the source cell for this column
HTMLElementHelper.CopyAttributes(column.BaseCell as IHTMLElement, newCell as IHTMLElement);
}
}
}
private class SelectionPreserver : IDisposable
{
public SelectionPreserver(MarkupRange selectedMarkupRange)
{
_preservedMarkupRange = selectedMarkupRange.Clone();
_preservedMarkupRange.Start.Cling = true;
_preservedMarkupRange.End.Cling = true;
}
public void Dispose()
{
_preservedMarkupRange.ToTextRange().select();
}
private MarkupRange _preservedMarkupRange = null;
}
#endregion
#region Private Data and Constants
private IHtmlEditorComponentContext _editorContext;
private MarkupRange _markupRange;
private TableSelection _tableSelection;
private const string EMPTY_CELL = " ";
#endregion
}
public class TableCreationParameters
{
public TableCreationParameters(int rows, int columns, TableProperties properties)
{
_rows = rows;
_columns = columns;
_properties = properties;
}
public int Rows { get { return _rows; } }
private int _rows;
public int Columns { get { return _columns; } }
private int _columns;
public TableProperties Properties { get { return _properties; } }
private TableProperties _properties;
}
public class TableProperties
{
public string CellPadding
{
get { return _cellPadding; }
set { _cellPadding = value; }
}
private string _cellPadding = String.Empty;
public string CellSpacing
{
get { return _cellSpacing; }
set { _cellSpacing = value; }
}
private string _cellSpacing = String.Empty;
public string BorderSize
{
get { return _borderSize; }
set { _borderSize = value; }
}
private string _borderSize = String.Empty;
public PixelPercent Width { get; set; }
}
public class CellProperties
{
public CellColor BackgroundColor
{
get { return _backgroundColor; }
set { _backgroundColor = value; }
}
private CellColor _backgroundColor = new CellColor();
public HorizontalAlignment HorizontalAlignment
{
get { return _horizontalAlignment; }
set { _horizontalAlignment = value; }
}
private HorizontalAlignment _horizontalAlignment = HorizontalAlignment.Left;
public VerticalAlignment VerticalAlignment
{
get { return _verticalAlignment; }
set { _verticalAlignment = value; }
}
private VerticalAlignment _verticalAlignment = VerticalAlignment.Middle;
}
public class RowProperties
{
public int Height
{
get { return _height; }
set { _height = value; }
}
private int _height = 0;
public CellProperties CellProperties
{
get { return _cellProperties; }
set { _cellProperties = value; }
}
private CellProperties _cellProperties = new CellProperties();
}
public class ColumnProperties
{
public PixelPercent Width { get; set; }
public CellProperties CellProperties
{
get { return _cellProperties; }
set { _cellProperties = value; }
}
private CellProperties _cellProperties = new CellProperties();
}
public class CellColor
{
public CellColor()
{
}
public CellColor(Color color)
{
Color = color;
}
public bool IsMixed
{
get
{
return _isMixed;
}
set
{
_isMixed = value;
if (_isMixed)
Color = Color.Empty;
}
}
private bool _isMixed = false;
public Color Color
{
get
{
return _color;
}
set
{
_color = value;
}
}
private Color _color = Color.Empty;
}
public enum HorizontalAlignment
{
Mixed,
Left,
Center,
Right
}
public enum VerticalAlignment
{
Mixed,
Top,
Middle,
Bottom
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NinjaBotCore.Models.Wow
{
public class Items
{
public int averageItemLevel { get; set; }
public int averageItemLevelEquipped { get; set; }
public Head head { get; set; }
public Neck neck { get; set; }
public Shoulder shoulder { get; set; }
public Back back { get; set; }
public Chest chest { get; set; }
public Tabard tabard { get; set; }
public Wrist wrist { get; set; }
public Hands hands { get; set; }
public Waist waist { get; set; }
public Legs legs { get; set; }
public Feet feet { get; set; }
public Finger1 finger1 { get; set; }
public Finger2 finger2 { get; set; }
public Trinket1 trinket1 { get; set; }
public Trinket2 trinket2 { get; set; }
public Mainhand mainHand { get; set; }
public OffHand offHand { get; set; }
}
public class Head
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams tooltipParams { get; set; }
public Stat[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance appearance { get; set; }
}
public class Tooltipparams
{
public int gem0 { get; set; }
public int timewalkerLevel { get; set; }
}
public class Appearance
{
}
public class Stat
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Neck
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams1 tooltipParams { get; set; }
public Stat1[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance1 appearance { get; set; }
public AzeriteItem azeriteItem { get; set; }
}
public class Tooltipparams1
{
public int enchant { get; set; }
public int timewalkerLevel { get; set; }
}
public class Appearance1
{
public int enchantDisplayInfoId { get; set; }
}
public class Stat1
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Shoulder
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams2 tooltipParams { get; set; }
public Stat2[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance2 appearance { get; set; }
}
public class AzeriteItem
{
public int azeriteExperience { get; set ; }
public int azeriteExperienceRemaining { get; set; }
public int azeriteLevel { get; set; }
}
public class Tooltipparams2
{
public int timewalkerLevel { get; set; }
}
public class Appearance2
{
}
public class Stat2
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Back
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams3 tooltipParams { get; set; }
public Stat3[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance3 appearance { get; set; }
}
public class Tooltipparams3
{
public int enchant { get; set; }
public int timewalkerLevel { get; set; }
}
public class Appearance3
{
public int enchantDisplayInfoId { get; set; }
}
public class Stat3
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Chest
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams4 tooltipParams { get; set; }
public Stat4[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance4 appearance { get; set; }
}
public class Tooltipparams4
{
public int timewalkerLevel { get; set; }
}
public class Appearance4
{
}
public class Stat4
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Tabard
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams5 tooltipParams { get; set; }
public object[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public object[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance5 appearance { get; set; }
}
public class Tooltipparams5
{
public int timewalkerLevel { get; set; }
}
public class Appearance5
{
}
public class Wrist
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams6 tooltipParams { get; set; }
public Stat5[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance6 appearance { get; set; }
}
public class Tooltipparams6
{
public int timewalkerLevel { get; set; }
}
public class Appearance6
{
}
public class Stat5
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Hands
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams7 tooltipParams { get; set; }
public Stat6[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance7 appearance { get; set; }
}
public class Tooltipparams7
{
public int timewalkerLevel { get; set; }
}
public class Appearance7
{
}
public class Stat6
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Waist
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams8 tooltipParams { get; set; }
public Stat7[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance8 appearance { get; set; }
}
public class Tooltipparams8
{
public int timewalkerLevel { get; set; }
}
public class Appearance8
{
}
public class Stat7
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Legs
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams9 tooltipParams { get; set; }
public Stat8[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance9 appearance { get; set; }
}
public class Tooltipparams9
{
public int timewalkerLevel { get; set; }
}
public class Appearance9
{
}
public class Stat8
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Feet
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams10 tooltipParams { get; set; }
public Stat9[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance10 appearance { get; set; }
}
public class Tooltipparams10
{
public int timewalkerLevel { get; set; }
}
public class Appearance10
{
}
public class Stat9
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Finger1
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams11 tooltipParams { get; set; }
public Stat10[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance11 appearance { get; set; }
}
public class Tooltipparams11
{
public int enchant { get; set; }
public int timewalkerLevel { get; set; }
}
public class Appearance11
{
public int enchantDisplayInfoId { get; set; }
}
public class Stat10
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Finger2
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams12 tooltipParams { get; set; }
public Stat11[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance12 appearance { get; set; }
}
public class Tooltipparams12
{
public int enchant { get; set; }
public int timewalkerLevel { get; set; }
}
public class Appearance12
{
public int enchantDisplayInfoId { get; set; }
}
public class Stat11
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Trinket1
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams13 tooltipParams { get; set; }
public Stat12[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance13 appearance { get; set; }
}
public class Tooltipparams13
{
public int timewalkerLevel { get; set; }
}
public class Appearance13
{
}
public class Stat12
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Trinket2
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams14 tooltipParams { get; set; }
public Stat13[] stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public object[] artifactTraits { get; set; }
public object[] relics { get; set; }
public Appearance14 appearance { get; set; }
}
public class Tooltipparams14
{
public int timewalkerLevel { get; set; }
}
public class Appearance14
{
}
public class Stat13
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Mainhand
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams15 tooltipParams { get; set; }
public Stat14[] stats { get; set; }
public int armor { get; set; }
public Weaponinfo weaponInfo { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public Artifacttrait[] artifactTraits { get; set; }
public Relic[] relics { get; set; }
public Appearance15 appearance { get; set; }
}
public class OffHand
{
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public Tooltipparams15 tooltipParams { get; set; }
public Stat14[] stats { get; set; }
public int armor { get; set; }
public Weaponinfo weaponInfo { get; set; }
public string context { get; set; }
public int[] bonusLists { get; set; }
public int artifactId { get; set; }
public int displayInfoId { get; set; }
public int artifactAppearanceId { get; set; }
public Artifacttrait[] artifactTraits { get; set; }
public Relic[] relics { get; set; }
public Appearance15 appearance { get; set; }
}
public class Tooltipparams15
{
public int gem0 { get; set; }
public int gem1 { get; set; }
public int gem2 { get; set; }
public int timewalkerLevel { get; set; }
}
public class Weaponinfo
{
public Damage damage { get; set; }
public float weaponSpeed { get; set; }
public float dps { get; set; }
}
public class Damage
{
public int min { get; set; }
public int max { get; set; }
public float exactMin { get; set; }
public float exactMax { get; set; }
}
public class Appearance15
{
public int itemAppearanceModId { get; set; }
}
public class Stat14
{
public int stat { get; set; }
public int amount { get; set; }
}
public class Artifacttrait
{
public int id { get; set; }
public int rank { get; set; }
}
public class Relic
{
public int socket { get; set; }
public int itemId { get; set; }
public int context { get; set; }
public int[] bonusLists { get; set; }
}
}
| |
namespace WpfAnalyzers.Test.DependencyProperties.WPF0041SetMutableUsingSetCurrentValue
{
using System.Threading.Tasks;
using NUnit.Framework;
using WpfAnalyzers.DependencyProperties;
internal class HappyPath : HappyPathVerifier<WPF0041SetMutableUsingSetCurrentValue>
{
[Test]
public async Task DependencyProperty()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty BarProperty = DependencyProperty.Register(
nameof(Bar),
typeof(int),
typeof(FooControl),
new PropertyMetadata(default(int)));
public int Bar
{
get { return (int)this.GetValue(BarProperty); }
set { this.SetValue(BarProperty, value); }
}
public void Meh()
{
this.SetCurrentValue(BarProperty, 1);
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[TestCase("this.fooControl.SetCurrentValue(FooControl.BarProperty, 1);")]
[TestCase("this.fooControl?.SetCurrentValue(FooControl.BarProperty, 1);")]
public async Task DependencyPropertyFromOutside(string setExpression)
{
var fooCode = @"
public class Foo
{
private readonly FooControl fooControl = new FooControl();
public void Meh()
{
this.fooControl.SetCurrentValue(FooControl.BarProperty, 1);
}
}";
var fooControlCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty BarProperty = DependencyProperty.Register(
nameof(Bar),
typeof(int),
typeof(FooControl),
new PropertyMetadata(default(int)));
public int Bar
{
get { return (int)this.GetValue(BarProperty); }
set { this.SetValue(BarProperty, value); }
}
public void Meh()
{
this.SetCurrentValue(BarProperty, 1);
}
}";
fooCode = fooCode.AssertReplace(
"this.fooControl.SetCurrentValue(FooControl.BarProperty, 1);",
setExpression);
await this.VerifyHappyPathAsync(new []{fooCode, fooControlCode}).ConfigureAwait(false);
}
[Test]
public async Task ReadOnlyDependencyProperty()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
private static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterReadOnly(
""Bar"",
typeof(int),
typeof(FooControl),
new PropertyMetadata(default(int)));
public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty;
public int Bar
{
get { return (int)GetValue(BarProperty); }
protected set { SetValue(BarPropertyKey, value); }
}
public int Baz { get; set; }
public void Meh()
{
Bar = 1;
this.Bar = 2;
this.Bar = this.CreateValue();
Baz = 5;
var control = new FooControl();
control.Bar = 6;
}
private int CreateValue() => 4;
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task ReadOnlyDependencyPropertyFromOutside()
{
var fooControlCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
internal static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterReadOnly(
""Bar"",
typeof(int),
typeof(FooControl),
new PropertyMetadata(default(int)));
public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty;
public int Bar
{
get { return (int)GetValue(BarProperty); }
internal set { SetValue(BarPropertyKey, value); }
}
}";
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public static class Foo
{
public static void Meh()
{
var fooControl = new FooControl();
fooControl.Bar = 1;
fooControl.SetValue(FooControl.BarPropertyKey, 1);
fooControl.Bar = CreateValue();
fooControl.SetValue(FooControl.BarPropertyKey, CreateValue());
fooControl.SetValue(FooControl.BarPropertyKey, CreateObjectValue());
}
private static int CreateValue() => 4;
private static object CreateObjectValue() => 4;
}";
await this.VerifyHappyPathAsync(new[] { testCode, fooControlCode }).ConfigureAwait(false);
}
[Test]
public async Task ReadOnlyDependencyPropertyThis()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
private static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterReadOnly(
""Bar"",
typeof(int),
typeof(FooControl),
new PropertyMetadata(default(int)));
public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty;
public int Bar
{
get { return (int)this.GetValue(BarProperty); }
set { this.SetValue(BarPropertyKey, value); }
}
public int Baz { get; set; }
public void Meh()
{
Bar = 1;
this.Bar = 2;
this.Bar = this.CreateValue();
Baz = 5;
var control = new FooControl();
control.Bar = 6;
}
private int CreateValue() => 4;
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task AttachedProperty()
{
var booleanBoxesCode = @"
internal static class BooleanBoxes
{
internal static readonly object True = true;
internal static readonly object False = false;
internal static object Box(bool value)
{
return value
? True
: False;
}
}";
var testCode = @"
using System;
using System.Windows;
public static class Foo
{
public static readonly DependencyProperty BarProperty = DependencyProperty.RegisterAttached(
""Bar"",
typeof(bool),
typeof(Foo),
new PropertyMetadata(default(bool)));
public static void SetBar(FrameworkElement element, bool value)
{
element.SetValue(BarProperty, value);
}
public static bool GetBar(FrameworkElement element)
{
return (bool)element.GetValue(BarProperty);
}
}";
await this.VerifyHappyPathAsync(new[] { testCode, booleanBoxesCode }).ConfigureAwait(false);
}
[Test]
public async Task AttachedPropertyWhenBoxed()
{
var booleanBoxesCode = @"
internal static class BooleanBoxes
{
internal static readonly object True = true;
internal static readonly object False = false;
internal static object Box(bool value)
{
return value
? True
: False;
}
}";
var testCode = @"
using System;
using System.Windows;
public static class Foo
{
public static readonly DependencyProperty BarProperty = DependencyProperty.RegisterAttached(
""Bar"",
typeof(bool),
typeof(Foo),
new PropertyMetadata(BooleanBoxes.False));
public static void SetBar(FrameworkElement element, bool value)
{
element.SetValue(BarProperty, BooleanBoxes.Box(value));
}
public static bool GetBar(FrameworkElement element)
{
return (bool)element.GetValue(BarProperty);
}
}";
await this.VerifyHappyPathAsync(new[] { testCode, booleanBoxesCode }).ConfigureAwait(false);
}
[Test]
public async Task IgnoredDependencyPropertyInClrProperty()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
nameof(Value),
typeof(double),
typeof(FooControl));
public double Value
{
get { return (double)this.GetValue(ValueProperty); }
set { this.SetValue(ValueProperty, value); }
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task IgnoredDependencyPropertyInClrPropertyWithAsCast()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
nameof(Value),
typeof(string),
typeof(FooControl));
public string Value
{
get { return this.GetValue(ValueProperty) as string; }
set { this.SetValue(ValueProperty, value); }
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task IgnoredDependencyPropertyInClrPropertyBoxed()
{
var boolBoxesCode = @"
public static class BooleanBoxes
{
public static readonly object True = true;
public static readonly object False = false;
}";
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty IsTrueProperty = DependencyProperty.Register(
nameof(IsTrue),
typeof(bool),
typeof(FooControl),
new PropertyMetadata(default(bool)));
public bool IsTrue
{
get { return (bool)this.GetValue(IsTrueProperty); }
set { this.SetValue(IsTrueProperty, value ? BooleanBoxes.True : BooleanBoxes.False); }
}
}";
await this.VerifyHappyPathAsync(new []{testCode, boolBoxesCode}).ConfigureAwait(false);
}
[Test]
public async Task IgnoredAttachedPropertyInClrSetMethod()
{
var testCode = @"
using System.Windows;
public static class Foo
{
public static readonly DependencyProperty IsTrueProperty = DependencyProperty.RegisterAttached(
""IsTrue"",
typeof(bool),
typeof(Foo),
new PropertyMetadata(default(bool)));
public static void SetIsTrue(this DependencyObject element, bool value)
{
element.SetValue(IsTrueProperty, value);
}
[AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static bool GetIsTrue(this DependencyObject element)
{
return (bool)element.GetValue(IsTrueProperty);
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task IgnoredAttachedPropertyInClrSetMethodWhenBoxed()
{
var boolBoxesCode = @"
public static class BooleanBoxes
{
public static readonly object True = true;
public static readonly object False = false;
}";
var testCode = @"
using System.Windows;
public static class Foo
{
public static readonly DependencyProperty IsTrueProperty = DependencyProperty.RegisterAttached(
""IsTrue"",
typeof(bool),
typeof(Foo),
new PropertyMetadata(default(bool)));
public static void SetIsTrue(this DependencyObject element, bool value)
{
element.SetValue(IsTrueProperty, value ? BooleanBoxes.True : BooleanBoxes.False);
}
[AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static bool GetIsTrue(this DependencyObject element)
{
return (bool)element.GetValue(IsTrueProperty);
}
}";
await this.VerifyHappyPathAsync(new[] { testCode, boolBoxesCode }).ConfigureAwait(false);
}
[Test]
public async Task IgnoredClrPropertyInObjectInitializer()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public static class Foo
{
public static void Bar()
{
var textBlock = new TextBlock
{
Text = ""abc"",
VerticalAlignment = VerticalAlignment.Center,
IsHitTestVisible = false
};
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task IgnoredClrPropertyInConstructor()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
nameof(Value),
typeof(double),
typeof(FooControl));
public FooControl()
{
this.Value = 2;
}
public double Value
{
get { return (double)this.GetValue(ValueProperty); }
set { this.SetValue(ValueProperty, value); }
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[Test]
public async Task IgnoredSetValueInConstructor()
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
nameof(Value),
typeof(double),
typeof(FooControl));
public FooControl()
{
SetValue(ValueProperty, 2);
this.SetValue(ValueProperty, 2);
}
public double Value
{
get { return (double)this.GetValue(ValueProperty); }
set { this.SetValue(ValueProperty, value); }
}
}";
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[TestCase("textBox.Visibility = Visibility.Hidden;")]
[TestCase("textBox.SetValue(TextBox.VisibilityProperty, Visibility.Hidden);")]
public async Task IgnoredWhenCreatedInScope(string setCall)
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public static class Foo
{
public static void MethodName()
{
var textBox = new TextBox();
textBox.Visibility = Visibility.Hidden;
}
}";
testCode = testCode.AssertReplace("textBox.Visibility = Visibility.Hidden;", setCall);
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[TestCase("textBox.Visibility = Visibility.Hidden;")]
[TestCase("textBox.SetValue(TextBox.VisibilityProperty, Visibility.Hidden);")]
public async Task IgnoredWhenCreatedInScopeWithBeginEndInit(string setCall)
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public static class Foo
{
public static void MethodName()
{
var textBox = new TextBox();
textBox.BeginInit();
textBox.Visibility = Visibility.Hidden;
textBox.EndInit();
}
}";
testCode = testCode.AssertReplace("textBox.Visibility = Visibility.Hidden;", setCall);
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[TestCase("textBox.Visibility = Visibility.Hidden;")]
[TestCase("textBox.SetValue(TextBox.VisibilityProperty, Visibility.Hidden);")]
public async Task IgnoredWhenCreatedInScopeWithIf(string setCall)
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public static class Foo
{
public static void MethodName()
{
var textBox = new TextBox();
if (true)
{
textBox.Visibility = Visibility.Hidden;
}
}
}";
testCode = testCode.AssertReplace("textBox.Visibility = Visibility.Hidden;", setCall);
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
[TestCase("SetValue")]
[TestCase("SetCurrentValue")]
public async Task IgnoredPropertyAsParameter(string setValueCall)
{
var testCode = @"
using System.Windows;
using System.Windows.Controls;
public class FooControl : Control
{
public static readonly DependencyProperty BarProperty = DependencyProperty.Register(
nameof(Bar),
typeof(int),
typeof(FooControl),
new PropertyMetadata(default(int)));
public int Bar
{
get { return (int)this.GetValue(BarProperty); }
set { this.SetValue(BarProperty, value); }
}
public void Meh(DependencyProperty property, object value)
{
this.SetCurrentValue(property, value);
}
}";
testCode = testCode.AssertReplace("SetCurrentValue", setValueCall);
await this.VerifyHappyPathAsync(testCode).ConfigureAwait(false);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Provider;
using System.Security.AccessControl;
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
#region private methods
/// <summary>
/// Gets an instance of an ISecurityDescriptorCmdletProvider given the provider ID.
/// </summary>
/// <param name="providerInstance">
/// An instance of a CmdletProvider.
/// </param>
/// <returns>
/// An instance of a ISecurityDescriptorCmdletProvider for the specified provider ID.
/// </returns>
/// <throws>
/// ArgumentNullException if providerId is null.
/// NotSupportedException if the providerId is not for a provider
/// that is derived from ISecurityDescriptorCmdletProvider.
/// </throws>
internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance(CmdletProvider providerInstance)
{
if (providerInstance == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
if (!(providerInstance is ISecurityDescriptorCmdletProvider permissionCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(
ProviderBaseSecurity.ISecurityDescriptorCmdletProvider_NotSupported);
}
return permissionCmdletProvider;
}
#endregion private methods
#region GetSecurityDescriptor
/// <summary>
/// Gets the security descriptor from the specified item.
/// </summary>
/// <param name="path">
/// The path to the item to retrieve the security descriptor from.
/// </param>
/// <param name="sections">
/// Specifies the parts of a security descriptor to retrieve.
/// </param>
/// <returns>
/// The security descriptor for the item at the specified path.
/// </returns>
internal Collection<PSObject> GetSecurityDescriptor(string path,
AccessControlSections sections)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
GetSecurityDescriptor(path, sections, context);
context.ThrowFirstErrorOrDoNothing();
Collection<PSObject> contextResults = context.GetAccumulatedObjects() ?? new Collection<PSObject>();
return contextResults;
}
/// <summary>
/// Gets the security descriptor from the specified item.
/// </summary>
/// <param name="path">
/// The path to the item to retrieve the security descriptor from.
/// </param>
/// <param name="sections">
/// Specifies the parts of a security descriptor to retrieve.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing. The security descriptor for the item at the specified path is
/// written to the context.
/// </returns>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void GetSecurityDescriptor(
string path,
AccessControlSections sections,
CmdletProviderContext context)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
GetSecurityDescriptor(providerInstance, providerPath, sections, context);
}
}
private void GetSecurityDescriptor(
CmdletProvider providerInstance,
string path,
AccessControlSections sections,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
// This just verifies that the provider supports the interface.
GetPermissionProviderInstance(providerInstance);
try
{
providerInstance.GetSecurityDescriptor(path, sections, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetSecurityDescriptorProviderException",
SessionStateStrings.GetSecurityDescriptorProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
#endregion GetSecurityDescriptor
#region SetSecurityDescriptor
/// <summary>
/// Sets the security descriptor on the specified item.
/// </summary>
/// <param name="path">
/// The path to the item to set the security descriptor on.
/// </param>
/// <param name="securityDescriptor">
/// The security descriptor to set on the item at the specified path.
/// </param>
/// <returns>
/// The security descriptor that was set on the item at the specified path.
/// </returns>
internal Collection<PSObject> SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
if (securityDescriptor == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
SetSecurityDescriptor(path, securityDescriptor, context);
context.ThrowFirstErrorOrDoNothing();
// Return an empty array instead of null
Collection<PSObject> contextResults = context.GetAccumulatedObjects() ?? new Collection<PSObject>();
return contextResults;
}
/// <summary>
/// Sets the security descriptor on the specified item.
/// </summary>
/// <param name="path">
/// The path to the item to set the security descriptor on.
/// </param>
/// <param name="securityDescriptor">
/// The security descriptor to set on the item at the specified path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing. The security descriptor that was set on the item at the specified path
/// is written to the context.
/// </returns>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void SetSecurityDescriptor(
string path,
ObjectSecurity securityDescriptor,
CmdletProviderContext context)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
if (securityDescriptor == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
SetSecurityDescriptor(
providerInstance,
providerPath,
securityDescriptor,
context);
}
}
private void SetSecurityDescriptor(
CmdletProvider providerInstance,
string path,
ObjectSecurity securityDescriptor,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Diagnostics.Assert(
securityDescriptor != null,
"Caller should validate securityDescriptor before calling this method");
Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
// This just verifies that the provider supports the interface.
GetPermissionProviderInstance(providerInstance);
try
{
providerInstance.SetSecurityDescriptor(path, securityDescriptor, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (PrivilegeNotHeldException e)
{
//
// thrown if one tries to set SACL and does not have
// SeSecurityPrivilege
//
context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
}
catch (UnauthorizedAccessException e)
{
//
// thrown if
// -- owner or pri. group are invalid OR
// -- marta returns ERROR_ACCESS_DENIED
//
context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
}
catch (NotSupportedException e)
{
//
// thrown if path points to an item that does not
// support access control.
//
// for example, FAT or FAT32 file in case of file system provider
//
context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path));
}
catch (SystemException e)
{
//
// thrown if the CLR gets back unexpected error
// from OS security or marta
//
context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path));
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetSecurityDescriptorProviderException",
SessionStateStrings.SetSecurityDescriptorProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
#endregion SetSecurityDescriptor
#region NewSecurityDescriptor
/// <summary>
/// Gets the security descriptor from the specified item.
/// </summary>
/// <param name="path">
/// The path to the item to retrieve the security descriptor from.
/// </param>
/// <param name="sections">
/// Specifies the parts of a security descriptor to retrieve.
/// </param>
/// <returns>
/// Nothing. The security descriptor for the item at the specified path is
/// written to the context.
/// </returns>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal ObjectSecurity NewSecurityDescriptorFromPath(
string path,
AccessControlSections sections)
{
ObjectSecurity sd = null;
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
out provider,
out providerInstance);
//
// path must resolve to exact 1 item,
// any other case is an error
//
if (providerPaths.Count == 1)
{
sd = NewSecurityDescriptorFromPath(providerInstance,
providerPaths[0],
sections);
}
else
{
throw PSTraceSource.NewArgumentException(nameof(path));
}
return sd;
}
private ObjectSecurity NewSecurityDescriptorFromPath(
CmdletProvider providerInstance,
string path,
AccessControlSections sections)
{
ObjectSecurity sd = null;
// All parameters should have been validated by caller
Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Diagnostics.Assert(
ExecutionContext != null,
"Caller should validate context before calling this method");
// This just verifies that the provider supports the interface.
ISecurityDescriptorCmdletProvider sdProvider =
GetPermissionProviderInstance(providerInstance);
try
{
sd = sdProvider.NewSecurityDescriptorFromPath(path,
sections);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"NewSecurityDescriptorProviderException",
SessionStateStrings.GetSecurityDescriptorProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return sd;
}
/// <summary>
/// Gets the security descriptor from the specified item.
/// </summary>
/// <param name="type">
/// The type of the item which corresponds to the security
/// descriptor that we want to create.
/// </param>
/// <param name="providerId">
/// The name of the provider.
/// </param>
/// <param name="sections">
/// Specifies the parts of a security descriptor to retrieve.
/// </param>
/// <returns>
/// Nothing. The security descriptor for the item at the specified type is
/// written to the context.
/// </returns>
internal ObjectSecurity NewSecurityDescriptorOfType(
string providerId,
string type,
AccessControlSections sections)
{
CmdletProvider providerInstance = GetProviderInstance(providerId);
return NewSecurityDescriptorOfType(providerInstance, type, sections);
}
/// <summary>
/// Gets the security descriptor from the specified item.
/// </summary>
/// <param name="type">
/// The type of the item which corresponds to the security
/// descriptor that we want to create.
/// </param>
/// <param name="providerInstance">
/// The type of the item which corresponds to the security
/// descriptor that we want to create.
/// </param>
/// <param name="sections">
/// Specifies the parts of a security descriptor to retrieve.
/// </param>
/// <returns>
/// Nothing. The security descriptor for the item at the specified type is
/// written to the context.
/// </returns>
internal ObjectSecurity NewSecurityDescriptorOfType(
CmdletProvider providerInstance,
string type,
AccessControlSections sections)
{
ObjectSecurity sd = null;
if (type == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(type));
}
if (providerInstance == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
// This just verifies that the provider supports the interface.
ISecurityDescriptorCmdletProvider sdProvider =
GetPermissionProviderInstance(providerInstance);
try
{
sd = sdProvider.NewSecurityDescriptorOfType(type,
sections);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"NewSecurityDescriptorProviderException",
SessionStateStrings.GetSecurityDescriptorProviderException,
providerInstance.ProviderInfo,
type,
e);
}
return sd;
}
#endregion NewSecurityDescriptor
}
}
| |
namespace ASCOM.NexStar
{
partial class SetupDialogForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetupDialogForm));
this.cmdOK = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.picASCOM = new System.Windows.Forms.PictureBox();
this.label_port = new System.Windows.Forms.Label();
this.text_lat = new System.Windows.Forms.TextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tab_scope = new System.Windows.Forms.TabPage();
this.label4 = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.label_align = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.text_foc_len = new System.Windows.Forms.TextBox();
this.label_focal_len = new System.Windows.Forms.Label();
this.text_ap_obs = new System.Windows.Forms.TextBox();
this.text_ap_dia = new System.Windows.Forms.TextBox();
this.lable_apature_obs = new System.Windows.Forms.Label();
this.label_apature_dia = new System.Windows.Forms.Label();
this.tab_site = new System.Windows.Forms.TabPage();
this.label3 = new System.Windows.Forms.Label();
this.text_lst = new System.Windows.Forms.TextBox();
this.label_lst = new System.Windows.Forms.Label();
this.lable_evel = new System.Windows.Forms.Label();
this.lable_long = new System.Windows.Forms.Label();
this.lable_lat = new System.Windows.Forms.Label();
this.text_evel = new System.Windows.Forms.TextBox();
this.text_long = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.picASCOM)).BeginInit();
this.tabControl1.SuspendLayout();
this.tab_scope.SuspendLayout();
this.tab_site.SuspendLayout();
this.SuspendLayout();
//
// cmdOK
//
this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.cmdOK.Location = new System.Drawing.Point(282, 118);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(59, 24);
this.cmdOK.TabIndex = 9;
this.cmdOK.Text = "OK";
this.cmdOK.UseVisualStyleBackColor = true;
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// cmdCancel
//
this.cmdCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdCancel.Location = new System.Drawing.Point(282, 151);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(59, 25);
this.cmdCancel.TabIndex = 10;
this.cmdCancel.Text = "Cancel";
this.cmdCancel.UseVisualStyleBackColor = true;
this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
//
// picASCOM
//
this.picASCOM.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.picASCOM.Cursor = System.Windows.Forms.Cursors.Hand;
this.picASCOM.Image = global::ASCOM.NexStar.Properties.Resources.ASCOM;
this.picASCOM.Location = new System.Drawing.Point(292, 9);
this.picASCOM.Name = "picASCOM";
this.picASCOM.Size = new System.Drawing.Size(48, 56);
this.picASCOM.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.picASCOM.TabIndex = 3;
this.picASCOM.TabStop = false;
this.picASCOM.Click += new System.EventHandler(this.BrowseToAscom);
this.picASCOM.DoubleClick += new System.EventHandler(this.BrowseToAscom);
//
// label_port
//
this.label_port.AutoSize = true;
this.label_port.Location = new System.Drawing.Point(3, 8);
this.label_port.Name = "label_port";
this.label_port.Size = new System.Drawing.Size(58, 13);
this.label_port.TabIndex = 0;
this.label_port.Text = "Comm Port";
//
// text_lat
//
this.text_lat.Location = new System.Drawing.Point(6, 25);
this.text_lat.Name = "text_lat";
this.text_lat.Size = new System.Drawing.Size(120, 20);
this.text_lat.TabIndex = 1;
this.text_lat.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_lat_KeyPress);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tab_scope);
this.tabControl1.Controls.Add(this.tab_site);
this.tabControl1.Location = new System.Drawing.Point(6, 9);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(270, 170);
this.tabControl1.TabIndex = 0;
//
// tab_scope
//
this.tab_scope.BackColor = System.Drawing.SystemColors.Control;
this.tab_scope.Controls.Add(this.label4);
this.tab_scope.Controls.Add(this.checkBox1);
this.tab_scope.Controls.Add(this.label2);
this.tab_scope.Controls.Add(this.label1);
this.tab_scope.Controls.Add(this.comboBox2);
this.tab_scope.Controls.Add(this.label_align);
this.tab_scope.Controls.Add(this.comboBox1);
this.tab_scope.Controls.Add(this.text_foc_len);
this.tab_scope.Controls.Add(this.label_focal_len);
this.tab_scope.Controls.Add(this.text_ap_obs);
this.tab_scope.Controls.Add(this.text_ap_dia);
this.tab_scope.Controls.Add(this.lable_apature_obs);
this.tab_scope.Controls.Add(this.label_apature_dia);
this.tab_scope.Controls.Add(this.label_port);
this.tab_scope.Location = new System.Drawing.Point(4, 22);
this.tab_scope.Name = "tab_scope";
this.tab_scope.Padding = new System.Windows.Forms.Padding(3);
this.tab_scope.Size = new System.Drawing.Size(262, 144);
this.tab_scope.TabIndex = 1;
this.tab_scope.Text = "Scope";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(72, 110);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(15, 13);
this.label4.TabIndex = 9;
this.label4.Text = "%";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(150, 109);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(83, 17);
this.checkBox1.TabIndex = 8;
this.checkBox1.Text = "Enable PEC";
this.checkBox1.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(216, 26);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(23, 13);
this.label2.TabIndex = 7;
this.label2.Text = "mm";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(72, 69);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(23, 13);
this.label1.TabIndex = 6;
this.label1.Text = "mm";
//
// comboBox2
//
this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Location = new System.Drawing.Point(150, 68);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(66, 21);
this.comboBox2.TabIndex = 5;
//
// label_align
//
this.label_align.AutoSize = true;
this.label_align.Location = new System.Drawing.Point(148, 51);
this.label_align.Name = "label_align";
this.label_align.Size = new System.Drawing.Size(53, 13);
this.label_align.TabIndex = 0;
this.label_align.Text = "Alignment";
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(6, 25);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(66, 21);
this.comboBox1.TabIndex = 1;
//
// text_foc_len
//
this.text_foc_len.Location = new System.Drawing.Point(150, 25);
this.text_foc_len.Name = "text_foc_len";
this.text_foc_len.Size = new System.Drawing.Size(66, 20);
this.text_foc_len.TabIndex = 4;
this.text_foc_len.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_foc_len_KeyPress);
//
// label_focal_len
//
this.label_focal_len.AutoSize = true;
this.label_focal_len.Location = new System.Drawing.Point(148, 8);
this.label_focal_len.Name = "label_focal_len";
this.label_focal_len.Size = new System.Drawing.Size(69, 13);
this.label_focal_len.TabIndex = 0;
this.label_focal_len.Text = "Focal Length";
//
// text_ap_obs
//
this.text_ap_obs.Location = new System.Drawing.Point(6, 109);
this.text_ap_obs.Name = "text_ap_obs";
this.text_ap_obs.Size = new System.Drawing.Size(66, 20);
this.text_ap_obs.TabIndex = 3;
this.text_ap_obs.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_ap_obs_KeyPress);
this.text_ap_obs.Leave += new System.EventHandler(this.text_ap_obs_Leave);
//
// text_ap_dia
//
this.text_ap_dia.Location = new System.Drawing.Point(6, 68);
this.text_ap_dia.Name = "text_ap_dia";
this.text_ap_dia.Size = new System.Drawing.Size(66, 20);
this.text_ap_dia.TabIndex = 2;
this.text_ap_dia.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_ap_dia_KeyPress);
this.text_ap_dia.Leave += new System.EventHandler(this.text_ap_dia_Leave);
//
// lable_apature_obs
//
this.lable_apature_obs.AutoSize = true;
this.lable_apature_obs.Location = new System.Drawing.Point(3, 92);
this.lable_apature_obs.Name = "lable_apature_obs";
this.lable_apature_obs.Size = new System.Drawing.Size(61, 13);
this.lable_apature_obs.TabIndex = 0;
this.lable_apature_obs.Text = "Obstruction";
//
// label_apature_dia
//
this.label_apature_dia.AutoSize = true;
this.label_apature_dia.Location = new System.Drawing.Point(3, 51);
this.label_apature_dia.Name = "label_apature_dia";
this.label_apature_dia.Size = new System.Drawing.Size(69, 13);
this.label_apature_dia.TabIndex = 0;
this.label_apature_dia.Text = "Aperture Dia.";
//
// tab_site
//
this.tab_site.BackColor = System.Drawing.SystemColors.Control;
this.tab_site.Controls.Add(this.label3);
this.tab_site.Controls.Add(this.text_lst);
this.tab_site.Controls.Add(this.label_lst);
this.tab_site.Controls.Add(this.lable_evel);
this.tab_site.Controls.Add(this.lable_long);
this.tab_site.Controls.Add(this.lable_lat);
this.tab_site.Controls.Add(this.text_evel);
this.tab_site.Controls.Add(this.text_long);
this.tab_site.Controls.Add(this.text_lat);
this.tab_site.Location = new System.Drawing.Point(4, 22);
this.tab_site.Name = "tab_site";
this.tab_site.Padding = new System.Windows.Forms.Padding(3);
this.tab_site.Size = new System.Drawing.Size(262, 144);
this.tab_site.TabIndex = 0;
this.tab_site.Text = "Site";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(72, 110);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(15, 13);
this.label3.TabIndex = 5;
this.label3.Text = "m";
//
// text_lst
//
this.text_lst.BackColor = System.Drawing.SystemColors.Window;
this.text_lst.Location = new System.Drawing.Point(150, 25);
this.text_lst.Name = "text_lst";
this.text_lst.ReadOnly = true;
this.text_lst.Size = new System.Drawing.Size(60, 20);
this.text_lst.TabIndex = 4;
this.text_lst.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label_lst
//
this.label_lst.AutoSize = true;
this.label_lst.Location = new System.Drawing.Point(148, 8);
this.label_lst.Name = "label_lst";
this.label_lst.Size = new System.Drawing.Size(27, 13);
this.label_lst.TabIndex = 0;
this.label_lst.Text = "LST";
//
// lable_evel
//
this.lable_evel.AutoSize = true;
this.lable_evel.Location = new System.Drawing.Point(3, 92);
this.lable_evel.Name = "lable_evel";
this.lable_evel.Size = new System.Drawing.Size(51, 13);
this.lable_evel.TabIndex = 0;
this.lable_evel.Text = "Elevation";
//
// lable_long
//
this.lable_long.AutoSize = true;
this.lable_long.Location = new System.Drawing.Point(3, 51);
this.lable_long.Name = "lable_long";
this.lable_long.Size = new System.Drawing.Size(54, 13);
this.lable_long.TabIndex = 0;
this.lable_long.Text = "Longitude";
//
// lable_lat
//
this.lable_lat.AutoSize = true;
this.lable_lat.Location = new System.Drawing.Point(3, 8);
this.lable_lat.Margin = new System.Windows.Forms.Padding(0);
this.lable_lat.Name = "lable_lat";
this.lable_lat.Size = new System.Drawing.Size(45, 13);
this.lable_lat.TabIndex = 0;
this.lable_lat.Text = "Latitude";
//
// text_evel
//
this.text_evel.Location = new System.Drawing.Point(6, 109);
this.text_evel.Name = "text_evel";
this.text_evel.Size = new System.Drawing.Size(66, 20);
this.text_evel.TabIndex = 3;
this.text_evel.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_evel_KeyPress);
//
// text_long
//
this.text_long.Location = new System.Drawing.Point(6, 68);
this.text_long.Name = "text_long";
this.text_long.Size = new System.Drawing.Size(120, 20);
this.text_long.TabIndex = 2;
this.text_long.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_long_KeyPress);
//
// SetupDialogForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(350, 187);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.picASCOM);
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SetupDialogForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "NexStar Setup";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SetupDialogForm_FormClosing);
((System.ComponentModel.ISupportInitialize)(this.picASCOM)).EndInit();
this.tabControl1.ResumeLayout(false);
this.tab_scope.ResumeLayout(false);
this.tab_scope.PerformLayout();
this.tab_site.ResumeLayout(false);
this.tab_site.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.Button cmdCancel;
private System.Windows.Forms.PictureBox picASCOM;
private System.Windows.Forms.Label label_port;
private System.Windows.Forms.TextBox text_lat;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tab_site;
private System.Windows.Forms.Label lable_evel;
private System.Windows.Forms.Label lable_long;
private System.Windows.Forms.Label lable_lat;
private System.Windows.Forms.TextBox text_evel;
private System.Windows.Forms.TextBox text_long;
private System.Windows.Forms.TabPage tab_scope;
private System.Windows.Forms.TextBox text_foc_len;
private System.Windows.Forms.Label label_focal_len;
private System.Windows.Forms.TextBox text_ap_obs;
private System.Windows.Forms.TextBox text_ap_dia;
private System.Windows.Forms.Label lable_apature_obs;
private System.Windows.Forms.Label label_apature_dia;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.TextBox text_lst;
private System.Windows.Forms.Label label_lst;
private System.Windows.Forms.ComboBox comboBox2;
private System.Windows.Forms.Label label_align;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System;
using System.Runtime;
// A mostly output-restricted double-ended queue. You can add an item to both ends
// and it is optimized for removing from the front. The list can be scanned and
// items can be removed from any location at the cost of performance.
class Quack<T>
{
T[] items;
// First element when items is not empty
int head;
// Next vacancy when items are not full
int tail;
// Number of elements.
int count;
public Quack()
{
this.items = new T[4];
}
public Quack(T[] items)
{
Fx.Assert(items != null, "This shouldn't get called with null");
Fx.Assert(items.Length > 0, "This shouldn't be called with a zero length array.");
this.items = items;
// The default value of 0 is correct for both
// head and tail.
this.count = this.items.Length;
}
public int Count
{
get { return this.count; }
}
public T this[int index]
{
get
{
Fx.Assert(index < this.count, "Index out of range.");
int realIndex = (this.head + index) % this.items.Length;
return this.items[realIndex];
}
}
public T[] ToArray()
{
Fx.Assert(this.count > 0, "We should only call this when we have items.");
T[] compressedItems = new T[this.count];
for (int i = 0; i < this.count; i++)
{
compressedItems[i] = this.items[(this.head + i) % this.items.Length];
}
return compressedItems;
}
public void PushFront(T item)
{
if (this.count == this.items.Length)
{
Enlarge();
}
if (--this.head == -1)
{
this.head = this.items.Length - 1;
}
this.items[this.head] = item;
++this.count;
}
public void Enqueue(T item)
{
if (this.count == this.items.Length)
{
Enlarge();
}
this.items[this.tail] = item;
if (++this.tail == this.items.Length)
{
this.tail = 0;
}
++this.count;
}
public T Dequeue()
{
Fx.Assert(this.count > 0, "Quack is empty");
T removed = this.items[this.head];
this.items[this.head] = default(T);
if (++this.head == this.items.Length)
{
this.head = 0;
}
--this.count;
return removed;
}
public bool Remove(T item)
{
int found = -1;
for (int i = 0; i < this.count; i++)
{
int realIndex = (this.head + i) % this.items.Length;
if (object.Equals(this.items[realIndex], item))
{
found = i;
break;
}
}
if (found == -1)
{
return false;
}
else
{
Remove(found);
return true;
}
}
public void Remove(int index)
{
Fx.Assert(index < this.count, "Index out of range");
for (int i = index - 1; i >= 0; i--)
{
int sourceIndex = (this.head + i) % this.items.Length;
int targetIndex = sourceIndex + 1;
if (targetIndex == this.items.Length)
{
targetIndex = 0;
}
this.items[targetIndex] = this.items[sourceIndex];
}
--this.count;
++this.head;
if (this.head == this.items.Length)
{
this.head = 0;
}
}
void Enlarge()
{
Fx.Assert(this.items.Length > 0, "Quack is empty");
int capacity = this.items.Length * 2;
this.SetCapacity(capacity);
}
void SetCapacity(int capacity)
{
Fx.Assert(capacity >= this.count, "Capacity is set to a smaller value");
T[] newArray = new T[capacity];
if (this.count > 0)
{
if (this.head < this.tail)
{
Array.Copy(this.items, this.head, newArray, 0, this.count);
}
else
{
Array.Copy(this.items, this.head, newArray, 0, this.items.Length - this.head);
Array.Copy(this.items, 0, newArray, this.items.Length - this.head, this.tail);
}
}
this.items = newArray;
this.head = 0;
this.tail = (this.count == capacity) ? 0 : this.count;
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !__IOS__ && !WINDOWS_PHONE && !__ANDROID__ && !NETSTANDARD || WCF_SUPPORTED
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
#if WCF_SUPPORTED
using System.ServiceModel;
using System.ServiceModel.Channels;
#endif
using System.Threading;
#if SILVERLIGHT
using System.Windows;
using System.Windows.Threading;
#endif
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using NLog.LogReceiverService;
/// <summary>
/// Sends log messages to a NLog Receiver Service (using WCF or Web Services).
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/LogReceiverService-target">Documentation on NLog Wiki</seealso>
[Target("LogReceiverService")]
public class LogReceiverWebServiceTarget : Target
{
private readonly LogEventInfoBuffer buffer = new LogEventInfoBuffer(10000, false, 10000);
private bool inCall;
/// <summary>
/// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class.
/// </summary>
public LogReceiverWebServiceTarget()
{
Parameters = new List<MethodCallParameter>();
}
/// <summary>
/// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public LogReceiverWebServiceTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the endpoint address.
/// </summary>
/// <value>The endpoint address.</value>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
public virtual string EndpointAddress { get; set; }
#if WCF_SUPPORTED
/// <summary>
/// Gets or sets the name of the endpoint configuration in WCF configuration file.
/// </summary>
/// <value>The name of the endpoint configuration.</value>
/// <docgen category='Connection Options' order='10' />
public string EndpointConfigurationName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use binary message encoding.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool UseBinaryEncoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply)
/// </summary>
/// <docgen category='Connection Options' order='10' />
public bool UseOneWayContract { get; set; }
#endif
/// <summary>
/// Gets or sets the client ID.
/// </summary>
/// <value>The client ID.</value>
/// <docgen category='Payload Options' order='10' />
public Layout ClientId { get; set; }
/// <summary>
/// Gets the list of parameters.
/// </summary>
/// <value>The parameters.</value>
/// <docgen category='Payload Options' order='10' />
[ArrayParameter(typeof(MethodCallParameter), "parameter")]
public IList<MethodCallParameter> Parameters { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeEventProperties { get; set; }
/// <summary>
/// Called when log events are being sent (test hook).
/// </summary>
/// <param name="events">The events.</param>
/// <param name="asyncContinuations">The async continuations.</param>
/// <returns>True if events should be sent, false to stop processing them.</returns>
protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations)
{
return true;
}
/// <summary>
/// Writes logging event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Logging event to be written out.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
Write((IList<AsyncLogEventInfo>)new[] { logEvent });
}
/// <summary>
/// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents)
///
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
[Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Write((IList<AsyncLogEventInfo>)logEvents);
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Append" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
// if web service call is being processed, buffer new events and return
// lock is being held here
if (inCall)
{
for (int i = 0; i < logEvents.Count; ++i)
{
PrecalculateVolatileLayouts(logEvents[i].LogEvent);
buffer.Append(logEvents[i]);
}
return;
}
// OptimizeBufferReuse = true, will reuse the input-array on method-exit (so we make clone here)
AsyncLogEventInfo[] logEventsArray = new AsyncLogEventInfo[logEvents.Count];
logEvents.CopyTo(logEventsArray, 0);
var networkLogEvents = TranslateLogEvents(logEventsArray);
Send(networkLogEvents, logEventsArray, null);
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
SendBufferedEvents(asyncContinuation);
}
/// <summary>
/// Add value to the <see cref="NLogEvents.Strings"/>, returns ordinal in <see cref="NLogEvents.Strings"/>
/// </summary>
/// <param name="context"></param>
/// <param name="stringTable">lookup so only unique items will be added to <see cref="NLogEvents.Strings"/></param>
/// <param name="value">value to add</param>
/// <returns></returns>
private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value)
{
if (value == null || !stringTable.TryGetValue(value, out var stringIndex))
{
stringIndex = context.Strings.Count;
if (value != null)
{
//don't add null to the string table, that would crash
stringTable.Add(value, stringIndex);
}
context.Strings.Add(value);
}
return stringIndex;
}
private NLogEvents TranslateLogEvents(IList<AsyncLogEventInfo> logEvents)
{
if (logEvents.Count == 0 && !LogManager.ThrowExceptions)
{
InternalLogger.Error("LogReceiverServiceTarget(Name={0}): LogEvents array is empty, sending empty event...", Name);
return new NLogEvents();
}
string clientID = string.Empty;
if (ClientId != null)
{
clientID = ClientId.Render(logEvents[0].LogEvent);
}
var networkLogEvents = new NLogEvents
{
ClientName = clientID,
LayoutNames = new StringCollection(),
Strings = new StringCollection(),
BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
};
var stringTable = new Dictionary<string, int>();
for (int i = 0; i < Parameters.Count; ++i)
{
networkLogEvents.LayoutNames.Add(Parameters[i].Name);
}
if (IncludeEventProperties)
{
for (int i = 0; i < logEvents.Count; ++i)
{
var ev = logEvents[i].LogEvent;
if (ev.HasProperties)
{
// add all event-level property names in 'LayoutNames' collection.
foreach (var prop in ev.Properties)
{
string propName = prop.Key as string;
if (propName != null)
{
if (!networkLogEvents.LayoutNames.Contains(propName))
{
networkLogEvents.LayoutNames.Add(propName);
}
}
}
}
}
}
networkLogEvents.Events = new NLogEvent[logEvents.Count];
for (int i = 0; i < logEvents.Count; ++i)
{
AsyncLogEventInfo ev = logEvents[i];
networkLogEvents.Events[i] = TranslateEvent(ev.LogEvent, networkLogEvents, stringTable);
}
return networkLogEvents;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")]
private void Send(NLogEvents events, IList<AsyncLogEventInfo> asyncContinuations, AsyncContinuation flushContinuations)
{
if (!OnSend(events, asyncContinuations))
{
if (flushContinuations != null)
flushContinuations(null);
return;
}
#if WCF_SUPPORTED
var client = CreateLogReceiver();
client.ProcessLogMessagesCompleted += (sender, e) =>
{
if (e.Error != null)
InternalLogger.Error(e.Error, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
// report error to the callers
for (int i = 0; i < asyncContinuations.Count; ++i)
{
asyncContinuations[i].Continuation(e.Error);
}
if (flushContinuations != null)
flushContinuations(e.Error);
// send any buffered events
SendBufferedEvents(null);
};
inCall = true;
#if SILVERLIGHT
if (!Deployment.Current.Dispatcher.CheckAccess())
{
Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
}
else
{
client.ProcessLogMessagesAsync(events);
}
#else
client.ProcessLogMessagesAsync(events);
#endif
#else
var client = new SoapLogReceiverClient(this.EndpointAddress);
this.inCall = true;
client.BeginProcessLogMessages(
events,
result =>
{
Exception exception = null;
try
{
client.EndProcessLogMessages(result);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
if (ex.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
exception = ex;
}
// report error to the callers
for (int i = 0; i < asyncContinuations.Count; ++i)
{
asyncContinuations[i].Continuation(exception);
}
if (flushContinuations != null)
flushContinuations(exception);
// send any buffered events
this.SendBufferedEvents(null);
},
null);
#endif
}
#if WCF_SUPPORTED
/// <summary>
/// Creating a new instance of WcfLogReceiverClient
///
/// Inheritors can override this method and provide their own
/// service configuration - binding and endpoint address
/// </summary>
/// <remarks>This method marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use CreateLogReceiver instead. Marked obsolete before v4.3.11 and it may be removed in a future release.")]
protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient()
{
WcfLogReceiverClient client;
if (string.IsNullOrEmpty(EndpointConfigurationName))
{
// endpoint not specified - use BasicHttpBinding
Binding binding;
if (UseBinaryEncoding)
{
binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
}
else
{
binding = new BasicHttpBinding();
}
client = new WcfLogReceiverClient(UseOneWayContract, binding, new EndpointAddress(EndpointAddress));
}
else
{
client = new WcfLogReceiverClient(UseOneWayContract, EndpointConfigurationName, new EndpointAddress(EndpointAddress));
}
client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted;
return client;
}
/// <summary>
/// Creating a new instance of IWcfLogReceiverClient
///
/// Inheritors can override this method and provide their own
/// service configuration - binding and endpoint address
/// </summary>
/// <returns></returns>
/// <remarks>virtual is used by endusers</remarks>
protected virtual IWcfLogReceiverClient CreateLogReceiver()
{
#pragma warning disable 612, 618
return CreateWcfLogReceiverClient();
#pragma warning restore 612, 618
}
private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
{
var client = sender as IWcfLogReceiverClient;
if (client != null && client.State == CommunicationState.Opened)
{
try
{
client.Close();
}
catch
{
client.Abort();
}
}
}
#endif
private void SendBufferedEvents(AsyncContinuation flushContinuation)
{
try
{
lock (SyncRoot)
{
// clear inCall flag
AsyncLogEventInfo[] bufferedEvents = buffer.GetEventsAndClear();
if (bufferedEvents.Length > 0)
{
var networkLogEvents = TranslateLogEvents(bufferedEvents);
Send(networkLogEvents, bufferedEvents, flushContinuation);
}
else
{
// nothing in the buffer, clear in-call flag
inCall = false;
if (flushContinuation != null)
flushContinuation(null);
}
}
}
catch (Exception exception)
{
if (flushContinuation != null)
{
InternalLogger.Error(exception, "LogReceiverServiceTarget(Name={0}): Error in flush async", Name);
#if !NETSTANDARD
if (exception.MustBeRethrown())
throw;
#endif
flushContinuation(exception);
}
else
{
InternalLogger.Error(exception, "LogReceiverServiceTarget(Name={0}): Error in send async", Name);
#if !NETSTANDARD
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
}
}
}
internal NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable)
{
var nlogEvent = new NLogEvent();
nlogEvent.Id = eventInfo.SequenceID;
nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage);
nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal;
nlogEvent.LoggerOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName);
nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc;
for (int i = 0; i < Parameters.Count; ++i)
{
var param = Parameters[i];
var value = param.Layout.Render(eventInfo);
int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
nlogEvent.ValueIndexes.Add(stringIndex);
}
// layout names beyond Parameters.Count are per-event property names.
for (int i = Parameters.Count; i < context.LayoutNames.Count; ++i)
{
string value;
object propertyValue;
if (eventInfo.HasProperties && eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue))
{
value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture);
}
else
{
value = string.Empty;
}
int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
nlogEvent.ValueIndexes.Add(stringIndex);
}
if (eventInfo.Exception != null)
{
nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString()));
}
return nlogEvent;
}
}
}
#endif
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
// <version>$Revision: 2819 $</version>
// </file>
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.Ast;
using Attribute = ICSharpCode.NRefactory.Ast.Attribute;
namespace ICSharpCode.NRefactory.Visitors
{
/// <summary>
/// Converts elements not supported by VB to their VB representation.
/// Not all elements are converted here, most simple elements (e.g. ConditionalExpression)
/// are converted in the output visitor.
/// </summary>
public class ToVBNetConvertVisitor : ConvertVisitorBase
{
// The following conversions are implemented:
// Conflicting field/property names -> m_field
// Conflicting variable names inside methods
// Anonymous methods are put into new methods
// Simple event handler creation is replaced with AddressOfExpression
// Move Imports-statements out of namespaces
// Parenthesis around Cast expressions remove - these are syntax errors in VB.NET
// Decrease array creation size - VB specifies upper bound instead of array length
List<INode> nodesToMoveToCompilationUnit = new List<INode>();
public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
{
base.VisitCompilationUnit(compilationUnit, data);
for (int i = 0; i < nodesToMoveToCompilationUnit.Count; i++) {
compilationUnit.Children.Insert(i, nodesToMoveToCompilationUnit[i]);
nodesToMoveToCompilationUnit[i].Parent = compilationUnit;
}
return null;
}
public override object VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data)
{
base.VisitUsingDeclaration(usingDeclaration, data);
if (usingDeclaration.Parent is NamespaceDeclaration) {
nodesToMoveToCompilationUnit.Add(usingDeclaration);
RemoveCurrentNode();
}
return null;
}
TypeDeclaration currentType;
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
{
// fix default inner type visibility
if (currentType != null && (typeDeclaration.Modifier & Modifiers.Visibility) == 0)
typeDeclaration.Modifier |= Modifiers.Private;
TypeDeclaration outerType = currentType;
currentType = typeDeclaration;
if ((typeDeclaration.Modifier & Modifiers.Static) == Modifiers.Static) {
typeDeclaration.Modifier &= ~Modifiers.Static;
typeDeclaration.Modifier |= Modifiers.Sealed;
typeDeclaration.Children.Insert(0, new ConstructorDeclaration("#ctor", Modifiers.Private, null, null));
}
// Conflicting field/property names -> m_field
List<string> properties = new List<string>();
foreach (object o in typeDeclaration.Children) {
PropertyDeclaration pd = o as PropertyDeclaration;
if (pd != null) {
properties.Add(pd.Name);
}
}
List<VariableDeclaration> conflicts = new List<VariableDeclaration>();
foreach (object o in typeDeclaration.Children) {
FieldDeclaration fd = o as FieldDeclaration;
if (fd != null) {
foreach (VariableDeclaration var in fd.Fields) {
string name = var.Name;
foreach (string propertyName in properties) {
if (name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase)) {
conflicts.Add(var);
}
}
}
}
}
new PrefixFieldsVisitor(conflicts, "m_").Run(typeDeclaration);
base.VisitTypeDeclaration(typeDeclaration, data);
currentType = outerType;
return null;
}
public override object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data)
{
// fix default inner type visibility
if (currentType != null && (delegateDeclaration.Modifier & Modifiers.Visibility) == 0)
delegateDeclaration.Modifier |= Modifiers.Private;
return base.VisitDelegateDeclaration(delegateDeclaration, data);
}
public override object VisitExpressionStatement(ExpressionStatement expressionStatement, object data)
{
base.VisitExpressionStatement(expressionStatement, data);
AssignmentExpression ass = expressionStatement.Expression as AssignmentExpression;
if (ass != null && ass.Right is AddressOfExpression) {
if (ass.Op == AssignmentOperatorType.Add) {
ReplaceCurrentNode(new AddHandlerStatement(ass.Left, ass.Right));
} else if (ass.Op == AssignmentOperatorType.Subtract) {
ReplaceCurrentNode(new RemoveHandlerStatement(ass.Left, ass.Right));
}
}
return null;
}
static string GetMemberNameOnThisReference(Expression expr)
{
IdentifierExpression ident = expr as IdentifierExpression;
if (ident != null)
return ident.Identifier;
MemberReferenceExpression fre = expr as MemberReferenceExpression;
if (fre != null && fre.TargetObject is ThisReferenceExpression)
return fre.MemberName;
return null;
}
public override object VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, object data)
{
base.VisitAnonymousMethodExpression(anonymousMethodExpression, data);
if (anonymousMethodExpression.Body.Children.Count == 1) {
ReturnStatement rs = anonymousMethodExpression.Body.Children[0] as ReturnStatement;
if (rs != null) {
LambdaExpression lambda = new LambdaExpression();
lambda.ExpressionBody = rs.Expression;
lambda.Parameters = anonymousMethodExpression.Parameters;
ReplaceCurrentNode(lambda);
}
}
return null;
}
public override object VisitAssignmentExpression(AssignmentExpression assignmentExpression, object data)
{
base.VisitAssignmentExpression(assignmentExpression, data);
if (assignmentExpression.Op == AssignmentOperatorType.Assign && !(assignmentExpression.Parent is ExpressionStatement)) {
AddInlineAssignHelper();
ReplaceCurrentNode(
new InvocationExpression(
new IdentifierExpression("InlineAssignHelper"),
new List<Expression> { assignmentExpression.Left, assignmentExpression.Right }
));
}
return null;
}
void AddInlineAssignHelper()
{
MethodDeclaration method;
foreach (INode node in currentType.Children) {
method = node as MethodDeclaration;
if (method != null && method.Name == "InlineAssignHelper") {
// inline assign helper already exists
return;
}
}
method = new MethodDeclaration {
Name = "InlineAssignHelper",
Modifier = Modifiers.Private | Modifiers.Static,
TypeReference = new TypeReference("T"),
Parameters = new List<ParameterDeclarationExpression> {
new ParameterDeclarationExpression(new TypeReference("T"), "target", ParameterModifiers.Ref),
new ParameterDeclarationExpression(new TypeReference("T"), "value")
}};
method.Templates.Add(new TemplateDefinition("T", null));
method.Body = new BlockStatement();
method.Body.AddChild(new ExpressionStatement(new AssignmentExpression(
new IdentifierExpression("target"),
AssignmentOperatorType.Assign,
new IdentifierExpression("value"))));
method.Body.AddChild(new ReturnStatement(new IdentifierExpression("value")));
currentType.AddChild(method);
}
bool IsClassType(ClassType c)
{
if (currentType == null) return false;
return currentType.Type == c;
}
public override object VisitMethodDeclaration(MethodDeclaration md, object data)
{
if (!IsClassType(ClassType.Interface) && (md.Modifier & Modifiers.Visibility) == 0)
md.Modifier |= Modifiers.Private;
base.VisitMethodDeclaration(md, data);
const Modifiers externStatic = Modifiers.Static | Modifiers.Extern;
if ((md.Modifier & externStatic) == externStatic
&& md.Body.IsNull)
{
foreach (AttributeSection sec in md.Attributes) {
foreach (Attribute att in sec.Attributes) {
if ("DllImport".Equals(att.Name, StringComparison.InvariantCultureIgnoreCase)) {
if (ConvertPInvoke(md, att)) {
sec.Attributes.Remove(att);
break;
}
}
}
if (sec.Attributes.Count == 0) {
md.Attributes.Remove(sec);
break;
}
}
}
ToVBNetRenameConflictingVariablesVisitor.RenameConflicting(md);
return null;
}
bool ConvertPInvoke(MethodDeclaration method, ICSharpCode.NRefactory.Ast.Attribute att)
{
if (att.PositionalArguments.Count != 1)
return false;
PrimitiveExpression pe = att.PositionalArguments[0] as PrimitiveExpression;
if (pe == null || !(pe.Value is string))
return false;
string libraryName = (string)pe.Value;
string alias = null;
bool setLastError = false;
bool exactSpelling = false;
CharsetModifier charSet = CharsetModifier.Auto;
foreach (NamedArgumentExpression arg in att.NamedArguments) {
switch (arg.Name) {
case "SetLastError":
pe = arg.Expression as PrimitiveExpression;
if (pe != null && pe.Value is bool)
setLastError = (bool)pe.Value;
else
return false;
break;
case "ExactSpelling":
pe = arg.Expression as PrimitiveExpression;
if (pe != null && pe.Value is bool)
exactSpelling = (bool)pe.Value;
else
return false;
break;
case "CharSet":
{
MemberReferenceExpression fre = arg.Expression as MemberReferenceExpression;
if (fre == null || !(fre.TargetObject is IdentifierExpression))
return false;
if ((fre.TargetObject as IdentifierExpression).Identifier != "CharSet")
return false;
switch (fre.MemberName) {
case "Unicode":
charSet = CharsetModifier.Unicode;
break;
case "Auto":
charSet = CharsetModifier.Auto;
break;
case "Ansi":
charSet = CharsetModifier.Ansi;
break;
default:
return false;
}
}
break;
case "EntryPoint":
pe = arg.Expression as PrimitiveExpression;
if (pe != null)
alias = pe.Value as string;
break;
default:
return false;
}
}
if (setLastError && exactSpelling) {
// Only P/Invokes with SetLastError and ExactSpelling can be converted to a DeclareDeclaration
const Modifiers removeModifiers = Modifiers.Static | Modifiers.Extern;
DeclareDeclaration decl = new DeclareDeclaration(method.Name, method.Modifier &~ removeModifiers,
method.TypeReference,
method.Parameters,
method.Attributes,
libraryName, alias, charSet);
ReplaceCurrentNode(decl);
base.VisitDeclareDeclaration(decl, null);
return true;
} else {
return false;
}
}
public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data)
{
if (!IsClassType(ClassType.Interface) && (propertyDeclaration.Modifier & Modifiers.Visibility) == 0)
propertyDeclaration.Modifier |= Modifiers.Private;
base.VisitPropertyDeclaration(propertyDeclaration, data);
ToVBNetRenameConflictingVariablesVisitor.RenameConflicting(propertyDeclaration);
return null;
}
public override object VisitEventDeclaration(EventDeclaration eventDeclaration, object data)
{
if (!IsClassType(ClassType.Interface) && (eventDeclaration.Modifier & Modifiers.Visibility) == 0)
eventDeclaration.Modifier |= Modifiers.Private;
return base.VisitEventDeclaration(eventDeclaration, data);
}
public override object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data)
{
// make constructor private if visiblity is not set (unless constructor is static)
if ((constructorDeclaration.Modifier & (Modifiers.Visibility | Modifiers.Static)) == 0)
constructorDeclaration.Modifier |= Modifiers.Private;
base.VisitConstructorDeclaration(constructorDeclaration, data);
ToVBNetRenameConflictingVariablesVisitor.RenameConflicting(constructorDeclaration);
return null;
}
public override object VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data)
{
base.VisitParenthesizedExpression(parenthesizedExpression, data);
if (parenthesizedExpression.Expression is CastExpression) {
ReplaceCurrentNode(parenthesizedExpression.Expression); // remove parenthesis
}
return null;
}
public override object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data)
{
for (int i = 0; i < arrayCreateExpression.Arguments.Count; i++) {
arrayCreateExpression.Arguments[i] = Expression.AddInteger(arrayCreateExpression.Arguments[i], -1);
}
return base.VisitArrayCreateExpression(arrayCreateExpression, data);
}
}
}
| |
using Microsoft.Extensions.Logging;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.ApplicationParts;
using Orleans.CodeGenerator.Utilities;
using Orleans.Hosting;
using Orleans.Serialization;
using Orleans.Utilities;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator
{
/// <summary>
/// Implements a code generator using the Roslyn C# compiler.
/// </summary>
public class RoslynCodeGenerator : ISourceCodeGenerator
{
private const string SerializerNamespacePrefix = "OrleansGeneratedCode";
/// <summary>
/// The logger.
/// </summary>
private readonly Logger Logger;
/// <summary>
/// The serializer generation manager.
/// </summary>
private readonly SerializerGenerationManager serializerGenerationManager;
private readonly TypeCollector typeCollector = new TypeCollector();
private readonly HashSet<string> knownTypes;
/// <summary>
/// Initializes a new instance of the <see cref="RoslynCodeGenerator"/> class.
/// </summary>
/// <param name="serializationManager">The serialization manager.</param>
/// <param name="loggerFactory">logger factory to use</param>
public RoslynCodeGenerator(SerializationManager serializationManager, ApplicationPartManager applicationPartManager, ILoggerFactory loggerFactory)
{
this.knownTypes = GetKnownTypes();
this.serializerGenerationManager = new SerializerGenerationManager(serializationManager, loggerFactory);
Logger = new LoggerWrapper<RoslynCodeGenerator>(loggerFactory);
HashSet<string> GetKnownTypes()
{
var serializerFeature = applicationPartManager.CreateAndPopulateFeature<SerializerFeature>();
var result = new HashSet<string>();
foreach (var kt in serializerFeature.KnownTypes) result.Add(kt.Type);
foreach (var serializer in serializerFeature.SerializerTypes)
{
result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
result.Add(RuntimeTypeNameFormatter.Format(serializer.Serializer));
}
foreach (var serializer in serializerFeature.SerializerDelegates)
{
result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
}
return result;
}
}
/// <summary>
/// Generates source code for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate source for.
/// </param>
/// <returns>
/// The generated source.
/// </returns>
public string GenerateSourceForAssembly(Assembly input)
{
if (input.GetCustomAttribute<GeneratedCodeAttribute>() != null
|| input.GetCustomAttribute<SkipCodeGenerationAttribute>() != null)
{
return string.Empty;
}
var generated = GenerateForAssemblies(input, false);
if (generated.Syntax == null)
{
return string.Empty;
}
return CodeGeneratorCommon.GenerateSourceCode(CodeGeneratorCommon.AddGeneratedCodeAttribute(generated));
}
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <param name="runtime">Whether or not runtime code generation is being performed.</param>
/// <returns>The generated syntax tree.</returns>
private GeneratedSyntax GenerateForAssemblies(Assembly targetAssembly, bool runtime)
{
var grainInterfaces = new List<GrainInterfaceDescription>();
var grainClasses = new List<GrainClassDescription>();
var serializationTypes = new SerializationTypeDescriptions();
var members = new List<MemberDeclarationSyntax>();
// Expand the list of included assemblies and types.
var (includedTypes, assemblies) = this.GetIncludedTypes(targetAssembly, runtime);
if (Logger.IsVerbose)
{
Logger.Verbose(
"Generating code for assemblies: {0}",
string.Join(", ", assemblies.Select(_ => _.FullName)));
}
var serializerNamespaceMembers = new List<MemberDeclarationSyntax>();
var serializerNamespaceName = $"{SerializerNamespacePrefix}{targetAssembly?.GetName().Name.GetHashCode():X}";
// Group the types by namespace and generate the required code in each namespace.
foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceMembers = new List<MemberDeclarationSyntax>();
var namespaceName = group.Key;
foreach (var type in group)
{
// Skip generated classes.
if (type.GetCustomAttribute<GeneratedCodeAttribute>() != null) continue;
// Every type which is encountered must be considered for serialization.
void OnEncounteredType(Type encounteredType)
{
// If a type was encountered which can be accessed, process it for serialization.
this.typeCollector.RecordEncounteredType(type);
this.serializerGenerationManager.RecordTypeToGenerate(encounteredType, targetAssembly);
}
if (Logger.IsVerbose2)
{
Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
}
if (GrainInterfaceUtils.IsGrainInterface(type))
{
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating GrainReference and MethodInvoker for {0}",
type.GetParseableName());
}
GrainInterfaceUtils.ValidateInterfaceRules(type);
var referenceTypeName = GrainReferenceGenerator.GetGeneratedClassName(type);
var invokerTypeName = GrainMethodInvokerGenerator.GetGeneratedClassName(type);
namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, referenceTypeName, OnEncounteredType));
namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type, invokerTypeName));
var genericTypeSuffix = GetGenericTypeSuffix(type.GetGenericArguments().Length);
grainInterfaces.Add(
new GrainInterfaceDescription
{
Interface = type.GetTypeSyntax(includeGenericParameters: false),
Reference = SF.ParseTypeName(namespaceName + '.' + referenceTypeName + genericTypeSuffix),
Invoker = SF.ParseTypeName(namespaceName + '.' + invokerTypeName + genericTypeSuffix),
InterfaceId = GrainInterfaceUtils.GetGrainInterfaceId(type)
});
}
if (TypeUtils.IsConcreteGrainClass(type))
{
grainClasses.Add(
new GrainClassDescription
{
ClassType = type.GetTypeSyntax(includeGenericParameters: false)
});
}
// Generate serializers.
var first = true;
while (this.serializerGenerationManager.GetNextTypeToProcess(out var toGen))
{
if (first)
{
Logger.Info("ClientGenerator - Generating serializer classes for types:");
first = false;
}
Logger.Info(
"\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
+ " defined in Assembly " + toGen.GetTypeInfo().Assembly.GetName());
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating serializer for type {0}",
toGen.GetParseableName());
}
var generatedSerializerName = SerializerGenerator.GetGeneratedClassName(toGen);
serializerNamespaceMembers.Add(SerializerGenerator.GenerateClass(generatedSerializerName, toGen, OnEncounteredType));
var qualifiedSerializerName = serializerNamespaceName + '.' + generatedSerializerName + GetGenericTypeSuffix(toGen.GetGenericArguments().Length);
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = SF.ParseTypeName(qualifiedSerializerName),
Target = toGen.GetTypeSyntax(includeGenericParameters: false)
});
}
}
if (namespaceMembers.Count == 0)
{
if (Logger.IsVerbose)
{
Logger.Verbose2("Skipping namespace: {0}", namespaceName);
}
continue;
}
members.Add(CreateNamespace(namespaceName, namespaceMembers));
}
// Add all generated serializers to their own namespace.
members.Add(CreateNamespace(serializerNamespaceName, serializerNamespaceMembers));
// Add serialization metadata for the types which were encountered.
this.AddSerializationTypes(serializationTypes, targetAssembly);
// Generate metadata directives for all of the relevant types.
var (attributeDeclarations, memberDeclarations) = FeaturePopulatorGenerator.GenerateSyntax(targetAssembly, grainInterfaces, grainClasses, serializationTypes);
members.AddRange(memberDeclarations);
var compilationUnit = SF.CompilationUnit().AddAttributeLists(attributeDeclarations.ToArray()).AddMembers(members.ToArray());
return new GeneratedSyntax
{
SourceAssemblies = assemblies,
Syntax = compilationUnit
};
string GetGenericTypeSuffix(int numParams)
{
if (numParams == 0) return string.Empty;
return '<' + new string(',', numParams - 1) + '>';
}
NamespaceDeclarationSyntax CreateNamespace(string namespaceName, IEnumerable<MemberDeclarationSyntax> namespaceMembers)
{
return
SF.NamespaceDeclaration(SF.ParseName(namespaceName))
.AddUsings(
TypeUtils.GetNamespaces(typeof(GrainExtensions), typeof(IntrospectionExtensions))
.Select(_ => SF.UsingDirective(SF.ParseName(_)))
.ToArray())
.AddMembers(namespaceMembers.ToArray());
}
}
private (List<Type>, List<Assembly>) GetIncludedTypes(Assembly targetAssembly, bool runtime)
{
// Include assemblies which are marked as included.
var knownAssemblyAttributes = new Dictionary<Assembly, KnownAssemblyAttribute>();
var knownAssemblies = new HashSet<Assembly> {targetAssembly};
foreach (var attribute in targetAssembly.GetCustomAttributes<KnownAssemblyAttribute>())
{
knownAssemblyAttributes[attribute.Assembly] = attribute;
knownAssemblies.Add(attribute.Assembly);
}
// Get types from assemblies which reference Orleans and are not generated assemblies.
var includedTypes = new HashSet<Type>();
foreach (var assembly in knownAssemblies)
{
var considerAllTypesForSerialization = knownAssemblyAttributes.TryGetValue(assembly, out var knownAssemblyAttribute)
&& knownAssemblyAttribute.TreatTypesAsSerializable;
foreach (var attribute in assembly.GetCustomAttributes<ConsiderForCodeGenerationAttribute>())
{
this.ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes, considerForSerialization: true);
if (attribute.ThrowOnFailure && !this.serializerGenerationManager.IsTypeRecorded(attribute.Type))
{
throw new CodeGenerationException(
$"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code"
+ " could not be generated. Ensure that the type is accessible.");
}
}
foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.Logger))
{
this.typeCollector.RecordEncounteredType(type);
var considerForSerialization = considerAllTypesForSerialization || type.IsSerializable;
this.ConsiderType(type.AsType(), runtime, targetAssembly, includedTypes, considerForSerialization);
}
}
return (includedTypes.ToList(), knownAssemblies.ToList());
}
/// <summary>
/// Adds serialization type descriptions from <paramref name="types"/> to <paramref name="serializationTypes"/>.
/// </summary>
/// <param name="serializationTypes">The serialization type descriptions.</param>
/// <param name="targetAssembly">The target assembly for generated code.</param>
/// <param name="types">The types.</param>
private void AddSerializationTypes(SerializationTypeDescriptions serializationTypes, Assembly targetAssembly)
{
// Only types which exist in assemblies referenced by the target assembly can be referenced.
var references = new HashSet<string>(targetAssembly.GetReferencedAssemblies().Select(asm => asm.Name));
bool IsAssemblyReferenced(Type type)
{
// If the target doesn't reference this type's assembly, it cannot reference a type within that assembly.
var asmName = type.Assembly.GetName().Name;
if (type.Assembly != targetAssembly)
{
if (!references.Contains(asmName)) return false;
if (!type.IsSerializable) return false;
}
return true;
}
// Visit all types in other assemblies for serialization metadata.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!references.Contains(assembly.GetName().Name)) continue;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.Logger))
{
this.typeCollector.RecordEncounteredType(type);
}
}
// Returns true if a type can be accessed from source and false otherwise.
bool IsAccessibleType(Type type)
{
var accessible = !type.IsGenericParameter;
if (type.IsSpecialName)
{
accessible = false;
}
if (type.GetCustomAttribute<CompilerGeneratedAttribute>() != null)
{
accessible = false;
}
// Obsolete types can be accessed, however obsolete types which have IsError set cannot.
var obsoleteAttr = type.GetCustomAttribute<ObsoleteAttribute>();
if (obsoleteAttr != null && obsoleteAttr.IsError)
{
accessible = false;
}
if (!TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly))
{
accessible = false;
}
return accessible;
}
foreach (var type in this.typeCollector.EncounteredTypes)
{
if (!IsAssemblyReferenced(type)) continue;
if (type.GetCustomAttribute<GeneratedCodeAttribute>() != null) continue;
var qualifiedTypeName = RuntimeTypeNameFormatter.Format(type);
if (this.knownTypes.Contains(qualifiedTypeName)) continue;
serializationTypes.KnownTypes.Add(new KnownTypeDescription
{
Type = qualifiedTypeName,
TypeKey = type.OrleansTypeKeyString()
});
if (!IsAccessibleType(type)) continue;
var typeSyntax = type.GetTypeSyntax(includeGenericParameters: false);
var serializerAttributes = type.GetCustomAttributes<SerializerAttribute>().ToList();
if (serializerAttributes.Count > 0)
{
// Account for serializer types.
foreach (var serializerAttribute in serializerAttributes)
{
if (!IsAccessibleType(serializerAttribute.TargetType)) continue;
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = typeSyntax,
Target = serializerAttribute.TargetType.GetTypeSyntax(includeGenericParameters: false)
});
}
}
else
{
// Account for self-serializing types.
SerializationManager.GetSerializationMethods(type, out var copier, out var serializer, out var deserializer);
if (copier != null || serializer != null || deserializer != null)
{
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = typeSyntax,
Target = typeSyntax
});
}
}
}
}
private void ConsiderType(
Type type,
bool runtime,
Assembly targetAssembly,
ISet<Type> includedTypes,
bool considerForSerialization = false)
{
// The module containing the serializer.
var typeInfo = type.GetTypeInfo();
// If a type was encountered which can be accessed and is marked as [Serializable], process it for serialization.
if (considerForSerialization)
{
this.RecordType(type, targetAssembly, includedTypes);
}
// Consider generic arguments to base types and implemented interfaces for code generation.
this.ConsiderGenericBaseTypeArguments(typeInfo, targetAssembly, includedTypes);
this.ConsiderGenericInterfacesArguments(typeInfo, targetAssembly, includedTypes);
// Include grain interface types.
if (GrainInterfaceUtils.IsGrainInterface(type))
{
// If code generation is being performed at runtime, the interface must be accessible to the generated code.
if (!runtime || TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly))
{
if (Logger.IsVerbose2) Logger.Verbose2("Will generate code for: {0}", type.GetParseableName());
includedTypes.Add(type);
}
}
if (TypeUtils.IsConcreteGrainClass(type))
{
includedTypes.Add(type);
}
}
private void RecordType(Type type, Assembly targetAssembly, ISet<Type> includedTypes)
{
this.typeCollector.RecordEncounteredType(type);
if (this.serializerGenerationManager.RecordTypeToGenerate(type, targetAssembly))
{
includedTypes.Add(type);
}
}
private void ConsiderGenericBaseTypeArguments(
TypeInfo typeInfo,
Assembly targetAssembly,
ISet<Type> includedTypes)
{
if (typeInfo.BaseType == null) return;
if (!typeInfo.BaseType.IsConstructedGenericType) return;
foreach (var type in typeInfo.BaseType.GetGenericArguments())
{
this.RecordType(type, targetAssembly, includedTypes);
}
}
private void ConsiderGenericInterfacesArguments(
TypeInfo typeInfo,
Assembly targetAssembly,
ISet<Type> includedTypes)
{
var interfaces = typeInfo.GetInterfaces().Where(x => x.IsConstructedGenericType);
foreach (var type in interfaces.SelectMany(v => v.GetTypeInfo().GetGenericArguments()))
{
this.RecordType(type, targetAssembly, includedTypes);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Xunit;
namespace System.ServiceModel.Syndication.Tests
{
public partial class SyndicationFeedTests
{
[Fact]
public void Ctor_Default()
{
var feed = new SyndicationFeed();
VerifySyndicationFeed(feed, null, null, null, null, default, null);
}
public static IEnumerable<object[]> Ctor_Items_TestData()
{
yield return new object[] { new SyndicationItem[0] };
yield return new object[] { new SyndicationItem[] { new SyndicationItem(), null } };
}
[Theory]
[InlineData(null)]
[MemberData(nameof(Ctor_Items_TestData))]
public void Ctor_Items(IEnumerable<SyndicationItem> items)
{
var feed = new SyndicationFeed(items);
VerifySyndicationFeed(feed, null, null, null, null, default, items);
}
public static IEnumerable<object[]> Ctor_String_String_Uri_TestData()
{
yield return new object[] { null, null, null };
yield return new object[] { "", "", new Uri("http://microsoft.com") };
yield return new object[] { "title", "description", new Uri("/relative", UriKind.Relative) };
}
[Theory]
[MemberData(nameof(Ctor_String_String_Uri_TestData))]
public void Ctor_String_String_Uri(string title, string description, Uri feedAlternateLink)
{
var feed = new SyndicationFeed(title, description, feedAlternateLink);
VerifySyndicationFeed(feed, title, description, feedAlternateLink, null, default, null);
}
public static IEnumerable<object[]> Ctor_String_String_Uri_Items_TestData()
{
yield return new object[] { null, null, null, null };
yield return new object[] { "", "", new Uri("http://microsoft.com"), new SyndicationItem[0] };
yield return new object[] { "title", "description", new Uri("/relative", UriKind.Relative), new SyndicationItem[] { new SyndicationItem(), null } };
}
[Theory]
[MemberData(nameof(Ctor_String_String_Uri_Items_TestData))]
public void Ctor_String_String_Uri_Items(string title, string description, Uri feedAlternateLink, IEnumerable<SyndicationItem> items)
{
var feed = new SyndicationFeed(title, description, feedAlternateLink, items);
VerifySyndicationFeed(feed, title, description, feedAlternateLink, null, default, items);
}
public static IEnumerable<object[]> Ctor_String_String_Uri_String_DateTimeOffset_TestData()
{
yield return new object[] { null, null, null, null, default(DateTimeOffset) };
yield return new object[] { "", "", new Uri("http://microsoft.com"), "", DateTimeOffset.Now };
yield return new object[] { "title", "description", new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) };
}
[Theory]
[MemberData(nameof(Ctor_String_String_Uri_String_DateTimeOffset_TestData))]
public void Ctor_String_String_Uri_String_DateTimeOffset(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime)
{
var feed = new SyndicationFeed(title, description, feedAlternateLink, id, lastUpdatedTime);
VerifySyndicationFeed(feed, title, description, feedAlternateLink, id, lastUpdatedTime, null);
}
public static IEnumerable<object[]> Ctor_String_String_Uri_String_DateTimeOffset_Items_TestData()
{
yield return new object[] { null, null, null, null, default(DateTimeOffset), null };
yield return new object[] { "", "", new Uri("http://microsoft.com"), "", DateTimeOffset.Now, new SyndicationItem[0] };
yield return new object[] { "title", "description", new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2), new SyndicationItem[] { new SyndicationItem(), null } };
}
[Theory]
[MemberData(nameof(Ctor_String_String_Uri_String_DateTimeOffset_Items_TestData))]
public void Ctor_String_String_Uri_String_DateTimeOffset_Items(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime, IEnumerable<SyndicationItem> items)
{
var feed = new SyndicationFeed(title, description, feedAlternateLink, id, lastUpdatedTime, items);
VerifySyndicationFeed(feed, title, description, feedAlternateLink, id, lastUpdatedTime, items);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Ctor_SyndicationFeed_Full(bool cloneItems)
{
var original = new SyndicationFeed();
original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");
original.Authors.Add(new SyndicationPerson("email", "author", "uri"));
original.BaseUri = new Uri("http://feed_baseuri.com");
original.Categories.Add(new SyndicationCategory("category"));
original.Contributors.Add(new SyndicationPerson("email", "contributor", "uri"));
original.Copyright = new TextSyndicationContent("copyright");
original.Description = new TextSyndicationContent("description");
original.ElementExtensions.Add(new ExtensionObject { Value = 10 });
original.Generator = "generator";
original.Id = "id";
original.ImageUrl = new Uri("http://imageurl.com");
original.Items = new SyndicationItem[]
{
new SyndicationItem("title", "content", null)
};
original.Language = "language";
original.LastUpdatedTime = DateTimeOffset.MinValue.AddTicks(10);
original.Links.Add(new SyndicationLink(new Uri("http://microsoft.com")));
original.Title = new TextSyndicationContent("title");
var clone = new SyndicationFeedSubclass(original, cloneItems);
Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions);
Assert.Equal(1, clone.AttributeExtensions.Count);
Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]);
Assert.NotSame(clone.Authors, original.Authors);
Assert.Equal(1, clone.Authors.Count);
Assert.NotSame(original.Authors[0], clone.Authors[0]);
Assert.Equal("author", clone.Authors[0].Name);
Assert.Equal(new Uri("http://feed_baseuri.com/"), clone.BaseUri);
Assert.NotSame(clone.Categories, original.Categories);
Assert.Equal(1, clone.Categories.Count);
Assert.NotSame(original.Categories[0], clone.Categories[0]);
Assert.Equal("category", clone.Categories[0].Name);
Assert.NotSame(clone.Contributors, original.Contributors);
Assert.Equal(1, clone.Contributors.Count);
Assert.NotSame(original.Contributors[0], clone.Contributors[0]);
Assert.Equal("contributor", clone.Contributors[0].Name);
Assert.NotSame(clone.Copyright, original.Copyright);
Assert.Equal("copyright", clone.Copyright.Text);
Assert.NotSame(clone.Description, original.Description);
Assert.Equal("description", clone.Description.Text);
Assert.NotSame(clone.ElementExtensions, original.ElementExtensions);
Assert.Equal(1, clone.ElementExtensions.Count);
Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value);
Assert.Equal("generator", original.Generator);
Assert.Equal("id", original.Id);
Assert.Equal(new Uri("http://imageurl.com"), original.ImageUrl);
Assert.NotSame(clone.Contributors, original.Items);
Assert.Equal(1, clone.Items.Count());
if (cloneItems)
{
Assert.NotSame(((IList<SyndicationItem>)original.Items)[0], ((IList<SyndicationItem>)clone.Items)[0]);
Assert.Equal("title", (((IList<SyndicationItem>)original.Items)[0]).Title.Text);
}
else
{
Assert.Same(((IList<SyndicationItem>)original.Items)[0], ((IList<SyndicationItem>)clone.Items)[0]);
}
Assert.Equal("language", original.Language);
Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime);
Assert.NotSame(clone.Links, original.Links);
Assert.Equal(1, clone.Links.Count);
Assert.NotSame(original.Links[0], clone.Links[0]);
Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri);
Assert.NotSame(clone.Title, original.Title);
Assert.Equal("title", clone.Title.Text);
}
[Fact]
public void Ctor_SyndicationFeed_Empty()
{
var original = new SyndicationFeed();
var clone = new SyndicationFeedSubclass(original, false);
Assert.Empty(clone.AttributeExtensions);
Assert.Empty(clone.Authors);
Assert.Null(clone.BaseUri);
Assert.Empty(clone.Categories);
Assert.Empty(clone.Contributors);
Assert.Null(clone.Copyright);
Assert.Null(clone.Description);
Assert.Empty(clone.ElementExtensions);
Assert.Null(clone.Generator);
Assert.Null(clone.Id);
Assert.Null(clone.ImageUrl);
Assert.Empty(clone.Items);
Assert.Null(clone.Language);
Assert.Equal(default, clone.LastUpdatedTime);
Assert.Empty(clone.Links);
Assert.Null(clone.Title);
}
[Fact]
public void Ctor_NullSource_ThrowsArgumentNullException()
{
var feed = new SyndicationFeed();
AssertExtensions.Throws<ArgumentNullException>("source", () => new SyndicationFeedSubclass(null, true));
}
[Fact]
public void Ctor_NullSourceItems_ThrowsInvalidOperationException()
{
var feed = new SyndicationFeed();
Assert.Throws<InvalidOperationException>(() => new SyndicationFeedSubclass(feed, true));
}
[Fact]
public void Ctor_SourceItemsNotIList_ThrowsInvalidOperationException()
{
var feed = new SyndicationFeed(new HashSet<SyndicationItem>());
Assert.Throws<InvalidOperationException>(() => new SyndicationFeedSubclass(feed, true));
}
[Fact]
public void Load_NullReader_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationFeed.Load(null));
AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationFeed.Load<SyndicationFeed>(null));
}
[Fact]
public void Load_InvalidReader_ThrowsXmlException()
{
XmlReader reader = new XElement("invalid").CreateReader();
Assert.Throws<XmlException>(() => SyndicationFeed.Load(reader));
Assert.Throws<XmlException>(() => SyndicationFeed.Load<SyndicationFeed>(reader));
}
[Fact]
public void GetAtom10Formatter_Invoke_ReturnsExpected()
{
var feed = new SyndicationFeed();
Atom10FeedFormatter formatter = Assert.IsType<Atom10FeedFormatter>(feed.GetAtom10Formatter());
Assert.Same(feed, formatter.Feed);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Atom10", formatter.Version);
}
[Fact]
public void GetRss20Formatter_Invoke_ReturnsExpected()
{
var feed = new SyndicationFeed();
Rss20FeedFormatter formatter = Assert.IsType<Rss20FeedFormatter>(feed.GetRss20Formatter());
Assert.Same(feed, formatter.Feed);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.True(formatter.SerializeExtensionsAsAtom);
Assert.Equal("Rss20", formatter.Version);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void GetRss20Formatter_Invoke_ReturnsExpected(bool serializeExtensionsAsAtom)
{
var feed = new SyndicationFeed();
Rss20FeedFormatter formatter = Assert.IsType<Rss20FeedFormatter>(feed.GetRss20Formatter(serializeExtensionsAsAtom));
Assert.Same(feed, formatter.Feed);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal(serializeExtensionsAsAtom, formatter.SerializeExtensionsAsAtom);
Assert.Equal("Rss20", formatter.Version);
}
[Fact]
public void CreateCategory_Invoke_ReturnsExpected()
{
var feed = new SyndicationFeedSubclass();
SyndicationCategory category = feed.CreateCategoryEntryPoint();
Assert.Empty(category.AttributeExtensions);
Assert.Empty(category.ElementExtensions);
Assert.Null(category.Name);
Assert.Null(category.Scheme);
Assert.Null(category.Label);
}
[Fact]
public void CreateLink_Invoke_ReturnsExpected()
{
var feed = new SyndicationFeedSubclass();
SyndicationLink link = feed.CreateLinkEntryPoint();
Assert.Empty(link.AttributeExtensions);
Assert.Null(link.BaseUri);
Assert.Empty(link.ElementExtensions);
Assert.Equal(0, link.Length);
Assert.Null(link.MediaType);
Assert.Null(link.RelationshipType);
Assert.Null(link.Title);
Assert.Null(link.Uri);
}
[Fact]
public void CreatePerson_Invoke_ReturnsExpected()
{
var feed = new SyndicationFeedSubclass();
SyndicationPerson person = feed.CreatePersonEntryPoint();
Assert.Empty(person.AttributeExtensions);
Assert.Empty(person.ElementExtensions);
Assert.Null(person.Email);
Assert.Null(person.Name);
Assert.Null(person.Uri);
}
[Theory]
[InlineData(null, null, null, null)]
[InlineData("", "", "", "")]
[InlineData("name", "ns", "value", "version")]
[InlineData("xmlns", "ns", "value", "version")]
[InlineData("name", "http://www.w3.org/2000/xmlns/", "value", "version")]
[InlineData("type", "ns", "value", "version")]
[InlineData("name", "http://www.w3.org/2001/XMLSchema-instance", "value", "version")]
public void TryParseAttribute_Invoke_ReturnsFalse(string name, string ns, string value, string version)
{
var feed = new SyndicationFeedSubclass();
Assert.False(feed.TryParseAttributeEntryPoint(name, ns, value, version));
}
public static IEnumerable<object[]> TryParseElement_TestData()
{
yield return new object[] { null, null };
yield return new object[] { new XElement("name").CreateReader(), "" };
yield return new object[] { new XElement("name").CreateReader(), "version" };
}
[Theory]
[MemberData(nameof(TryParseElement_TestData))]
public void TryParseElement_Invoke_ReturnsFalse(XmlReader reader, string version)
{
var feed = new SyndicationFeedSubclass();
Assert.False(feed.TryParseElementEntryPoint(reader, version));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("version")]
public void WriteAttributeExtensions_Invoke_ReturnsExpected(string version)
{
var feed = new SyndicationFeedSubclass();
CompareHelper.AssertEqualWriteOutput("", writer => feed.WriteAttributeExtensionsEntryPoint(writer, version));
feed.AttributeExtensions.Add(new XmlQualifiedName("name1"), "value");
feed.AttributeExtensions.Add(new XmlQualifiedName("name2", "namespace"), "");
feed.AttributeExtensions.Add(new XmlQualifiedName("name3"), null);
CompareHelper.AssertEqualWriteOutput(@"name1=""value"" d0p1:name2="""" name3=""""", writer => feed.WriteAttributeExtensionsEntryPoint(writer, "version"));
}
[Fact]
public void WriteAttributeExtensions_NullWriter_ThrowsArgumentNullException()
{
var feed = new SyndicationFeedSubclass();
AssertExtensions.Throws<ArgumentNullException>("writer", () => feed.WriteAttributeExtensionsEntryPoint(null, "version"));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("version")]
public void WriteElementExtensions_Invoke_ReturnsExpected(string version)
{
var feed = new SyndicationFeedSubclass();
CompareHelper.AssertEqualWriteOutput("", writer => feed.WriteElementExtensionsEntryPoint(writer, version));
feed.ElementExtensions.Add(new ExtensionObject { Value = 10 });
feed.ElementExtensions.Add(new ExtensionObject { Value = 11 });
CompareHelper.AssertEqualWriteOutput(
@"<SyndicationFeedTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</SyndicationFeedTests.ExtensionObject>
<SyndicationFeedTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>11</Value>
</SyndicationFeedTests.ExtensionObject>", writer => feed.WriteElementExtensionsEntryPoint(writer, version));
}
[Fact]
public void WriteElementExtensions_NullWriter_ThrowsArgumentNullException()
{
var feed = new SyndicationFeedSubclass();
AssertExtensions.Throws<ArgumentNullException>("writer", () => feed.WriteElementExtensionsEntryPoint(null, "version"));
}
[Theory]
[MemberData(nameof(Ctor_Items_TestData))]
public void Items_Set_GetReturnsExpected(IEnumerable<SyndicationItem> value)
{
var feed = new SyndicationFeed
{
Items = value
};
Assert.Same(value, feed.Items);
}
[Fact]
public void Items_SetNull_ThrowsArgumentNullException()
{
var feed = new SyndicationFeed();
AssertExtensions.Throws<ArgumentNullException>("value", () => feed.Items = null);
}
private static void VerifySyndicationFeed(SyndicationFeed feed, string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime, IEnumerable<SyndicationItem> items)
{
Assert.Empty(feed.AttributeExtensions);
Assert.Empty(feed.Authors);
Assert.Null(feed.BaseUri);
Assert.Empty(feed.Categories);
Assert.Empty(feed.Contributors);
Assert.Null(feed.Copyright);
if (description == null)
{
Assert.Null(feed.Description);
}
else
{
Assert.Empty(feed.Description.AttributeExtensions);
Assert.Equal(description, feed.Description.Text);
Assert.Equal("text", feed.Description.Type);
}
Assert.Empty(feed.ElementExtensions);
Assert.Null(feed.Generator);
Assert.Equal(id, feed.Id);
Assert.Null(feed.ImageUrl);
if (items == null)
{
Assert.Empty(feed.Items);
}
else
{
Assert.Same(items, feed.Items);
}
Assert.Null(feed.Language);
Assert.Equal(lastUpdatedTime, feed.LastUpdatedTime);
if (feedAlternateLink == null)
{
Assert.Empty(feed.Links);
}
else
{
SyndicationLink link = Assert.Single(feed.Links);
Assert.Empty(link.AttributeExtensions);
Assert.Null(link.BaseUri);
Assert.Empty(link.ElementExtensions);
Assert.Equal(0, link.Length);
Assert.Null(link.MediaType);
Assert.Equal("alternate", link.RelationshipType);
Assert.Null(link.Title);
Assert.Equal(feedAlternateLink, link.Uri);
}
if (title == null)
{
Assert.Null(feed.Title);
}
else
{
Assert.Empty(feed.Title.AttributeExtensions);
Assert.Equal(title, feed.Title.Text);
Assert.Equal("text", feed.Title.Type);
}
}
private class SyndicationFeedSubclass : SyndicationFeed
{
public SyndicationFeedSubclass() : base() { }
public SyndicationFeedSubclass(SyndicationFeed source, bool cloneItems) : base(source, cloneItems) { }
public SyndicationCategory CreateCategoryEntryPoint() => CreateCategory();
public SyndicationItem CreateItemEntryPoint() => CreateItem();
public SyndicationLink CreateLinkEntryPoint() => CreateLink();
public SyndicationPerson CreatePersonEntryPoint() => CreatePerson();
public bool TryParseAttributeEntryPoint(string name, string ns, string value, string version) => TryParseAttribute(name, ns, value, version);
public bool TryParseElementEntryPoint(XmlReader reader, string version) => TryParseElement(reader, version);
public void WriteAttributeExtensionsEntryPoint(XmlWriter writer, string version) => WriteAttributeExtensions(writer, version);
public void WriteElementExtensionsEntryPoint(XmlWriter writer, string version) => WriteElementExtensions(writer, version);
}
[DataContract]
public class ExtensionObject
{
[DataMember]
public int Value { get; set; }
}
}
}
| |
// MIT License
//
// Copyright (c) 2017 Maarten van Sambeek.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace ConnectQl.Azure.Sources
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ConnectQl.AsyncEnumerables;
using ConnectQl.AsyncEnumerables.Policies;
using ConnectQl.Expressions;
using ConnectQl.Expressions.Visitors;
using ConnectQl.Intellisense;
using ConnectQl.Interfaces;
using ConnectQl.Results;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// The table query source.
/// </summary>
internal class TableDataSource : IDataSource, IDataTarget, IDataSourceFilterSupport, IDataSourceOrderBySupport, IDescriptableDataSource
{
/// <summary>
/// Converts an <see cref="ExpressionType"/> to <see cref="string"/>.
/// </summary>
private static readonly Dictionary<ExpressionType, string> ExpressionTypeToString =
new Dictionary<ExpressionType, string>
{
{
ExpressionType.GreaterThan, "gt"
},
{
ExpressionType.GreaterThanOrEqual, "ge"
},
{
ExpressionType.LessThan, "lt"
},
{
ExpressionType.LessThanOrEqual, "le"
},
{
ExpressionType.AndAlso, "and"
},
{
ExpressionType.And, "and"
},
{
ExpressionType.OrElse, "or"
},
{
ExpressionType.Or, "or"
},
{
ExpressionType.Equal, "eq"
},
{
ExpressionType.NotEqual, "neq"
},
{
ExpressionType.Add, "+"
},
{
ExpressionType.Subtract, "-"
}
};
/// <summary>
/// The connection string.
/// </summary>
private readonly string connectionString;
/// <summary>
/// The name.
/// </summary>
private readonly string name;
/// <summary>
/// Initializes a new instance of the <see cref="TableDataSource"/> class.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
public TableDataSource(string name)
{
this.name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="TableDataSource"/> class.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="connectionString">
/// The connection string.
/// </param>
public TableDataSource(string name, string connectionString)
{
this.name = name;
this.connectionString = connectionString;
}
/// <summary>
/// Gets the descriptor for this data source.
/// </summary>
/// <param name="sourceAlias">
/// The source alias.
/// </param>
/// <param name="context">
/// The execution context.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public async Task<IDataSourceDescriptor> GetDataSourceDescriptorAsync(string sourceAlias, IExecutionContext context)
{
var maxRowsToScan = context.MaxRowsToScan;
var table = this.GetTable(context);
TableContinuationToken token = null;
var rows = new List<RowEntity>();
var lines = 0;
var fields = new HashSet<string>();
var types = new Dictionary<string, Type>();
do
{
var segment = await table.ExecuteQuerySegmentedAsync(new TableQuery(), CreateRowEntity, token);
token = segment.ContinuationToken;
foreach (var rowEntity in segment.Results.Select(r => r.GetValues(null)))
{
if (++lines > maxRowsToScan)
{
token = null;
break;
}
foreach (var kv in rowEntity)
{
var fieldType = kv.Value?.GetType() ?? typeof(object);
if (fields.Add(kv.Key))
{
types[kv.Key] = fieldType;
}
else
{
var type = types[kv.Key];
if (type != fieldType && type != typeof(object))
{
types[kv.Key] = typeof(object);
}
}
}
}
rows.AddRange(segment.Results);
}
while (token != null);
return Descriptor.ForDataSource(sourceAlias, fields.Select(f => Descriptor.ForColumn(f, types[f])));
}
/// <summary>
/// Retrieves the data from the source as an <see cref="IAsyncEnumerable{T}"/>.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <param name="rowBuilder">
/// The row builder.
/// </param>
/// <param name="query">
/// The query expression. Can be <c>null</c>.
/// </param>
/// <returns>
/// A task returning the data set.
/// </returns>
public IAsyncEnumerable<Row> GetRows(IExecutionContext context, IRowBuilder rowBuilder, IQuery query)
{
var table = this.GetTable(context);
var tableQuery =
new TableQuery().Select(query.RetrieveAllFields ? null : query.Fields.Select(f => f).ToList())
.Where(ToTableQuery(query.GetFilter(context)))
.Take(query.Count);
var result = context.CreateAsyncEnumerable(
async (GetDataState state) =>
{
if (state.Done)
{
return null;
}
var segment = await table.ExecuteQuerySegmentedAsync(tableQuery, CreateRowEntity, state.Token);
state.Done = segment.ContinuationToken == null;
state.Token = segment.ContinuationToken;
return segment.Results.Count != 0
? segment.Select(
row =>
rowBuilder.CreateRow(
Tuple.Create(row.PartitionKey, row.RowKey),
row.GetValues(tableQuery.SelectColumns)))
: null;
});
result.BeforeFirstElement(
() =>
context.Logger.Verbose(
tableQuery.FilterString == null
? $"Retrieving all records from table '{table.Name}'."
: $"Retrieving records from table '{table.Name}', query : {tableQuery.FilterString}."));
result.AfterLastElement(
count => context.Logger.Verbose($"Retrieved {count} records from table '{table.Name}'."));
return result;
}
/// <summary>
/// Checks if the source supports the expression.
/// </summary>
/// <param name="expression">
/// The expression to check for.
/// </param>
/// <returns>
/// <c>true</c> if the expression is supported, false otherwise.
/// </returns>
public bool SupportsExpression(BinaryExpression expression)
{
var field = (expression.Left as FieldExpression)?.FieldName;
return (field == "RowKey" || field == "PartitionKey") && !expression.Right.GetFields().Any();
}
/// <summary>
/// Checks if the data source supports the ORDER BY expressions.
/// </summary>
/// <param name="orderBy">
/// The expression to check.
/// </param>
/// <returns>
/// <c>true</c> if the expressions are supported, false otherwise.
/// </returns>
public bool SupportsOrderBy(IEnumerable<IOrderByExpression> orderBy)
{
var sortOrders = orderBy;
return !sortOrders.Any(
s =>
{
var field = s.Expression as FieldExpression;
return field == null
|| (!field.FieldName.Equals("RowKey", StringComparison.OrdinalIgnoreCase) && !field.FieldName.Equals("PartitionKey", StringComparison.OrdinalIgnoreCase))
|| s.Ascending == false;
});
}
/// <summary>
/// Writes the rowsToWrite to the specified target.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <param name="rowsToWrite">
/// The rowsToWrite.
/// </param>
/// <param name="upsert">
/// True to also update records, false to insert.
/// </param>
/// <returns>
/// The <see cref="System.Threading.Tasks.Task"/>.
/// </returns>
public async Task<long> WriteRowsAsync(IExecutionContext context, IAsyncEnumerable<Row> rowsToWrite, bool upsert)
{
var action = upsert
? (operation, entity) => operation.InsertOrReplace(entity)
: (Action<TableBatchOperation, ITableEntity>)((operation, entity) => operation.Insert(entity));
long duplicates = 0;
Func<IEnumerable<ITableEntity>, IEnumerable<ITableEntity>> detectDuplicates =
batch => batch.GroupBy(o => new
{
o.PartitionKey,
o.RowKey
}).Select(
g =>
{
ITableEntity result = null;
var groupCount = 0;
foreach (var row in g)
{
groupCount++;
result = row;
}
duplicates += groupCount - 1;
return result;
});
var operations =
rowsToWrite.Select(ToEntity)
.Batch(100, row => row.PartitionKey)
.Select(
async batch =>
CreateTableBatchOperation(
detectDuplicates(await batch.ToArrayAsync().ConfigureAwait(false)),
action));
var account =
CloudStorageAccount.Parse(
this.connectionString ?? context.GetDefault("CONNECTIONSTRING", this).ToString());
var table = account.CreateCloudTableClient().GetTableReference(this.name);
var tableNotCreatedYet = true;
long count = 0;
await operations.Batch(3).ForEachAsync(
async ops =>
{
var operationArray = await ops.ToArrayAsync().ConfigureAwait(false);
if (tableNotCreatedYet)
{
await table.CreateIfNotExistsAsync().ConfigureAwait(false);
tableNotCreatedYet = false;
}
Func<TableBatchOperation, Task<long>> createBatch = async operation =>
{
var tries = 3;
while (tries-- > 0)
{
try
{
await table.ExecuteBatchAsync(operation).ConfigureAwait(false);
return operation.Count;
}
catch (StorageException)
{
if (tries == 0)
{
throw;
}
}
}
return 0;
};
count += (await Task.WhenAll(operationArray.Select(createBatch)).ConfigureAwait(false)).Sum();
}).ConfigureAwait(false);
if (duplicates > 0)
{
context.Logger.Warning(
"Found records with identical PartitionKey/RowKey combinations. This can impact performance.");
}
return count;
}
/// <summary>
/// Creates a row entity.
/// </summary>
/// <param name="partitionkey">
/// The partition key.
/// </param>
/// <param name="rowkey">
/// The row key.
/// </param>
/// <param name="timestamp">
/// The time stamp.
/// </param>
/// <param name="properties">
/// The properties.
/// </param>
/// <param name="etag">
/// The E-tag.
/// </param>
/// <returns>
/// The <see cref="RowEntity"/>.
/// </returns>
private static RowEntity CreateRowEntity(
string partitionkey,
string rowkey,
DateTimeOffset timestamp,
IDictionary<string, EntityProperty> properties,
string etag)
{
var result = new RowEntity
{
PartitionKey = partitionkey, RowKey = rowkey
};
var tableEntity = (ITableEntity)result;
tableEntity.ETag = etag;
tableEntity.ReadEntity(properties, null);
return result;
}
/// <summary>
/// Creates a table batch operation.
/// </summary>
/// <param name="batch">
/// The batch.
/// </param>
/// <param name="entityAction">
/// The entity action.
/// </param>
/// <returns>
/// The <see cref="TableBatchOperation"/>.
/// </returns>
private static TableBatchOperation CreateTableBatchOperation(
IEnumerable<ITableEntity> batch,
Action<TableBatchOperation, ITableEntity> entityAction)
{
return batch.Aggregate(
new TableBatchOperation(),
(operation, entity) =>
{
entityAction(operation, entity);
return operation;
});
}
/// <summary>
/// Converts the row to an entity.
/// </summary>
/// <param name="row">
/// The row.
/// </param>
/// <returns>
/// The row as a table entity.
/// </returns>
private static ITableEntity ToEntity(Row row)
{
var dte = new DynamicTableEntity();
foreach (var value in row.ToDictionary())
{
if (value.Key.Equals("PartitionKey", StringComparison.OrdinalIgnoreCase))
{
dte.PartitionKey = value.Value?.ToString() ?? string.Empty;
}
else if (value.Key.Equals("RowKey", StringComparison.OrdinalIgnoreCase))
{
dte.RowKey = value.Value?.ToString() ?? string.Empty;
}
else if (value.Key.Equals("Timestamp", StringComparison.OrdinalIgnoreCase))
{
var timestamp = row[value.Key];
dte.Timestamp = timestamp is DateTime
? new DateTimeOffset((DateTime)timestamp)
: (DateTimeOffset)timestamp;
}
else
{
dte.Properties[value.Key] = EntityProperty.CreateEntityPropertyFromObject(value.Value);
}
}
if (dte.PartitionKey == null)
{
throw new InvalidOperationException("Missing partition key.");
}
if (dte.RowKey == null)
{
throw new InvalidOperationException("Missing row key.");
}
return dte;
}
/// <summary>
/// The to table query.
/// </summary>
/// <param name="filter">
/// The filter.
/// </param>
/// <returns>
/// The <see cref="Expression"/>.
/// </returns>
/// <exception cref="Exception">
/// Throw when trying to filter on anything else than a row key or partition key.
/// </exception>
private static string ToTableQuery(Expression filter)
{
if (filter == null)
{
return null;
}
var sb = new StringBuilder();
// ReSharper disable once AccessToModifiedClosure
new GenericVisitor
{
(FieldExpression node) =>
{
sb.Append(node.FieldName);
return node;
},
(GenericVisitor visitor, BinaryExpression node) =>
{
sb.Append("(");
visitor.Visit(node.Left);
sb.Append($" {ExpressionTypeToString[node.NodeType]} ");
visitor.Visit(node.Right);
sb.Append(")");
return node;
},
(ConstantExpression node) =>
{
sb.Append($"'{node.Value}'");
return node;
}
}
// .Default(node => { throw new InvalidOperationException($"Could not translate query part {node}."); })
.Visit(filter);
return sb.ToString();
}
/// <summary>
/// The get table.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <returns>
/// The <see cref="CloudTable"/>.
/// </returns>
private CloudTable GetTable(IExecutionContext context)
{
var table =
CloudStorageAccount.Parse(
this.connectionString ?? context.GetDefault("CONNECTIONSTRING", this).ToString())
.CreateCloudTableClient()
.GetTableReference(this.name);
return table;
}
/// <summary>
/// Stores the state for the enumerator.
/// </summary>
private class GetDataState
{
/// <summary>
/// Gets or sets a value indicating whether done.
/// </summary>
public bool Done { get; set; }
/// <summary>
/// Gets or sets the token.
/// </summary>
public TableContinuationToken Token { get; set; }
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Threading;
using System.Globalization;
using System.Collections;
using System.ComponentModel;
using PHP.Core;
using System.Diagnostics;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Library
{
/// <summary>
/// This class manages locale information for PHP and interacts .NET Framework.
/// </summary>
/// <threadsafety static="true"/>
public static class Locale
{
[ImplementsConstant("CHAR_MAX")]
public const int CHAR_MAX = 127;
private static readonly char[] CultureNameSeparators = new char[] { '-', '_' };
#region Categorized Cultures
/// <summary>
/// A locale categories.
/// </summary>
/// <exclude/>
public enum Category
{
/// <summary>
/// Assigning a culture to this category is equivalent to assigning it to all other categories.
/// </summary>
[ImplementsConstant("LC_ALL")]
All,
/// <summary>
/// Influences function <c>strcoll</c>.
/// </summary>
[ImplementsConstant("LC_COLLATE")]
Collate,
/// <summary>
/// Influences functions <c>strtolower</c>, <c>strtoupper</c>
/// </summary>
[ImplementsConstant("LC_CTYPE")]
CType,
/// <summary>
/// Influences functions <c>money_format</c>, <c>localeconv</c>
/// </summary>
[ImplementsConstant("LC_MONETARY")]
Monetary,
/// <summary>
/// Influences function <c>localeconv</c> and formatting of all floating-point numbers.
/// </summary>
[ImplementsConstant("LC_NUMERIC")]
Numeric,
/// <summary>
/// Influences function <c>strftime</c>.
/// </summary>
[ImplementsConstant("LC_TIME")]
Time
}
/// <summary>
/// Cultures associated with cathegories.
/// </summary>
private static CultureInfo[] cultures
{
get
{
if (_cultures == null)
_cultures = new CultureInfo[(int)Category.Time + 1];
return _cultures;
}
}
#if !SILVERLIGHT
[ThreadStatic]
#endif
private static CultureInfo[] _cultures;
static Locale()
{
RequestContext.RequestEnd += new Action(Clear);
}
private static void Clear()
{
_cultures = null;
}
/// <summary>
/// Gets a culture specific for the given category.
/// </summary>
/// <param name="category">The category.</param>
/// <returns>Non-null culture info.</returns>
public static CultureInfo GetCulture(Category category)
{
if ((int)category < 0 || (int)category >= cultures.Length)
throw new ArgumentOutOfRangeException("category");
return cultures[(int)category] ?? CultureInfo.CurrentCulture;
}
/// <summary>
/// Sets a culture specific for the given category.
/// </summary>
/// <param name="category">The category.</param>
/// <param name="culture">The culture.</param>
public static void SetCulture(Category category, CultureInfo culture)
{
if ((int)category < 0 || (int)category >= cultures.Length)
throw new ArgumentOutOfRangeException("category");
// sets specific culture:
if (category == Category.All)
{
for (int i = 0; i < cultures.Length; i++)
cultures[i] = culture;
}
else
{
cultures[(int)category] = culture;
}
// sets global culture used in many places:
if (category == Category.All || category == Category.Numeric)
Thread.CurrentThread.CurrentCulture = culture;
}
/// <summary>
/// Creates a new <see cref="PhpLocaleStringComparer"/> comparing according to the current collate.
/// </summary>
/// <param name="ignoreCase">Whether to create a case-insensitive comparer.</param>
/// <returns>The comparer.</returns>
public static PhpLocaleStringComparer GetStringComparer(bool ignoreCase)
{
return new PhpLocaleStringComparer(GetCulture(Category.Collate), ignoreCase);
}
#endregion
#region localeconv
/// <summary>
/// Converts .NET groups information to PHP array.
/// </summary>
private static PhpArray GetGroupingArray(int[] groups)
{
Debug.Assert(groups != null);
int length = groups.Length;
PhpArray result = new PhpArray(length, 0);
for (int i = 0; i < length; i++)
if (groups[i] == 0)
result.Add(i, CHAR_MAX);
else
result.Add(i, groups[i]);
return result;
}
/// <summary>
/// Gets information about the current thread culture.
/// </summary>
/// <returns>The associative array of number and currency information.</returns>
[ImplementsFunction("localeconv")]
public static PhpArray localeconv()
{
PhpArray result = new PhpArray(0, 18);
NumberFormatInfo number;
number = GetCulture(Category.Numeric).NumberFormat;
result.Add("decimal_point", number.NumberDecimalSeparator);
result.Add("thousands_sep", number.NumberGroupSeparator);
result.Add("grouping", GetGroupingArray(number.CurrencyGroupSizes));
result.Add("positive_sign", number.PositiveSign);
result.Add("negative_sign", number.NegativeSign);
result.Add("frac_digits", number.CurrencyDecimalDigits);
number = GetCulture(Category.Monetary).NumberFormat;
result.Add("currency_symbol", number.CurrencySymbol);
result.Add("mon_decimal_point", number.CurrencyDecimalSeparator);
result.Add("mon_thousands_sep", number.CurrencyGroupSeparator);
result.Add("mon_grouping", GetGroupingArray(number.CurrencyGroupSizes));
// currency patterns: 0 -> $n, 1 -> n$, 2 -> $ n, 3 -> n $
result.Add("p_cs_precedes", number.CurrencyPositivePattern == 0 || number.CurrencyPositivePattern == 2);
result.Add("p_sep_by_space", number.CurrencyPositivePattern == 2 || number.CurrencyPositivePattern == 3);
result.Add("n_cs_precedes", number.CurrencyNegativePattern == 0 || number.CurrencyNegativePattern == 2);
result.Add("n_sep_by_space", number.CurrencyNegativePattern == 2 || number.CurrencyNegativePattern == 3);
result.Add("p_sign_posn", 1);
result.Add("n_sign_posn", 1);
return result;
}
#endregion
#region setlocale, strcoll, nl_langinfo (NS)
#if !SILVERLIGHT
/// <summary>
/// Sets or gets the current thread culture settings.
/// </summary>
/// <param name="category">
/// A category to be modified. The only supported value in this version is <see cref="Category.All"/>.
/// </param>
/// <param name="locale">Either an instance of <see cref="PhpArray"/> containing locales or a locale.</param>
/// <param name="moreLocales">If <paramref name="locale"/> is not of type <see cref="PhpArray"/> contains locales, ignored otherwise.</param>
/// <returns>The culture string (e.g. "en-US").</returns>
/// <remarks>
/// <para>
/// Values specified in <paramref name="locale"/> and <paramref name="moreLocales"/> are converted to strings.
/// Each value should have format "{language}-{region}" or "{language}_{region}" or "{language}" or special values "C" or empty string
/// which represents the invariant culture or special values <B>null</B> or "0" which means no changes is made
/// by the method rather the current culture name is returned.
/// The first value containing am existing culture string is used.
/// </para>
/// </remarks>
/// <exception cref="PhpException"><paramref name="category"/> has an invalid or unsupported value. (Warning)</exception>
[ImplementsFunction("setlocale")]
[return: CastToFalse]
public static string SetLocale(Category category, object locale, params object[] moreLocales)
{
CultureInfo new_culture;
if (GetFirstExistingCulture(locale, moreLocales, out new_culture))
{
if ((int)category < 0 || (int)category > cultures.Length)
{
PhpException.InvalidArgument("category", LibResources.GetString("arg:invalid_value"));
return null;
}
// sets specific culture:
SetCulture(category, new_culture);
}
else
{
new_culture = CultureInfo.CurrentCulture;
}
if (new_culture == CultureInfo.InvariantCulture)
return "C";
return String.Format("{0}.{1}",
new_culture.EnglishName.Replace(" (", "_").Replace(")", ""),
new_culture.TextInfo.ANSICodePage);
}
/// <summary>
/// Searches in given objects for a locale string describing an existing culture.
/// </summary>
/// <param name="locale">Contains either an instance of <see cref="PhpArray"/> containing locales or a locale.</param>
/// <param name="moreLocales">If <paramref name="locale"/> is not of type <see cref="PhpArray"/> contains locales, ignored otherwise.</param>
/// <param name="culture">The resulting culture. A <B>null</B> reference means no culture has been found.</param>
/// <returns>Whether a culture settings should be changed.</returns>
private static bool GetFirstExistingCulture(object locale, object[] moreLocales, out CultureInfo culture)
{
PhpArray array;
IEnumerator locales;
culture = null;
if ((array = locale as PhpArray) != null)
{
// locales are stored in the "locale" array:
locales = array.GetEnumerator();
locales.MoveNext();
locale = locales.Current;
}
else if (moreLocales != null)
{
// locales are stored in the "locale" and "moreLocales":
locales = moreLocales.GetEnumerator();
}
else
{
throw new ArgumentNullException("moreLocales");
}
// enumerates locales and finds out the first which is valid:
for (; ; )
{
string name = (locale != null) ? Core.Convert.ObjectToString(locale) : null;
culture = GetCultureByName(name);
// name is "empty" then the current culture is not changed:
if (name == null || name == "0") return false;
// if culture exists and is specific then finish searching:
if (culture != null) return true;
// the next locale:
if (!locales.MoveNext()) return false;
locale = locales.Current;
}
}
/// <summary>
/// Gets a culture of a specified name.
/// Tries "{language}-{country}", "{country}-{language}".
/// Recognizes "C", "", "0" and <B>null</B> as invariant culture.
/// Note, PHP swaps language and country codes.
/// </summary>
private static CultureInfo GetCultureByName(string name)
{
// invariant culture:
if (name == null || name == "0" || name == String.Empty || name == "C")
return CultureInfo.InvariantCulture;
int separator = name.IndexOfAny(CultureNameSeparators);
if (separator < 0)
{
try
{
return CultureInfo.CreateSpecificCulture(name);
}
catch (ArgumentException)
{
}
}
else
{
string part1 = name.Substring(0, separator);
string part2 = name.Substring(separator + 1);
try
{
return CultureInfo.CreateSpecificCulture(String.Concat(part1, "-", part2));
}
catch (ArgumentException)
{
try
{
return CultureInfo.CreateSpecificCulture(String.Concat(part2, "-", part1));
}
catch (ArgumentException)
{
}
}
}
return null;
}
/// <summary>
/// Compares two specified strings, honoring their case, using culture specific comparison.
/// </summary>
/// <param name="str1">A string.</param>
/// <param name="str2">A string.</param>
/// <returns>
/// Returns -1 if <paramref name="str1"/> is less than <paramref name="str2"/>; +1 if <paramref name="str1"/> is greater than <paramref name="str2"/>,
/// and 0 if they are equal.
/// </returns>
[ImplementsFunction("strcoll")]
public static int StringCollate(string str1, string str2)
{
return String.Compare(str1, str2, false, GetCulture(Category.Collate));
}
/// <summary>
/// Not supported.
/// </summary>
[ImplementsFunction("nl_langinfo", FunctionImplOptions.NotSupported)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static string nl_langinfo(int item)
{
PhpException.FunctionNotSupported();
return null;
}
#endif
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Debugger;
using Microsoft.PythonTools.Debugger.Remote;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Repl {
[InteractiveWindowRole("Debug")]
[ContentType(PythonCoreConstants.ContentType)]
[ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)]
internal class PythonDebugProcessReplEvaluator : PythonInteractiveEvaluator {
private readonly PythonProcess _process;
private readonly IThreadIdMapper _threadIdMapper;
private long _threadId;
private int _frameId;
private PythonLanguageVersion _languageVersion;
private Dictionary<string, string> _moduleToFileName;
private string _currentScopeName;
private string _currentScopeFileName;
private string _currentFrameFilename;
private CompletionResult[] _currentFrameLocals;
/// <summary>
/// Backwards compatible and non-localized name for the scope
/// that represents execution on the current frame.
/// </summary>
private const string CurrentFrameScopeFixedName = "<CurrentFrame>";
public PythonDebugProcessReplEvaluator(IServiceProvider serviceProvider, PythonProcess process, IThreadIdMapper threadIdMapper)
: base(serviceProvider) {
_process = process;
_threadIdMapper = threadIdMapper;
_threadId = process.GetThreads()[0].Id;
_languageVersion = process.LanguageVersion;
_currentScopeName = CurrentFrameScopeFixedName;
DisplayName = Strings.DebugReplDisplayName;
}
public override async Task<ExecutionResult> InitializeAsync() {
var result = await base.InitializeAsync();
if (!result.IsSuccessful) {
return result;
}
result = await _serviceProvider.GetUIThread().InvokeTask(async () => {
UpdatePropertiesFromProjectMoniker();
var remoteProcess = _process as PythonRemoteProcess;
try {
_serviceProvider.GetPythonToolsService().Logger?.LogEvent(Logging.PythonLogEvent.DebugRepl, new Logging.DebugReplInfo {
RemoteProcess = remoteProcess != null,
Version = _process.LanguageVersion.ToVersion().ToString()
});
} catch (Exception ex) {
Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
}
_process.ModulesChanged += OnModulesChanged;
var threads = _process.GetThreads();
PythonThread activeThread = null;
var dte = _serviceProvider.GetDTE();
if (dte != null) {
// If we are broken into the debugger, let's set the debug REPL active thread
// to be the one that is active in the debugger
var dteDebugger = dte.Debugger;
if (dteDebugger.CurrentMode == EnvDTE.dbgDebugMode.dbgBreakMode &&
dteDebugger.CurrentProcess != null &&
dteDebugger.CurrentThread != null) {
if (_process.Id == dteDebugger.CurrentProcess.ProcessID) {
var activeThreadId = _threadIdMapper.GetPythonThreadId((uint)dteDebugger.CurrentThread.ID);
activeThread = threads.SingleOrDefault(t => t.Id == activeThreadId);
}
}
}
if (activeThread == null) {
activeThread = threads.Count > 0 ? threads[0] : null;
}
if (activeThread != null) {
SwitchThread(activeThread, false);
}
return ExecutionResult.Success;
});
return result;
}
private async void OnModulesChanged(object sender, EventArgs e) {
await RefreshAvailableScopes();
}
public override VsProjectAnalyzer Analyzer {
get {
if (_analyzer != null) {
return _analyzer;
}
if (!string.IsNullOrEmpty(_currentFrameFilename)) {
var project = _serviceProvider.GetProjectContainingFile(_currentFrameFilename);
_analyzer = project?.TryGetAnalyzer();
if (_analyzer != null) {
return _analyzer;
}
}
return base.Analyzer;
}
}
internal async Task<KeyValuePair<string, string>[]> RefreshAvailableScopes() {
var modules = await _process.GetModuleNamesAndPaths();
var moduleToFile = new Dictionary<string, string>();
foreach (var item in modules) {
if (!string.IsNullOrEmpty(item.Value)) {
moduleToFile[item.Key] = item.Value;
}
}
_moduleToFileName = moduleToFile;
SetAvailableScopes(modules.Select(m => m.Key).ToArray());
EnableMultipleScopes = true;
return modules;
}
protected override Task ExecuteStartupScripts(string scriptsPath) {
// Do not execute scripts for debug evaluator
return Task.FromResult<object>(null);
}
public override async Task<ExecutionResult> ExecuteCodeAsync(string text) {
var tcs = new TaskCompletionSource<ExecutionResult>();
var ct = new CancellationToken();
var cancellationRegistration = ct.Register(() => tcs.TrySetCanceled());
EventHandler<ProcessExitedEventArgs> processExited = delegate {
tcs.TrySetCanceled();
};
EventHandler<OutputEventArgs> debuggerOutput = (object sender, OutputEventArgs e) => {
switch (e.Channel) {
case OutputChannel.StdOut:
WriteOutput(e.Output, addNewline: false);
break;
case OutputChannel.StdErr:
WriteError(e.Output, addNewline: false);
break;
}
};
Action<PythonEvaluationResult> resultReceived = (PythonEvaluationResult result) => {
if (!string.IsNullOrEmpty(result.ExceptionText)) {
tcs.TrySetResult(ExecutionResult.Failure);
} else {
tcs.TrySetResult(ExecutionResult.Success);
}
};
_process.ProcessExited += processExited;
_process.DebuggerOutput += debuggerOutput;
try {
if (_currentScopeName == CurrentFrameScopeFixedName) {
var frame = GetFrames().SingleOrDefault(f => f.FrameId == _frameId);
if (frame != null) {
await _process.ExecuteTextAsync(text, PythonEvaluationResultReprKind.Normal, frame, true, resultReceived, ct);
} else {
WriteError(Strings.DebugReplCannotRetrieveFrameError);
tcs.TrySetResult(ExecutionResult.Failure);
}
} else {
await _process.ExecuteTextAsync(text, PythonEvaluationResultReprKind.Normal, _currentScopeName, true, resultReceived, ct);
}
return await tcs.Task;
} finally {
_process.ProcessExited -= processExited;
_process.DebuggerOutput -= debuggerOutput;
cancellationRegistration.Dispose();
}
}
public PythonProcess Process {
get { return _process; }
}
public int ProcessId {
get { return _process.Id; }
}
public long ThreadId {
get { return _threadId; }
}
public int FrameId {
get { return _frameId; }
}
public override string CurrentScopeName {
get {
// Callers expect the localized name
return _currentScopeName == CurrentFrameScopeFixedName
? Strings.DebugReplCurrentFrameScope : _currentScopeName;
}
}
public override string CurrentScopePath {
get {
return _currentScopeFileName;
}
}
public override string CurrentWorkingDirectory {
get {
// This is never called
return null;
}
}
public override IEnumerable<KeyValuePair<string, string>> GetAvailableScopesAndPaths() {
var t = RefreshAvailableScopes();
if (t != null && t.Wait(1000) && t.Result != null) {
return t.Result;
}
return Enumerable.Empty<KeyValuePair<string, string>>();
}
public override CompletionResult[] GetMemberNames(string text) {
if (_currentScopeName == CurrentFrameScopeFixedName && string.IsNullOrEmpty(text) && _currentFrameLocals != null) {
return _currentFrameLocals.ToArray();
};
return _serviceProvider.GetUIThread().InvokeTaskSync(async () => await GetMemberNamesAsync(text), CancellationToken.None);
}
public override OverloadDoc[] GetSignatureDocumentation(string text) {
// TODO: implement this
return new OverloadDoc[0];
}
private async Task<CompletionResult[]> GetMemberNamesAsync(string text) {
// TODO: implement support for getting members for module scope,
// not just for current frame scope
if (_currentScopeName == CurrentFrameScopeFixedName) {
var frame = GetFrames().SingleOrDefault(f => f.FrameId == _frameId);
if (frame != null) {
using (var completion = new AutoResetEvent(false)) {
PythonEvaluationResult result = null;
var expression = string.Format(CultureInfo.InvariantCulture, "':'.join(dir({0}))", text ?? "");
_serviceProvider.GetUIThread().InvokeTaskSync(() => frame.ExecuteTextAsync(expression, PythonEvaluationResultReprKind.Raw, (obj) => {
result = obj;
try {
completion.Set();
} catch (ObjectDisposedException) {
}
}, CancellationToken.None), CancellationToken.None);
if (completion.WaitOne(100) && !_process.HasExited && result?.StringRepr != null) {
// We don't really know if it's a field, function or else...
var completionResults = result.StringRepr
.Split(':')
.Where(r => !string.IsNullOrEmpty(r))
.Select(r => new CompletionResult(r, Interpreter.PythonMemberType.Field))
.ToArray();
return completionResults;
}
}
}
}
return Array.Empty<CompletionResult>();
}
public override void SetScope(string scopeName) {
if (!string.IsNullOrWhiteSpace(scopeName)) {
if (scopeName == Strings.DebugReplCurrentFrameScope) {
// Most callers will pass in the localized name, but the $mod command may have either.
// Always store the unlocalized name.
scopeName = CurrentFrameScopeFixedName;
}
_currentScopeName = scopeName;
if (!(_moduleToFileName?.TryGetValue(scopeName, out _currentScopeFileName) ?? false)) {
_currentScopeFileName = null;
}
WriteOutput(Strings.ReplModuleChanged.FormatUI(CurrentScopeName));
} else {
WriteOutput(CurrentScopeName);
}
}
internal IList<PythonThread> GetThreads() {
return _process.GetThreads();
}
internal IList<PythonStackFrame> GetFrames() {
var activeThread = _process.GetThreads().SingleOrDefault(t => t.Id == _threadId);
return activeThread != null ? activeThread.Frames : new List<PythonStackFrame>();
}
internal void SwitchThread(PythonThread thread, bool verbose) {
var frame = thread.Frames.FirstOrDefault();
if (frame == null) {
WriteError(Strings.DebugReplCannotChangeCurrentThreadNoFrame.FormatUI(thread.Id));
return;
}
_threadId = thread.Id;
_frameId = frame.FrameId;
_currentScopeName = CurrentFrameScopeFixedName;
_currentScopeFileName = null;
if (_currentFrameFilename != frame.FileName) {
_currentFrameFilename = frame.FileName;
_analyzer = null;
}
UpdateFrameLocals(frame);
if (verbose) {
WriteOutput(Strings.DebugReplThreadChanged.FormatUI(_threadId, _frameId));
}
}
internal void SwitchFrame(PythonStackFrame frame) {
_frameId = frame.FrameId;
_currentScopeName = CurrentFrameScopeFixedName;
_currentScopeFileName = null;
UpdateFrameLocals(frame);
WriteOutput(Strings.DebugReplFrameChanged.FormatUI(frame.FrameId));
}
internal void FrameUp() {
var frames = GetFrames();
var currentFrame = frames.SingleOrDefault(f => f.FrameId == _frameId);
if (currentFrame != null) {
int index = frames.IndexOf(currentFrame);
if (index < (frames.Count - 1)) {
SwitchFrame(frames[index + 1]);
}
}
}
internal void FrameDown() {
var frames = GetFrames();
var currentFrame = frames.SingleOrDefault(f => f.FrameId == _frameId);
if (currentFrame != null) {
int index = frames.IndexOf(currentFrame);
if (index > 0) {
SwitchFrame(frames[index - 1]);
}
}
}
internal void StepOut() {
UpdateDTEDebuggerProcessAndThread();
_serviceProvider.GetDTE().Debugger.CurrentThread.Parent.StepOut();
}
internal void StepInto() {
UpdateDTEDebuggerProcessAndThread();
_serviceProvider.GetDTE().Debugger.CurrentThread.Parent.StepInto();
}
internal void StepOver() {
UpdateDTEDebuggerProcessAndThread();
_serviceProvider.GetDTE().Debugger.CurrentThread.Parent.StepOver();
}
internal void Resume() {
UpdateDTEDebuggerProcessAndThread();
_serviceProvider.GetDTE().Debugger.CurrentThread.Parent.Go();
}
private void UpdateFrameLocals(PythonStackFrame frame) {
_currentFrameLocals = frame.Locals.Union(frame.Parameters)
.Where(r => !string.IsNullOrEmpty(r.Expression))
.Select(r => new CompletionResult(r.Expression, Interpreter.PythonMemberType.Field))
.ToArray();
}
private void UpdateDTEDebuggerProcessAndThread() {
EnvDTE.Process dteActiveProcess = null;
foreach (EnvDTE.Process dteProcess in _serviceProvider.GetDTE().Debugger.DebuggedProcesses) {
if (dteProcess.ProcessID == _process.Id) {
dteActiveProcess = dteProcess;
break;
}
}
if (dteActiveProcess != _serviceProvider.GetDTE().Debugger.CurrentProcess) {
_serviceProvider.GetDTE().Debugger.CurrentProcess = dteActiveProcess;
}
EnvDTE.Thread dteActiveThread = null;
foreach (EnvDTE.Thread dteThread in _serviceProvider.GetDTE().Debugger.CurrentProgram.Threads) {
if (_threadIdMapper.GetPythonThreadId((uint)dteThread.ID) == _threadId) {
dteActiveThread = dteThread;
break;
}
}
if (dteActiveThread != _serviceProvider.GetDTE().Debugger.CurrentThread) {
_serviceProvider.GetDTE().Debugger.CurrentThread = dteActiveThread;
}
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
// Abstract base class for various different socket "modes" (sync, async, etc)
// See SendReceive.cs for usage
public abstract class SocketHelperBase
{
public abstract Task<Socket> AcceptAsync(Socket s);
public abstract Task<Socket> AcceptAsync(Socket s, Socket acceptSocket);
public abstract Task ConnectAsync(Socket s, EndPoint endPoint);
public abstract Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port);
public abstract Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer);
public abstract Task<SocketReceiveFromResult> ReceiveFromAsync(
Socket s, ArraySegment<byte> buffer, EndPoint endPoint);
public abstract Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList);
public abstract Task<int> SendAsync(Socket s, ArraySegment<byte> buffer);
public abstract Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList);
public abstract Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint);
public virtual bool GuaranteedSendOrdering => true;
public virtual bool ValidatesArrayArguments => true;
public virtual bool UsesSync => false;
public virtual bool DisposeDuringOperationResultsInDisposedException => false;
public virtual bool ConnectAfterDisconnectResultsInInvalidOperationException => false;
public virtual bool SupportsMultiConnect => true;
public virtual bool SupportsAcceptIntoExistingSocket => true;
public virtual void Listen(Socket s, int backlog) { s.Listen(backlog); }
}
public class SocketHelperArraySync : SocketHelperBase
{
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Run(() => s.Accept());
public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => throw new NotSupportedException();
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Run(() => s.Connect(endPoint));
public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) =>
Task.Run(() => s.Connect(addresses, port));
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Receive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None));
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Run(() => s.Receive(bufferList, SocketFlags.None));
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Run(() =>
{
int received = s.ReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint);
return new SocketReceiveFromResult
{
ReceivedBytes = received,
RemoteEndPoint = endPoint
};
});
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Send(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None));
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Run(() => s.Send(bufferList, SocketFlags.None));
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Run(() => s.SendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint));
public override bool GuaranteedSendOrdering => false;
public override bool UsesSync => true;
public override bool ConnectAfterDisconnectResultsInInvalidOperationException => true;
public override bool SupportsAcceptIntoExistingSocket => false;
}
public sealed class SocketHelperSyncForceNonBlocking : SocketHelperArraySync
{
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Run(() => { Socket accepted = s.Accept(); accepted.ForceNonBlocking(true); return accepted; });
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Run(() => { s.ForceNonBlocking(true); s.Connect(endPoint); });
public override void Listen(Socket s, int backlog)
{
s.Listen(backlog);
s.ForceNonBlocking(true);
}
}
public sealed class SocketHelperApm : SocketHelperBase
{
public override bool DisposeDuringOperationResultsInDisposedException => true;
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, null);
public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) =>
Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, acceptSocket, 0, null);
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, endPoint, null);
public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) =>
Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, addresses, port, null);
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Factory.FromAsync((callback, state) =>
s.BeginReceive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state),
s.EndReceive, null);
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Factory.FromAsync(s.BeginReceive, s.EndReceive, bufferList, SocketFlags.None, null);
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint)
{
var tcs = new TaskCompletionSource<SocketReceiveFromResult>();
s.BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint, iar =>
{
try
{
int receivedBytes = s.EndReceiveFrom(iar, ref endPoint);
tcs.TrySetResult(new SocketReceiveFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = endPoint
});
}
catch (Exception e) { tcs.TrySetException(e); }
}, null);
return tcs.Task;
}
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Factory.FromAsync((callback, state) =>
s.BeginSend(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state),
s.EndSend, null);
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Factory.FromAsync(s.BeginSend, s.EndSend, bufferList, SocketFlags.None, null);
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Factory.FromAsync(
(callback, state) => s.BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint, callback, state),
s.EndSendTo, null);
}
public class SocketHelperTask : SocketHelperBase
{
public override Task<Socket> AcceptAsync(Socket s) =>
s.AcceptAsync();
public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) =>
s.AcceptAsync(acceptSocket);
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
s.ConnectAsync(endPoint);
public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) =>
s.ConnectAsync(addresses, port);
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
s.ReceiveAsync(buffer, SocketFlags.None);
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
s.ReceiveAsync(bufferList, SocketFlags.None);
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
s.ReceiveFromAsync(buffer, SocketFlags.None, endPoint);
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
s.SendAsync(buffer, SocketFlags.None);
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
s.SendAsync(bufferList, SocketFlags.None);
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
s.SendToAsync(buffer, SocketFlags.None, endPoint);
}
public sealed class SocketHelperEap : SocketHelperBase
{
public override bool ValidatesArrayArguments => false;
public override Task<Socket> AcceptAsync(Socket s) =>
InvokeAsync(s, e => e.AcceptSocket, e => s.AcceptAsync(e));
public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) =>
InvokeAsync(s, e => e.AcceptSocket, e =>
{
e.AcceptSocket = acceptSocket;
return s.AcceptAsync(e);
});
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
InvokeAsync(s, e => true, e =>
{
e.RemoteEndPoint = endPoint;
return s.ConnectAsync(e);
});
public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => throw new NotSupportedException();
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
return s.ReceiveAsync(e);
});
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.BufferList = bufferList;
return s.ReceiveAsync(e);
});
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
InvokeAsync(s, e => new SocketReceiveFromResult { ReceivedBytes = e.BytesTransferred, RemoteEndPoint = e.RemoteEndPoint }, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
e.RemoteEndPoint = endPoint;
return s.ReceiveFromAsync(e);
});
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
return s.SendAsync(e);
});
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.BufferList = bufferList;
return s.SendAsync(e);
});
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
e.RemoteEndPoint = endPoint;
return s.SendToAsync(e);
});
private static Task<TResult> InvokeAsync<TResult>(
Socket s,
Func<SocketAsyncEventArgs, TResult> getResult,
Func<SocketAsyncEventArgs, bool> invoke)
{
var tcs = new TaskCompletionSource<TResult>();
var saea = new SocketAsyncEventArgs();
EventHandler<SocketAsyncEventArgs> handler = (_, e) =>
{
if (e.SocketError == SocketError.Success)
tcs.SetResult(getResult(e));
else
tcs.SetException(new SocketException((int)e.SocketError));
saea.Dispose();
};
saea.Completed += handler;
if (!invoke(saea))
handler(s, saea);
return tcs.Task;
}
public override bool SupportsMultiConnect => false;
}
public abstract class SocketTestHelperBase<T> : MemberDatas
where T : SocketHelperBase, new()
{
private readonly T _socketHelper;
public readonly ITestOutputHelper _output;
public SocketTestHelperBase(ITestOutputHelper output)
{
_socketHelper = new T();
_output = output;
}
//
// Methods that delegate to SocketHelper implementation
//
public Task<Socket> AcceptAsync(Socket s) => _socketHelper.AcceptAsync(s);
public Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => _socketHelper.AcceptAsync(s, acceptSocket);
public Task ConnectAsync(Socket s, EndPoint endPoint) => _socketHelper.ConnectAsync(s, endPoint);
public Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => _socketHelper.MultiConnectAsync(s, addresses, port);
public Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => _socketHelper.ReceiveAsync(s, buffer);
public Task<SocketReceiveFromResult> ReceiveFromAsync(
Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => _socketHelper.ReceiveFromAsync(s, buffer, endPoint);
public Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => _socketHelper.ReceiveAsync(s, bufferList);
public Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => _socketHelper.SendAsync(s, buffer);
public Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => _socketHelper.SendAsync(s, bufferList);
public Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint) => _socketHelper.SendToAsync(s, buffer, endpoint);
public bool GuaranteedSendOrdering => _socketHelper.GuaranteedSendOrdering;
public bool ValidatesArrayArguments => _socketHelper.ValidatesArrayArguments;
public bool UsesSync => _socketHelper.UsesSync;
public bool DisposeDuringOperationResultsInDisposedException => _socketHelper.DisposeDuringOperationResultsInDisposedException;
public bool ConnectAfterDisconnectResultsInInvalidOperationException => _socketHelper.ConnectAfterDisconnectResultsInInvalidOperationException;
public bool SupportsMultiConnect => _socketHelper.SupportsMultiConnect;
public bool SupportsAcceptIntoExistingSocket => _socketHelper.SupportsAcceptIntoExistingSocket;
public void Listen(Socket s, int backlog) => _socketHelper.Listen(s, backlog);
}
//
// MemberDatas that are generally useful
//
public abstract class MemberDatas : RemoteExecutorTestBase
{
public static readonly object[][] Loopbacks = new[]
{
new object[] { IPAddress.Loopback },
new object[] { IPAddress.IPv6Loopback },
};
public static readonly object[][] LoopbacksAndBuffers = new object[][]
{
new object[] { IPAddress.IPv6Loopback, true },
new object[] { IPAddress.IPv6Loopback, false },
new object[] { IPAddress.Loopback, true },
new object[] { IPAddress.Loopback, false },
};
}
//
// Utility stuff
//
internal struct FakeArraySegment
{
public byte[] Array;
public int Offset;
public int Count;
public ArraySegment<byte> ToActual()
{
ArraySegmentWrapper wrapper = default(ArraySegmentWrapper);
wrapper.Fake = this;
return wrapper.Actual;
}
}
[StructLayout(LayoutKind.Explicit)]
internal struct ArraySegmentWrapper
{
[FieldOffset(0)] public ArraySegment<byte> Actual;
[FieldOffset(0)] public FakeArraySegment Fake;
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Widget;
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Ogc;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ArcGISRuntime;
using Android.Views;
namespace ArcGISRuntimeXamarin.Samples.ListKmlContents
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "List KML contents",
category: "Layers",
description: "List the contents of a KML file.",
instructions: "The contents of the KML file are shown in a tree. Select a node to zoom to that node. Not all nodes can be zoomed to (e.g. screen overlays).",
tags: new[] { "KML", "KMZ", "Keyhole", "OGC", "layers" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("da301cb122874d5497f8a8f6c81eb36e")]
[ArcGISRuntime.Samples.Shared.Attributes.AndroidLayoutAttribute("ListKmlContents.axml")]
public class ListKmlContents : Activity
{
// Hold references to UI controls.
private SceneView _mySceneView;
private ListView _myDisplayList;
// Hold a list of LayerDisplayVM; this is the ViewModel.
private readonly ObservableCollection<LayerDisplayVM> _viewModelList = new ObservableCollection<LayerDisplayVM>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "List KML contents";
CreateLayout();
Initialize();
}
private async void Initialize()
{
// Add a basemap.
_mySceneView.Scene = new Scene(Basemap.CreateImageryWithLabels());
_mySceneView.Scene.BaseSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));
// Get the URL to the data.
Uri kmlUrl = new Uri(DataManager.GetDataFolder("da301cb122874d5497f8a8f6c81eb36e", "esri_test_data.kmz"));
// Create the KML dataset and layer.
KmlDataset dataset = new KmlDataset(kmlUrl);
KmlLayer layer = new KmlLayer(dataset);
// Add the layer to the map.
_mySceneView.Scene.OperationalLayers.Add(layer);
try
{
await dataset.LoadAsync();
// Build the ViewModel from the expanded list of layer infos.
foreach (KmlNode node in dataset.RootNodes)
{
// LayerDisplayVM is a custom type made for this sample to serve as the ViewModel; it is not a part of ArcGIS Runtime.
LayerDisplayVM nodeVm = new LayerDisplayVM(node, null);
_viewModelList.Add(nodeVm);
LayerDisplayVM.BuildLayerInfoList(nodeVm, _viewModelList);
}
// Create an array adapter for the content display
ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, _viewModelList.Select(item => item.Name).ToList());
// Apply the adapter
_myDisplayList.Adapter = adapter;
// Subscribe to selection change notifications
_myDisplayList.ItemClick += MyDisplayList_ItemClick;
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
}
}
private void MyDisplayList_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
// Get the KML node.
LayerDisplayVM selectedItem = _viewModelList[e.Position];
NavigateToNode(selectedItem.Node);
}
private void CreateLayout()
{
// Show the layout in the app
SetContentView(Resource.Layout.ListKmlContents);
// Get the views
_myDisplayList = FindViewById<ListView>(Resource.Id.ListKmlContents_ContentList);
_mySceneView = FindViewById<SceneView>(Resource.Id.ListKmlContents_MySceneView);
}
protected override void OnDestroy()
{
base.OnDestroy();
// Remove the sceneview
(_mySceneView.Parent as ViewGroup).RemoveView(_mySceneView);
_mySceneView.Dispose();
_mySceneView = null;
}
#region viewpoint_conversion
private async void NavigateToNode(KmlNode node)
{
try
{
// Get a corrected Runtime viewpoint using the KmlViewpoint.
bool viewpointNeedsAltitudeAdjustment;
Viewpoint runtimeViewpoint = ViewpointFromKmlViewpoint(node, out viewpointNeedsAltitudeAdjustment);
if (viewpointNeedsAltitudeAdjustment)
{
runtimeViewpoint = await GetAltitudeAdjustedViewpointAsync(node, runtimeViewpoint);
}
// Set the viewpoint.
if (runtimeViewpoint != null && !runtimeViewpoint.TargetGeometry.IsEmpty)
{
await _mySceneView.SetViewpointAsync(runtimeViewpoint);
}
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
}
}
private Viewpoint ViewpointFromKmlViewpoint(KmlNode node, out bool needsAltitudeFix)
{
KmlViewpoint kvp = node.Viewpoint;
// If KmlViewpoint is specified, use it.
if (kvp != null)
{
// Altitude adjustment is needed for everything except Absolute altitude mode.
needsAltitudeFix = (kvp.AltitudeMode != KmlAltitudeMode.Absolute);
switch (kvp.Type)
{
case KmlViewpointType.LookAt:
return new Viewpoint(kvp.Location,
new Camera(kvp.Location, kvp.Range, kvp.Heading, kvp.Pitch, kvp.Roll));
case KmlViewpointType.Camera:
return new Viewpoint(kvp.Location,
new Camera(kvp.Location, kvp.Heading, kvp.Pitch, kvp.Roll));
default:
throw new InvalidOperationException("Unexpected KmlViewPointType: " + kvp.Type);
}
}
if (node.Extent != null && !node.Extent.IsEmpty)
{
// When no altitude specified, assume elevation should be taken into account.
needsAltitudeFix = true;
// Workaround: it's possible for "IsEmpty" to be true but for width/height to still be zero.
if (node.Extent.Width == 0 && node.Extent.Height == 0)
{
// Defaults based on Google Earth.
return new Viewpoint(node.Extent, new Camera(node.Extent.GetCenter(), 1000, 0, 45, 0));
}
else
{
Envelope tx = node.Extent;
// Add padding on each side.
double bufferDistance = Math.Max(node.Extent.Width, node.Extent.Height) / 20;
Envelope bufferedExtent = new Envelope(
tx.XMin - bufferDistance, tx.YMin - bufferDistance,
tx.XMax + bufferDistance, tx.YMax + bufferDistance,
tx.ZMin - bufferDistance, tx.ZMax + bufferDistance,
SpatialReferences.Wgs84);
return new Viewpoint(bufferedExtent);
}
}
else
{
// Can't fly to.
needsAltitudeFix = false;
return null;
}
}
// Asynchronously adjust the given viewpoint, taking into consideration elevation and KML altitude mode.
private async Task<Viewpoint> GetAltitudeAdjustedViewpointAsync(KmlNode node, Viewpoint baseViewpoint)
{
// Get the altitude mode; assume clamp-to-ground if not specified.
KmlAltitudeMode altMode = KmlAltitudeMode.ClampToGround;
if (node.Viewpoint != null)
{
altMode = node.Viewpoint.AltitudeMode;
}
// If the altitude mode is Absolute, the base viewpoint doesn't need adjustment.
if (altMode == KmlAltitudeMode.Absolute)
{
return baseViewpoint;
}
double altitude;
Envelope lookAtExtent = baseViewpoint.TargetGeometry as Envelope;
MapPoint lookAtPoint = baseViewpoint.TargetGeometry as MapPoint;
if (lookAtExtent != null)
{
// Get the altitude for the extent.
try
{
altitude = await _mySceneView.Scene.BaseSurface.GetElevationAsync(lookAtExtent.GetCenter());
}
catch (Exception)
{
altitude = 0;
}
// Apply elevation adjustment to the geometry.
Envelope target;
if (altMode == KmlAltitudeMode.ClampToGround)
{
target = new Envelope(
lookAtExtent.XMin, lookAtExtent.YMin,
lookAtExtent.XMax, lookAtExtent.YMax,
altitude, lookAtExtent.Depth + altitude,
lookAtExtent.SpatialReference);
}
else
{
target = new Envelope(
lookAtExtent.XMin, lookAtExtent.YMin,
lookAtExtent.XMax, lookAtExtent.YMax,
lookAtExtent.ZMin + altitude, lookAtExtent.ZMax + altitude,
lookAtExtent.SpatialReference);
}
if (node.Viewpoint != null)
{
// Return adjusted geometry with adjusted camera if a viewpoint was specified on the node.
return new Viewpoint(target, baseViewpoint.Camera.Elevate(altitude));
}
else
{
// Return adjusted geometry.
return new Viewpoint(target);
}
}
else if (lookAtPoint != null)
{
// Get the altitude adjustment.
try
{
altitude = await _mySceneView.Scene.BaseSurface.GetElevationAsync(lookAtPoint);
}
catch (Exception)
{
altitude = 0;
}
// Apply elevation adjustment to the geometry.
MapPoint target;
if (altMode == KmlAltitudeMode.ClampToGround)
{
target = new MapPoint(lookAtPoint.X, lookAtPoint.Y, altitude, lookAtPoint.SpatialReference);
}
else
{
target = new MapPoint(
lookAtPoint.X, lookAtPoint.Y, lookAtPoint.Z + altitude,
lookAtPoint.SpatialReference);
}
if (node.Viewpoint != null)
{
// Return adjusted geometry with adjusted camera if a viewpoint was specified on the node.
return new Viewpoint(target, baseViewpoint.Camera.Elevate(altitude));
}
else
{
// Google Earth defaults: 1000m away and 45-degree tilt.
return new Viewpoint(target, new Camera(target, 1000, 0, 45, 0));
}
}
else
{
throw new InvalidOperationException("KmlNode has unexpected Geometry for its Extent: " +
baseViewpoint.TargetGeometry);
}
}
#endregion viewpoint_conversion
}
public class LayerDisplayVM
{
public KmlNode Node { get; }
private LayerDisplayVM Parent { get; set; }
private int NestLevel
{
get
{
if (Parent == null)
{
return 0;
}
return Parent.NestLevel + 1;
}
}
public LayerDisplayVM(KmlNode info, LayerDisplayVM parent)
{
Node = info;
Parent = parent;
}
public string Name => new string(' ', NestLevel * 3) + Node.GetType().Name + " - " + Node.Name;
public static void BuildLayerInfoList(LayerDisplayVM root, IList<LayerDisplayVM> result)
{
// Add the root node to the result list.
result.Add(root);
// Make the node visible.
root.Node.IsVisible = true;
// Recursively add children. KmlContainers and KmlNetworkLinks can both have children.
var containerNode = root.Node as KmlContainer;
var networkLinkNode = root.Node as KmlNetworkLink;
List<KmlNode> children = new List<KmlNode>();
if (containerNode != null)
{
children.AddRange(containerNode.ChildNodes);
}
if (networkLinkNode != null)
{
children.AddRange(networkLinkNode.ChildNodes);
}
foreach (KmlNode node in children)
{
// Create the view model for the sublayer.
LayerDisplayVM layerVM = new LayerDisplayVM(node, root);
// Recursively add children.
BuildLayerInfoList(layerVM, result);
}
}
}
}
| |
//
// System.Collections.Generic.SortedList.cs
//
// Author:
// Sergey Chaban (serge@wildwestsoftware.com)
// Duncan Mak (duncan@ximian.com)
// Herve Poussineau (hpoussineau@fr.st
// Zoltan Varga (vargaz@gmail.com)
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Mono.Collections.Generic
{
/// <summary>
/// Represents a collection of associated keys and values
/// that are sorted by the keys and are accessible by key
/// and by index.
/// </summary>
[ComVisible(false)]
[DebuggerDisplay ("Count={Count}")]
[DebuggerTypeProxy (typeof (CollectionDebuggerView<,>))]
internal class SortedList<TKey, TValue> : IDictionary<TKey, TValue>,
IDictionary,
ICollection,
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>,
IEnumerable {
private readonly static int INITIAL_SIZE = 16;
private enum EnumeratorMode : int { KEY_MODE = 0, VALUE_MODE, ENTRY_MODE }
private int inUse;
private int modificationCount;
private KeyValuePair<TKey, TValue>[] table;
private IComparer<TKey> comparer;
private int defaultCapacity;
//
// Constructors
//
public SortedList ()
: this (INITIAL_SIZE, null)
{
}
public SortedList (int capacity)
: this (capacity, null)
{
}
public SortedList (int capacity, IComparer<TKey> comparer)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException ("initialCapacity");
if (capacity == 0)
defaultCapacity = 0;
else
defaultCapacity = INITIAL_SIZE;
Init (comparer, capacity, true);
}
public SortedList (IComparer<TKey> comparer) : this (INITIAL_SIZE, comparer)
{
}
public SortedList (IDictionary<TKey, TValue> dictionary) : this (dictionary, null)
{
}
public SortedList (IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer)
{
if (dictionary == null)
throw new ArgumentNullException ("dictionary");
Init (comparer, dictionary.Count, true);
foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
Add (kvp.Key, kvp.Value);
}
//
// Properties
//
// ICollection
public int Count {
get {
return inUse;
}
}
bool ICollection.IsSynchronized {
get {
return false;
}
}
Object ICollection.SyncRoot {
get {
return this;
}
}
// IDictionary
bool IDictionary.IsFixedSize {
get {
return false;
}
}
bool IDictionary.IsReadOnly {
get {
return false;
}
}
public TValue this [TKey key] {
get {
if (key == null)
throw new ArgumentNullException("key");
int i = Find (key);
if (i >= 0)
return table [i].Value;
else
throw new KeyNotFoundException ();
}
set {
if (key == null)
throw new ArgumentNullException("key");
PutImpl (key, value, true);
}
}
object IDictionary.this [object key] {
get {
if (!(key is TKey))
return null;
else
return this [(TKey)key];
}
set {
this [ToKey (key)] = ToValue (value);
}
}
public int Capacity {
get {
return table.Length;
}
set {
int current = this.table.Length;
if (inUse > value) {
throw new ArgumentOutOfRangeException("capacity too small");
}
else if (value == 0) {
// return to default size
KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [defaultCapacity];
Array.Copy (table, newTable, inUse);
this.table = newTable;
}
#if NET_1_0
else if (current > defaultCapacity && value < current) {
KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [defaultCapacity];
Array.Copy (table, newTable, inUse);
this.table = newTable;
}
#endif
else if (value > inUse) {
KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [value];
Array.Copy (table, newTable, inUse);
this.table = newTable;
}
else if (value > current) {
KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [value];
Array.Copy (table, newTable, current);
this.table = newTable;
}
}
}
public IList<TKey> Keys {
get {
return new ListKeys (this);
}
}
public IList<TValue> Values {
get {
return new ListValues (this);
}
}
ICollection IDictionary.Keys {
get {
return new ListKeys (this);
}
}
ICollection IDictionary.Values {
get {
return new ListValues (this);
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys {
get {
return Keys;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
return Values;
}
}
public IComparer<TKey> Comparer {
get {
return comparer;
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
get {
return false;
}
}
//
// Public instance methods.
//
public void Add (TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException ("key");
PutImpl (key, value, false);
}
public bool ContainsKey (TKey key)
{
if (key == null)
throw new ArgumentNullException ("key");
return (Find (key) >= 0);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
{
for (int i = 0; i < inUse; i ++) {
KeyValuePair<TKey, TValue> current = this.table [i];
yield return new KeyValuePair<TKey, TValue> (current.Key, current.Value);
}
}
public bool Remove (TKey key)
{
if (key == null)
throw new ArgumentNullException ("key");
int i = IndexOfKey (key);
if (i >= 0) {
RemoveAt (i);
return true;
}
else
return false;
}
// ICollection<KeyValuePair<TKey, TValue>>
void ICollection<KeyValuePair<TKey, TValue>>.Clear ()
{
defaultCapacity = INITIAL_SIZE;
this.table = new KeyValuePair<TKey, TValue> [defaultCapacity];
inUse = 0;
modificationCount++;
}
public void Clear ()
{
defaultCapacity = INITIAL_SIZE;
this.table = new KeyValuePair<TKey, TValue> [defaultCapacity];
inUse = 0;
modificationCount++;
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
if (Count == 0)
return;
if (null == array)
throw new ArgumentNullException();
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (arrayIndex >= array.Length)
throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
int i = arrayIndex;
foreach (KeyValuePair<TKey, TValue> pair in this)
array [i++] = pair;
}
void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> keyValuePair) {
Add (keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> keyValuePair) {
int i = Find (keyValuePair.Key);
if (i >= 0)
return Comparer<KeyValuePair<TKey, TValue>>.Default.Compare (table [i], keyValuePair) == 0;
else
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> keyValuePair) {
int i = Find (keyValuePair.Key);
if (i >= 0 && (Comparer<KeyValuePair<TKey, TValue>>.Default.Compare (table [i], keyValuePair) == 0)) {
RemoveAt (i);
return true;
}
else
return false;
}
// IEnumerable<KeyValuePair<TKey, TValue>>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator ()
{
for (int i = 0; i < inUse; i ++) {
KeyValuePair<TKey, TValue> current = this.table [i];
yield return new KeyValuePair<TKey, TValue> (current.Key, current.Value);
}
}
// IEnumerable
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
// IDictionary
void IDictionary.Add (object key, object value)
{
PutImpl (ToKey (key), ToValue (value), false);
}
bool IDictionary.Contains (object key)
{
if (null == key)
throw new ArgumentNullException();
if (!(key is TKey))
return false;
return (Find ((TKey)key) >= 0);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
}
void IDictionary.Remove (object key)
{
if (null == key)
throw new ArgumentNullException ("key");
if (!(key is TKey))
return;
int i = IndexOfKey ((TKey)key);
if (i >= 0) RemoveAt (i);
}
// ICollection
void ICollection.CopyTo (Array array, int arrayIndex)
{
if (Count == 0)
return;
if (null == array)
throw new ArgumentNullException();
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (array.Rank > 1)
throw new ArgumentException("array is multi-dimensional");
if (arrayIndex >= array.Length)
throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
IEnumerator<KeyValuePair<TKey,TValue>> it = GetEnumerator ();
int i = arrayIndex;
while (it.MoveNext ()) {
array.SetValue (it.Current, i++);
}
}
//
// SortedList<TKey, TValue>
//
public void RemoveAt (int index)
{
KeyValuePair<TKey, TValue> [] table = this.table;
int cnt = Count;
if (index >= 0 && index < cnt) {
if (index != cnt - 1) {
Array.Copy (table, index+1, table, index, cnt-1-index);
} else {
table [index] = default (KeyValuePair <TKey, TValue>);
}
--inUse;
++modificationCount;
} else {
throw new ArgumentOutOfRangeException("index out of range");
}
}
public int IndexOfKey (TKey key)
{
if (key == null)
throw new ArgumentNullException ("key");
int indx = 0;
try {
indx = Find (key);
} catch (Exception) {
throw new InvalidOperationException();
}
return (indx | (indx >> 31));
}
public int IndexOfValue (TValue value)
{
if (inUse == 0)
return -1;
for (int i = 0; i < inUse; i ++) {
KeyValuePair<TKey, TValue> current = this.table [i];
if (Equals (value, current.Value))
return i;
}
return -1;
}
public bool ContainsValue (TValue value)
{
return IndexOfValue (value) >= 0;
}
public void TrimExcess ()
{
if (inUse < table.Length * 0.9)
Capacity = inUse;
}
public bool TryGetValue (TKey key, out TValue value)
{
if (key == null)
throw new ArgumentNullException("key");
int i = Find (key);
if (i >= 0) {
value = table [i].Value;
return true;
}
else {
value = default (TValue);
return false;
}
}
//
// Private methods
//
private void EnsureCapacity (int n, int free)
{
KeyValuePair<TKey, TValue> [] table = this.table;
KeyValuePair<TKey, TValue> [] newTable = null;
int cap = Capacity;
bool gap = (free >=0 && free < Count);
if (n > cap) {
newTable = new KeyValuePair<TKey, TValue> [n << 1];
}
if (newTable != null) {
if (gap) {
int copyLen = free;
if (copyLen > 0) {
Array.Copy (table, 0, newTable, 0, copyLen);
}
copyLen = Count - free;
if (copyLen > 0) {
Array.Copy (table, free, newTable, free+1, copyLen);
}
} else {
// Just a resizing, copy the entire table.
Array.Copy (table, newTable, Count);
}
this.table = newTable;
} else if (gap) {
Array.Copy (table, free, table, free+1, Count - free);
}
}
private void PutImpl (TKey key, TValue value, bool overwrite)
{
if (key == null)
throw new ArgumentNullException ("null key");
KeyValuePair<TKey, TValue> [] table = this.table;
int freeIndx = -1;
try {
freeIndx = Find (key);
} catch (Exception) {
throw new InvalidOperationException();
}
if (freeIndx >= 0) {
if (!overwrite)
throw new ArgumentException("element already exists");
table [freeIndx] = new KeyValuePair <TKey, TValue> (key, value);
++modificationCount;
return;
}
freeIndx = ~freeIndx;
if (freeIndx > Capacity + 1)
throw new Exception ("SortedList::internal error ("+key+", "+value+") at ["+freeIndx+"]");
EnsureCapacity (Count+1, freeIndx);
table = this.table;
table [freeIndx] = new KeyValuePair <TKey, TValue> (key, value);
++inUse;
++modificationCount;
}
private void Init (IComparer<TKey> comparer, int capacity, bool forceSize)
{
if (comparer == null)
comparer = Comparer<TKey>.Default;
this.comparer = comparer;
if (!forceSize && (capacity < defaultCapacity))
capacity = defaultCapacity;
this.table = new KeyValuePair<TKey, TValue> [capacity];
this.inUse = 0;
this.modificationCount = 0;
}
private void CopyToArray (Array arr, int i,
EnumeratorMode mode)
{
if (arr == null)
throw new ArgumentNullException ("arr");
if (i < 0 || i + this.Count > arr.Length)
throw new ArgumentOutOfRangeException ("i");
IEnumerator it = new Enumerator (this, mode);
while (it.MoveNext ()) {
arr.SetValue (it.Current, i++);
}
}
private int Find (TKey key)
{
KeyValuePair<TKey, TValue> [] table = this.table;
int len = Count;
if (len == 0) return ~0;
int left = 0;
int right = len-1;
while (left <= right) {
int guess = (left + right) >> 1;
int cmp = comparer.Compare (table[guess].Key, key);
if (cmp == 0) return guess;
if (cmp < 0) left = guess+1;
else right = guess-1;
}
return ~left;
}
private TKey ToKey (object key) {
if (key == null)
throw new ArgumentNullException ("key");
if (!(key is TKey))
throw new ArgumentException ("The value \"" + key + "\" isn't of type \"" + typeof (TKey) + "\" and can't be used in this generic collection.", "key");
return (TKey)key;
}
private TValue ToValue (object value) {
if (!(value is TValue))
throw new ArgumentException ("The value \"" + value + "\" isn't of type \"" + typeof (TValue) + "\" and can't be used in this generic collection.", "value");
return (TValue)value;
}
internal TKey KeyAt (int index) {
if (index >= 0 && index < Count)
return table [index].Key;
else
throw new ArgumentOutOfRangeException("Index out of range");
}
internal TValue ValueAt (int index) {
if (index >= 0 && index < Count)
return table [index].Value;
else
throw new ArgumentOutOfRangeException("Index out of range");
}
//
// Inner classes
//
private sealed class Enumerator : IDictionaryEnumerator, IEnumerator {
private SortedList<TKey, TValue>host;
private int stamp;
private int pos;
private int size;
private EnumeratorMode mode;
private object currentKey;
private object currentValue;
bool invalid = false;
private readonly static string xstr = "SortedList.Enumerator: snapshot out of sync.";
public Enumerator (SortedList<TKey, TValue>host, EnumeratorMode mode)
{
this.host = host;
stamp = host.modificationCount;
size = host.Count;
this.mode = mode;
Reset ();
}
public Enumerator (SortedList<TKey, TValue>host)
: this (host, EnumeratorMode.ENTRY_MODE)
{
}
public void Reset ()
{
if (host.modificationCount != stamp || invalid)
throw new InvalidOperationException (xstr);
pos = -1;
currentKey = null;
currentValue = null;
}
public bool MoveNext ()
{
if (host.modificationCount != stamp || invalid)
throw new InvalidOperationException (xstr);
KeyValuePair<TKey, TValue> [] table = host.table;
if (++pos < size) {
KeyValuePair<TKey, TValue> entry = table [pos];
currentKey = entry.Key;
currentValue = entry.Value;
return true;
}
currentKey = null;
currentValue = null;
return false;
}
public DictionaryEntry Entry
{
get {
if (invalid || pos >= size || pos == -1)
throw new InvalidOperationException (xstr);
return new DictionaryEntry (currentKey,
currentValue);
}
}
public Object Key {
get {
if (invalid || pos >= size || pos == -1)
throw new InvalidOperationException (xstr);
return currentKey;
}
}
public Object Value {
get {
if (invalid || pos >= size || pos == -1)
throw new InvalidOperationException (xstr);
return currentValue;
}
}
public Object Current {
get {
if (invalid || pos >= size || pos == -1)
throw new InvalidOperationException (xstr);
switch (mode) {
case EnumeratorMode.KEY_MODE:
return currentKey;
case EnumeratorMode.VALUE_MODE:
return currentValue;
case EnumeratorMode.ENTRY_MODE:
return this.Entry;
default:
throw new NotSupportedException (mode + " is not a supported mode.");
}
}
}
// ICloneable
public object Clone ()
{
Enumerator e = new Enumerator (host, mode);
e.stamp = stamp;
e.pos = pos;
e.size = size;
e.currentKey = currentKey;
e.currentValue = currentValue;
e.invalid = invalid;
return e;
}
}
struct KeyEnumerator : IEnumerator <TKey>, IDisposable {
const int NOT_STARTED = -2;
// this MUST be -1, because we depend on it in move next.
// we just decr the size, so, 0 - 1 == FINISHED
const int FINISHED = -1;
SortedList <TKey, TValue> l;
int idx;
int ver;
internal KeyEnumerator (SortedList<TKey, TValue> l)
{
this.l = l;
idx = NOT_STARTED;
ver = l.modificationCount;
}
public void Dispose ()
{
idx = NOT_STARTED;
}
public bool MoveNext ()
{
if (ver != l.modificationCount)
throw new InvalidOperationException ("Collection was modified after the enumerator was instantiated.");
if (idx == NOT_STARTED)
idx = l.Count;
return idx != FINISHED && -- idx != FINISHED;
}
public TKey Current {
get {
if (idx < 0)
throw new InvalidOperationException ();
return l.KeyAt (l.Count - 1 - idx);
}
}
void IEnumerator.Reset ()
{
if (ver != l.modificationCount)
throw new InvalidOperationException ("Collection was modified after the enumerator was instantiated.");
idx = NOT_STARTED;
}
object IEnumerator.Current {
get { return Current; }
}
}
struct ValueEnumerator : IEnumerator <TValue>, IDisposable {
const int NOT_STARTED = -2;
// this MUST be -1, because we depend on it in move next.
// we just decr the size, so, 0 - 1 == FINISHED
const int FINISHED = -1;
SortedList <TKey, TValue> l;
int idx;
int ver;
internal ValueEnumerator (SortedList<TKey, TValue> l)
{
this.l = l;
idx = NOT_STARTED;
ver = l.modificationCount;
}
public void Dispose ()
{
idx = NOT_STARTED;
}
public bool MoveNext ()
{
if (ver != l.modificationCount)
throw new InvalidOperationException ("Collection was modified after the enumerator was instantiated.");
if (idx == NOT_STARTED)
idx = l.Count;
return idx != FINISHED && -- idx != FINISHED;
}
public TValue Current {
get {
if (idx < 0)
throw new InvalidOperationException ();
return l.ValueAt (l.Count - 1 - idx);
}
}
void IEnumerator.Reset ()
{
if (ver != l.modificationCount)
throw new InvalidOperationException ("Collection was modified after the enumerator was instantiated.");
idx = NOT_STARTED;
}
object IEnumerator.Current {
get { return Current; }
}
}
private class ListKeys : IList<TKey>, ICollection, IEnumerable {
private SortedList<TKey, TValue> host;
public ListKeys (SortedList<TKey, TValue> host)
{
if (host == null)
throw new ArgumentNullException ();
this.host = host;
}
// ICollection<TKey>
public virtual void Add (TKey item) {
throw new NotSupportedException();
}
public virtual bool Remove (TKey key) {
throw new NotSupportedException ();
}
public virtual void Clear () {
throw new NotSupportedException();
}
public virtual void CopyTo (TKey[] array, int arrayIndex) {
if (host.Count == 0)
return;
if (array == null)
throw new ArgumentNullException ("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (arrayIndex >= array.Length)
throw new ArgumentOutOfRangeException ("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentOutOfRangeException("Not enough space in array from arrayIndex to end of array");
int j = arrayIndex;
for (int i = 0; i < Count; ++i)
array [j ++] = host.KeyAt (i);
}
public virtual bool Contains (TKey item) {
return host.IndexOfKey (item) > -1;
}
//
// IList<TKey>
//
public virtual int IndexOf (TKey item) {
return host.IndexOfKey (item);
}
public virtual void Insert (int index, TKey item) {
throw new NotSupportedException ();
}
public virtual void RemoveAt (int index) {
throw new NotSupportedException ();
}
public virtual TKey this [int index] {
get {
return host.KeyAt (index);
}
set {
throw new NotSupportedException("attempt to modify a key");
}
}
//
// IEnumerable<TKey>
//
public virtual IEnumerator<TKey> GetEnumerator ()
{
/* We couldn't use yield as it does not support Reset () */
return new KeyEnumerator (host);
}
//
// ICollection
//
public virtual int Count {
get {
return host.Count;
}
}
public virtual bool IsSynchronized {
get {
return ((ICollection)host).IsSynchronized;
}
}
public virtual bool IsReadOnly {
get {
return true;
}
}
public virtual Object SyncRoot {
get {
return ((ICollection)host).SyncRoot;
}
}
public virtual void CopyTo (Array array, int arrayIndex)
{
host.CopyToArray (array, arrayIndex, EnumeratorMode.KEY_MODE);
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator ()
{
for (int i = 0; i < host.Count; ++i)
yield return host.KeyAt (i);
}
}
private class ListValues : IList<TValue>, ICollection, IEnumerable {
private SortedList<TKey, TValue>host;
public ListValues (SortedList<TKey, TValue>host)
{
if (host == null)
throw new ArgumentNullException ();
this.host = host;
}
// ICollection<TValue>
public virtual void Add (TValue item) {
throw new NotSupportedException();
}
public virtual bool Remove (TValue value) {
throw new NotSupportedException ();
}
public virtual void Clear () {
throw new NotSupportedException();
}
public virtual void CopyTo (TValue[] array, int arrayIndex) {
if (host.Count == 0)
return;
if (array == null)
throw new ArgumentNullException ("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (arrayIndex >= array.Length)
throw new ArgumentOutOfRangeException ("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentOutOfRangeException("Not enough space in array from arrayIndex to end of array");
int j = arrayIndex;
for (int i = 0; i < Count; ++i)
array [j ++] = host.ValueAt (i);
}
public virtual bool Contains (TValue item) {
return host.IndexOfValue (item) > -1;
}
//
// IList<TValue>
//
public virtual int IndexOf (TValue item) {
return host.IndexOfValue (item);
}
public virtual void Insert (int index, TValue item) {
throw new NotSupportedException ();
}
public virtual void RemoveAt (int index) {
throw new NotSupportedException ();
}
public virtual TValue this [int index] {
get {
return host.ValueAt (index);
}
set {
throw new NotSupportedException("attempt to modify a key");
}
}
//
// IEnumerable<TValue>
//
public virtual IEnumerator<TValue> GetEnumerator ()
{
/* We couldn't use yield as it does not support Reset () */
return new ValueEnumerator (host);
}
//
// ICollection
//
public virtual int Count {
get {
return host.Count;
}
}
public virtual bool IsSynchronized {
get {
return ((ICollection)host).IsSynchronized;
}
}
public virtual bool IsReadOnly {
get {
return true;
}
}
public virtual Object SyncRoot {
get {
return ((ICollection)host).SyncRoot;
}
}
public virtual void CopyTo (Array array, int arrayIndex)
{
host.CopyToArray (array, arrayIndex, EnumeratorMode.VALUE_MODE);
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator ()
{
for (int i = 0; i < host.Count; ++i)
yield return host.ValueAt (i);
}
}
} // SortedList
} // System.Collections.Generic
| |
// This file is part of SNMP#NET.
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET 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 SNMP#NET. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
namespace SnmpSharpNet
{
/// <summary>ASN.1 OctetString type implementation</summary>
[Serializable]
public class OctetString : AsnType, ICloneable, IComparable<byte[]>, IComparable<OctetString>, IEnumerable<byte>
{
/// <summary>Data buffer</summary>
protected byte[] _data;
/// <summary>Constructor</summary>
public OctetString()
{
_asnType = SnmpConstants.SMI_STRING;
}
/// <summary> Constructs an Octet String with the contents of the supplied string.
/// </summary>
/// <param name="data">String data to convert into OctetString class value.</param>
public OctetString(String data):this()
{
Set(data);
}
/// <summary>Constructs the object and sets the data buffer to the byte array values
/// </summary>
/// <param name="data">Byte array to copy into the data buffer</param>
public OctetString(byte[] data):this()
{
Set(data);
}
/// <summary>
/// Construct the class and set value. Value can be set by reference (assigned passed array parameter
/// to the interal class variable) or by value (copy data in the array into a new buffer).
/// </summary>
/// <param name="data">Byte array to set class value to</param>
/// <param name="useReference">If true, set class value to reference byte array parameter, otherwise copy data into new internal byte array</param>
public OctetString(byte[] data, bool useReference):this()
{
if (useReference)
SetRef(data);
else
Set(data);
}
/// <summary>Constructor creating class from values in the supplied class.</summary>
/// <param name="second">OctetString object to copy data from.</param>
public OctetString(OctetString second):this()
{
Set(second);
}
/// <summary>
/// Constructor. Initialize the class value to a 1 byte array with the supplied value
/// </summary>
/// <param name="data">Value to initialize the class data to.</param>
public OctetString(byte data):this()
{
Set(data);
}
/// <summary>Get length of the internal byte array. 0 if byte array is undefined or zero length.</summary>
virtual public int Length
{
get
{
int len = 0;
if (_data != null)
len = _data.Length;
return len;
}
}
/// <summary>
/// Internal method to return OctetString byte array. Used for copy operations, comparisons and similar within the
/// library. Not available for users of the library
/// </summary>
/// <returns></returns>
internal byte[] GetData()
{
return _data;
}
/// <summary>
/// Empty data buffer
/// </summary>
public void Clear()
{
_data = null;
}
/// <summary>
/// Convert the OctetString class to a byte array. Internal class data buffer is *copied* and not passed to the caller.
/// </summary>
/// <returns>Byte array representing the OctetString class data</returns>
public byte[] ToArray()
{
if (_data == null)
{
return null;
}
byte[] tmp = new byte[_data.Length];
Buffer.BlockCopy(_data, 0, tmp, 0, _data.Length);
return tmp;
}
/// <summary>Set object value to bytes from the supplied string. If argument string length == 0, internal OctetString
/// buffer is set to null.</summary>
/// <param name="value">String containing new class data</param>
public virtual void Set(String value)
{
if (value == null)
{
_data = null;
}
if (value.Length == 0)
{
_data = null;
}
else
{
_data = System.Text.UTF8Encoding.UTF8.GetBytes(value);
}
}
/// <summary>
/// Set class value from the argument byte array. If byte array argument is null or length == 0,
/// internal <see cref="OctetString"/> buffer is set to null.
/// </summary>
/// <param name="data">Byte array to copy data from.</param>
public virtual void Set(byte[] data)
{
if (data == null || data.Length <= 0)
{
_data = null;
}
else
{
_data = new byte[data.Length];
Buffer.BlockCopy(data, 0, _data, 0, data.Length);
}
}
/// <summary>
/// Set class value to an array 1 byte long and set the value to the supplied argument.
/// </summary>
/// <param name="data">Byte value to initialize the class value with</param>
public virtual void Set(byte data)
{
_data = new byte[1];
_data[0] = data;
}
/// <summary>
/// Set value at specified position to the supplied value
/// </summary>
/// <param name="position">Zero based offset from the beginning of the buffer</param>
/// <param name="value">Value to set</param>
public virtual void Set(int position, byte value)
{
if (position < 0 || position >= Length)
{
return; // Don't throw exceptions here
}
_data[position] = value;
}
/// <summary>
/// Set class value to reference of parameter byte array
/// </summary>
/// <param name="data">Data buffer parameter</param>
public virtual void SetRef(byte[] data)
{
_data = data;
}
/// <summary>
/// Append string value to the OctetString class. If current class content is length 0, new
/// string value is set as the value of this class.
///
/// Class assumes that string value is UTF8 encoded.
/// </summary>
/// <param name="value">UTF8 encoded string value</param>
public void Append(string value)
{
if (_data == null)
{
Set(value);
}
else
{
if (value.Length > 0)
{
byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(value);
if (buffer != null && buffer.Length > 0)
{
Append(buffer);
}
}
}
}
/// <summary>
/// Append contents of the byte array to the class value. If class value is length 0, byte array
/// content is set as the class value.
/// </summary>
/// <param name="value">Byte array</param>
public void Append(byte[] value)
{
if (value == null || value.Length == 0)
throw new ArgumentNullException("value");
if (_data == null)
{
Set(value);
}
else
{
byte[] tempBuffer = new byte[_data.Length + value.Length];
Buffer.BlockCopy(_data, 0, tempBuffer, 0, _data.Length);
Buffer.BlockCopy(value, 0, tempBuffer, _data.Length, value.Length);
_data = tempBuffer;
}
}
/// <summary>
/// Indexed access to the OctetString class data members.
/// <code>
/// OctetString os = new OctetString("test");
/// for(int i = 0;i < os.Length;i++) {
/// Console.WriteLine("{0}",os[i]);
/// }
/// </code>
/// </summary>
/// <param name="index">Index position of the data value to access</param>
/// <returns>Byte value at the index position. 0 if index is out of range</returns>
public byte this[int index]
{
get
{
if (index < 0 || index >= Length)
{
return 0; // Don't throw exceptions here
}
return _data[index];
}
set
{
if (index < 0 || index >= Length)
{
return; // Don't throw exceptions here
}
_data[index] = value;
}
}
/// <summary>Creates a duplicate copy of the object and returns it to the caller.</summary>
/// <returns> A newly constructed copy of self</returns>
public override Object Clone()
{
return new OctetString(this);
}
/// <summary>
/// Return true if OctetString contains non-printable characters, otherwise return false.
/// </summary>
/// <remarks>Values recognized as hex are byte values less then decimal 32 that are not decimal
/// 10 or 13 and byte values that are greater then 127 decimal. One exception is byte value 0x00
/// when it is at the end of the byte array is not considered a hex value but a c-like string
/// termination character.</remarks>
public bool IsHex
{
get
{
if (_data == null || _data.Length < 0)
return false; // empty string can't be hex :)
bool isHex = false;
for(int i=0;i<_data.Length;i++)
{
byte b = _data[i];
if ( b < 32 ) {
if (b != 10 && b != 13 && !(b == 0x00 && (_data.Length - 1) == i))
{
isHex = true;
}
}
else if (b > 127)
{
isHex = true;
}
}
return isHex;
}
}
/// <summary>Utility function to print a MAC address (binary string of 6 byte length.</summary>
/// <returns>If data is of the correct length (6 bytes), string representing hex mac address in the
/// format xxxx.xxxx.xxxx. If data is not of the correct length, empty string is returned.</returns>
public System.String ToMACAddressString()
{
if( Length == 6 ) {
return string.Format(CultureInfo.CurrentCulture, "{0:x2}{1:x2}.{2:x2}{3:x2}.{4:x2}{5:x2}",
_data[0],_data[1],_data[2],_data[3],_data[4],_data[5]);
}
return "";
}
/// <summary>Return string representation of the OctetStrig object. If non-printable characters have been
/// found in the object, output is a hex representation of the string.
/// </summary>
/// <returns>String representation of the object.</returns>
public override String ToString()
{
if (_data == null || _data.Length <= 0)
{
return "";
}
bool asHex = IsHex;
System.String rs = null;
if (asHex)
{
rs = ToHexString();
}
else
{
rs = new String(UTF8Encoding.UTF8.GetChars(_data));
}
return rs;
}
/// <summary>
/// Return string formatted hexadecimal representation of the objects value.
/// </summary>
/// <returns>String representation of hexadecimal formatted class value.</returns>
public string ToHexString()
{
StringBuilder b = new StringBuilder();
for (int i = 0; i < _data.Length; ++i)
{
int x = (int)_data[i] & 0xff;
if (x < 16)
b.Append('0');
b.Append(System.Convert.ToString(x, 16).ToUpper());
if (i < _data.Length - 1)
b.Append(' ');
}
return b.ToString();
}
/// <summary>
/// Compare against another object. Acceptable object types are <see cref="OctetString"/> and
/// <see cref="System.String"/>.
/// </summary>
/// <param name="obj">Object of type <see cref="OctetString"/> or <see cref="System.String"/> to compare against</param>
/// <returns>true if object content is the same, false if different or if incompatible object type</returns>
public override bool Equals(object obj)
{
byte[] d = null;
if( obj is OctetString ) {
OctetString o = obj as OctetString;
d = o.GetData();
} else if( obj is System.String ) {
d = System.Text.UTF8Encoding.UTF8.GetBytes((String)obj);
} else {
return false; // Incompatible object type
}
// check for null value in comparison
if (d == null || _data == null)
{
if (d == null && _data == null)
return true; // both values are null
return false; // one value is not null
}
if( d.Length != _data.Length ) {
return false; // Objects have different length
}
for(int cnt=0;cnt<d.Length;cnt++) {
if( d[cnt] != _data[cnt] ) {
return false;
}
}
return true;
}
/// <summary>
/// Dummy override to prevent compiler warning messages.
/// </summary>
/// <returns>Nothing of interest</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Overloading equality operator
/// </summary>
/// <param name="str1">Source (this) string</param>
/// <param name="str2">String to compare with</param>
/// <returns>True if equal, otherwise false</returns>
public static bool operator ==(OctetString str1, OctetString str2)
{
if (((Object)str1) == null && ((Object)str2) == null)
return true;
if (((Object)str1) == null || ((Object)str2) == null)
return false;
return str1.Equals(str2);
}
/// <summary>
/// Negative equality operator
/// </summary>
/// <param name="str1">Source (this) string</param>
/// <param name="str2">String to compare with</param>
/// <returns>True if not equal, otherwise false</returns>
public static bool operator !=(OctetString str1, OctetString str2)
{
return !(str1 == str2);
}
/// <summary>
/// IComparable interface implementation. Compare class contents with contents of the byte array.
/// </summary>
/// <param name="other">Byte array to compare against</param>
/// <returns>-1 if class value is greater (longer or higher value), 1 if byte array is greater or 0 if the same</returns>
public int CompareTo(byte[] other)
{
if (_data == null && (other != null && other.Length > 0))
return 1;
if ((other == null || other.Length == 0) && _data.Length > 0)
return -1;
if (_data == null && other == null)
return 0;
if (_data.Length > other.Length)
return -1;
else if (_data.Length < other.Length)
return 1;
else
{
for (int i = 0; i < _data.Length; i++)
{
if (_data[i] > other[i])
return -1;
else if (_data[i] < other[i])
return 1;
}
return 0;
}
}
/// <summary>
/// IComparable interface implementation. Compare class contents against another class.
/// </summary>
/// <param name="other">OctetString class to compare against.</param>
/// <returns>-1 if class value is greater (longer or higher value), 1 if byte array is greater or 0 if the same</returns>
public int CompareTo(OctetString other)
{
return CompareTo(other.GetData());
}
/// <summary>
/// Implicit operator allowing cast of OctetString objects to byte[] array
/// </summary>
/// <param name="oStr">OctetString to cast as byte array</param>
/// <returns>Byte array value of the supplied OctetString</returns>
public static implicit operator byte[](OctetString oStr)
{
if (oStr == null)
return null;
return oStr.ToArray();
}
/// <summary>
/// Reset internal buffer to null.
/// </summary>
public void Reset()
{
_data = null;
}
#region Encode and decode methods
/// <summary>BER encode OctetString variable.</summary>
/// <param name="buffer"><see cref="MutableByte"/> encoding destination.</param>
public override void encode(MutableByte buffer)
{
if (_data == null || _data.Length == 0)
BuildHeader(buffer, Type, 0);
else
{
BuildHeader(buffer, Type, _data.Length);
buffer.Append(_data);
}
}
/// <summary>
/// Decode OctetString from the BER format.
/// </summary>
/// <param name="buffer">BER encoded buffer</param>
/// <param name="offset">Offset in the <see cref="MutableByte"/> to start the decoding from</param>
/// <returns>Buffer position after the decoded value</returns>
/// <exception cref="SnmpException">Thrown if parsed data type is invalid.</exception>
public override int decode(byte[] buffer, int offset)
{
int headerLength;
byte asnType = ParseHeader(buffer, ref offset, out headerLength);
if (asnType != Type)
throw new SnmpException("Invalid ASN.1 type.");
// verify that there is enough data to decode
if ((buffer.Length - offset) < headerLength)
throw new OverflowException("Data buffer is too small");
if (headerLength == 0)
{
// Packet contains string length == 0
_data = null;
}
else
{
//
// copy the data
//
_data = new byte[headerLength];
Buffer.BlockCopy(buffer, offset, _data, 0, headerLength);
offset += headerLength;
}
return offset;
}
#endregion Encode and decode methods
/// <summary>
/// Returns an enumerator that iterates through the OctetString byte collection
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<byte> GetEnumerator()
{
if (_data != null)
return ((IEnumerable<byte>)_data).GetEnumerator();
return null;
}
/// <summary>
/// Returns an enumerator that iterates through the OctetString byte collection
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
if (_data != null)
return _data.GetEnumerator();
return null;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Graphics;
using osu.Game.Rulesets;
using osu.Game.Screens.Menu;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Components
{
public class SongBar : CompositeDrawable
{
private BeatmapInfo beatmap;
public const float HEIGHT = 145 / 2f;
[Resolved]
private IBindable<RulesetInfo> ruleset { get; set; }
public BeatmapInfo Beatmap
{
get => beatmap;
set
{
if (beatmap == value)
return;
beatmap = value;
update();
}
}
private LegacyMods mods;
public LegacyMods Mods
{
get => mods;
set
{
mods = value;
update();
}
}
private FillFlowContainer flow;
private bool expanded;
public bool Expanded
{
get => expanded;
set
{
expanded = value;
flow.Direction = expanded ? FillDirection.Full : FillDirection.Vertical;
}
}
// Todo: This is a hack for https://github.com/ppy/osu-framework/issues/3617 since this container is at the very edge of the screen and potentially initially masked away.
protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false;
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
flow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
LayoutDuration = 500,
LayoutEasing = Easing.OutQuint,
Direction = FillDirection.Full,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
}
};
Expanded = true;
}
private void update()
{
if (beatmap == null)
{
flow.Clear();
return;
}
var bpm = beatmap.BeatmapSet.OnlineInfo.BPM;
var length = beatmap.Length;
string hardRockExtra = "";
string srExtra = "";
var ar = beatmap.BaseDifficulty.ApproachRate;
if ((mods & LegacyMods.HardRock) > 0)
{
hardRockExtra = "*";
srExtra = "*";
}
if ((mods & LegacyMods.DoubleTime) > 0)
{
// temporary local calculation (taken from OsuDifficultyCalculator)
double preempt = (int)BeatmapDifficulty.DifficultyRange(ar, 1800, 1200, 450) / 1.5;
ar = (float)(preempt > 1200 ? (1800 - preempt) / 120 : (1200 - preempt) / 150 + 5);
bpm *= 1.5f;
length /= 1.5f;
srExtra = "*";
}
(string heading, string content)[] stats;
switch (ruleset.Value.ID)
{
default:
stats = new (string heading, string content)[]
{
("CS", $"{beatmap.BaseDifficulty.CircleSize:0.#}{hardRockExtra}"),
("AR", $"{ar:0.#}{hardRockExtra}"),
("OD", $"{beatmap.BaseDifficulty.OverallDifficulty:0.#}{hardRockExtra}"),
};
break;
case 1:
case 3:
stats = new (string heading, string content)[]
{
("OD", $"{beatmap.BaseDifficulty.OverallDifficulty:0.#}{hardRockExtra}"),
("HP", $"{beatmap.BaseDifficulty.DrainRate:0.#}{hardRockExtra}")
};
break;
case 2:
stats = new (string heading, string content)[]
{
("CS", $"{beatmap.BaseDifficulty.CircleSize:0.#}{hardRockExtra}"),
("AR", $"{ar:0.#}"),
};
break;
}
flow.Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = HEIGHT,
Width = 0.5f,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Children = new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new DiffPiece(stats),
new DiffPiece(("Star Rating", $"{beatmap.StarDifficulty:0.#}{srExtra}"))
}
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new DiffPiece(("Length", TimeSpan.FromMilliseconds(length).ToString(@"mm\:ss"))),
new DiffPiece(("BPM", $"{bpm:0.#}"))
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
Alpha = 0.1f,
},
new OsuLogo
{
Triangles = false,
Scale = new Vector2(0.08f),
Margin = new MarginPadding(50),
X = -10,
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
},
}
},
},
}
}
}
},
new TournamentBeatmapPanel(beatmap)
{
RelativeSizeAxes = Axes.X,
Width = 0.5f,
Height = HEIGHT,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
}
};
}
public class DiffPiece : TextFlowContainer
{
public DiffPiece(params (string heading, string content)[] tuples)
{
Margin = new MarginPadding { Horizontal = 15, Vertical = 1 };
AutoSizeAxes = Axes.Both;
static void cp(SpriteText s, bool bold)
{
s.Font = OsuFont.Torus.With(weight: bold ? FontWeight.Bold : FontWeight.Regular, size: 15);
}
for (var i = 0; i < tuples.Length; i++)
{
var (heading, content) = tuples[i];
if (i > 0)
{
AddText(" / ", s =>
{
cp(s, false);
s.Spacing = new Vector2(-2, 0);
});
}
AddText(new TournamentSpriteText { Text = heading }, s => cp(s, false));
AddText(" ", s => cp(s, false));
AddText(new TournamentSpriteText { Text = content }, s => cp(s, true));
}
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Cms.Tests
{
[TestFixture]
public class MiscDataStreamTest
{
private const string TestMessage = "Hello World!";
private const string SignDN = "O=Bouncy Castle, C=AU";
private static IAsymmetricCipherKeyPair signKP;
private static X509Certificate signCert;
private const string OrigDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU";
private static IAsymmetricCipherKeyPair origKP;
private static X509Certificate origCert;
private const string ReciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU";
// private static IAsymmetricCipherKeyPair reciKP;
// private static X509Certificate reciCert;
private static IAsymmetricCipherKeyPair origDsaKP;
private static X509Certificate origDsaCert;
private static X509Crl signCrl;
private static X509Crl origCrl;
private static IAsymmetricCipherKeyPair SignKP
{
get { return signKP == null ? (signKP = CmsTestUtil.MakeKeyPair()) : signKP; }
}
private static IAsymmetricCipherKeyPair OrigKP
{
get { return origKP == null ? (origKP = CmsTestUtil.MakeKeyPair()) : origKP; }
}
// private static IAsymmetricCipherKeyPair ReciKP
// {
// get { return reciKP == null ? (reciKP = CmsTestUtil.MakeKeyPair()) : reciKP; }
// }
private static IAsymmetricCipherKeyPair OrigDsaKP
{
get { return origDsaKP == null ? (origDsaKP = CmsTestUtil.MakeDsaKeyPair()) : origDsaKP; }
}
private static X509Certificate SignCert
{
get { return signCert == null ? (signCert = CmsTestUtil.MakeCertificate(SignKP, SignDN, SignKP, SignDN)) : signCert; }
}
private static X509Certificate OrigCert
{
get { return origCert == null ? (origCert = CmsTestUtil.MakeCertificate(OrigKP, OrigDN, SignKP, SignDN)) : origCert; }
}
// private static X509Certificate ReciCert
// {
// get { return reciCert == null ? (reciCert = CmsTestUtil.MakeCertificate(ReciKP, ReciDN, SignKP, SignDN)) : reciCert; }
// }
private static X509Certificate OrigDsaCert
{
get { return origDsaCert == null ? (origDsaCert = CmsTestUtil.MakeCertificate(OrigDsaKP, OrigDN, SignKP, SignDN)) : origDsaCert; }
}
private static X509Crl SignCrl
{
get { return signCrl == null ? (signCrl = CmsTestUtil.MakeCrl(SignKP)) : signCrl; }
}
private static X509Crl OrigCrl
{
get { return origCrl == null ? (origCrl = CmsTestUtil.MakeCrl(OrigKP)) : origCrl; }
}
private void VerifySignatures(
CmsSignedDataParser sp,
byte[] contentDigest)
{
IX509Store certStore = sp.GetCertificates("Collection");
SignerInformationStore signers = sp.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
ICollection certCollection = certStore.GetMatches(signer.SignerID);
IEnumerator certEnum = certCollection.GetEnumerator();
certEnum.MoveNext();
X509Certificate cert = (X509Certificate) certEnum.Current;
Assert.IsTrue(signer.Verify(cert));
if (contentDigest != null)
{
Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
}
}
}
private void VerifySignatures(
CmsSignedDataParser sp)
{
VerifySignatures(sp, null);
}
private void VerifyEncodedData(
MemoryStream bOut)
{
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
sp.Close();
}
private void CheckSigParseable(byte[] sig)
{
CmsSignedDataParser sp = new CmsSignedDataParser(sig);
sp.Version.ToString();
CmsTypedStream sc = sp.GetSignedContent();
if (sc != null)
{
sc.Drain();
}
sp.GetAttributeCertificates("Collection");
sp.GetCertificates("Collection");
sp.GetCrls("Collection");
sp.GetSignerInfos();
sp.Close();
}
[Test]
public void TestSha1WithRsa()
{
IList certList = new ArrayList();
IList crlList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
crlList.Add(SignCrl);
crlList.Add(OrigCrl);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
IX509Store x509Crls = X509StoreFactory.Create(
"CRL/Collection",
new X509CollectionStoreParameters(crlList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
gen.AddCrls(x509Crls);
Stream sigOut = gen.Open(bOut);
CmsCompressedDataStreamGenerator cGen = new CmsCompressedDataStreamGenerator();
Stream cOut = cGen.Open(sigOut, CmsCompressedDataStreamGenerator.ZLib);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
cOut.Write(testBytes, 0, testBytes.Length);
cOut.Close();
sigOut.Close();
CheckSigParseable(bOut.ToArray());
// generate compressed stream
MemoryStream cDataOut = new MemoryStream();
cOut = cGen.Open(cDataOut, CmsCompressedDataStreamGenerator.ZLib);
cOut.Write(testBytes, 0, testBytes.Length);
cOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(
new CmsTypedStream(new MemoryStream(cDataOut.ToArray(), false)), bOut.ToArray());
sp.GetSignedContent().Drain();
//
// compute expected content digest
//
IDigest md = DigestUtilities.GetDigest("SHA1");
byte[] cDataOutBytes = cDataOut.ToArray();
md.BlockUpdate(cDataOutBytes, 0, cDataOutBytes.Length);
byte[] hash = DigestUtilities.DoFinal(md);
VerifySignatures(sp, hash);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Impromptu.Compare;
namespace Impromptu.Collection
{
/// <summary>
///
/// </summary>
/// <remarks>Not thread safe.</remarks>
public sealed class PriorityQueue<T> : IEnumerable<T>, ICollection
{
#region Fields
private readonly IComparer<T> _comparer = InvertedComparer<T>.Default;
private readonly List<T> _queue;
private object m_syncRoot;
#endregion
#region Public IEnumerable<T>
public IEnumerator<T> GetEnumerator()
{
var copy = new List<T>(_queue);
copy.Sort(_comparer);
return copy.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Public ICollection
public int Count
{
get { return _queue.Count; }
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_queue).CopyTo(array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (m_syncRoot == null)
Interlocked.CompareExchange(ref m_syncRoot, new object(), null);
return m_syncRoot;
}
}
#endregion
#region Properties
//public IComparer<T> Comparer { get; private set; }
public int Capacity
{
get { return _queue.Capacity; }
set { _queue.Capacity = value; }
}
#endregion
#region Constructor
public PriorityQueue() : this((IComparer<T>)null)
{
}
public PriorityQueue(IEnumerable<T> collection, IComparer<T> comparer) : this((List<T>)null, comparer)
{
_comparer = comparer;
if (collection == null)
throw new ArgumentNullException("collection");
_queue = new List<T>(collection);
if (_queue.Count > 1)
{
for (var index = (_queue.Count - 1) >> 1; index >= 0; --index)
DownList(index);
}
}
public PriorityQueue(IEnumerable<T> collection) : this(collection, null)
{
}
public PriorityQueue(int capacity, IComparer<T> comparer) : this(new List<T>(capacity), comparer)
{
}
public PriorityQueue(IComparer<T> comparer) : this(new List<T>(), comparer)
{
}
private PriorityQueue(List<T> queue, IComparer<T> comparer)
{
_comparer = comparer ?? Comparer<T>.Default;
_queue = queue;
}
private PriorityQueue(T[] queue, IComparer<T> comparer)
{
_comparer = comparer ?? Comparer<T>.Default;
_queue = new List<T>();
foreach (var item in queue)
_queue.Add(item);
}
#endregion
#region Public Methods
public void Enqueue(T item)
{
_queue.Add(item);
UpList();
}
public T Dequeue()
{
if (_queue.Count == 0)
throw new InvalidOperationException("Empty");
var result = _queue[0];
var lastIndex = _queue.Count - 1;
_queue[0] = _queue[lastIndex];
_queue.RemoveAt(lastIndex);
if (_queue.Count > 0)
DownList(0);
return result;
}
public T Peek()
{
if (_queue.Count == 0)
throw new InvalidOperationException("Empty");
return _queue[0];
}
public void AdjustFirstItem()
{
if (_queue.Count == 0)
throw new InvalidOperationException("Empty");
DownList(0);
}
public void Clear()
{
_queue.Clear();
}
public void TrimExcess()
{
_queue.TrimExcess();
}
public bool Contains(T item)
{
return _queue.Contains(item);
}
public T[] ToArray()
{
var result = _queue.ToArray();
//return the elements in the same order in which they are enumerated
Array.Sort(result, _comparer);
return result;
}
public void CopyTo(T[] array, int arrayIndex)
{
_queue.CopyTo(array, arrayIndex);
Array.Sort(array, arrayIndex, _queue.Count, _comparer);
}
#endregion
#region Private Methods
private void UpList()
{
var index = _queue.Count - 1;
var item = _queue[index];
var parentIndex = (index - 1) >> 1;
//if already at zero then at top
while (index > 0 && _comparer.Compare(item, _queue[parentIndex]) < 0)
{
_queue[index] = _queue[parentIndex];
index = parentIndex;
parentIndex = (index - 1) >> 1;
}
_queue[index] = item;
}
private void DownList(int index)
{
var item = _queue[index];
var count = _queue.Count;
var firstChild = (index << 1) + 1;
var secondChild = firstChild + 1;
var smallestChild = (secondChild < count && _comparer.Compare(_queue[secondChild], _queue[firstChild]) < 0) ? secondChild : firstChild;
while (smallestChild < count && _comparer.Compare(_queue[smallestChild], item) < 0)
{
_queue[index] = _queue[smallestChild];
index = smallestChild;
firstChild = (index << 1) + 1;
secondChild = firstChild + 1;
smallestChild = (secondChild < count && _comparer.Compare(_queue[secondChild], _queue[firstChild]) < 0) ? secondChild : firstChild;
}
_queue[index] = item;
}
#endregion
}
}
| |
// Author: Robert Scheller, Melissa Lucash
using Landis.Core;
using Landis.SpatialModeling;
using Landis.Utilities;
using Landis.Library.Succession;
using Landis.Library.Parameters;
using System.Collections.Generic;
using System.Diagnostics;
namespace Landis.Extension.Succession.NECN
{
/// <summary>
/// The parameters for biomass succession.
/// </summary>
public class InputParameters
: IInputParameters
{
private int timestep;
private SeedingAlgorithms seedAlg;
private string climateConfigFile;
private string initCommunities;
private string communitiesMap;
private string soilDepthMapName;
private string soilDrainMapName;
private string soilBaseFlowMapName;
private string soilStormFlowMapName;
private string soilFieldCapacityMapName;
private string soilWiltingPointMapName;
private string soilPercentSandMapName;
private string soilPercentClayMapName;
private string initialSOM1CSurfaceMapName;
private string initialSOM1NSurfaceMapName;
private string initialSOM1CSoilMapName;
private string initialSOM1NSoilMapName;
private string initialSOM2CMapName;
private string initialSOM2NMapName;
private string initialSOM3CMapName;
private string initialSOM3NMapName;
private string initialDeadSurfaceMapName;
private string initialDeadSoilMapName;
private bool calibrateMode;
private bool smokeModelOutputs;
private bool henne_watermode;
private WaterType wtype;
private double probEstablishAdjust;
private double atmosNslope;
private double atmosNintercept;
private double latitude;
private double denitrif;
private double decayRateSurf;
private double decayRateSOM1;
private double decayRateSOM2;
private double decayRateSOM3;
private double[] maximumShadeLAI;
private double initMineralN;
private double initFineFuels;
private ISpeciesDataset speciesDataset;
private FunctionalTypeTable functionalTypes;
private FireReductions[] fireReductionsTable;
private List<HarvestReductions> harvestReductionsTable;
private Landis.Library.Parameters.Species.AuxParm<int> sppFunctionalType;
private Landis.Library.Parameters.Species.AuxParm<bool> nFixer;
private Landis.Library.Parameters.Species.AuxParm<int> gddMin;
private Landis.Library.Parameters.Species.AuxParm<int> gddMax;
private Landis.Library.Parameters.Species.AuxParm<int> minJanTemp;
private Landis.Library.Parameters.Species.AuxParm<double> maxDrought;
private Landis.Library.Parameters.Species.AuxParm<double> leafLongevity;
private Landis.Library.Parameters.Species.AuxParm<bool> epicormic;
private Landis.Library.Parameters.Species.AuxParm<double> leafLignin;
private Landis.Library.Parameters.Species.AuxParm<double> woodLignin;
private Landis.Library.Parameters.Species.AuxParm<double> coarseRootLignin;
private Landis.Library.Parameters.Species.AuxParm<double> fineRootLignin;
private Landis.Library.Parameters.Species.AuxParm<double> leafCN;
private Landis.Library.Parameters.Species.AuxParm<double> woodCN;
private Landis.Library.Parameters.Species.AuxParm<double> coarseRootCN;
private Landis.Library.Parameters.Species.AuxParm<double> foliageLitterCN;
private Landis.Library.Parameters.Species.AuxParm<double> fineRootCN;
private Landis.Library.Parameters.Species.AuxParm<int> maxANPP;
private Landis.Library.Parameters.Species.AuxParm<int> maxBiomass;
private Landis.Library.Parameters.Species.AuxParm<bool> grass; // optional
private Landis.Library.Parameters.Species.AuxParm<double> growthLAI; // optional
private List<ISufficientLight> sufficientLight;
private Landis.Library.Parameters.Species.AuxParm<bool> grass;
private Landis.Library.Parameters.Species.AuxParm<bool> nlog_depend;
private double grassThresholdMultiplier; // W.Hotta 2020.07.07
public double GrassThresholdMultiplier { get { return grassThresholdMultiplier; } }
//---------------------------------------------------------------------
/// <summary>
/// Timestep (years)
/// </summary>
public int Timestep
{
get {
return timestep;
}
set {
if (value < 0)
throw new InputValueException(value.ToString(), "Timestep must be > or = 0");
timestep = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Seeding algorithm
/// </summary>
public SeedingAlgorithms SeedAlgorithm
{
get {
return seedAlg;
}
set {
seedAlg = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Path to the file with the initial communities' definitions.
/// </summary>
public string InitialCommunities
{
get
{
return initCommunities;
}
set
{
if (value != null)
{
ValidatePath(value);
}
initCommunities = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Path to the raster file showing where the initial communities are.
/// </summary>
public string InitialCommunitiesMap
{
get
{
return communitiesMap;
}
set
{
if (value != null)
{
ValidatePath(value);
}
communitiesMap = value;
}
}
//---------------------------------------------------------------------
public string ClimateConfigFile
{
get
{
return climateConfigFile;
}
set
{
climateConfigFile = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Determines whether months are simulated 0 - 12 (calibration mode) or
/// 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5 (normal mode with disturbance at June 30).
/// </summary>
public bool CalibrateMode
{
get {
return calibrateMode;
}
set {
calibrateMode = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// </summary>
public bool SoilWater_Henne
{
get
{
return henne_watermode;
}
set
{
henne_watermode = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// </summary>
public bool SmokeModelOutputs
{
get
{
return smokeModelOutputs;
}
set
{
smokeModelOutputs = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Determines whether moisture effects on decomposition follow a linear or ratio calculation.
/// </summary>
public WaterType WType
{
get {
return wtype;
}
set {
wtype = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Adjust probability of establishment due to variable time step. A multiplier.
/// </summary>
public double ProbEstablishAdjustment
{
get
{
return probEstablishAdjust;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Probability of adjustment factor must be > 0.0 and < 1");
probEstablishAdjust = value;
}
}
//---------------------------------------------------------------------
public double AtmosNslope
{
get
{
return atmosNslope;
}
}
//---------------------------------------------------------------------
public double AtmosNintercept
{
get
{
return atmosNintercept;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Functional type parameters.
/// </summary>
public FunctionalTypeTable FunctionalTypes
{
get {
return functionalTypes;
}
set {
functionalTypes = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Fire reduction of leaf and wood litter parameters.
/// </summary>
public FireReductions[] FireReductionsTable
{
get {
return fireReductionsTable;
}
set {
fireReductionsTable = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Harvest reduction of leaf and wood litter parameters.
/// </summary>
public List<HarvestReductions> HarvestReductionsTable
{
get
{
return harvestReductionsTable;
}
set
{
harvestReductionsTable = value;
}
}
//---------------------------------------------------------------------
public double[] MaximumShadeLAI
{
get
{
return maximumShadeLAI;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<int> SppFunctionalType {get {return sppFunctionalType;}}
public Landis.Library.Parameters.Species.AuxParm<bool> NFixer { get {return nFixer;}}
public Landis.Library.Parameters.Species.AuxParm<bool> Grass { get { return grass; } }
public Landis.Library.Parameters.Species.AuxParm<bool> Nlog_depend { get { return nlog_depend; } }
public Landis.Library.Parameters.Species.AuxParm<int> GDDmin { get { return gddMin; }}
public Landis.Library.Parameters.Species.AuxParm<int> GDDmax { get { return gddMax; }}
public Landis.Library.Parameters.Species.AuxParm<int> MinJanTemp { get { return minJanTemp; }}
public Landis.Library.Parameters.Species.AuxParm<double> MaxDrought { get { return maxDrought; }}
public Landis.Library.Parameters.Species.AuxParm<double> LeafLongevity {get {return leafLongevity;}}
public Landis.Library.Parameters.Species.AuxParm<double> GrowthLAI { get { return growthLAI; } }
//---------------------------------------------------------------------
/// <summary>
/// Can the species resprout epicormically following a fire?
/// </summary>
public Landis.Library.Parameters.Species.AuxParm<bool> Epicormic
{
get {
return epicormic;
}
set {
epicormic = value;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> LeafLignin
{
get {
return leafLignin;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> WoodLignin
{
get {
return woodLignin;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> CoarseRootLignin
{
get {
return coarseRootLignin;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> FineRootLignin
{
get {
return fineRootLignin;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> LeafCN
{
get {
return leafCN;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> WoodCN
{
get {
return woodCN;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> CoarseRootCN
{
get {
return coarseRootCN;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> FoliageLitterCN
{
get {
return foliageLitterCN;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> FineRootCN
{
get {
return fineRootCN;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<int> MaxANPP
{
get
{
return maxANPP;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<int> MaxBiomass
{
get
{
return maxBiomass;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Definitions of sufficient light probabilities.
/// </summary>
public List<ISufficientLight> LightClassProbabilities
{
get {
return sufficientLight;
}
set
{
Debug.Assert(sufficientLight.Count != 0);
sufficientLight = value;
}
}
//---------------------------------------------------------------------
public double Latitude
{
get {
return latitude;
}
}
//-----------------------------------------------
public double DecayRateSurf
{
get
{
return decayRateSurf;
}
}
//-----------------------------------------------
public double DecayRateSOM1
{
get
{
return decayRateSOM1;
}
}//---------------------------------------------------------------------
public double DecayRateSOM2
{
get
{
return decayRateSOM2;
}
}
//---------------------------------------------------------------------
public double DecayRateSOM3
{
get
{
return decayRateSOM3;
}
}
//-----------------------------------------------
public double DenitrificationRate
{
get
{
return denitrif;
}
}
public double InitialMineralN { get { return initMineralN; } }
public double InitialFineFuels { get { return initFineFuels; } }
//---------------------------------------------------------------------
//public string AgeOnlyDisturbanceParms
//{
// get {
// return ageOnlyDisturbanceParms;
// }
// set {
// string path = value;
// if (path.Trim(null).Length == 0)
// throw new InputValueException(path,"\"{0}\" is not a valid path.",path);
// ageOnlyDisturbanceParms = value;
// }
//}
//---------------------------------------------------------------------
public string SoilDepthMapName
{
get
{
return soilDepthMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilDepthMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilDrainMapName
{
get
{
return soilDrainMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilDrainMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilBaseFlowMapName
{
get
{
return soilBaseFlowMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilBaseFlowMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilStormFlowMapName
{
get
{
return soilStormFlowMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilStormFlowMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilFieldCapacityMapName
{
get
{
return soilFieldCapacityMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilFieldCapacityMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilWiltingPointMapName
{
get
{
return soilWiltingPointMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilWiltingPointMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilPercentSandMapName
{
get
{
return soilPercentSandMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilPercentSandMapName = value;
}
}
//---------------------------------------------------------------------
public string SoilPercentClayMapName
{
get
{
return soilPercentClayMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
soilPercentClayMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM1CSurfaceMapName
{
get
{
return initialSOM1CSurfaceMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM1CSurfaceMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM1NSurfaceMapName
{
get
{
return initialSOM1NSurfaceMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM1NSurfaceMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM1CSoilMapName
{
get
{
return initialSOM1CSoilMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM1CSoilMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM1NSoilMapName
{
get
{
return initialSOM1NSoilMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM1NSoilMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM2CMapName
{
get
{
return initialSOM2CMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM2CMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM2NMapName
{
get
{
return initialSOM2NMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM2NMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM3CMapName
{
get
{
return initialSOM3CMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM3CMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialSOM3NMapName
{
get
{
return initialSOM3NMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialSOM3NMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialDeadSurfaceMapName
{
get
{
return initialDeadSurfaceMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialDeadSurfaceMapName = value;
}
}
//---------------------------------------------------------------------
public string InitialDeadSoilMapName
{
get
{
return initialDeadSoilMapName;
}
set
{
string path = value;
if (path.Trim(null).Length == 0)
throw new InputValueException(path, "\"{0}\" is not a valid path.", path);
initialDeadSoilMapName = value;
}
}
//---------------------------------------------------------------------
public void SetMaximumShadeLAI(byte shadeClass,
//IEcoregion ecoregion,
InputValue<double> newValue)
{
Debug.Assert(1 <= shadeClass && shadeClass <= 5);
//Debug.Assert(ecoregion != null);
if (newValue != null) {
if (newValue.Actual < 0.0 || newValue.Actual > 20)
throw new InputValueException(newValue.String,
"{0} is not between 0 and 20", newValue.String);
}
maximumShadeLAI[shadeClass] = newValue;
//minRelativeBiomass[shadeClass][ecoregion] = newValue;
}
//---------------------------------------------------------------------
public void SetFunctionalType(ISpecies species, InputValue<int> newValue)
{
Debug.Assert(species != null);
sppFunctionalType[species] = VerifyRange(newValue, 0, 100);
}
public void SetFunctionalType(ISpecies species, int newValue)
{
Debug.Assert(species != null);
sppFunctionalType[species] = VerifyRange(newValue, 0, 100);
}
//---------------------------------------------------------------------
//public void SetNFixer(ISpecies species,
// InputValue<int> newValue)
//{
// Debug.Assert(species != null);
// nTolerance[species] = CheckBiomassParm(newValue, 1, 4);
//}
//---------------------------------------------------------------------
public void SetGDDmin(ISpecies species,
InputValue<int> newValue)
{
Debug.Assert(species != null);
gddMin[species] = VerifyRange(newValue, 1, 4000);
}
public void SetGDDmin(ISpecies species,int newValue)
{
Debug.Assert(species != null);
gddMin[species] = VerifyRange(newValue, 1, 4000);
}
//---------------------------------------------------------------------
public void SetGDDmax(ISpecies species,
InputValue<int> newValue)
{
Debug.Assert(species != null);
gddMax[species] = VerifyRange(newValue, 500, 7000);
}
public void SetGDDmax(ISpecies species,int newValue)
{
Debug.Assert(species != null);
gddMax[species] = VerifyRange(newValue, 500, 7000);
}
//---------------------------------------------------------------------
public void SetMinJanTemp(ISpecies species,
InputValue<int> newValue)
{
Debug.Assert(species != null);
minJanTemp[species] = VerifyRange(newValue, -60, 20);
}
public void SetMinJanTemp(ISpecies species,int newValue)
{
Debug.Assert(species != null);
minJanTemp[species] = VerifyRange(newValue, -60, 20);
}
//---------------------------------------------------------------------
public void SetMaxDrought(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
maxDrought[species] = VerifyRange(newValue, 0.0, 1.0);
}
public void SetMaxDrought(ISpecies species,double newValue)
{
Debug.Assert(species != null);
maxDrought[species] = VerifyRange(newValue, 0.0, 1.0);
}
//---------------------------------------------------------------------
public void SetLeafLongevity(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
leafLongevity[species] = VerifyRange(newValue, 1.0, 10.0);
}
public void SetLeafLongevity(ISpecies species,double newValue)
{
Debug.Assert(species != null);
leafLongevity[species] = VerifyRange(newValue, 1.0, 10.0);
}
//---------------------------------------------------------------------
public void SetLeafLignin(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
leafLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
public void SetLeafLignin(ISpecies species,double newValue)
{
Debug.Assert(species != null);
leafLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
//---------------------------------------------------------------------
public void SetWoodLignin(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
woodLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
public void SetWoodLignin(ISpecies species,double newValue)
{
Debug.Assert(species != null);
woodLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
//---------------------------------------------------------------------
public void SetCoarseRootLignin(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
coarseRootLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
public void SetCoarseRootLignin(ISpecies species,double newValue)
{
Debug.Assert(species != null);
coarseRootLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
//---------------------------------------------------------------------
public void SetFineRootLignin(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
fineRootLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
public void SetFineRootLignin(ISpecies species,double newValue)
{
Debug.Assert(species != null);
fineRootLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
//---------------------------------------------------------------------
public void SetLeafCN(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
leafCN[species] = VerifyRange(newValue, 5.0, 100.0);
}
public void SetLeafCN(ISpecies species,double newValue)
{
Debug.Assert(species != null);
leafCN[species] = VerifyRange(newValue, 5.0, 100.0);
}
//---------------------------------------------------------------------
public void SetWoodCN(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
woodCN[species] = VerifyRange(newValue, 5.0, 900.0);
}
public void SetWoodCN(ISpecies species,double newValue)
{
Debug.Assert(species != null);
woodCN[species] = VerifyRange(newValue, 5.0, 900.0);
}
//---------------------------------------------------------------------
public void SetCoarseRootCN(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
coarseRootCN[species] = VerifyRange(newValue, 5.0, 500.0);
}
public void SetCoarseRootCN(ISpecies species,double newValue)
{
Debug.Assert(species != null);
coarseRootCN[species] = VerifyRange(newValue, 5.0, 500.0);
}
//---------------------------------------------------------------------
public void SetFoliageLitterCN(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
foliageLitterCN[species] = VerifyRange(newValue, 5.0, 100.0);
}
public void SetFoliageLitterCN(ISpecies species,double newValue)
{
Debug.Assert(species != null);
foliageLitterCN[species] = VerifyRange(newValue, 5.0, 100.0);
}
//---------------------------------------------------------------------
public void SetFineRootCN(ISpecies species,
InputValue<double> newValue)
{
Debug.Assert(species != null);
fineRootCN[species] = VerifyRange(newValue, 5.0, 100.0);
}
public void SetFineRootCN(ISpecies species,double newValue)
{
Debug.Assert(species != null);
fineRootCN[species] = VerifyRange(newValue, 5.0, 100.0);
}
//---------------------------------------------------------------------
public void SetMaxANPP(ISpecies species,
InputValue<int> newValue)
{
Debug.Assert(species != null);
maxANPP[species] = VerifyRange(newValue, 2, 1000);
}
public void SetMaxANPP(ISpecies species,int newValue)
{
Debug.Assert(species != null);
maxANPP[species] = VerifyRange(newValue, 2, 1000);
}
//---------------------------------------------------------------------
public void SetMaxBiomass(ISpecies species, InputValue<int> newValue)
{
Debug.Assert(species != null);
maxBiomass[species] = VerifyRange(newValue, 2, 100000);
}
public void SetMaxBiomass(ISpecies species, int newValue)
{
Debug.Assert(species != null);
maxBiomass[species] = VerifyRange(newValue, 2, 100000);
}
public void SetGrowthLAI(ISpecies species, double newValue)
{
Debug.Assert(species != null);
growthLAI[species] = VerifyRange(newValue, 0.0, 1.0);
}
//---------------------------------------------------------------------
public void SetAtmosNslope(InputValue<double> newValue)
{
atmosNslope = VerifyRange(newValue, -1.0, 2.0);
}
//---------------------------------------------------------------------
public void SetAtmosNintercept(InputValue<double> newValue)
{
atmosNintercept = VerifyRange(newValue, -1.0, 2.0);
}
//---------------------------------------------------------------------
public void SetLatitude(InputValue<double> newValue)
{
latitude = VerifyRange(newValue, 0.0, 50.0);
}
//---------------------------------------------------------------------
public void SetDecayRateSurf(InputValue<double> newValue)
{
decayRateSurf = VerifyRange(newValue, 0.0, 10.0);
}
//---------------------------------------------------------------------
public void SetDecayRateSOM1(InputValue<double> newValue)
{
decayRateSOM1 = VerifyRange(newValue, 0.0, 10.0);
}
//---------------------------------------------------------------------
public void SetDecayRateSOM2(InputValue<double> newValue)
{
decayRateSOM2 = VerifyRange(newValue, 0.0, 1.0);
}
//---------------------------------------------------------------------
public void SetDecayRateSOM3(InputValue<double> newValue)
{
decayRateSOM3 = VerifyRange(newValue, 0.0, 1.0);
}
// --------------------------------------------------------------------
// Multiplier to adjust judgement whether a tree-cohort is larger than grass layer
// W.Hotta 2020.07.07
public void SetGrassThresholdMultiplier(InputValue<double> newValue)
{
grassThresholdMultiplier = VerifyRange(newValue, 0.0, 10.0);
}
//---------------------------------------------------------------------
public void SetDenitrif(InputValue<double> newValue)
{
denitrif = VerifyRange(newValue, 0.0, 1.0);
}
//---------------------------------------------------------------------
public void SetInitMineralN(InputValue<double> newValue)
{
initMineralN = VerifyRange(newValue, 0.0, 5000.0);
}
//---------------------------------------------------------------------
public void SetInitFineFuels(InputValue<double> newValue)
{
initFineFuels = VerifyRange(newValue, 0.0, 1.0);
}
//---------------------------------------------------------------------
public InputParameters(ISpeciesDataset speciesDataset, int litterCnt, int functionalCnt)
{
this.speciesDataset = speciesDataset;
functionalTypes = new FunctionalTypeTable(functionalCnt);
fireReductionsTable = new FireReductions[11];
harvestReductionsTable = new List<HarvestReductions>();
sppFunctionalType = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset);
nFixer = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset);
grass = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset);
nlog_depend = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset);
gddMin = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset);
gddMax = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset);
minJanTemp = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset);
maxDrought = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
leafLongevity = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
epicormic = new Landis.Library.Parameters.Species.AuxParm<bool>(speciesDataset);
leafLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
woodLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
coarseRootLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
fineRootLignin = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
leafCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
woodCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
coarseRootCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
foliageLitterCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
fineRootCN = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
maxANPP = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset);
maxBiomass = new Landis.Library.Parameters.Species.AuxParm<int>(speciesDataset);
growthLAI = new Landis.Library.Parameters.Species.AuxParm<double>(speciesDataset);
maximumShadeLAI = new double[6];
sufficientLight = new List<ISufficientLight>();
}
//---------------------------------------------------------------------
public static double VerifyRange(InputValue<double> newValue, double minValue, double maxValue)
{
if (newValue != null) {
if (newValue.Actual < minValue || newValue.Actual > maxValue)
throw new InputValueException(newValue.String,
"{0} is not between {1:0.0} and {2:0.0}",
newValue.String, minValue, maxValue);
}
return newValue.Actual;
}
public static double VerifyRange(double newValue, double minValue, double maxValue)
{
if (newValue < minValue || newValue > maxValue)
throw new InputValueException(newValue.ToString(),
"{0} is not between {1:0.0} and {2:0.0}",
newValue.ToString(), minValue, maxValue);
return newValue;
}
//---------------------------------------------------------------------
public static int VerifyRange(InputValue<int> newValue, int minValue, int maxValue)
{
if (newValue != null) {
if (newValue.Actual < minValue || newValue.Actual > maxValue)
throw new InputValueException(newValue.String,
"{0} is not between {1:0.0} and {2:0.0}",
newValue.String, minValue, maxValue);
}
return newValue.Actual;
}
public static int VerifyRange(int newValue, int minValue, int maxValue)
{
if (newValue < minValue || newValue > maxValue)
throw new InputValueException(newValue.ToString(),
"{0} is not between {1:0.0} and {2:0.0}",
newValue.ToString(), minValue, maxValue);
return newValue;
}
//---------------------------------------------------------------------
private void ValidatePath(string path)
{
if (string.IsNullOrEmpty(path))
throw new InputValueException();
if (path.Trim(null).Length == 0)
throw new InputValueException(path,
"\"{0}\" is not a valid path.",
path);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Cluster
{
using System;
/// <summary>
/// Represents runtime information of a cluster. Apart from obvious
/// statistical value, this information is used for implementation of
/// load balancing, failover, and collision SPIs. For example, collision SPI
/// in combination with fail-over SPI could check if other nodes don't have
/// any active or waiting jobs and fail-over some jobs to those nodes.
/// <para />
/// Node metrics for any node can be accessed via <see cref="IClusterNode.GetMetrics"/>
/// method. Keep in mind that there will be a certain network delay (usually
/// equal to heartbeat delay) for the accuracy of node metrics. However, when accessing
/// metrics on local node the metrics are always accurate and up to date.
/// </summary>
public interface IClusterMetrics
{
/// <summary>
/// Last update time of this node metrics.
/// </summary>
DateTime LastUpdateTime { get; }
/// <summary>
/// Maximum number of jobs that ever ran concurrently on this node.
/// </summary>
int MaximumActiveJobs { get; }
/// <summary>
/// Number of currently active jobs concurrently executing on the node.
/// </summary>
int CurrentActiveJobs { get; }
/// <summary>
/// Average number of active jobs.
/// </summary>
float AverageActiveJobs { get; }
/// <summary>
/// Maximum number of waiting jobs.
/// </summary>
int MaximumWaitingJobs { get; }
/// <summary>
/// Number of queued jobs currently waiting to be executed.
/// </summary>
int CurrentWaitingJobs { get; }
/// <summary>
/// Average number of waiting jobs.
/// </summary>
float AverageWaitingJobs { get; }
/// <summary>
/// Maximum number of jobs rejected at once.
/// </summary>
int MaximumRejectedJobs { get; }
/// <summary>
/// Number of jobs rejected after more recent collision resolution operation.
/// </summary>
int CurrentRejectedJobs { get; }
/// <summary>
/// Average number of jobs this node rejects during collision resolution operations.
/// </summary>
float AverageRejectedJobs { get; }
/// <summary>
/// Total number of jobs this node rejects during collision resolution operations since node startup.
/// </summary>
int TotalRejectedJobs { get; }
/// <summary>
/// Maximum number of cancelled jobs ever had running concurrently.
/// </summary>
int MaximumCancelledJobs { get; }
/// <summary>
/// Number of cancelled jobs that are still running.
/// </summary>
int CurrentCancelledJobs { get; }
/// <summary>
/// Average number of cancelled jobs.
/// </summary>
float AverageCancelledJobs { get; }
/// <summary>
/// Total number of cancelled jobs since node startup.
/// </summary>
int TotalCancelledJobs { get; }
/// <summary>
/// Total number of jobs handled by the node since node startup.
/// </summary>
int TotalExecutedJobs { get; }
/// <summary>
/// Maximum time a job ever spent waiting in a queue to be executed.
/// </summary>
long MaximumJobWaitTime { get; }
/// <summary>
/// Current time an oldest jobs has spent waiting to be executed.
/// </summary>
long CurrentJobWaitTime { get; }
/// <summary>
/// Average time jobs spend waiting in the queue to be executed.
/// </summary>
double AverageJobWaitTime { get; }
/// <summary>
/// Time it took to execute the longest job on the node.
/// </summary>
long MaximumJobExecuteTime { get; }
/// <summary>
/// Longest time a current job has been executing for.
/// </summary>
long CurrentJobExecuteTime { get; }
/// <summary>
/// Average job execution time.
/// </summary>
double AverageJobExecuteTime { get; }
/// <summary>
/// Total number of jobs handled by the node.
/// </summary>
int TotalExecutedTasks { get; }
/// <summary>
/// Total time this node spent executing jobs.
/// </summary>
long TotalBusyTime { get; }
/// <summary>
/// Total time this node spent idling.
/// </summary>
long TotalIdleTime { get; }
/// <summary>
/// Time this node spend idling since executing last job.
/// </summary>
long CurrentIdleTime { get; }
/// <summary>
/// Percentage of time this node is busy.
/// </summary>
float BusyTimePercentage { get; }
/// <summary>
/// Percentage of time this node is idle
/// </summary>
float IdleTimePercentage { get; }
/// <summary>
/// Returns the number of CPUs available to the Java Virtual Machine.
/// </summary>
int TotalCpus { get; }
/// <summary>
/// Returns the CPU usage usage in [0, 1] range.
/// </summary>
double CurrentCpuLoad { get; }
/// <summary>
/// Average of CPU load values in [0, 1] range over all metrics kept in the history.
/// </summary>
double AverageCpuLoad { get; }
/// <summary>
/// Average time spent in CG since the last update.
/// </summary>
double CurrentGcCpuLoad { get; }
/// <summary>
/// Amount of heap memory in bytes that the JVM
/// initially requests from the operating system for memory management.
/// This method returns <code>-1</code> if the initial memory size is undefined.
/// <para />
/// This value represents a setting of the heap memory for Java VM and is
/// not a sum of all initial heap values for all memory pools.
/// </summary>
long HeapMemoryInitialized { get; }
/// <summary>
/// Current heap size that is used for object allocation.
/// The heap consists of one or more memory pools. This value is
/// the sum of used heap memory values of all heap memory pools.
/// <para />
/// The amount of used memory in the returned is the amount of memory
/// occupied by both live objects and garbage objects that have not
/// been collected, if any.
/// </summary>
long HeapMemoryUsed { get; }
/// <summary>
/// Amount of heap memory in bytes that is committed for the JVM to use. This amount of memory is
/// guaranteed for the JVM to use. The heap consists of one or more memory pools. This value is
/// the sum of committed heap memory values of all heap memory pools.
/// </summary>
long HeapMemoryCommitted { get; }
/// <summary>
/// Mmaximum amount of heap memory in bytes that can be used for memory management.
/// This method returns <code>-1</code> if the maximum memory size is undefined.
/// <para />
/// This amount of memory is not guaranteed to be available for memory management if
/// it is greater than the amount of committed memory. The JVM may fail to allocate
/// memory even if the amount of used memory does not exceed this maximum size.
/// <para />
/// This value represents a setting of the heap memory for Java VM and is
/// not a sum of all initial heap values for all memory pools.
/// </summary>
long HeapMemoryMaximum { get; }
/// <summary>
/// Total amount of heap memory in bytes. This method returns <code>-1</code>
/// if the total memory size is undefined.
/// <para />
/// This amount of memory is not guaranteed to be available for memory management if it is
/// greater than the amount of committed memory. The JVM may fail to allocate memory even
/// if the amount of used memory does not exceed this maximum size.
/// <para />
/// This value represents a setting of the heap memory for Java VM and is
/// not a sum of all initial heap values for all memory pools.
/// </summary>
long HeapMemoryTotal { get; }
/// <summary>
/// Amount of non-heap memory in bytes that the JVM initially requests from the operating
/// system for memory management.
/// </summary>
long NonHeapMemoryInitialized { get; }
/// <summary>
/// Current non-heap memory size that is used by Java VM.
/// </summary>
long NonHeapMemoryUsed { get; }
/// <summary>
/// Amount of non-heap memory in bytes that is committed for the JVM to use.
/// </summary>
long NonHeapMemoryCommitted { get; }
/// <summary>
/// Maximum amount of non-heap memory in bytes that can be used for memory management.
/// </summary>
long NonHeapMemoryMaximum { get; }
/// <summary>
/// Total amount of non-heap memory in bytes that can be used for memory management.
/// </summary>
long NonHeapMemoryTotal { get; }
/// <summary>
/// Uptime of the JVM in milliseconds.
/// </summary>
long Uptime { get; }
/// <summary>
/// Start time of the JVM in milliseconds.
/// </summary>
DateTime StartTime { get; }
/// <summary>
/// Start time of the Ignite node in milliseconds.
/// </summary>
DateTime NodeStartTime { get; }
/// <summary>
/// Current number of live threads.
/// </summary>
int CurrentThreadCount { get; }
/// <summary>
/// The peak live thread count.
/// </summary>
int MaximumThreadCount { get; }
/// <summary>
/// The total number of threads started.
/// </summary>
long TotalStartedThreadCount { get; }
/// <summary>
/// Current number of live daemon threads.
/// </summary>
int CurrentDaemonThreadCount { get; }
/// <summary>
/// Ignite assigns incremental versions to all cache operations. This property provides
/// the latest data version on the node.
/// </summary>
long LastDataVersion { get; }
/// <summary>
/// Sent messages count
/// </summary>
int SentMessagesCount { get; }
/// <summary>
/// Sent bytes count.
/// </summary>
long SentBytesCount { get; }
/// <summary>
/// Received messages count.
/// </summary>
int ReceivedMessagesCount { get; }
/// <summary>
/// Received bytes count.
/// </summary>
long ReceivedBytesCount { get; }
/// <summary>
/// Outbound messages queue size.
/// </summary>
int OutboundMessagesQueueSize { get; }
/// <summary>
/// Gets total number of nodes.
/// </summary>
int TotalNodes { get; }
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using FileHelpers;
namespace FileHelpersSamples
{
/// <summary>
/// Run the engine in Async mode to speed
/// the processing times of the file up.
/// </summary>
public class frmEasySampleAsync : frmFather
{
private TextBox txtClass;
private Button cmdRun;
private Label label2;
private Label label1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox txtOut;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public frmEasySampleAsync()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof (frmEasySampleAsync));
this.txtClass = new System.Windows.Forms.TextBox();
this.cmdRun = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.txtOut = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// pictureBox3
//
//
// txtClass
//
this.txtClass.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.txtClass.Location = new System.Drawing.Point(8, 288);
this.txtClass.Multiline = true;
this.txtClass.Name = "txtClass";
this.txtClass.ReadOnly = true;
this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtClass.Size = new System.Drawing.Size(328, 160);
this.txtClass.TabIndex = 0;
this.txtClass.Text = resources.GetString("txtClass.Text");
this.txtClass.WordWrap = false;
//
// cmdRun
//
this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((int) (((byte) (0)))),
((int) (((byte) (0)))),
((int) (((byte) (110)))));
this.cmdRun.Font = new System.Drawing.Font("Tahoma",
9.75F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.cmdRun.ForeColor = System.Drawing.Color.White;
this.cmdRun.Location = new System.Drawing.Point(336, 8);
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(152, 32);
this.cmdRun.TabIndex = 0;
this.cmdRun.Text = "RUN >>";
this.cmdRun.UseVisualStyleBackColor = false;
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(8, 272);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(216, 16);
this.label2.TabIndex = 7;
this.label2.Text = "Code of the Mapping Class";
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(344, 272);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(216, 16);
this.label1.TabIndex = 8;
this.label1.Text = "Console Output";
//
// label4
//
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(8, 64);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(152, 16);
this.label4.TabIndex = 10;
this.label4.Text = "Code to Read the File";
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.textBox1.Location = new System.Drawing.Point(8, 80);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(656, 184);
this.textBox1.TabIndex = 11;
this.textBox1.Text = resources.GetString("textBox1.Text");
this.textBox1.WordWrap = false;
//
// txtOut
//
this.txtOut.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((byte) (0)));
this.txtOut.Location = new System.Drawing.Point(344, 288);
this.txtOut.Multiline = true;
this.txtOut.Name = "txtOut";
this.txtOut.ReadOnly = true;
this.txtOut.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtOut.Size = new System.Drawing.Size(328, 160);
this.txtOut.TabIndex = 12;
this.txtOut.WordWrap = false;
//
// frmEasySampleAsync
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(680, 480);
this.Controls.Add(this.txtOut);
this.Controls.Add(this.label4);
this.Controls.Add(this.label1);
this.Controls.Add(this.label2);
this.Controls.Add(this.cmdRun);
this.Controls.Add(this.txtClass);
this.Controls.Add(this.textBox1);
this.Name = "frmEasySampleAsync";
this.Text = "FileHelpers - Easy Example";
this.Controls.SetChildIndex(this.textBox1, 0);
this.Controls.SetChildIndex(this.txtClass, 0);
this.Controls.SetChildIndex(this.cmdRun, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.label4, 0);
this.Controls.SetChildIndex(this.txtOut, 0);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// Run the Async engine with a vertical bar file
/// </summary>
private void cmdRun_Click(object sender, EventArgs e)
{
txtOut.Text = string.Empty;
var engine = new FileHelperAsyncEngine<CustomersVerticalBar>();
engine.BeginReadString(TestData.mCustomersTest);
// The Async engines are IEnumerable
foreach (CustomersVerticalBar cust in engine) {
// your code here
txtOut.Text += cust.CustomerID + " - " + cust.ContactTitle + Environment.NewLine;
}
engine.Close();
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
internal class MessageGenerator : SourceGeneratorBase<MessageDescriptor>, ISourceGenerator
{
private string[] _fieldNames;
internal MessageGenerator(MessageDescriptor descriptor) : base(descriptor)
{
}
private string ClassName
{
get { return Descriptor.Name; }
}
private string FullClassName
{
get { return GetClassName(Descriptor); }
}
/// <summary>
/// Get an identifier that uniquely identifies this type within the file.
/// This is used to declare static variables related to this type at the
/// outermost file scope.
/// </summary>
private static string GetUniqueFileScopeIdentifier(IDescriptor descriptor)
{
return "static_" + descriptor.FullName.Replace(".", "_");
}
internal void GenerateStaticVariables(TextGenerator writer)
{
// Because descriptor.proto (Google.ProtocolBuffers.DescriptorProtos) is
// used in the construction of descriptors, we have a tricky bootstrapping
// problem. To help control static initialization order, we make sure all
// descriptors and other static data that depends on them are members of
// the proto-descriptor class. This way, they will be initialized in
// a deterministic order.
string identifier = GetUniqueFileScopeIdentifier(Descriptor);
if (!UseLiteRuntime)
{
// The descriptor for this type.
string access = Descriptor.File.CSharpOptions.NestClasses ? "private" : "internal";
writer.WriteLine("{0} static pbd::MessageDescriptor internal__{1}__Descriptor;", access, identifier);
writer.WriteLine(
"{0} static pb::FieldAccess.FieldAccessorTable<{1}, {1}.Builder> internal__{2}__FieldAccessorTable;",
access, FullClassName, identifier);
}
// Generate static members for all nested types.
foreach (MessageDescriptor nestedMessage in Descriptor.NestedTypes)
{
new MessageGenerator(nestedMessage).GenerateStaticVariables(writer);
}
}
internal void GenerateStaticVariableInitializers(TextGenerator writer)
{
string identifier = GetUniqueFileScopeIdentifier(Descriptor);
if (!UseLiteRuntime)
{
writer.Write("internal__{0}__Descriptor = ", identifier);
if (Descriptor.ContainingType == null)
{
writer.WriteLine("Descriptor.MessageTypes[{0}];", Descriptor.Index);
}
else
{
writer.WriteLine("internal__{0}__Descriptor.NestedTypes[{1}];",
GetUniqueFileScopeIdentifier(Descriptor.ContainingType), Descriptor.Index);
}
writer.WriteLine("internal__{0}__FieldAccessorTable = ", identifier);
writer.WriteLine(
" new pb::FieldAccess.FieldAccessorTable<{1}, {1}.Builder>(internal__{0}__Descriptor,",
identifier, FullClassName);
writer.Print(" new string[] { ");
foreach (FieldDescriptor field in Descriptor.Fields)
{
writer.Write("\"{0}\", ", field.CSharpOptions.PropertyName);
}
writer.WriteLine("});");
}
// Generate static member initializers for all nested types.
foreach (MessageDescriptor nestedMessage in Descriptor.NestedTypes)
{
new MessageGenerator(nestedMessage).GenerateStaticVariableInitializers(writer);
}
foreach (FieldDescriptor extension in Descriptor.Extensions)
{
new ExtensionGenerator(extension).GenerateStaticVariableInitializers(writer);
}
}
public string[] FieldNames
{
get
{
if (_fieldNames == null)
{
List<string> names = new List<string>();
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields)
{
names.Add(fieldDescriptor.Name);
}
//if you change this, the search must also change in GenerateBuilderParsingMethods
names.Sort(StringComparer.Ordinal);
_fieldNames = names.ToArray();
}
return _fieldNames;
}
}
internal int FieldOrdinal(FieldDescriptor field)
{
return Array.BinarySearch(FieldNames, field.Name, StringComparer.Ordinal);
}
private IFieldSourceGenerator CreateFieldGenerator(FieldDescriptor fieldDescriptor)
{
return SourceGenerators.CreateFieldGenerator(fieldDescriptor, FieldOrdinal(fieldDescriptor));
}
public void Generate(TextGenerator writer)
{
if (Descriptor.File.CSharpOptions.AddSerializable)
{
writer.WriteLine("[global::System.SerializableAttribute()]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
WriteGeneratedCodeAttributes(writer);
writer.WriteLine("{0} sealed partial class {1} : pb::{2}Message{3}<{1}, {1}.Builder> {{",
ClassAccessLevel, ClassName,
Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated",
RuntimeSuffix);
writer.Indent();
if (Descriptor.File.CSharpOptions.GeneratePrivateCtor)
{
writer.WriteLine("private {0}() {{ }}", ClassName);
}
// Must call MakeReadOnly() to make sure all lists are made read-only
writer.WriteLine("private static readonly {0} defaultInstance = new {0}().MakeReadOnly();", ClassName);
if (OptimizeSpeed)
{
writer.WriteLine("private static readonly string[] _{0}FieldNames = new string[] {{ {2}{1}{2} }};",
NameHelpers.UnderscoresToCamelCase(ClassName), String.Join("\", \"", FieldNames),
FieldNames.Length > 0 ? "\"" : "");
List<string> tags = new List<string>();
foreach (string name in FieldNames)
{
tags.Add(WireFormat.MakeTag(Descriptor.FindFieldByName(name)).ToString());
}
writer.WriteLine("private static readonly uint[] _{0}FieldTags = new uint[] {{ {1} }};",
NameHelpers.UnderscoresToCamelCase(ClassName), String.Join(", ", tags.ToArray()));
}
writer.WriteLine("public static {0} DefaultInstance {{", ClassName);
writer.WriteLine(" get { return defaultInstance; }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override {0} DefaultInstanceForType {{", ClassName);
writer.WriteLine(" get { return DefaultInstance; }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("protected override {0} ThisMessage {{", ClassName);
writer.WriteLine(" get { return this; }");
writer.WriteLine("}");
writer.WriteLine();
if (!UseLiteRuntime)
{
writer.WriteLine("public static pbd::MessageDescriptor Descriptor {");
writer.WriteLine(" get {{ return {0}.internal__{1}__Descriptor; }}",
DescriptorUtil.GetFullUmbrellaClassName(Descriptor),
GetUniqueFileScopeIdentifier(Descriptor));
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine(
"protected override pb::FieldAccess.FieldAccessorTable<{0}, {0}.Builder> InternalFieldAccessors {{",
ClassName);
writer.WriteLine(" get {{ return {0}.internal__{1}__FieldAccessorTable; }}",
DescriptorUtil.GetFullUmbrellaClassName(Descriptor),
GetUniqueFileScopeIdentifier(Descriptor));
writer.WriteLine("}");
writer.WriteLine();
}
// Extensions don't need to go in an extra nested type
WriteChildren(writer, null, Descriptor.Extensions);
if (Descriptor.EnumTypes.Count + Descriptor.NestedTypes.Count > 0)
{
writer.WriteLine("#region Nested types");
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
WriteGeneratedCodeAttributes(writer);
writer.WriteLine("public static partial class Types {");
writer.Indent();
WriteChildren(writer, null, Descriptor.EnumTypes);
WriteChildren(writer, null, Descriptor.NestedTypes);
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine("#endregion");
writer.WriteLine();
}
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields)
{
if (Descriptor.File.CSharpOptions.ClsCompliance && GetFieldConstantName(fieldDescriptor).StartsWith("_"))
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
// Rats: we lose the debug comment here :(
writer.WriteLine("public const int {0} = {1};", GetFieldConstantName(fieldDescriptor),
fieldDescriptor.FieldNumber);
CreateFieldGenerator(fieldDescriptor).GenerateMembers(writer);
writer.WriteLine();
}
if (OptimizeSpeed)
{
GenerateIsInitialized(writer);
GenerateMessageSerializationMethods(writer);
}
if (UseLiteRuntime)
{
GenerateLiteRuntimeMethods(writer);
}
GenerateParseFromMethods(writer);
GenerateBuilder(writer);
// Force the static initialization code for the file to run, since it may
// initialize static variables declared in this class.
writer.WriteLine("static {0}() {{", ClassName);
// We call object.ReferenceEquals() just to make it a valid statement on its own.
// Another option would be GetType(), but that causes problems in DescriptorProtoFile,
// where the bootstrapping is somewhat recursive - type initializers call
// each other, effectively. We temporarily see Descriptor as null.
writer.WriteLine(" object.ReferenceEquals({0}.Descriptor, null);",
DescriptorUtil.GetFullUmbrellaClassName(Descriptor));
writer.WriteLine("}");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
}
private void GenerateLiteRuntimeMethods(TextGenerator writer)
{
bool callbase = Descriptor.Proto.ExtensionRangeCount > 0;
writer.WriteLine("#region Lite runtime methods");
writer.WriteLine("public override int GetHashCode() {");
writer.Indent();
writer.WriteLine("int hash = GetType().GetHashCode();");
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields)
{
CreateFieldGenerator(fieldDescriptor).WriteHash(writer);
}
if (callbase)
{
writer.WriteLine("hash ^= base.GetHashCode();");
}
writer.WriteLine("return hash;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override bool Equals(object obj) {");
writer.Indent();
writer.WriteLine("{0} other = obj as {0};", ClassName);
writer.WriteLine("if (other == null) return false;");
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields)
{
CreateFieldGenerator(fieldDescriptor).WriteEquals(writer);
}
if (callbase)
{
writer.WriteLine("if (!base.Equals(other)) return false;");
}
writer.WriteLine("return true;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override void PrintTo(global::System.IO.TextWriter writer) {");
writer.Indent();
List<FieldDescriptor> sorted = new List<FieldDescriptor>(Descriptor.Fields);
sorted.Sort(
new Comparison<FieldDescriptor>(
delegate(FieldDescriptor a, FieldDescriptor b) { return a.FieldNumber.CompareTo(b.FieldNumber); }));
foreach (FieldDescriptor fieldDescriptor in sorted)
{
CreateFieldGenerator(fieldDescriptor).WriteToString(writer);
}
if (callbase)
{
writer.WriteLine("base.PrintTo(writer);");
}
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine("#endregion");
writer.WriteLine();
}
private void GenerateMessageSerializationMethods(TextGenerator writer)
{
List<FieldDescriptor> sortedFields = new List<FieldDescriptor>(Descriptor.Fields);
sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber));
List<DescriptorProto.Types.ExtensionRange> sortedExtensions =
new List<DescriptorProto.Types.ExtensionRange>(Descriptor.Proto.ExtensionRangeList);
sortedExtensions.Sort((r1, r2) => (r1.Start.CompareTo(r2.Start)));
writer.WriteLine("public override void WriteTo(pb::ICodedOutputStream output) {");
writer.Indent();
// Make sure we've computed the serialized length, so that packed fields are generated correctly.
writer.WriteLine("CalcSerializedSize();");
writer.WriteLine("string[] field_names = _{0}FieldNames;", NameHelpers.UnderscoresToCamelCase(ClassName));
if (Descriptor.Proto.ExtensionRangeList.Count > 0)
{
writer.WriteLine(
"pb::ExtendableMessage{1}<{0}, {0}.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);",
ClassName, RuntimeSuffix);
}
// Merge the fields and the extension ranges, both sorted by field number.
for (int i = 0, j = 0; i < Descriptor.Fields.Count || j < sortedExtensions.Count;)
{
if (i == Descriptor.Fields.Count)
{
GenerateSerializeOneExtensionRange(writer, sortedExtensions[j++]);
}
else if (j == sortedExtensions.Count)
{
GenerateSerializeOneField(writer, sortedFields[i++]);
}
else if (sortedFields[i].FieldNumber < sortedExtensions[j].Start)
{
GenerateSerializeOneField(writer, sortedFields[i++]);
}
else
{
GenerateSerializeOneExtensionRange(writer, sortedExtensions[j++]);
}
}
if (!UseLiteRuntime)
{
if (Descriptor.Proto.Options.MessageSetWireFormat)
{
writer.WriteLine("UnknownFields.WriteAsMessageSetTo(output);");
}
else
{
writer.WriteLine("UnknownFields.WriteTo(output);");
}
}
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("private int memoizedSerializedSize = -1;");
writer.WriteLine("public override int SerializedSize {");
writer.Indent();
writer.WriteLine("get {");
writer.Indent();
writer.WriteLine("int size = memoizedSerializedSize;");
writer.WriteLine("if (size != -1) return size;");
writer.WriteLine("return CalcSerializedSize();");
writer.Outdent();
writer.WriteLine("}");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("private int CalcSerializedSize() {");
writer.Indent();
writer.WriteLine("int size = memoizedSerializedSize;");
writer.WriteLine("if (size != -1) return size;");
writer.WriteLine();
writer.WriteLine("size = 0;");
foreach (FieldDescriptor field in Descriptor.Fields)
{
CreateFieldGenerator(field).GenerateSerializedSizeCode(writer);
}
if (Descriptor.Proto.ExtensionRangeCount > 0)
{
writer.WriteLine("size += ExtensionsSerializedSize;");
}
if (!UseLiteRuntime)
{
if (Descriptor.Options.MessageSetWireFormat)
{
writer.WriteLine("size += UnknownFields.SerializedSizeAsMessageSet;");
}
else
{
writer.WriteLine("size += UnknownFields.SerializedSize;");
}
}
writer.WriteLine("memoizedSerializedSize = size;");
writer.WriteLine("return size;");
writer.Outdent();
writer.WriteLine("}");
}
private void GenerateSerializeOneField(TextGenerator writer, FieldDescriptor fieldDescriptor)
{
CreateFieldGenerator(fieldDescriptor).GenerateSerializationCode(writer);
}
private static void GenerateSerializeOneExtensionRange(TextGenerator writer,
DescriptorProto.Types.ExtensionRange extensionRange)
{
writer.WriteLine("extensionWriter.WriteUntil({0}, output);", extensionRange.End);
}
private void GenerateParseFromMethods(TextGenerator writer)
{
// Note: These are separate from GenerateMessageSerializationMethods()
// because they need to be generated even for messages that are optimized
// for code size.
writer.WriteLine("public static {0} ParseFrom(pb::ByteString data) {{", ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine(
"public static {0} ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {{",
ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine("public static {0} ParseFrom(byte[] data) {{", ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine("public static {0} ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {{",
ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine("public static {0} ParseFrom(global::System.IO.Stream input) {{", ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine(
"public static {0} ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {{",
ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine("public static {0} ParseDelimitedFrom(global::System.IO.Stream input) {{", ClassName);
writer.WriteLine(" return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine(
"public static {0} ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {{",
ClassName);
writer.WriteLine(" return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine("public static {0} ParseFrom(pb::ICodedInputStream input) {{", ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();");
writer.WriteLine("}");
writer.WriteLine(
"public static {0} ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {{",
ClassName);
writer.WriteLine(" return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();");
writer.WriteLine("}");
}
/// <summary>
/// Returns whether or not the specified message type has any required fields.
/// If it doesn't, calls to check for initialization can be optimised.
/// TODO(jonskeet): Move this into MessageDescriptor?
/// </summary>
private static bool HasRequiredFields(MessageDescriptor descriptor,
Dictionary<MessageDescriptor, object> alreadySeen)
{
if (alreadySeen.ContainsKey(descriptor))
{
// The type is already in cache. This means that either:
// a. The type has no required fields.
// b. We are in the midst of checking if the type has required fields,
// somewhere up the stack. In this case, we know that if the type
// has any required fields, they'll be found when we return to it,
// and the whole call to HasRequiredFields() will return true.
// Therefore, we don't have to check if this type has required fields
// here.
return false;
}
alreadySeen[descriptor] = descriptor; // Value is irrelevant
// If the type has extensions, an extension with message type could contain
// required fields, so we have to be conservative and assume such an
// extension exists.
if (descriptor.Extensions.Count > 0)
{
return true;
}
foreach (FieldDescriptor field in descriptor.Fields)
{
if (field.IsRequired)
{
return true;
}
// Message or group
if (field.MappedType == MappedType.Message)
{
if (HasRequiredFields(field.MessageType, alreadySeen))
{
return true;
}
}
}
return false;
}
private void GenerateBuilder(TextGenerator writer)
{
writer.WriteLine("private {0} MakeReadOnly() {{", ClassName);
writer.Indent();
foreach (FieldDescriptor field in Descriptor.Fields)
{
CreateFieldGenerator(field).GenerateBuildingCode(writer);
}
writer.WriteLine("return this;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public static Builder CreateBuilder() { return new Builder(); }");
writer.WriteLine("public override Builder ToBuilder() { return CreateBuilder(this); }");
writer.WriteLine("public override Builder CreateBuilderForType() { return new Builder(); }");
writer.WriteLine("public static Builder CreateBuilder({0} prototype) {{", ClassName);
writer.WriteLine(" return new Builder(prototype);");
writer.WriteLine("}");
writer.WriteLine();
if (Descriptor.File.CSharpOptions.AddSerializable)
{
writer.WriteLine("[global::System.SerializableAttribute()]");
}
writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]");
WriteGeneratedCodeAttributes(writer);
writer.WriteLine("{0} sealed partial class Builder : pb::{2}Builder{3}<{1}, Builder> {{",
ClassAccessLevel, ClassName,
Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated", RuntimeSuffix);
writer.Indent();
writer.WriteLine("protected override Builder ThisBuilder {");
writer.WriteLine(" get { return this; }");
writer.WriteLine("}");
GenerateCommonBuilderMethods(writer);
if (OptimizeSpeed)
{
GenerateBuilderParsingMethods(writer);
}
foreach (FieldDescriptor field in Descriptor.Fields)
{
writer.WriteLine();
// No field comment :(
CreateFieldGenerator(field).GenerateBuilderMembers(writer);
}
writer.Outdent();
writer.WriteLine("}");
}
private void GenerateCommonBuilderMethods(TextGenerator writer)
{
//default constructor
writer.WriteLine("public Builder() {");
//Durring static initialization of message, DefaultInstance is expected to return null.
writer.WriteLine(" result = DefaultInstance;");
writer.WriteLine(" resultIsReadOnly = true;");
writer.WriteLine("}");
//clone constructor
writer.WriteLine("internal Builder({0} cloneFrom) {{", ClassName);
writer.WriteLine(" result = cloneFrom;");
writer.WriteLine(" resultIsReadOnly = true;");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("private bool resultIsReadOnly;");
writer.WriteLine("private {0} result;", ClassName);
writer.WriteLine();
writer.WriteLine("private {0} PrepareBuilder() {{", ClassName);
writer.WriteLine(" if (resultIsReadOnly) {");
writer.WriteLine(" {0} original = result;", ClassName);
writer.WriteLine(" result = new {0}();", ClassName);
writer.WriteLine(" resultIsReadOnly = false;");
writer.WriteLine(" MergeFrom(original);");
writer.WriteLine(" }");
writer.WriteLine(" return result;");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override bool IsInitialized {");
writer.WriteLine(" get { return result.IsInitialized; }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("protected override {0} MessageBeingBuilt {{", ClassName);
writer.WriteLine(" get { return PrepareBuilder(); }");
writer.WriteLine("}");
writer.WriteLine();
//Not actually expecting that DefaultInstance would ever be null here; however, we will ensure it does not break
writer.WriteLine("public override Builder Clear() {");
writer.WriteLine(" result = DefaultInstance;", ClassName);
writer.WriteLine(" resultIsReadOnly = true;");
writer.WriteLine(" return this;");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override Builder Clone() {");
writer.WriteLine(" if (resultIsReadOnly) {");
writer.WriteLine(" return new Builder(result);");
writer.WriteLine(" } else {");
writer.WriteLine(" return new Builder().MergeFrom(result);");
writer.WriteLine(" }");
writer.WriteLine("}");
writer.WriteLine();
if (!UseLiteRuntime)
{
writer.WriteLine("public override pbd::MessageDescriptor DescriptorForType {");
writer.WriteLine(" get {{ return {0}.Descriptor; }}", FullClassName);
writer.WriteLine("}");
writer.WriteLine();
}
writer.WriteLine("public override {0} DefaultInstanceForType {{", ClassName);
writer.WriteLine(" get {{ return {0}.DefaultInstance; }}", FullClassName);
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override {0} BuildPartial() {{", ClassName);
writer.Indent();
writer.WriteLine("if (resultIsReadOnly) {");
writer.WriteLine(" return result;");
writer.WriteLine("}");
writer.WriteLine("resultIsReadOnly = true;");
writer.WriteLine("return result.MakeReadOnly();");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
if (OptimizeSpeed)
{
writer.WriteLine("public override Builder MergeFrom(pb::IMessage{0} other) {{", RuntimeSuffix);
writer.WriteLine(" if (other is {0}) {{", ClassName);
writer.WriteLine(" return MergeFrom(({0}) other);", ClassName);
writer.WriteLine(" } else {");
writer.WriteLine(" base.MergeFrom(other);");
writer.WriteLine(" return this;");
writer.WriteLine(" }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override Builder MergeFrom({0} other) {{", ClassName);
// Optimization: If other is the default instance, we know none of its
// fields are set so we can skip the merge.
writer.Indent();
writer.WriteLine("if (other == {0}.DefaultInstance) return this;", FullClassName);
writer.WriteLine("PrepareBuilder();");
foreach (FieldDescriptor field in Descriptor.Fields)
{
CreateFieldGenerator(field).GenerateMergingCode(writer);
}
// if message type has extensions
if (Descriptor.Proto.ExtensionRangeCount > 0)
{
writer.WriteLine(" this.MergeExtensionFields(other);");
}
if (!UseLiteRuntime)
{
writer.WriteLine("this.MergeUnknownFields(other.UnknownFields);");
}
writer.WriteLine("return this;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
}
}
private void GenerateBuilderParsingMethods(TextGenerator writer)
{
List<FieldDescriptor> sortedFields = new List<FieldDescriptor>(Descriptor.Fields);
sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber));
writer.WriteLine("public override Builder MergeFrom(pb::ICodedInputStream input) {");
writer.WriteLine(" return MergeFrom(input, pb::ExtensionRegistry.Empty);");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine(
"public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {");
writer.Indent();
writer.WriteLine("PrepareBuilder();");
if (!UseLiteRuntime)
{
writer.WriteLine("pb::UnknownFieldSet.Builder unknownFields = null;");
}
writer.WriteLine("uint tag;");
writer.WriteLine("string field_name;");
writer.WriteLine("while (input.ReadTag(out tag, out field_name)) {");
writer.Indent();
writer.WriteLine("if(tag == 0 && field_name != null) {");
writer.Indent();
//if you change from StringComparer.Ordinal, the array sort in FieldNames { get; } must also change
writer.WriteLine(
"int field_ordinal = global::System.Array.BinarySearch(_{0}FieldNames, field_name, global::System.StringComparer.Ordinal);",
NameHelpers.UnderscoresToCamelCase(ClassName));
writer.WriteLine("if(field_ordinal >= 0)");
writer.WriteLine(" tag = _{0}FieldTags[field_ordinal];", NameHelpers.UnderscoresToCamelCase(ClassName));
writer.WriteLine("else {");
if (!UseLiteRuntime)
{
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
}
writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag, field_name);",
UseLiteRuntime ? "" : "unknownFields, ");
writer.WriteLine(" continue;");
writer.WriteLine("}");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine("switch (tag) {");
writer.Indent();
writer.WriteLine("case 0: {"); // 0 signals EOF / limit reached
writer.WriteLine(" throw pb::InvalidProtocolBufferException.InvalidTag();");
writer.WriteLine("}");
writer.WriteLine("default: {");
writer.WriteLine(" if (pb::WireFormat.IsEndGroupTag(tag)) {");
if (!UseLiteRuntime)
{
writer.WriteLine(" if (unknownFields != null) {");
writer.WriteLine(" this.UnknownFields = unknownFields.Build();");
writer.WriteLine(" }");
}
writer.WriteLine(" return this;"); // it's an endgroup tag
writer.WriteLine(" }");
if (!UseLiteRuntime)
{
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
}
writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag, field_name);",
UseLiteRuntime ? "" : "unknownFields, ");
writer.WriteLine(" break;");
writer.WriteLine("}");
foreach (FieldDescriptor field in sortedFields)
{
WireFormat.WireType wt = WireFormat.GetWireType(field.FieldType);
uint tag = WireFormat.MakeTag(field.FieldNumber, wt);
if (field.IsRepeated &&
(wt == WireFormat.WireType.Varint || wt == WireFormat.WireType.Fixed32 ||
wt == WireFormat.WireType.Fixed64))
{
writer.WriteLine("case {0}:",
WireFormat.MakeTag(field.FieldNumber, WireFormat.WireType.LengthDelimited));
}
writer.WriteLine("case {0}: {{", tag);
writer.Indent();
CreateFieldGenerator(field).GenerateParsingCode(writer);
writer.WriteLine("break;");
writer.Outdent();
writer.WriteLine("}");
}
writer.Outdent();
writer.WriteLine("}");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
if (!UseLiteRuntime)
{
writer.WriteLine("if (unknownFields != null) {");
writer.WriteLine(" this.UnknownFields = unknownFields.Build();");
writer.WriteLine("}");
}
writer.WriteLine("return this;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
}
private void GenerateIsInitialized(TextGenerator writer)
{
writer.WriteLine("public override bool IsInitialized {");
writer.Indent();
writer.WriteLine("get {");
writer.Indent();
// Check that all required fields in this message are set.
// TODO(kenton): We can optimize this when we switch to putting all the
// "has" fields into a single bitfield.
foreach (FieldDescriptor field in Descriptor.Fields)
{
if (field.IsRequired)
{
writer.WriteLine("if (!has{0}) return false;", field.CSharpOptions.PropertyName);
}
}
// Now check that all embedded messages are initialized.
foreach (FieldDescriptor field in Descriptor.Fields)
{
if (field.FieldType != FieldType.Message ||
!HasRequiredFields(field.MessageType, new Dictionary<MessageDescriptor, object>()))
{
continue;
}
string propertyName = NameHelpers.UnderscoresToPascalCase(GetFieldName(field));
if (field.IsRepeated)
{
writer.WriteLine("foreach ({0} element in {1}List) {{", GetClassName(field.MessageType),
propertyName);
writer.WriteLine(" if (!element.IsInitialized) return false;");
writer.WriteLine("}");
}
else if (field.IsOptional)
{
writer.WriteLine("if (Has{0}) {{", propertyName);
writer.WriteLine(" if (!{0}.IsInitialized) return false;", propertyName);
writer.WriteLine("}");
}
else
{
writer.WriteLine("if (!{0}.IsInitialized) return false;", propertyName);
}
}
if (Descriptor.Proto.ExtensionRangeCount > 0)
{
writer.WriteLine("if (!ExtensionsAreInitialized) return false;");
}
writer.WriteLine("return true;");
writer.Outdent();
writer.WriteLine("}");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
}
internal void GenerateExtensionRegistrationCode(TextGenerator writer)
{
foreach (FieldDescriptor extension in Descriptor.Extensions)
{
new ExtensionGenerator(extension).GenerateExtensionRegistrationCode(writer);
}
foreach (MessageDescriptor nestedMessage in Descriptor.NestedTypes)
{
new MessageGenerator(nestedMessage).GenerateExtensionRegistrationCode(writer);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Common.Core;
using static Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO.MsBuildFileSystemWatcherEntries.EntryState;
using static Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO.MsBuildFileSystemWatcherEntries.EntryType;
namespace Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO {
public class MsBuildFileSystemWatcherEntries {
private readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase);
public bool ContainsFileEntry(string relativeFilePath) {
return _entries.ContainsKey(relativeFilePath);
}
public bool ContainsDirectoryEntry(string relativePath) {
relativePath = PathHelper.EnsureTrailingSlash(relativePath);
return GetDirectoryEntries(relativePath).Count() > 0;
}
public bool RescanRequired { get; private set; }
public void AddFile(string relativeFilePath, string shortPath) {
AddEntry(relativeFilePath, shortPath, File);
}
public void DeleteFile(string relativeFilePath) {
try {
Entry entry;
if (_entries.TryGetValue(relativeFilePath, out entry)) {
DeleteEntry(entry);
}
} catch (InvalidStateException) {
RescanRequired = true;
}
}
public void RenameFile(string previousRelativePath, string relativeFilePath, string shortPath) {
try {
RenameEntry(previousRelativePath, relativeFilePath, shortPath, File);
} catch (InvalidStateException) {
RescanRequired = true;
}
}
public void AddDirectory(string relativePath, string shortPath) {
AddEntry(relativePath, shortPath, Directory);
}
public void DeleteDirectory(string relativePath) {
try {
relativePath = PathHelper.EnsureTrailingSlash(relativePath);
foreach (var entry in GetDirectoryEntries(relativePath).ToList()) {
DeleteEntry(entry);
}
} catch (InvalidStateException) {
RescanRequired = true;
}
}
public ISet<string> RenameDirectory(string previousRelativePath, string relativePath, string shortPath) {
try {
previousRelativePath = PathHelper.EnsureTrailingSlash(previousRelativePath);
relativePath = PathHelper.EnsureTrailingSlash(relativePath);
shortPath = PathHelper.EnsureTrailingSlash(shortPath);
var newPaths = new HashSet<string>();
var entriesToRename = _entries.Values
.Where(v => v.State == Unchanged || v.State == Added || v.State == RenamedThenAdded)
.Where(v => EntryPathStartsWith(v, previousRelativePath)).ToList();
foreach (var entry in entriesToRename) {
var newEntryPath = entry.RelativePath.Replace(previousRelativePath, relativePath, 0, previousRelativePath.Length);
RenameEntry(entry.RelativePath, newEntryPath, shortPath, entry.Type);
newPaths.Add(newEntryPath);
}
return newPaths;
} catch (InvalidStateException) {
RescanRequired = true;
return null;
}
}
public void MarkAllDeleted() {
foreach (var entry in _entries.Values.ToList()) {
entry.PreviousRelativePath = null;
switch (entry.State) {
case Unchanged:
case Renamed:
case RenamedThenAdded:
entry.State = Deleted;
break;
case Added:
_entries.Remove(entry.RelativePath);
break;
case Deleted:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
RescanRequired = false;
}
private IEnumerable<Entry> GetDirectoryEntries(string relativeDirectoryPath) =>
_entries.Values.Where(v => EntryPathStartsWith(v, relativeDirectoryPath));
private bool EntryPathStartsWith(Entry v, string relativePath) =>
v.RelativePath.StartsWithIgnoreCase(relativePath) || v.ShortPath.StartsWithIgnoreCase(relativePath);
private Entry AddEntry(string relativeFilePath, string shortPath, EntryType type) {
if (type == EntryType.Directory) {
relativeFilePath = PathHelper.EnsureTrailingSlash(relativeFilePath);
shortPath = PathHelper.EnsureTrailingSlash(shortPath);
}
Entry entry;
if (!_entries.TryGetValue(relativeFilePath, out entry)) {
entry = new Entry(relativeFilePath, shortPath, type) {
State = Added
};
_entries[relativeFilePath] = entry;
return entry;
}
switch (entry.State) {
case Unchanged:
case RenamedThenAdded:
case Added:
break;
case Deleted:
entry.State = Unchanged;
break;
case Renamed:
entry.State = RenamedThenAdded;
break;
default:
throw new ArgumentOutOfRangeException();
}
return entry;
}
private void DeleteEntry(Entry entry) {
switch (entry.State) {
case Unchanged:
entry.State = Deleted;
return;
case Added:
_entries.Remove(entry.RelativePath);
UpdateRenamedEntryOnDelete(entry);
return;
case Deleted:
return;
case RenamedThenAdded:
entry.State = Renamed;
UpdateRenamedEntryOnDelete(entry);
return;
case Renamed:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
private void RenameEntry(string previousRelativePath, string relativePath, string shortPath, EntryType type) {
Entry renamedEntry;
if (_entries.TryGetValue(previousRelativePath, out renamedEntry)) {
switch (renamedEntry.State) {
case Unchanged:
renamedEntry.State = Renamed;
var entry = AddEntry(relativePath, shortPath, type);
entry.PreviousRelativePath = previousRelativePath;
return;
case Added:
_entries.Remove(previousRelativePath);
if (renamedEntry.PreviousRelativePath == null) {
AddEntry(relativePath, shortPath, type);
} else {
UpdateRenamingChain(renamedEntry, relativePath, shortPath, type);
}
return;
case RenamedThenAdded:
renamedEntry.State = Renamed;
if (renamedEntry.PreviousRelativePath == null) {
AddEntry(relativePath, shortPath, type);
} else {
UpdateRenamingChain(renamedEntry, relativePath, shortPath, type);
renamedEntry.PreviousRelativePath = null;
}
return;
case Deleted:
case Renamed:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
}
private void UpdateRenamingChain(Entry renamedEntry, string relativePath, string shortPath, EntryType type) {
var previouslyRenamedEntryPath = renamedEntry.PreviousRelativePath;
Entry previouslyRenamedEntry;
if (!_entries.TryGetValue(previouslyRenamedEntryPath, out previouslyRenamedEntry)) {
return;
}
if (previouslyRenamedEntryPath == relativePath) {
switch (previouslyRenamedEntry.State) {
case Renamed:
previouslyRenamedEntry.State = Unchanged;
return;
case RenamedThenAdded:
case Unchanged:
case Added:
case Deleted:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
var entry = AddEntry(relativePath, shortPath, type);
entry.PreviousRelativePath = previouslyRenamedEntryPath;
}
private void UpdateRenamedEntryOnDelete(Entry entry) {
if (entry.PreviousRelativePath == null) {
return;
}
Entry renamedEntry;
if (!_entries.TryGetValue(entry.PreviousRelativePath, out renamedEntry)) {
return;
}
switch (renamedEntry.State) {
case Renamed:
renamedEntry.State = Deleted;
return;
case RenamedThenAdded:
renamedEntry.State = Added;
return;
case Unchanged:
case Added:
case Deleted:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
public MsBuildFileSystemWatcher.Changeset ProduceChangeset() {
var changeset = new MsBuildFileSystemWatcher.Changeset();
foreach (var entry in _entries.Values.ToList()) {
switch (entry.State) {
case Added:
case RenamedThenAdded:
if (entry.PreviousRelativePath != null) {
switch (entry.Type) {
case File:
changeset.RenamedFiles.Add(entry.PreviousRelativePath, entry.RelativePath);
break;
case Directory:
changeset.RenamedDirectories.Add(entry.PreviousRelativePath, entry.RelativePath);
break;
default:
throw new ArgumentOutOfRangeException();
}
} else {
switch (entry.Type) {
case File:
changeset.AddedFiles.Add(entry.RelativePath);
break;
case Directory:
changeset.AddedDirectories.Add(entry.RelativePath);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
entry.State = Unchanged;
break;
case Deleted:
switch (entry.Type) {
case File:
changeset.RemovedFiles.Add(entry.RelativePath);
break;
case Directory:
changeset.RemovedDirectories.Add(entry.RelativePath);
break;
default:
throw new ArgumentOutOfRangeException();
}
_entries.Remove(entry.RelativePath);
break;
case Renamed:
_entries.Remove(entry.RelativePath);
break;
default:
entry.State = Unchanged;
break;
}
}
return changeset;
}
[DebuggerDisplay("{Type} {PreviousRelativePath == null ? RelativePath : PreviousRelativePath + \" -> \" + RelativePath}, {State}")]
private class Entry {
public Entry(string relativePath, string shortPath, EntryType type) {
RelativePath = relativePath;
ShortPath = shortPath;
Type = type;
}
public string RelativePath { get; }
public EntryType Type { get; }
public string PreviousRelativePath { get; set; }
public EntryState State { get; set; } = Unchanged;
public string ShortPath { get; }
}
private class InvalidStateException : Exception {
}
internal enum EntryState {
Unchanged,
Added,
Deleted,
Renamed,
// This state marks special case when file/directory was first renamed and then another file/directory with the same name was added
RenamedThenAdded
}
internal enum EntryType {
File,
Directory
}
}
}
| |
namespace Mepham.Forum.DataAccess.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class InitialMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Comments",
c => new
{
Id = c.Guid(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "NEWID()")
},
}),
Description = c.String(nullable: false),
AuthorId = c.Guid(nullable: false),
PostId = c.Guid(nullable: false),
ResponseToCommentId = c.Guid(),
CreateDateTime = c.DateTime(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "GETDATE()")
},
}),
UpdateDateTime = c.DateTime(),
DeleteDateTime = c.DateTime(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Posts", t => t.PostId)
.ForeignKey("dbo.Users", t => t.AuthorId)
.ForeignKey("dbo.Comments", t => t.ResponseToCommentId)
.Index(t => t.AuthorId)
.Index(t => t.PostId)
.Index(t => t.ResponseToCommentId);
CreateTable(
"dbo.Users",
c => new
{
Id = c.Guid(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "NEWID()")
},
}),
Username = c.String(nullable: false),
Password = c.String(nullable: false),
CreateDateTime = c.DateTime(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "GETDATE()")
},
}),
UpdateDateTime = c.DateTime(),
DeleteDateTime = c.DateTime(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Posts",
c => new
{
Id = c.Guid(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "NEWID()")
},
}),
Title = c.String(nullable: false),
Description = c.String(nullable: false),
AuthorId = c.Guid(nullable: false),
TopicId = c.Guid(nullable: false),
CreateDateTime = c.DateTime(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "GETDATE()")
},
}),
UpdateDateTime = c.DateTime(),
DeleteDateTime = c.DateTime(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.AuthorId)
.ForeignKey("dbo.Topics", t => t.TopicId)
.Index(t => t.AuthorId)
.Index(t => t.TopicId);
CreateTable(
"dbo.Topics",
c => new
{
Id = c.Guid(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "NEWID()")
},
}),
Title = c.String(nullable: false),
Description = c.String(),
ModeratingUserId = c.Guid(nullable: false),
CreateDateTime = c.DateTime(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"SqlDefaultValue",
new AnnotationValues(oldValue: null, newValue: "GETDATE()")
},
}),
UpdateDateTime = c.DateTime(),
DeleteDateTime = c.DateTime(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.ModeratingUserId)
.Index(t => t.ModeratingUserId);
}
public override void Down()
{
DropForeignKey("dbo.Comments", "ResponseToCommentId", "dbo.Comments");
DropForeignKey("dbo.Comments", "AuthorId", "dbo.Users");
DropForeignKey("dbo.Posts", "TopicId", "dbo.Topics");
DropForeignKey("dbo.Topics", "ModeratingUserId", "dbo.Users");
DropForeignKey("dbo.Comments", "PostId", "dbo.Posts");
DropForeignKey("dbo.Posts", "AuthorId", "dbo.Users");
DropIndex("dbo.Topics", new[] { "ModeratingUserId" });
DropIndex("dbo.Posts", new[] { "TopicId" });
DropIndex("dbo.Posts", new[] { "AuthorId" });
DropIndex("dbo.Comments", new[] { "ResponseToCommentId" });
DropIndex("dbo.Comments", new[] { "PostId" });
DropIndex("dbo.Comments", new[] { "AuthorId" });
DropTable("dbo.Topics",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreateDateTime",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "GETDATE()" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "NEWID()" },
}
},
});
DropTable("dbo.Posts",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreateDateTime",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "GETDATE()" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "NEWID()" },
}
},
});
DropTable("dbo.Users",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreateDateTime",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "GETDATE()" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "NEWID()" },
}
},
});
DropTable("dbo.Comments",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreateDateTime",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "GETDATE()" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "SqlDefaultValue", "NEWID()" },
}
},
});
}
}
}
| |
//================================
// Classes aka Ranks
//================================
new scriptObject(EywaRanks)
{
class = "Eywa";
dataFile = "config/server/WorldRP/Ranks.dat";
Debug = false;
};
function EywaRanks::AddRank(%s,%id,%name,%level,%value,%color,%desc,%upgrademsg,%perks)
{
// ================= Rank Debug ================ \\
%msg = "WorldRP: Failed adding Rank because";
if(%s.RankName[%id] $= %name) { %msg = %msg @ ", Rank Already Exists"; }
if(%id $= "") { %msg = %msg @ ", ID is missing"; }
if(%name $= "") { %msg = %msg @ ", No name"; }
if(%level $= "") { %msg = %msg @ ", Level is blank"; }
if(%value $= "") { %msg = %msg @ ", Value is blank"; }
if(%color $= "") { %msg = %msg @ ", Color is blank"; }
if(%desc $= "") { %msg = %msg @ ", No description"; }
// Show Report
if(EywaPopulation.Debug && %msg !$= "WorldRP: Failed adding Rank because")
{ warn(%msg); return; }
// =============================================== \\
// Guiness World Records
%level = strReplace(%level,"_"," ");
%money = getWord(%level,0);
%exp = getWord(%level,1);
if(%money > %s.HighestMoneyValue)
%s.HighestMoneyValue = %money;
if(%exp > %s.HighestExp)
%s.HighestExpValue = %exp;
%s.Count++;
if(%id $= "" || %id <= 0) { %id = %s.Count; }
%s.RankName[%id] = %name;
%s.RankLevel[%id] = %level;
%s.RankValue[%id] = %value;
%s.RankColor[%id] = getWord(%color,0);
%s.RankRGBColor[%id] = getWords(%color,1,getWordCount(%color));
%s.RankDesc[%id] = %desc;
%s.RankUpgradeMsg[%id] = %upgrademsg;
%s.RankPerks[%id] = %perks;
// Create Spawn Rank Brick
%SpawnBrickName = "WRPRank" @ %id @ "SpawnBrickData";
if(!isObject(%SpawnBrickName))
{
datablock fxDtsBrickData(WRPSpawnBrickData : brickSpawnPointData)
{
category = "WorldRP Bricks";
subCategory = "WorldRP Rank Spawns";
uiName = %s.RankName[%id] @ " Rank Spawn";
specialBrickType = "";
AdminPlantOnly = true;
spawnData = "Rank" @ %id @ "Spawn";
};
WRPSpawnBrickData.setName(%SpawnBrickName);
}
}
function EywaRanks::LoadRanks(%s)
{
%s.Count = 0;
%dat = "config/server/WorldRP/Ranks.dat";
if(!isFile(%dat))
WRPCopyFile("Add-Ons/Gamemode_WorldRP/Default Files/Ranks.dat", %dat);
%stream = new fileObject();
%stream.openForRead(%dat);
while(!%stream.isEOF())
{
%line = trim(%stream.readLine());
// Blanks to pass
if(getSubStr(%line, 0, 2) $= "//" || %line $= "")
continue;
%valueData = strlwr(getWord(%line, 0));
%start = strlen(%ValueData) + 1;
%str = getSubStr(%line,%start,strlen(%line));
// Stack up temp data for new Rank addition
switch$(%valueData)
{
case "id":
$WRP::temp::ID = %str;
case "name":
$WRP::temp::Name = %str;
case "level":
$WRP::temp::Level = %str;
case "value":
$WRP::temp::Value = %str;
case "color":
$WRP::temp::Color = %str;
case "desc":
$WRP::temp::Desc = %str;
case "upgrademsg":
$WRP::temp::UpgradeMsg = %str;
case "perks":
$WRP::temp::Perks = %str;
}
// Make Sure we got all the info we need
if($WRP::temp::ID !$= "" && $WRP::temp::Name !$= "" && $WRP::temp::Level !$= "" && $WRP::temp::Value !$= "" && $WRP::temp::Color !$= "" && $WRP::temp::Desc !$= "" && $WRP::temp::UpgradeMsg !$= "" && $WRP::temp::Perks !$= "")
{
%s.AddRank($WRP::temp::ID,$WRP::temp::Name,$WRP::temp::Level,$WRP::temp::Value,$WRP::temp::Color,$WRP::temp::Desc,$WRP::temp::UpgradeMsg,$WRP::temp::Perks);
deleteVariables("$WRP::temp::*");
}
}
deleteVariables("$WRP::temp::*");
%stream.close();
%stream.delete();
}
if(isObject(EywaRanks)) { EywaRanks.LoadRanks(); }
function EywaRanks::isRank(%s,%f)
{
if(%f $= "")
return;
for(%c=0;%c<%s.Count;%c++)
{
if(strlwr(%f) $= strlwr(%s.Rankname))
{
return true;
}
}
}
// BETA vv--(Flagged for removal)--vv
//=======================================
function EywaRanks::getRankColor(%s,%RankID,%type)
{
if(%RankID < 1 || %RankID $= "")
return;
%Ccolor = EywaRanks.RankColor[%RankID];
if(%type $= "hex")
{
%num1 = getsubstr(%Ccolor,0,2);
%num2 = getsubstr(%Ccolor,3,2);
%num3 = getsubstr(%Ccolor,6,2);
for(%a=0;%a<3;%a++)
{
%anum = (%a * 2) - 1;
%num = getsubstr(%num[%a], %anum, 1);
switch$(strlwr(%num))
{
case "f":
%Nnum = "1";
case "e":
%Nnum = "0.95";
case "d":
%Nnum = "0.9";
case "c":
%Nnum = "0.85";
case "b":
%Nnum = "0.8";
case "9":
%Nnum = "0.75";
case "8":
%Nnum = "0.7";
case "7":
%Nnum = "0.65";
case "6":
%Nnum = "0.6";
case "5":
%Nnum = "0.55";
case "4":
%Nnum = "0.5";
case "3":
%Nnum = "0.4";
case "2":
%Nnum = "0.2";
case "1":
%Nnum = "0.1";
case "0":
%Nnum = "0";
}
if(%Nnum !$= "")
{
%Nnum = %Nnum @ " ";
%Nnumlist = %Nnumlist @ %Nnum;
}
}
if(getWordCount(%Nnumlist) == 4)
{
return %Nnumlist @ "1";
}
}
else
{
return %Ccolor;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.OS;
using Java.Lang;
using Xamarin.Forms.Platform.Android;
using Math = System.Math;
namespace Xamarin.Forms.Maps.Android
{
public class MapRenderer : ViewRenderer<Map, MapView>,
GoogleMap.IOnCameraChangeListener
{
const string MoveMessageName = "MapMoveToRegion";
static Bundle s_bundle;
bool _disposed;
bool _init = true;
List<Marker> _markers;
public MapRenderer()
{
AutoPackage = false;
}
protected Map Map => Element;
#pragma warning disable 618
protected GoogleMap NativeMap => Control.Map;
#pragma warning restore 618
internal static Bundle Bundle
{
set { s_bundle = value; }
}
public void OnCameraChange(CameraPosition pos)
{
UpdateVisibleRegion(pos.Target);
}
public override SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
return new SizeRequest(new Size(Context.ToPixels(40), Context.ToPixels(40)));
}
protected override MapView CreateNativeControl()
{
return new MapView(Context);
}
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
if (Element != null)
{
MessagingCenter.Unsubscribe<Map, MapSpan>(this, MoveMessageName);
((ObservableCollection<Pin>)Element.Pins).CollectionChanged -= OnCollectionChanged;
}
if (NativeMap != null)
{
NativeMap.MyLocationEnabled = false;
NativeMap.SetOnCameraChangeListener(null);
NativeMap.InfoWindowClick -= MapOnMarkerClick;
NativeMap.Dispose();
}
Control?.OnDestroy();
}
base.Dispose(disposing);
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
MapView oldMapView = Control;
MapView mapView = CreateNativeControl();
mapView.OnCreate(s_bundle);
mapView.OnResume();
SetNativeControl(mapView);
if (e.OldElement != null)
{
Map oldMapModel = e.OldElement;
((ObservableCollection<Pin>)oldMapModel.Pins).CollectionChanged -= OnCollectionChanged;
MessagingCenter.Unsubscribe<Map, MapSpan>(this, MoveMessageName);
#pragma warning disable 618
if (oldMapView.Map != null)
{
#pragma warning restore 618
#pragma warning disable 618
oldMapView.Map.SetOnCameraChangeListener(null);
#pragma warning restore 618
NativeMap.InfoWindowClick -= MapOnMarkerClick;
}
oldMapView.Dispose();
}
GoogleMap map = NativeMap;
if (map != null)
{
map.SetOnCameraChangeListener(this);
NativeMap.InfoWindowClick += MapOnMarkerClick;
map.UiSettings.ZoomControlsEnabled = Map.HasZoomEnabled;
map.UiSettings.ZoomGesturesEnabled = Map.HasZoomEnabled;
map.UiSettings.ScrollGesturesEnabled = Map.HasScrollEnabled;
map.MyLocationEnabled = map.UiSettings.MyLocationButtonEnabled = Map.IsShowingUser;
SetMapType();
}
MessagingCenter.Subscribe<Map, MapSpan>(this, MoveMessageName, OnMoveToRegionMessage, Map);
var incc = Map.Pins as INotifyCollectionChanged;
if (incc != null)
{
incc.CollectionChanged += OnCollectionChanged;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Map.MapTypeProperty.PropertyName)
{
SetMapType();
return;
}
GoogleMap gmap = NativeMap;
if (gmap == null)
{
return;
}
if (e.PropertyName == Map.IsShowingUserProperty.PropertyName)
{
gmap.MyLocationEnabled = gmap.UiSettings.MyLocationButtonEnabled = Map.IsShowingUser;
}
else if (e.PropertyName == Map.HasScrollEnabledProperty.PropertyName)
{
gmap.UiSettings.ScrollGesturesEnabled = Map.HasScrollEnabled;
}
else if (e.PropertyName == Map.HasZoomEnabledProperty.PropertyName)
{
gmap.UiSettings.ZoomControlsEnabled = Map.HasZoomEnabled;
gmap.UiSettings.ZoomGesturesEnabled = Map.HasZoomEnabled;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (_init)
{
MoveToRegion(Element.LastMoveToRegion, false);
OnCollectionChanged(Element.Pins, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
_init = false;
}
else if (changed)
{
UpdateVisibleRegion(NativeMap.CameraPosition.Target);
MoveToRegion(Element.LastMoveToRegion, false);
}
}
void AddPins(IList pins)
{
GoogleMap map = NativeMap;
if (map == null)
{
return;
}
if (_markers == null)
{
_markers = new List<Marker>();
}
_markers.AddRange(pins.Cast<Pin>().Select(p =>
{
Pin pin = p;
var opts = new MarkerOptions();
opts.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
opts.SetTitle(pin.Label);
opts.SetSnippet(pin.Address);
var marker = map.AddMarker(opts);
// associate pin with marker for later lookup in event handlers
pin.Id = marker.Id;
return marker;
}));
}
void MapOnMarkerClick(object sender, GoogleMap.InfoWindowClickEventArgs eventArgs)
{
// clicked marker
var marker = eventArgs.Marker;
// lookup pin
Pin targetPin = null;
for (var i = 0; i < Map.Pins.Count; i++)
{
Pin pin = Map.Pins[i];
if ((string)pin.Id != marker.Id)
{
continue;
}
targetPin = pin;
break;
}
// only consider event handled if a handler is present.
// Else allow default behavior of displaying an info window.
targetPin?.SendTap();
}
void MoveToRegion(MapSpan span, bool animate)
{
GoogleMap map = NativeMap;
if (map == null)
{
return;
}
span = span.ClampLatitude(85, -85);
var ne = new LatLng(span.Center.Latitude + span.LatitudeDegrees / 2,
span.Center.Longitude + span.LongitudeDegrees / 2);
var sw = new LatLng(span.Center.Latitude - span.LatitudeDegrees / 2,
span.Center.Longitude - span.LongitudeDegrees / 2);
CameraUpdate update = CameraUpdateFactory.NewLatLngBounds(new LatLngBounds(sw, ne), 0);
try
{
if (animate)
{
map.AnimateCamera(update);
}
else
{
map.MoveCamera(update);
}
}
catch (IllegalStateException exc)
{
System.Diagnostics.Debug.WriteLine("MoveToRegion exception: " + exc);
Log.Warning("Xamarin.Forms MapRenderer", $"MoveToRegion exception: {exc}");
}
}
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
switch (notifyCollectionChangedEventArgs.Action)
{
case NotifyCollectionChangedAction.Add:
AddPins(notifyCollectionChangedEventArgs.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
RemovePins(notifyCollectionChangedEventArgs.OldItems);
break;
case NotifyCollectionChangedAction.Replace:
RemovePins(notifyCollectionChangedEventArgs.OldItems);
AddPins(notifyCollectionChangedEventArgs.NewItems);
break;
case NotifyCollectionChangedAction.Reset:
_markers?.ForEach(m => m.Remove());
_markers = null;
AddPins((IList)Element.Pins);
break;
case NotifyCollectionChangedAction.Move:
//do nothing
break;
}
}
void OnMoveToRegionMessage(Map s, MapSpan a)
{
MoveToRegion(a, true);
}
void RemovePins(IList pins)
{
GoogleMap map = NativeMap;
if (map == null)
{
return;
}
if (_markers == null)
{
return;
}
foreach (Pin p in pins)
{
var marker = _markers.FirstOrDefault(m => (object)m.Id == p.Id);
if (marker == null)
{
continue;
}
marker.Remove();
_markers.Remove(marker);
}
}
void SetMapType()
{
GoogleMap map = NativeMap;
if (map == null)
{
return;
}
switch (Map.MapType)
{
case MapType.Street:
map.MapType = GoogleMap.MapTypeNormal;
break;
case MapType.Satellite:
map.MapType = GoogleMap.MapTypeSatellite;
break;
case MapType.Hybrid:
map.MapType = GoogleMap.MapTypeHybrid;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
void UpdateVisibleRegion(LatLng pos)
{
GoogleMap map = NativeMap;
if (map == null)
{
return;
}
Projection projection = map.Projection;
int width = Control.Width;
int height = Control.Height;
LatLng ul = projection.FromScreenLocation(new global::Android.Graphics.Point(0, 0));
LatLng ur = projection.FromScreenLocation(new global::Android.Graphics.Point(width, 0));
LatLng ll = projection.FromScreenLocation(new global::Android.Graphics.Point(0, height));
LatLng lr = projection.FromScreenLocation(new global::Android.Graphics.Point(width, height));
double dlat = Math.Max(Math.Abs(ul.Latitude - lr.Latitude), Math.Abs(ur.Latitude - ll.Latitude));
double dlong = Math.Max(Math.Abs(ul.Longitude - lr.Longitude), Math.Abs(ur.Longitude - ll.Longitude));
Element.VisibleRegion = new MapSpan(new Position(pos.Latitude, pos.Longitude), dlat, dlong);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the virtual
/// networks for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for
/// more information)
/// </summary>
internal partial class NetworkOperations : IServiceOperations<NetworkManagementClient>, Microsoft.WindowsAzure.Management.Network.INetworkOperations
{
/// <summary>
/// Initializes a new instance of the NetworkOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal NetworkOperations(NetworkManagementClient client)
{
this._client = client;
}
private NetworkManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient.
/// </summary>
public NetworkManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Begin Setting Network Configuration operation asynchronously
/// configures the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> BeginSettingConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Configuration == null)
{
throw new ArgumentNullException("parameters.Configuration");
}
// 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("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginSettingConfigurationAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/media";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Configuration;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
// 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));
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>
/// The Get Network Configuration operation retrieves the network
/// configuration file for the given subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Network Configuration operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.NetworkGetConfigurationResponse> GetConfigurationAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "GetConfigurationAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/media";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-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));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
NetworkGetConfigurationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkGetConfigurationResponse();
result.Configuration = responseContent;
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>
/// The List Virtual network sites operation retrieves the virtual
/// networks configured for the subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response structure for the Network Operations List operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.NetworkListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/virtualnetwork";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-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));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
NetworkListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement virtualNetworkSitesSequenceElement = responseDoc.Element(XName.Get("VirtualNetworkSites", "http://schemas.microsoft.com/windowsazure"));
if (virtualNetworkSitesSequenceElement != null)
{
foreach (XElement virtualNetworkSitesElement in virtualNetworkSitesSequenceElement.Elements(XName.Get("VirtualNetworkSite", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.VirtualNetworkSite virtualNetworkSiteInstance = new NetworkListResponse.VirtualNetworkSite();
result.VirtualNetworkSites.Add(virtualNetworkSiteInstance);
XElement nameElement = virtualNetworkSitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
virtualNetworkSiteInstance.Name = nameInstance;
}
XElement labelElement = virtualNetworkSitesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = labelElement.Value;
virtualNetworkSiteInstance.Label = labelInstance;
}
XElement idElement = virtualNetworkSitesElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
virtualNetworkSiteInstance.Id = idInstance;
}
XElement affinityGroupElement = virtualNetworkSitesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure"));
if (affinityGroupElement != null)
{
string affinityGroupInstance = affinityGroupElement.Value;
virtualNetworkSiteInstance.AffinityGroup = affinityGroupInstance;
}
XElement locationElement = virtualNetworkSitesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
virtualNetworkSiteInstance.Location = locationInstance;
}
XElement stateElement = virtualNetworkSitesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
virtualNetworkSiteInstance.State = stateInstance;
}
XElement addressSpaceElement = virtualNetworkSitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure"));
if (addressSpaceElement != null)
{
NetworkListResponse.AddressSpace addressSpaceInstance = new NetworkListResponse.AddressSpace();
virtualNetworkSiteInstance.AddressSpace = addressSpaceInstance;
XElement addressPrefixesSequenceElement = addressSpaceElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixesSequenceElement != null)
{
foreach (XElement addressPrefixesElement in addressPrefixesSequenceElement.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
{
addressSpaceInstance.AddressPrefixes.Add(addressPrefixesElement.Value);
}
}
}
XElement subnetsSequenceElement = virtualNetworkSitesElement.Element(XName.Get("Subnets", "http://schemas.microsoft.com/windowsazure"));
if (subnetsSequenceElement != null)
{
foreach (XElement subnetsElement in subnetsSequenceElement.Elements(XName.Get("Subnet", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.Subnet subnetInstance = new NetworkListResponse.Subnet();
virtualNetworkSiteInstance.Subnets.Add(subnetInstance);
XElement nameElement2 = subnetsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
subnetInstance.Name = nameInstance2;
}
XElement addressPrefixElement = subnetsElement.Element(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixElement != null)
{
string addressPrefixInstance = addressPrefixElement.Value;
subnetInstance.AddressPrefix = addressPrefixInstance;
}
XElement networkSecurityGroupElement = subnetsElement.Element(XName.Get("NetworkSecurityGroup", "http://schemas.microsoft.com/windowsazure"));
if (networkSecurityGroupElement != null)
{
string networkSecurityGroupInstance = networkSecurityGroupElement.Value;
subnetInstance.NetworkSecurityGroup = networkSecurityGroupInstance;
}
}
}
XElement dnsElement = virtualNetworkSitesElement.Element(XName.Get("Dns", "http://schemas.microsoft.com/windowsazure"));
if (dnsElement != null)
{
XElement dnsServersSequenceElement = dnsElement.Element(XName.Get("DnsServers", "http://schemas.microsoft.com/windowsazure"));
if (dnsServersSequenceElement != null)
{
foreach (XElement dnsServersElement in dnsServersSequenceElement.Elements(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.DnsServer dnsServerInstance = new NetworkListResponse.DnsServer();
virtualNetworkSiteInstance.DnsServers.Add(dnsServerInstance);
XElement nameElement3 = dnsServersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement3 != null)
{
string nameInstance3 = nameElement3.Value;
dnsServerInstance.Name = nameInstance3;
}
XElement addressElement = dnsServersElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
if (addressElement != null)
{
string addressInstance = addressElement.Value;
dnsServerInstance.Address = addressInstance;
}
}
}
}
XElement gatewayElement = virtualNetworkSitesElement.Element(XName.Get("Gateway", "http://schemas.microsoft.com/windowsazure"));
if (gatewayElement != null)
{
NetworkListResponse.Gateway gatewayInstance = new NetworkListResponse.Gateway();
virtualNetworkSiteInstance.Gateway = gatewayInstance;
XElement profileElement = gatewayElement.Element(XName.Get("Profile", "http://schemas.microsoft.com/windowsazure"));
if (profileElement != null)
{
GatewayProfile profileInstance = ((GatewayProfile)Enum.Parse(typeof(GatewayProfile), profileElement.Value, true));
gatewayInstance.Profile = profileInstance;
}
XElement sitesSequenceElement = gatewayElement.Element(XName.Get("Sites", "http://schemas.microsoft.com/windowsazure"));
if (sitesSequenceElement != null)
{
foreach (XElement sitesElement in sitesSequenceElement.Elements(XName.Get("LocalNetworkSite", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.LocalNetworkSite localNetworkSiteInstance = new NetworkListResponse.LocalNetworkSite();
gatewayInstance.Sites.Add(localNetworkSiteInstance);
XElement nameElement4 = sitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement4 != null)
{
string nameInstance4 = nameElement4.Value;
localNetworkSiteInstance.Name = nameInstance4;
}
XElement vpnGatewayAddressElement = sitesElement.Element(XName.Get("VpnGatewayAddress", "http://schemas.microsoft.com/windowsazure"));
if (vpnGatewayAddressElement != null)
{
string vpnGatewayAddressInstance = vpnGatewayAddressElement.Value;
localNetworkSiteInstance.VpnGatewayAddress = vpnGatewayAddressInstance;
}
XElement addressSpaceElement2 = sitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure"));
if (addressSpaceElement2 != null)
{
NetworkListResponse.AddressSpace addressSpaceInstance2 = new NetworkListResponse.AddressSpace();
localNetworkSiteInstance.AddressSpace = addressSpaceInstance2;
XElement addressPrefixesSequenceElement2 = addressSpaceElement2.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixesSequenceElement2 != null)
{
foreach (XElement addressPrefixesElement2 in addressPrefixesSequenceElement2.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
{
addressSpaceInstance2.AddressPrefixes.Add(addressPrefixesElement2.Value);
}
}
}
XElement connectionsSequenceElement = sitesElement.Element(XName.Get("Connections", "http://schemas.microsoft.com/windowsazure"));
if (connectionsSequenceElement != null)
{
foreach (XElement connectionsElement in connectionsSequenceElement.Elements(XName.Get("Connection", "http://schemas.microsoft.com/windowsazure")))
{
NetworkListResponse.Connection connectionInstance = new NetworkListResponse.Connection();
localNetworkSiteInstance.Connections.Add(connectionInstance);
XElement typeElement = connectionsElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
LocalNetworkConnectionType typeInstance = NetworkManagementClient.ParseLocalNetworkConnectionType(typeElement.Value);
connectionInstance.Type = typeInstance;
}
}
}
}
}
XElement vPNClientAddressPoolElement = gatewayElement.Element(XName.Get("VPNClientAddressPool", "http://schemas.microsoft.com/windowsazure"));
if (vPNClientAddressPoolElement != null)
{
NetworkListResponse.VPNClientAddressPool vPNClientAddressPoolInstance = new NetworkListResponse.VPNClientAddressPool();
gatewayInstance.VPNClientAddressPool = vPNClientAddressPoolInstance;
XElement addressPrefixesSequenceElement3 = vPNClientAddressPoolElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
if (addressPrefixesSequenceElement3 != null)
{
foreach (XElement addressPrefixesElement3 in addressPrefixesSequenceElement3.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
{
vPNClientAddressPoolInstance.AddressPrefixes.Add(addressPrefixesElement3.Value);
}
}
}
}
}
}
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>
/// The Set Network Configuration operation asynchronously configures
/// the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// 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 System.Threading.Tasks.Task<OperationStatusResponse> SetConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
{
NetworkManagementClient 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("parameters", parameters);
Tracing.Enter(invocationId, this, "SetConfigurationAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
OperationResponse response = await client.Networks.BeginSettingConfigurationAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
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;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Security;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal static class ObjectToDataContractConverter
{
private static void CheckDuplicateNames(ClassDataContract dataContract)
{
if (dataContract.MemberNames != null)
{
Dictionary<string, object> memberTable = new Dictionary<string, object>();
for (int i = 0; i < dataContract.MemberNames.Length; i++)
{
if (memberTable.ContainsKey(dataContract.MemberNames[i].Value))
{
throw new SerializationException(SR.Format(SR.JsonDuplicateMemberInInput, dataContract.MemberNames[i].Value));
}
memberTable.Add(dataContract.MemberNames[i].Value, null);
}
}
}
public static object ConvertDictionaryToClassDataContract(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, XmlObjectSerializerReadContextComplexJson context)
{
if (deserialzedValue == null)
{
return null;
}
if (dataContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
{
var tuple = deserialzedValue["DateTime"] as Tuple<DateTime, string>;
DateTimeOffset dto = new DateTimeOffset(tuple != null ? tuple.Item1 : (DateTime)deserialzedValue["DateTime"]);
return dto.ToOffset(new TimeSpan(0, (int)deserialzedValue["OffsetMinutes"], 0));
}
object serverTypeStringValue;
if (deserialzedValue.TryGetValue(JsonGlobals.ServerTypeString, out serverTypeStringValue))
{
dataContract = ResolveDataContractFromTypeInformation(serverTypeStringValue.ToString(), dataContract, context);
}
object o = CreateInstance(dataContract);
CheckDuplicateNames(dataContract);
DataContractJsonSerializer.InvokeOnDeserializing(o, dataContract, context);
ReadClassDataContractMembers(serializer, dataContract, deserialzedValue, o, context);
DataContractJsonSerializer.InvokeOnDeserialized(o, dataContract, context);
if (dataContract.IsKeyValuePairAdapter)
{
return dataContract.GetKeyValuePairMethodInfo.Invoke(o, Array.Empty<Type>());
}
return o;
}
private static void ReadClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, object newInstance, XmlObjectSerializerReadContextComplexJson context)
{
if (dataContract.BaseContract != null)
{
ReadClassDataContractMembers(serializer, dataContract.BaseContract, deserialzedValue, newInstance, context);
}
for (int i = 0; i < dataContract.Members.Count; i++)
{
DataMember member = dataContract.Members[i];
object currentMemberValue;
if (deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name), out currentMemberValue) ||
dataContract.IsKeyValuePairAdapter && deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name.ToLowerInvariant()), out currentMemberValue))
{
if (member.MemberType.GetTypeInfo().IsPrimitive || currentMemberValue == null)
{
SetMemberValue(newInstance, serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context), dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
}
else
{
context.PushKnownTypes(dataContract);
object subMemberValue = serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context);
Type declaredType = (member.MemberType.GetTypeInfo().IsGenericType && member.MemberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
? Nullable.GetUnderlyingType(member.MemberType)
: member.MemberType;
if (!(declaredType == Globals.TypeOfObject && subMemberValue.GetType() == Globals.TypeOfObjectArray) && declaredType != subMemberValue.GetType())
{
DataContract memberValueContract = DataContract.GetDataContract(subMemberValue.GetType());
context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract);
}
if (member.IsGetOnlyCollection)
{
PopulateReadOnlyCollection(newInstance, member, (IEnumerable)subMemberValue);
}
else
{
SetMemberValue(newInstance, subMemberValue, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
}
context.PopKnownTypes(dataContract);
}
}
else if (member.IsRequired)
{
XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(dataContract.MemberNames[i].Value, dataContract.UnderlyingType);
}
}
}
private static void PopulateReadOnlyCollection(object instance, DataMember member, IEnumerable value)
{
Debug.Assert(member.IsGetOnlyCollection);
CollectionDataContract memberContract = (CollectionDataContract)member.MemberTypeContract;
var collection = DataContractToObjectConverter.GetMemberValue(instance, member.MemberInfo, instance.GetType());
// Special case an array
var array = collection as Array;
if (array != null)
{
Array srcArray = (Array)value;
Type elementType = srcArray.GetType().GetElementType();
// Resize
var resizeMethod = typeof(Array).GetMethod("Resize", BindingFlags.Static | BindingFlags.Public);
var properResizeMethod = resizeMethod.MakeGenericMethod(elementType);
properResizeMethod.Invoke(null, new object[] { array, srcArray.Length });
// Copy
Array.Copy(srcArray, 0, array, 0, srcArray.Length);
return;
}
// General collection
IEnumerator enumerator = value.GetEnumerator();
object currentItem = null;
object[] currentItemArray = null;
while (enumerator.MoveNext())
{
currentItem = enumerator.Current;
currentItemArray = new object[] { currentItem };
// Dictionary
if (memberContract.IsDictionary)
{
Type currentItemType = currentItem.GetType();
MemberInfo keyMember = currentItemType.GetMember("Key")[0];
MemberInfo valueMember = currentItemType.GetMember("Value")[0];
currentItemArray = new object[] { DataContractToObjectConverter.GetMemberValue(currentItem, keyMember, currentItemType), DataContractToObjectConverter.GetMemberValue(currentItem, valueMember, currentItemType) };
}
memberContract.AddMethod.Invoke(collection, currentItemArray);
}
}
//Deserialize '[...]' json string. The contents of the list can also be a dictionary i.e. [{...}]. The content type is detected
//based on the type of CollectionDataContract.ItemContract.
public static object ConvertICollectionToCollectionDataContract(DataContractJsonSerializer serializer, CollectionDataContract contract, object deserializedValue, XmlObjectSerializerReadContextComplexJson context)
{
Dictionary<string, object> valueAsDictionary = deserializedValue as Dictionary<string, object>;
//Check to see if the dictionary (if it is a dictionary)is a regular Dictionary i.e { Key="key"; Value="value} and doesnt contain the __type string
//for ex. the dictionary { __type="XXX"; Key="key"; Value="value} needs to be parsed as ClassDataContract
if (valueAsDictionary != null && (!valueAsDictionary.ContainsKey(JsonGlobals.KeyString) || valueAsDictionary.ContainsKey(JsonGlobals.ServerTypeString)))
{
//If not then its a dictionary for either of these cases
//1. Empty object - {}
//2. Containes the __type information
//3. Is a DateTimeOffsetDictionary
return ConvertDictionary(serializer, contract, valueAsDictionary, context);
}
object returnValue = (contract.Constructor != null) ? contract.Constructor.Invoke(Array.Empty<Type>()) : null;
bool isCollectionDataContractDictionary = contract.IsDictionary;
MethodInfo addMethod = contract.AddMethod;
bool convertToArray = contract.Kind == CollectionKind.Array;
if (contract.UnderlyingType.GetTypeInfo().IsInterface || returnValue == null)
{
switch (contract.Kind)
{
case CollectionKind.Collection:
case CollectionKind.GenericCollection:
case CollectionKind.Enumerable:
case CollectionKind.GenericEnumerable:
case CollectionKind.List:
case CollectionKind.GenericList:
case CollectionKind.Array:
if (contract.UnderlyingType.GetTypeInfo().IsValueType)
{
//Initialize struct
returnValue = XmlFormatReaderGenerator.TryGetUninitializedObjectWithFormatterServices(contract.UnderlyingType);
}
else
{
returnValue = Activator.CreateInstance(Globals.TypeOfListGeneric.MakeGenericType(contract.ItemType));
convertToArray = true;
}
break;
case CollectionKind.GenericDictionary:
returnValue = Activator.CreateInstance(Globals.TypeOfDictionaryGeneric.MakeGenericType(contract.ItemType.GetGenericArguments()));
break;
case CollectionKind.Dictionary:
returnValue = Activator.CreateInstance(Globals.TypeOfDictionaryGeneric.MakeGenericType(Globals.TypeOfObject, Globals.TypeOfObject));
break;
}
}
if (addMethod == null)
{
//addMethod is null for IDictionary, IList and array types.
Type[] paramArray = (contract.ItemType.GetTypeInfo().IsGenericType && !convertToArray) ? contract.ItemType.GetGenericArguments() : new Type[] { contract.ItemType };
addMethod = returnValue.GetType().GetMethod(Globals.AddMethodName, paramArray);
}
IEnumerator enumerator = ((ICollection)deserializedValue).GetEnumerator();
object currentItem = null;
object[] currentItemArray = null;
while (enumerator.MoveNext())
{
DataContract itemContract = contract.ItemContract;
if (itemContract is ClassDataContract)
{
itemContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(itemContract);
}
currentItem = serializer.ConvertObjectToDataContract(itemContract, enumerator.Current, context);
currentItemArray = new object[] { currentItem };
if (isCollectionDataContractDictionary)
{
Type currentItemType = currentItem.GetType();
MemberInfo keyMember = currentItemType.GetMember("Key")[0];
MemberInfo valueMember = currentItemType.GetMember("Value")[0];
currentItemArray = new object[] { DataContractToObjectConverter.GetMemberValue(currentItem, keyMember, currentItemType), DataContractToObjectConverter.GetMemberValue(currentItem, valueMember, currentItemType) };
}
addMethod.Invoke(returnValue, currentItemArray);
}
return (convertToArray) ? ConvertToArray(contract.ItemType, (ICollection)returnValue) : returnValue;
}
public static object ConvertToArray(Type type, ICollection newList)
{
if (newList.GetType().IsArray)
{
//Optimization if its already an array
return newList;
}
Array array = Array.CreateInstance(type, newList.Count);
//Special case byte[] as Int32 cant be implicitly converted to byte.
if (type == typeof(Byte))
{
int index = 0;
foreach (object o in newList)
array.SetValue(Convert.ChangeType(o, type, null), index++);
}
else
{
newList.CopyTo(array, 0);
}
return array;
}
private static object ConvertDictionary(DataContractJsonSerializer serializer, DataContract contract, object obj, XmlObjectSerializerReadContextComplexJson context)
{
System.Diagnostics.Debug.Assert(obj is IDictionary, "obj is IDictionary");
Dictionary<string, object> dictOfStringObject = obj as Dictionary<string, object>;
object serverTypeStringValue;
if (dictOfStringObject.TryGetValue(JsonGlobals.ServerTypeString, out serverTypeStringValue))
{
return ConvertDictionaryToClassDataContract(serializer,
ResolveDataContractFromTypeInformation(serverTypeStringValue.ToString(), null, context),
dictOfStringObject, context);
}
else if (dictOfStringObject.ContainsKey("DateTime") && dictOfStringObject.ContainsKey("OffsetMinutes"))
{
return ConvertDictionaryToClassDataContract(serializer, (ClassDataContract)DataContract.GetDataContract(typeof(DateTimeOffset)), dictOfStringObject, context);
}
else
{
//Its either an empty object "{}" or a weakly typed Json Object such as {"a",1;"b";2} which we don't support reading in Orcas
return new Object();
}
}
private static ClassDataContract ResolveDataContractFromTypeInformation(string typeName, DataContract contract, XmlObjectSerializerReadContextComplexJson context)
{
DataContract dataContract = context.ResolveDataContractFromType(typeName, Globals.DataContractXsdBaseNamespace, contract);
if (dataContract == null)
{
XmlQualifiedName qname = XmlObjectSerializerReadContextComplexJson.ParseQualifiedName(typeName);
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnDeserialize, qname.Namespace, qname.Name)));
}
return (ClassDataContract)dataContract;
}
private static void SetMemberValue(object newInstance, object value, MemberInfo memberInfo, Type typeToInvokeOn)
{
try
{
FieldInfo fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != null)
{
fieldInfo.SetValue(newInstance, value);
}
else
{
((PropertyInfo)memberInfo).SetValue(newInstance, value);
}
}
catch (Exception e)
{
if (e is MemberAccessException || e is ArgumentException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractMemberSetNotPublic,
DataContract.GetClrTypeFullName(typeToInvokeOn),
memberInfo.Name),
e));
}
throw;
}
}
private static object CreateInstance(ClassDataContract dataContract)
{
if (dataContract.IsNonAttributedType && !Globals.TypeOfScriptObject_IsAssignableFrom(dataContract.UnderlyingType))
{
try
{
return Activator.CreateInstance(dataContract.UnderlyingType);
}
catch (MemberAccessException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor,
DataContract.GetClrTypeFullName(dataContract.UnderlyingType)),
e));
}
}
if (dataContract.UnderlyingType == Globals.TypeOfDBNull)
{
return Globals.ValueOfDBNull;
}
return XmlFormatReaderGenerator.UnsafeGetUninitializedObject(DataContract.GetIdForInitialization(dataContract));
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Syndication;
using System.ServiceModel.Web;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
class HelpPage
{
public const string OperationListHelpPageUriTemplate = "help";
public const string OperationHelpPageUriTemplate = "help/operations/{operation}";
const string HelpMethodName = "GetHelpPage";
const string HelpOperationMethodName = "GetOperationHelpPage";
DateTime startupTime = DateTime.UtcNow;
Dictionary<string, OperationHelpInformation> operationInfoDictionary;
NameValueCache<string> operationPageCache;
NameValueCache<string> helpPageCache;
public HelpPage(WebHttpBehavior behavior, ContractDescription description)
{
this.operationInfoDictionary = new Dictionary<string, OperationHelpInformation>();
this.operationPageCache = new NameValueCache<string>();
this.helpPageCache = new NameValueCache<string>();
foreach (OperationDescription od in description.Operations)
{
operationInfoDictionary.Add(od.Name, new OperationHelpInformation(behavior, od));
}
}
Message GetHelpPage()
{
Uri baseUri = UriTemplate.RewriteUri(OperationContext.Current.Channel.LocalAddress.Uri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]);
string helpPage = this.helpPageCache.Lookup(baseUri.Authority);
if (String.IsNullOrEmpty(helpPage))
{
helpPage = HelpHtmlBuilder.CreateHelpPage(baseUri, operationInfoDictionary.Values).ToString();
if (HttpContext.Current == null)
{
this.helpPageCache.AddOrUpdate(baseUri.Authority, helpPage);
}
}
return WebOperationContext.Current.CreateTextResponse(helpPage, "text/html");
}
Message GetOperationHelpPage(string operation)
{
Uri requestUri = UriTemplate.RewriteUri(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]);
string helpPage = this.operationPageCache.Lookup(requestUri.AbsoluteUri);
if (String.IsNullOrEmpty(helpPage))
{
OperationHelpInformation operationInfo;
if (this.operationInfoDictionary.TryGetValue(operation, out operationInfo))
{
Uri baseUri = UriTemplate.RewriteUri(OperationContext.Current.Channel.LocalAddress.Uri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]);
helpPage = HelpHtmlBuilder.CreateOperationHelpPage(baseUri, operationInfo).ToString();
if (HttpContext.Current == null)
{
this.operationPageCache.AddOrUpdate(requestUri.AbsoluteUri, helpPage);
}
}
else
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WebFaultException(HttpStatusCode.NotFound));
}
}
return WebOperationContext.Current.CreateTextResponse(helpPage, "text/html");
}
public static IEnumerable<KeyValuePair<UriTemplate, object>> GetOperationTemplatePairs()
{
return new KeyValuePair<UriTemplate, object>[]
{
new KeyValuePair<UriTemplate, object>(new UriTemplate(OperationListHelpPageUriTemplate), HelpMethodName),
new KeyValuePair<UriTemplate, object>(new UriTemplate(OperationHelpPageUriTemplate), HelpOperationMethodName)
};
}
public object Invoke(UriTemplateMatch match)
{
if (HttpContext.Current != null)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
HttpContext.Current.Response.Cache.SetMaxAge(TimeSpan.MaxValue);
HttpContext.Current.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidationCallback), this.startupTime);
HttpContext.Current.Response.Cache.SetValidUntilExpires(true);
}
switch ((string)match.Data)
{
case HelpMethodName:
return GetHelpPage();
case HelpOperationMethodName:
return GetOperationHelpPage(match.BoundVariables["operation"]);
default:
return null;
}
}
void CacheValidationCallback(HttpContext context, object state, ref HttpValidationStatus result)
{
if (((DateTime)state) == this.startupTime)
{
result = HttpValidationStatus.Valid;
}
else
{
result = HttpValidationStatus.Invalid;
}
}
}
class OperationHelpInformation
{
OperationDescription od;
WebHttpBehavior behavior;
MessageHelpInformation request;
MessageHelpInformation response;
internal OperationHelpInformation(WebHttpBehavior behavior, OperationDescription od)
{
this.od = od;
this.behavior = behavior;
}
public string Name
{
get
{
return od.Name;
}
}
public string UriTemplate
{
get
{
return UriTemplateClientFormatter.GetUTStringOrDefault(od);
}
}
public string Method
{
get
{
return WebHttpBehavior.GetWebMethod(od);
}
}
public string Description
{
get
{
return WebHttpBehavior.GetDescription(od);
}
}
public string JavascriptCallbackParameterName
{
get
{
if (this.Response.SupportsJson && this.Method == WebHttpBehavior.GET)
{
return behavior.JavascriptCallbackParameterName;
}
return null;
}
}
public WebMessageBodyStyle BodyStyle
{
get
{
return behavior.GetBodyStyle(od);
}
}
public MessageHelpInformation Request
{
get
{
if (this.request == null)
{
this.request = new MessageHelpInformation(od, true, GetRequestBodyType(od, this.UriTemplate),
this.BodyStyle == WebMessageBodyStyle.WrappedRequest || this.BodyStyle == WebMessageBodyStyle.Wrapped);
}
return this.request;
}
}
public MessageHelpInformation Response
{
get
{
if (this.response == null)
{
this.response = new MessageHelpInformation(od, false, GetResponseBodyType(od),
this.BodyStyle == WebMessageBodyStyle.WrappedResponse || this.BodyStyle == WebMessageBodyStyle.Wrapped);
}
return this.response;
}
}
static Type GetResponseBodyType(OperationDescription od)
{
if (WebHttpBehavior.IsUntypedMessage(od.Messages[1]))
{
return typeof(Message);
}
else if (WebHttpBehavior.IsTypedMessage(od.Messages[1]))
{
return od.Messages[1].MessageType;
}
else if (od.Messages[1].Body.Parts.Count > 0)
{
// If it is more than 0 the response is wrapped and not supported
return null;
}
else
{
return (od.Messages[1].Body.ReturnValue.Type);
}
}
static Type GetRequestBodyType(OperationDescription od, string uriTemplate)
{
if (od.Behaviors.Contains(typeof(WebGetAttribute)))
{
return typeof(void);
}
else if (WebHttpBehavior.IsUntypedMessage(od.Messages[0]))
{
return typeof(Message);
}
else if (WebHttpBehavior.IsTypedMessage(od.Messages[0]))
{
return od.Messages[0].MessageType;
}
else
{
UriTemplate template = new UriTemplate(uriTemplate);
IEnumerable<MessagePartDescription> parts =
from part in od.Messages[0].Body.Parts
where !template.PathSegmentVariableNames.Contains(part.Name.ToUpperInvariant()) && !template.QueryValueVariableNames.Contains(part.Name.ToUpperInvariant())
select part;
if (parts.Count() == 1)
{
return parts.First().Type;
}
else if (parts.Count() == 0)
{
return typeof(void);
}
else
{
// The request is wrapped and not supported
return null;
}
}
}
}
class MessageHelpInformation
{
public string BodyDescription { get; private set; }
public string FormatString { get; private set; }
public Type Type { get; private set; }
public bool SupportsJson { get; private set; }
public XmlSchemaSet SchemaSet { get; private set; }
public XmlSchema Schema { get; private set; }
public XElement XmlExample { get; private set; }
public XElement JsonExample { get; private set; }
internal MessageHelpInformation(OperationDescription od, bool isRequest, Type type, bool wrapped)
{
this.Type = type;
this.SupportsJson = WebHttpBehavior.SupportsJsonFormat(od);
string direction = isRequest ? SR2.GetString(SR2.HelpPageRequest) : SR2.GetString(SR2.HelpPageResponse);
if (wrapped && !typeof(void).Equals(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsWrapped, direction);
this.FormatString = SR2.GetString(SR2.HelpPageUnknown);
}
else if (typeof(void).Equals(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsEmpty, direction);
this.FormatString = SR2.GetString(SR2.HelpPageNA);
}
else if (typeof(Message).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsMessage, direction);
this.FormatString = SR2.GetString(SR2.HelpPageUnknown);
}
else if (typeof(Stream).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsStream, direction);
this.FormatString = SR2.GetString(SR2.HelpPageUnknown);
}
else if (typeof(Atom10FeedFormatter).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Feed, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else if (typeof(Atom10ItemFormatter).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Entry, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else if (typeof(AtomPub10ServiceDocumentFormatter).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubServiceDocument, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else if (typeof(AtomPub10CategoriesDocumentFormatter).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubCategoriesDocument, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else if (typeof(Rss20FeedFormatter).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsRSS20Feed, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else if (typeof(SyndicationFeedFormatter).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsSyndication, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else if (typeof(XElement).IsAssignableFrom(type) || typeof(XmlElement).IsAssignableFrom(type))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageIsXML, direction);
this.FormatString = WebMessageFormat.Xml.ToString();
}
else
{
try
{
bool usesXmlSerializer = od.Behaviors.Contains(typeof(XmlSerializerOperationBehavior));
XmlQualifiedName name;
this.SchemaSet = new XmlSchemaSet();
IDictionary<XmlQualifiedName, Type> knownTypes = new Dictionary<XmlQualifiedName, Type>();
if (usesXmlSerializer)
{
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping typeMapping = importer.ImportTypeMapping(this.Type);
name = new XmlQualifiedName(typeMapping.ElementName, typeMapping.Namespace);
XmlSchemas schemas = new XmlSchemas();
XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
exporter.ExportTypeMapping(typeMapping);
foreach (XmlSchema schema in schemas)
{
this.SchemaSet.Add(schema);
}
}
else
{
XsdDataContractExporter exporter = new XsdDataContractExporter();
List<Type> listTypes = new List<Type>(od.KnownTypes);
bool isQueryable;
Type dataContractType = DataContractSerializerOperationFormatter.GetSubstituteDataContractType(this.Type, out isQueryable);
listTypes.Add(dataContractType);
exporter.Export(listTypes);
if (!exporter.CanExport(dataContractType))
{
this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema);
this.FormatString = SR2.GetString(SR2.HelpPageUnknown);
return;
}
name = exporter.GetRootElementName(dataContractType);
DataContract typeDataContract = DataContract.GetDataContract(dataContractType);
if (typeDataContract.KnownDataContracts != null)
{
foreach (XmlQualifiedName dataContractName in typeDataContract.KnownDataContracts.Keys)
{
knownTypes.Add(dataContractName, typeDataContract.KnownDataContracts[dataContractName].UnderlyingType);
}
}
foreach (Type knownType in od.KnownTypes)
{
XmlQualifiedName knownTypeName = exporter.GetSchemaTypeName(knownType);
if (!knownTypes.ContainsKey(knownTypeName))
{
knownTypes.Add(knownTypeName, knownType);
}
}
foreach (XmlSchema schema in exporter.Schemas.Schemas())
{
this.SchemaSet.Add(schema);
}
}
this.SchemaSet.Compile();
XmlWriterSettings settings = new XmlWriterSettings
{
CloseOutput = false,
Indent = true,
};
if (this.SupportsJson)
{
XDocument exampleDocument = new XDocument();
using (XmlWriter writer = XmlWriter.Create(exampleDocument.CreateWriter(), settings))
{
HelpExampleGenerator.GenerateJsonSample(this.SchemaSet, name, writer, knownTypes);
}
this.JsonExample = exampleDocument.Root;
}
if (name.Namespace != "http://schemas.microsoft.com/2003/10/Serialization/")
{
foreach (XmlSchema schema in this.SchemaSet.Schemas(name.Namespace))
{
this.Schema = schema;
}
}
XDocument XmlExampleDocument = new XDocument();
using (XmlWriter writer = XmlWriter.Create(XmlExampleDocument.CreateWriter(), settings))
{
HelpExampleGenerator.GenerateXmlSample(this.SchemaSet, name, writer);
}
this.XmlExample = XmlExampleDocument.Root;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema);
this.FormatString = SR2.GetString(SR2.HelpPageUnknown);
this.Schema = null;
this.JsonExample = null;
this.XmlExample = null;
}
}
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// LUCENENET specific - functionality for scanning the API to ensure
/// naming and .NET conventions are followed consistently. Not for use
/// by end users.
/// </summary>
public abstract class ApiScanTestBase : LuceneTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
{
internal ApiScanTestBase(BeforeAfterClass beforeAfter)
: base(beforeAfter)
{
}
#else
{
internal ApiScanTestBase() { } // LUCENENET: Not for use by end users
#endif
/// <summary>
/// Private fields must be upper case separated with underscores,
/// must be camelCase (optionally may be prefixed with underscore,
/// but it is preferred not to use the underscore to match Lucene).
/// </summary>
private static readonly Regex PrivateFieldName = new Regex("^_?[a-z][a-zA-Z0-9_]*$|^[A-Z0-9_]+$", RegexOptions.Compiled);
/// <summary>
/// Protected fields must either be upper case separated with underscores or
/// must be prefixed with m_ (to avoid naming conflicts with properties).
/// </summary>
private static readonly Regex ProtectedFieldName = new Regex("^m_[a-z][a-zA-Z0-9_]*$|^[A-Z0-9_]+$", RegexOptions.Compiled);
/// <summary>
/// Method parameters must be camelCase and not begin or end with underscore.
/// </summary>
private static readonly Regex MethodParameterName = new Regex("^[a-z](?:[a-zA-Z0-9_]*[a-zA-Z0-9])?$", RegexOptions.Compiled);
/// <summary>
/// Interfaces must begin with "I" followed by another captial letter. Note this includes a
/// fix for generic interface names, that end with `{number}.
/// </summary>
private static readonly Regex InterfaceName = new Regex("^I[A-Z][a-zA-Z0-9_]*(?:`\\d+)?$", RegexOptions.Compiled);
/// <summary>
/// Class names must be pascal case and not use the interface naming convention.
/// </summary>
private static readonly Regex ClassName = new Regex("^[A-Z][a-zA-Z0-9_]*(?:`\\d+)?$", RegexOptions.Compiled);
/// <summary>
/// Public members should not contain the word "Comparer". In .NET, these should be named "Comparer".
/// </summary>
private static readonly Regex ContainsComparer = new Regex("[Cc]omparator", RegexOptions.Compiled);
/// <summary>
/// Public methods and properties should not contain the word "Int" that is not followed by 16, 32, or 64,
/// "Long", "Short", or "Float". These should be converted to their .NET names "Int32", "Int64", "Int16", and "Short".
/// Note we need to ignore common words such as "point", "intern", and "intersect".
/// </summary>
private static readonly Regex ContainsNonNetNumeric = new Regex("(?<![Pp]o|[Pp]r|[Jj]o)[Ii]nt(?!16|32|64|er|eg|ro)|[Ll]ong(?!est|er)|[Ss]hort(?!est|er)|[Ff]loat", RegexOptions.Compiled);
/// <summary>
/// Constants should not contain the word INT that is not followed by 16, 32, or 64, LONG, SHORT, or FLOAT
/// </summary>
private static readonly Regex ConstContainsNonNetNumeric = new Regex("(?<!PO|PR|JO)INT(?!16|32|64|ER|EG|RO)|LONG(?!EST|ER)|SHORT(?!EST|ER)|FLOAT", RegexOptions.Compiled);
/// <summary>
/// Matches IL code pattern for a method body with only a return statement for a local variable.
/// In this case, the array is writable by the consumer.
/// </summary>
private static readonly Regex MethodBodyReturnValueOnly = new Regex("\\0\\u0002\\{(?:.|\\\\u\\d\\d\\d\\d|\\0|\\[a-z]){3}\\u0004\\n\\+\\0\\u0006\\*", RegexOptions.Compiled);
//[Test, LuceneNetSpecific]
public virtual void TestProtectedFieldNames(Type typeFromTargetAssembly)
{
var names = GetInvalidProtectedFields(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " invalid protected field names detected. " +
"Protected fields must be camelCase and prefixed with 'm_' to prevent naming conflicts with properties.");
}
//[Test, LuceneNetSpecific]
public virtual void TestPrivateFieldNames(Type typeFromTargetAssembly)
{
TestPrivateFieldNames(typeFromTargetAssembly, null);
}
//[Test, LuceneNetSpecific]
public virtual void TestPrivateFieldNames(Type typeFromTargetAssembly, string exceptionRegex)
{
var names = GetInvalidPrivateFields(typeFromTargetAssembly.Assembly, exceptionRegex);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " invalid private field names detected. " +
"Private field names should be camelCase.");
}
public virtual void TestPublicFields(Type typeFromTargetAssembly)
{
TestPublicFields(typeFromTargetAssembly, null);
}
//[Test, LuceneNetSpecific]
public virtual void TestPublicFields(Type typeFromTargetAssembly, string exceptionRegex)
{
var names = GetInvalidPublicFields(typeFromTargetAssembly.Assembly, exceptionRegex);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " public fields detected. Consider using public properties instead." +
"Public properties that return arrays should be decorated with the WritableArray attribute.");
}
//[Test, LuceneNetSpecific]
public virtual void TestMethodParameterNames(Type typeFromTargetAssembly)
{
var names = GetInvalidMethodParameterNames(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " invalid method parameter names detected. " +
"Parameter names must be camelCase and may not start or end with '_'.");
}
//[Test, LuceneNetSpecific]
public virtual void TestInterfaceNames(Type typeFromTargetAssembly)
{
var names = GetInvalidInterfaceNames(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " invalid interface names detected. " +
"Interface names must begin with a capital 'I' followed by another capital letter.");
}
//[Test, LuceneNetSpecific]
public virtual void TestClassNames(Type typeFromTargetAssembly)
{
var names = GetInvalidClassNames(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " invalid class names detected. " +
"Class names must be Pascal case, but may not follow the interface naming " +
"convention of captial 'I' followed by another capital letter.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForPropertiesWithNoGetter(Type typeFromTargetAssembly)
{
var names = GetPropertiesWithNoGetter(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " properties with a setter but no getter detected. " +
"Getters are required for properties. If the main functionality is to set a value, " +
"consider using a method instead (prefixed with Set).");
}
//[Test, LuceneNetSpecific]
public virtual void TestForPropertiesThatReturnArray(Type typeFromTargetAssembly)
{
var names = GetPropertiesThatReturnArray(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " properties that return Array detected. " +
"Properties should generally not return Array. Change to a method (prefixed with Get) " +
"or if returning an array that can be written to was intended, decorate with the WritableArray attribute. " +
"Note that returning an array field from either a property or method means the array can be written to by " +
"the consumer if the array is not cloned using arr.ToArray().");
}
#if FEATURE_METHODBASE_GETMETHODBODY
//[Test, LuceneNetSpecific]
public virtual void TestForMethodsThatReturnWritableArray(Type typeFromTargetAssembly)
{
var names = GetMethodsThatReturnWritableArray(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " methods that return a writable Array detected. " +
"An array should be cloned before returning using arr.ToArray() or if it is intended to be writable, " +
"decorate with the WritableArray attribute and consider making it a property for clarity.");
}
#endif
//[Test, LuceneNetSpecific]
public virtual void TestForPublicMembersContainingComparer(Type typeFromTargetAssembly)
{
var names = new List<string>();
names.AddRange(GetProtectedFieldsContainingComparer(typeFromTargetAssembly.Assembly));
names.AddRange(GetMembersContainingComparer(typeFromTargetAssembly.Assembly));
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " member names containing the word 'comparer' detected. " +
"In .NET, we need to change the word 'comparer' to 'comparer'.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForPublicMembersNamedSize(Type typeFromTargetAssembly)
{
var names = GetMembersNamedSize(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " member names named 'Size'. " +
"In .NET, we need to change the name 'Size' to either 'Count' or 'Length', " +
"and it should generally be made a property.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForPublicMembersContainingNonNetNumeric(Type typeFromTargetAssembly)
{
var names = GetMembersContainingNonNetNumeric(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " member names containing the word 'Int' not followed " +
"by 16, 32, or 64, 'Long', 'Short', or 'Float' detected. " +
"In .NET, we need to change to 'Short' to 'Int16', 'Int' to 'Int32', 'Long' to 'Int64', and 'Float' to 'Single'.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForTypesContainingNonNetNumeric(Type typeFromTargetAssembly)
{
var names = GetTypesContainingNonNetNumeric(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " member names containing the word 'Int' not followed " +
"by 16, 32, or 64, 'Long', 'Short', or 'Float' detected. " +
"In .NET, we need to change to 'Short' to 'Int16', 'Int' to 'Int32', 'Long' to 'Int64', and 'Float' to 'Single'." +
"\n\nIMPORTANT: Before making changes, make sure to rename any types with ambiguous use of the word `Single` (meaning 'singular' rather than `System.Single`) to avoid confusion.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForPublicMembersWithNullableEnum(Type typeFromTargetAssembly)
{
var names = GetPublicNullableEnumMembers(typeFromTargetAssembly.Assembly);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " members that are type nullable enum detected. " +
"Nullable enum parameters, fields, methods, and properties should be eliminated (where possible), either by " +
"eliminating the logic that depends on 'null'. Sometimes, it makes sense to keep a nullable enum parameter. " +
"In those cases, mark the member with the [ExceptionToNullableEnumConvention] attribute.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForMembersAcceptingOrReturningIEnumerable(Type typeFromTargetAssembly)
{
TestForMembersAcceptingOrReturningIEnumerable(typeFromTargetAssembly, null);
}
//[Test, LuceneNetSpecific]
public virtual void TestForMembersAcceptingOrReturningIEnumerable(Type typeFromTargetAssembly, string exceptionRegex)
{
var names = GetMembersAcceptingOrReturningType(typeof(IEnumerable<>), typeFromTargetAssembly.Assembly, false, exceptionRegex);
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " members that accept or return IEnumerable<T> detected.");
}
//[Test, LuceneNetSpecific]
public virtual void TestForMembersAcceptingOrReturningListOrDictionary(Type typeFromTargetAssembly)
{
TestForMembersAcceptingOrReturningListOrDictionary(typeFromTargetAssembly, null);
}
//[Test, LuceneNetSpecific]
public virtual void TestForMembersAcceptingOrReturningListOrDictionary(Type typeFromTargetAssembly, string exceptionRegex)
{
var names = new List<string>();
names.AddRange(GetMembersAcceptingOrReturningType(typeof(List<>), typeFromTargetAssembly.Assembly, true, exceptionRegex));
names.AddRange(GetMembersAcceptingOrReturningType(typeof(Dictionary<,>), typeFromTargetAssembly.Assembly, true, exceptionRegex));
//if (VERBOSE)
//{
foreach (var name in names)
{
Console.WriteLine(name);
}
//}
Assert.IsFalse(names.Any(), names.Count() + " members that accept or return List<T> or Dictionary<K, V> detected. " +
"These should be changed to IList<T> and IDictionary<K, V>, respectively.");
}
private static IEnumerable<string> GetInvalidPrivateFields(Assembly assembly, string exceptionRegex)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
var fields = c.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var field in fields)
{
if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
{
continue;
}
if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
{
continue;
}
if ((field.IsPrivate || field.IsAssembly) && !PrivateFieldName.IsMatch(field.Name) && field.DeclaringType.Equals(c.UnderlyingSystemType))
{
var name = string.Concat(c.FullName, ".", field.Name);
if (!IsException(name, exceptionRegex))
{
result.Add(name);
}
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetInvalidProtectedFields(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
if (!string.IsNullOrEmpty(c.Namespace) && c.Namespace.StartsWith("Lucene.Net.Support", StringComparison.Ordinal))
{
continue;
}
if (!string.IsNullOrEmpty(c.Name) && c.Name.Equals("AssemblyKeys", StringComparison.Ordinal))
{
continue;
}
var fields = c.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var field in fields)
{
if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
{
continue;
}
if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
{
continue;
}
if ((field.IsFamily || field.IsFamilyOrAssembly) && !ProtectedFieldName.IsMatch(field.Name) && field.DeclaringType.Equals(c.UnderlyingSystemType))
{
result.Add(string.Concat(c.FullName, ".", field.Name));
}
}
}
return result.ToArray();
}
/// <summary>
/// All public fields are invalid
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
private static IEnumerable<string> GetInvalidPublicFields(Assembly assembly, string exceptionRegex)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
if (c.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore classes produced by anonymous methods
{
continue;
}
if (!string.IsNullOrEmpty(c.Namespace) && c.Namespace.StartsWith("Lucene.Net.Support", StringComparison.Ordinal))
{
continue;
}
var fields = c.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (var field in fields)
{
if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
{
continue;
}
if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
{
continue;
}
if (field.IsPublic && field.DeclaringType.Equals(c.UnderlyingSystemType))
{
var name = string.Concat(c.FullName, ".", field.Name);
if (!IsException(name, exceptionRegex))
{
result.Add(name);
}
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetInvalidMethodParameterNames(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
var methods = c.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var method in methods)
{
if (method.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-generated methods
{
continue;
}
var parameters = method.GetParameters();
foreach (var parameter in parameters)
{
if (!MethodParameterName.IsMatch(parameter.Name) && method.DeclaringType.Equals(c.UnderlyingSystemType))
{
result.Add(string.Concat(c.FullName, ".", method.Name, " -parameter- ", parameter.Name));
}
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetInvalidInterfaceNames(Assembly assembly)
{
var result = new List<string>();
var interfaces = assembly.GetTypes().Where(t => t.IsInterface);
foreach (var i in interfaces)
{
if (!InterfaceName.IsMatch(i.Name))
{
result.Add(i.FullName);
}
}
return result.ToArray();
}
private static IEnumerable<string> GetInvalidClassNames(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
if (c.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore classes produced by anonymous methods
{
continue;
}
if (c.IsDefined(typeof(ExceptionToClassNameConventionAttribute)))
{
continue;
}
if (!ClassName.IsMatch(c.Name) || InterfaceName.IsMatch(c.Name))
{
result.Add(c.FullName);
}
}
return result.ToArray();
}
private static IEnumerable<string> GetPropertiesWithNoGetter(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
var properties = c.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
if (property.GetSetMethod(true) != null && property.GetGetMethod(true) == null && property.DeclaringType.Equals(c.UnderlyingSystemType))
{
result.Add(string.Concat(c.FullName, ".", property.Name));
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetPropertiesThatReturnArray(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
var properties = c.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
// Skip attributes with WritableArrayAttribute defined. These are
// properties that were intended to expose arrays, as per MSDN this
// is not a .NET best practice. However, Lucene's design requires that
// this be done.
if (property.IsDefined(typeof(WritableArrayAttribute)))
{
continue;
}
var getMethod = property.GetGetMethod();
if (getMethod != null && getMethod.ReturnParameter != null && getMethod.ReturnParameter.ParameterType.IsArray && property.DeclaringType.Equals(c.UnderlyingSystemType))
{
result.Add(string.Concat(c.FullName, ".", property.Name));
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetProtectedFieldsContainingComparer(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
var fields = c.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var field in fields)
{
if (field.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-implemented properties
{
continue;
}
if (field.DeclaringType.GetEvent(field.Name) != null) // Ignore events
{
continue;
}
if ((field.IsFamily || field.IsFamilyOrAssembly) && ContainsComparer.IsMatch(field.Name) && field.DeclaringType.Equals(c.UnderlyingSystemType))
{
result.Add(string.Concat(c.FullName, ".", field.Name));
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetMembersContainingComparer(Assembly assembly)
{
var result = new List<string>();
var types = assembly.GetTypes();
foreach (var t in types)
{
if (ContainsComparer.IsMatch(t.Name) && t.IsVisible)
{
result.Add(t.FullName);
}
var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
if (ContainsComparer.IsMatch(member.Name) && member.DeclaringType.Equals(t.UnderlyingSystemType))
{
if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
{
result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
}
else if (member.MemberType == MemberTypes.Property)
{
result.Add(string.Concat(t.FullName, ".", member.Name));
}
else if (member.MemberType == MemberTypes.Event)
{
result.Add(string.Concat(t.FullName, ".", member.Name, " (event)"));
}
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetMembersNamedSize(Assembly assembly)
{
var result = new List<string>();
var types = assembly.GetTypes();
foreach (var t in types)
{
var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
if ("Size".Equals(member.Name, StringComparison.OrdinalIgnoreCase) && member.DeclaringType.Equals(t.UnderlyingSystemType))
{
if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
{
var method = (MethodInfo)member;
// Ignore methods with parameters
if (!method.GetParameters().Any())
{
result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
}
}
else if (member.MemberType == MemberTypes.Property)
{
result.Add(string.Concat(t.FullName, ".", member.Name));
}
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetMembersContainingNonNetNumeric(Assembly assembly)
{
var result = new List<string>();
var types = assembly.GetTypes();
foreach (var t in types)
{
//if (ContainsComparer.IsMatch(t.Name) && t.IsVisible)
//{
// result.Add(t.FullName);
//}
var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
// Ignore properties, methods, and events with IgnoreNetNumericConventionAttribute
if (member.IsDefined(typeof(ExceptionToNetNumericConventionAttribute)))
{
continue;
}
if (ContainsNonNetNumeric.IsMatch(member.Name) && member.DeclaringType.Equals(t.UnderlyingSystemType))
{
if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
{
result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
}
else if (member.MemberType == MemberTypes.Property)
{
result.Add(string.Concat(t.FullName, ".", member.Name));
}
else if (member.MemberType == MemberTypes.Event)
{
result.Add(string.Concat(t.FullName, ".", member.Name, " (event)"));
}
}
}
}
return result.ToArray();
}
private static IEnumerable<string> GetTypesContainingNonNetNumeric(Assembly assembly)
{
var result = new List<string>();
var types = assembly.GetTypes();
foreach (var t in types)
{
if (t.IsDefined(typeof(ExceptionToNetNumericConventionAttribute)))
{
continue;
}
if (ContainsNonNetNumeric.IsMatch(t.Name))
{
result.Add(t.FullName);
}
}
return result.ToArray();
}
#if FEATURE_METHODBASE_GETMETHODBODY
private static IEnumerable<string> GetMethodsThatReturnWritableArray(Assembly assembly)
{
var result = new List<string>();
var classes = assembly.GetTypes().Where(t => t.IsClass);
foreach (var c in classes)
{
if (c.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore classes produced by anonymous methods
{
continue;
}
var methods = c.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var method in methods)
{
// Skip attributes with WritableArrayAttribute defined. These are
// properties that were intended to expose arrays, as per MSDN this
// is not a .NET best practice. However, Lucene's design requires that
// this be done.
if (method.IsDefined(typeof(WritableArrayAttribute)))
{
continue;
}
// Ignore property method definitions
if (method.Name.StartsWith("get_", StringComparison.Ordinal) || method.Name.StartsWith("set_", StringComparison.Ordinal))
{
continue;
}
if (method != null && method.ReturnParameter != null
&& method.ReturnParameter.ParameterType.IsArray
&& method.DeclaringType.Equals(c.UnderlyingSystemType))
{
var methodBody = method.GetMethodBody();
if (methodBody != null)
{
var il = Encoding.UTF8.GetString(methodBody.GetILAsByteArray());
if (MethodBodyReturnValueOnly.IsMatch(il))
{
result.Add(string.Concat(c.FullName, ".", method.Name));
}
}
}
}
}
return result.ToArray();
}
#endif
private static IEnumerable<string> GetPublicNullableEnumMembers(Assembly assembly)
{
var result = new List<string>();
var types = assembly.GetTypes();
foreach (var t in types)
{
var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
if (member.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-generated methods
{
continue;
}
// Ignore properties, methods, and events with IgnoreNetNumericConventionAttribute
if (member.IsDefined(typeof(ExceptionToNullableEnumConventionAttribute)))
{
continue;
}
if (member.DeclaringType.Equals(t.UnderlyingSystemType))
{
if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
{
var method = (MethodInfo)member;
if (!method.IsPrivate)
{
if (method.ReturnParameter != null
&& Nullable.GetUnderlyingType(method.ReturnParameter.ParameterType) != null
&& method.ReturnParameter.ParameterType.GetGenericArguments()[0].IsEnum)
{
result.Add(string.Concat(t.FullName, ".", member.Name, "()"));
}
var parameters = method.GetParameters();
foreach (var parameter in parameters)
{
if (Nullable.GetUnderlyingType(parameter.ParameterType) != null
&& parameter.ParameterType.GetGenericArguments()[0].IsEnum
&& member.DeclaringType.Equals(t.UnderlyingSystemType))
{
result.Add(string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name));
}
}
}
}
else if (member.MemberType == MemberTypes.Constructor)
{
var constructor = (ConstructorInfo)member;
if (!constructor.IsPrivate)
{
var parameters = constructor.GetParameters();
foreach (var parameter in parameters)
{
if (Nullable.GetUnderlyingType(parameter.ParameterType) != null
&& parameter.ParameterType.GetGenericArguments()[0].IsEnum
&& member.DeclaringType.Equals(t.UnderlyingSystemType))
{
result.Add(string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name));
}
}
}
}
else if (member.MemberType == MemberTypes.Property
&& Nullable.GetUnderlyingType(((PropertyInfo)member).PropertyType) != null
&& ((PropertyInfo)member).PropertyType.GetGenericArguments()[0].IsEnum
&& IsNonPrivateProperty((PropertyInfo)member))
{
result.Add(string.Concat(t.FullName, ".", member.Name));
}
else if (member.MemberType == MemberTypes.Field
&& Nullable.GetUnderlyingType(((FieldInfo)member).FieldType) != null
&& ((FieldInfo)member).FieldType.GetGenericArguments()[0].IsEnum
&& (((FieldInfo)member).IsFamily || ((FieldInfo)member).IsFamilyOrAssembly))
{
result.Add(string.Concat(t.FullName, ".", member.Name, " (field)"));
}
}
}
}
return result.ToArray();
}
private static bool IsNonPrivateProperty(PropertyInfo property)
{
var getMethod = property.GetGetMethod();
var setMethod = property.GetSetMethod();
return ((getMethod != null && !getMethod.IsPrivate) ||
(setMethod != null && !setMethod.IsPrivate));
}
private static bool IsException(string name, string exceptionRegex)
{
bool hasExceptions = !string.IsNullOrWhiteSpace(exceptionRegex);
return (hasExceptions && Regex.IsMatch(name, exceptionRegex));
}
/// <summary>
/// Some parameters were incorrectly changed from List to IEnumerable during the port. This is
/// to track down constructor and method parameters and property and method return types
/// containing IEnumerable
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
private static IEnumerable<string> GetMembersAcceptingOrReturningType(Type lookFor, Assembly assembly, bool publiclyVisibleOnly, string exceptionRegex)
{
var result = new List<string>();
var types = assembly.GetTypes();
foreach (var t in types)
{
var members = t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
if (member.Name.StartsWith("<", StringComparison.Ordinal)) // Ignore auto-generated methods
{
continue;
}
if (member.DeclaringType.Equals(t.UnderlyingSystemType))
{
if (member.MemberType == MemberTypes.Method && !(member.Name.StartsWith("get_", StringComparison.Ordinal) || member.Name.StartsWith("set_", StringComparison.Ordinal)))
{
var method = (MethodInfo)member;
if (!publiclyVisibleOnly || !method.IsPrivate)
{
if (method.ReturnParameter != null
&& method.ReturnParameter.ParameterType.IsGenericType
&& method.ReturnParameter.ParameterType.GetGenericTypeDefinition().IsAssignableFrom(lookFor))
{
var name = string.Concat(t.FullName, ".", member.Name, "()");
if (!IsException(name, exceptionRegex))
{
result.Add(name);
}
}
var parameters = method.GetParameters();
foreach (var parameter in parameters)
{
if (parameter.ParameterType.IsGenericType
&& parameter.ParameterType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
&& member.DeclaringType.Equals(t.UnderlyingSystemType))
{
var name = string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name);
if (!IsException(name, exceptionRegex))
{
result.Add(name);
}
}
}
}
}
else if (member.MemberType == MemberTypes.Constructor)
{
var constructor = (ConstructorInfo)member;
if (!publiclyVisibleOnly || !constructor.IsPrivate)
{
var parameters = constructor.GetParameters();
foreach (var parameter in parameters)
{
if (parameter.ParameterType.IsGenericType
&& parameter.ParameterType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
&& member.DeclaringType.Equals(t.UnderlyingSystemType))
{
var name = string.Concat(t.FullName, ".", member.Name, "()", " -parameter- ", parameter.Name);
if (!IsException(name, exceptionRegex))
{
result.Add(name);
}
}
}
}
}
else if (member.MemberType == MemberTypes.Property
&& ((PropertyInfo)member).PropertyType.IsGenericType
&& ((PropertyInfo)member).PropertyType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
&& (!publiclyVisibleOnly || IsNonPrivateProperty((PropertyInfo)member)))
{
var name = string.Concat(string.Concat(t.FullName, ".", member.Name));
if (!IsException(name, exceptionRegex))
{
result.Add(name);
}
}
//else if (member.MemberType == MemberTypes.Field
// && ((FieldInfo)member).IndexableFieldType.IsGenericType
// && ((FieldInfo)member).IndexableFieldType.GetGenericTypeDefinition().IsAssignableFrom(lookFor)
// && (!publiclyVisibleOnly || (((FieldInfo)member).IsFamily || ((FieldInfo)member).IsFamilyOrAssembly)))
//{
// result.Add(string.Concat(t.FullName, ".", member.Name, " (field)"));
//}
}
}
}
return result.ToArray();
}
}
}
| |
/*
* ======================
* Bram's FolderSync
* ======================
* http://www.codeproject.com/KB/files/kratfoldersync.aspx
* kratchkov@inbox.lv
*
* Description:
* These classes can be used to compare and to synchronize two
* folders by defining simple rules (very basic).
*
* This is the first release.
*
* The FolderDiff class gets differencies between two directories.
* It raises a state for each file or folder:
* Possible states are described in enum FolderSynchronisation.ComparisonResult
*
* The FolderSync class uses the FolderDiff and reacts to its events to handle
* file copying, moving or whatsoever.
* Possible actions are desctibed in enum FolderSynchronisation.FileActions
*
* btw: If you sense missing 'z' in the comments, don't panic. It's alright, my
* keyboard has a little something against me writing 'z'...
*
* DISCLAIMER:
* THIS CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THIS
* CODE IS WITH YOU. SHOULD THIS CODE PROVE DEFECTIVE, YOU ASSUME
* THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION .
* You take full responsibility for the use of this code and any
* consequences thereof. I can not accept liability for damages
* or failures arising from the use of this code, or parts of this code.
*
*/
using System;
using System.IO;
namespace FolderSynchronisation
{
/// <summary>
/// Describes the comparison results between scanned files and directories.
/// </summary>
public enum ComparisonResult
{
/// <summary>
/// The two files are identical. That means, they have the same size. There
/// is nothing such as a CRC check.
/// </summary>
Identical = 0,
/// <summary>
/// The file is present in the second folder but is missing in the first one.
/// This is also raised for missing folders.
/// </summary>
MissingInFolder1,
/// <summary>
/// The file is present in the first folder but is missing in the second one.
/// This is also raised for missing folders.
/// </summary>
MissingInFolder2,
/// <summary>
/// The two files have different sizes.
/// </summary>
SizeDifferent
}
/// <summary>
/// This delegate describes the event raised from comparing a file.
/// </summary>
public delegate void CompareDelegate(ComparisonResult comparisonResult,
FileSystemInfo[] files, bool isAFolder);
/// <summary>
/// Gets differencies between two folders.
/// </summary>
public class FolderDiff
{
/// <summary>
/// Gets the first foldername.
/// </summary>
public string FolderName1
{
get
{
if (baseFolderInfo[1] == null)
return null;
return baseFolderInfo[1].FullName;
}
}
/// <summary>
/// Gets the second foldername.
/// </summary>
public string FolderName2
{
get
{
if (baseFolderInfo[2] == null)
return null;
return baseFolderInfo[2].FullName;
}
}
/// <summary>
/// This event is raised for each compared file or directory
/// </summary>
public event CompareDelegate CompareEvent;
private DirectoryInfo[] baseFolderInfo = new DirectoryInfo[2]; // The two base folders
private bool stop = false; // When set to true, the class stops all activity.
/// <summary>
/// Creates a new instance of a FolderDiff which can compare two folders.
/// </summary>
/// <param name="folderName1">Path to the first folder.</param>
/// <param name="folderName2">Path to the second folder.</param>
public FolderDiff(string folderName1, string folderName2)
{
folderName1 = folderName1.TrimEnd('\\');
folderName2 = folderName2.TrimEnd('\\');
baseFolderInfo[0] = new DirectoryInfo(folderName1);
baseFolderInfo[1] = new DirectoryInfo(folderName2);
}
/// <summary>
/// Starts comparing (This may take some time...)
/// </summary>
public void Compare()
{
if (this.CompareEvent == null)
return;
this.stop = false;
// Compares the dirs
CompareDirs("\\", 0); // Looks for missing dirs in dir 2
CompareDirs("\\", 1); // " " " " " " in dir 1
Compare2(@"\"); // Compares the files
}
/// <summary>
/// It compares the two folders and calls itself to recurse.
/// </summary>
/// <param name="relativeFolderName">where to start from</param>
private void Compare2(string relativeFolderName)
{
DirectoryInfo[] folderInfo = new DirectoryInfo[2];
folderInfo[0] = new DirectoryInfo(baseFolderInfo[0].FullName + relativeFolderName);
folderInfo[1] = new DirectoryInfo(baseFolderInfo[1].FullName + relativeFolderName);
bool fileCompReturn = CompareFiles(folderInfo); // Compares the files
if (!fileCompReturn)
return;
DirectoryInfo[] subDirs = folderInfo[0].GetDirectories();
foreach (DirectoryInfo subDir in subDirs) // Recursion
{
if (this.stop)
return;
string newRelativeFolderName = relativeFolderName + @"\" + subDir.Name;
Compare2(newRelativeFolderName);
}
}
/// <summary>
/// This cancels all activity immediately.
/// </summary>
public void CancelNow()
{
this.stop = true;
}
/// <summary>
/// Compares the files in the two folders described by folderInfo[]
/// </summary>
private bool CompareFiles(DirectoryInfo[] folderInfo)
{
FileInfo[][] filesInFolders = new FileInfo[2][];
try
{
filesInFolders[0] = folderInfo[0].GetFiles();
filesInFolders[1] = folderInfo[1].GetFiles();
}
catch (DirectoryNotFoundException)
{
return false; // We won't do anything here because missing folders are handled
// by FolderDiff.CompareDirs(string, int)
}
for (int i = 0; i < 2; i++)
{
foreach (FileInfo thisDirFile in filesInFolders[i])
{
if (this.stop)
return true;
int otherIndex = Math.Abs(i - 1); // Returns 0 if i == 1; returns 1 if i == 0
FileInfo otherDirFile = new FileInfo(folderInfo[otherIndex].FullName + @"\" + thisDirFile.Name);
FileInfo[] files = new FileInfo[2];
// CompareEvent must return as first files index the file in the first
// folder, that's why I need to set the index of files with i.
files[i] = thisDirFile; // thisDirFile is the first if i == 0
files[otherIndex] = otherDirFile; // otherDirFile is the second if i == 0
/*
if (i == 0)
{
files[0] = thisDirFile;
files[1] = otherDirFile;
} // Ugly, but working.
else // The former code is nicer, and works too.
{
files[0] = otherDirFile;
files[1] = thisDirFile;
}*/
if (otherDirFile.Exists) // The file exists in both dirs
{
if (i == 0)
continue;
if (otherDirFile.Length == thisDirFile.Length)
{
// both files have same length
// they are considered identical even though
// they might be different.
this.CompareEvent(ComparisonResult.Identical, files, false);
continue;
}
else // the files have different sizes, they are
{ // different
this.CompareEvent(ComparisonResult.SizeDifferent, files, false);
continue;
}
}
else // The file does not exist in other dir
{
if (i == 0) // i is the index in which the file exists
{
this.CompareEvent(ComparisonResult.MissingInFolder2, files, false);
continue;
}
else
{
this.CompareEvent(ComparisonResult.MissingInFolder1, files, false);
continue;
}
}
}
}
return true;
}
/// <summary>
/// Scans directories only. Recursive. It's divided into two parts, one for each base dir.
/// As it only sees missing dirs in one folder, it has to be called twice. That's why the
/// int directoryIndexToScan.
/// </summary>
/// <param name="relativeFolder">Where to begin (normally \). Used for recursion.</param>
/// <param name="directoryIndexToScan">Dir index, begins at 0</param>
private void CompareDirs(string relativeFolder, int directoryIndexToScan)
{
DirectoryInfo[] baseDirs = new DirectoryInfo[2];
baseDirs[0] = new DirectoryInfo(this.baseFolderInfo[0].FullName + relativeFolder);
baseDirs[1] = new DirectoryInfo(this.baseFolderInfo[1].FullName + relativeFolder);
int otherDirIndex = Math.Abs(directoryIndexToScan - 1);
foreach (DirectoryInfo subDir in baseDirs[directoryIndexToScan].GetDirectories())
{
if (this.stop)
return;
DirectoryInfo[] bothDirs = new DirectoryInfo[2];// This'll contain the info sent
// by the event.
bothDirs[directoryIndexToScan] = subDir;
bothDirs[otherDirIndex] = new DirectoryInfo
(this.baseFolderInfo[otherDirIndex].FullName
+ relativeFolder + @"\" + subDir.Name);
if (!bothDirs[otherDirIndex].Exists)
{
if (directoryIndexToScan == 0)
this.CompareEvent(ComparisonResult.MissingInFolder2, bothDirs, true);
else if (directoryIndexToScan == 1)
this.CompareEvent(ComparisonResult.MissingInFolder1, bothDirs, true);
}
else
CompareDirs(relativeFolder + @"\" + subDir.Name, directoryIndexToScan);
// calls itself to recurse
}
}
}
/// <summary>
/// Describes the possible actions that may be taken after a compare.
/// </summary>
public enum FileActions
{
/// <summary>
/// This cancels the copy. It's like CancelAll()
/// May only be used as an answer to the AskWhatToDo event.
/// </summary>
CancelCopy = 0,
/// <summary>
/// When used as defaultaction, it sends an AskWhatToDo event.
/// </summary>
Ask,
/// <summary>
/// Nothing has to be done.
/// </summary>
Ignore,
/// <summary>
/// The file must be copied.
/// May only be used for missing files.
/// </summary>
Copy,
/// <summary>
/// The file must be deleted (!! NO CONFIRMATION !!).
/// May only be used for missing files.
/// </summary>
Delete,
/// <summary>
/// The file with the older modification date must be overwritten.
/// May only be used for different size files.
/// </summary>
OverwriteOlder,
/// <summary>
/// The file with the newer modification date must be overwritten.
/// May only be used for different size files.
/// </summary>
OverwriteNewer,
/// <summary>
/// The file must be copied from folder 1 to folder 2.
/// May not be used as default action or as AskWhatToDo event answer for folder
/// with index 1. (Duh, missing files can't be copied)
/// </summary>
Write1to2,
/// <summary>
/// The file must be copied from folder 2 to folder 1.
/// May not be used as default action or as AskWhatToDo event answer for folder
/// with index 2. (Duh, missing files can't be copied)
/// </summary>
Write2to1
}
/// <summary>
/// This describes the event used when the user must be asked what to do.
/// </summary>
public delegate FileActions AskWhatToDoDelegate(FileSystemInfo[] files,
bool isADir, int missingIndex);
/// <summary>
/// This is raised when an error occurs.
/// </summary>
public delegate void ErrorDelegate(Exception e, string[] files);
/// <summary>
/// Synchronizes two folders.
/// </summary>
public class FolderSync
{
private FolderDiff diff; // Used to get the differencies
private string folderName1;
private string folderName2;
private FileActions defMissing1; // default action for files missing in folder 1
private FileActions defMissing2; // " " " " " " " 2
private FileActions defSize; // " " " " with different sizes
private bool initialized = true;
public event AskWhatToDoDelegate AskWhatToDo;
public event ErrorDelegate ErrorEvent; // If this is raised, then you have a problem
/// <summary>
/// Initializes a new instance of the FolderSync class which uses FolderDiff to
/// synchronize two folders. Call Sync() to start synchronizing.
/// </summary>
/// <param name="folderName1">First folder name</param>
/// <param name="folderName2">Second folder name</param>
/// <param name="defMissingInFolder1">Default action for files which are missing in the first folder.</param>
/// <param name="defMissingInFolder2">Default action for files which are missing in the second folder.</param>
/// <param name="defDifferentFiles">Default action for files which have different sizes.</param>
public FolderSync(string folderName1, string folderName2,
FileActions defMissingInFolder1,
FileActions defMissingInFolder2,
FileActions defDifferentFiles)
{
if (defMissingInFolder1 == FileActions.OverwriteNewer |
defMissingInFolder1 == FileActions.OverwriteOlder |
defMissingInFolder1 == FileActions.Write1to2 | // These choices are not valid
defMissingInFolder1 == FileActions.Write2to1)
{
this.initialized = false;
if (this.ErrorEvent != null)
this.ErrorEvent(new ArgumentException("defaultActionForMissingFiles1 is not correct"), null);
}
if (defMissingInFolder2 == FileActions.OverwriteNewer |
defMissingInFolder2 == FileActions.OverwriteOlder |
defMissingInFolder2 == FileActions.Write1to2 | // These choices are not valid
defMissingInFolder2 == FileActions.Write2to1)
{
this.initialized = false;
if (this.ErrorEvent != null)
this.ErrorEvent(new ArgumentException("defaultActionForMissingFiles2 is not correct"), null);
}
if (defDifferentFiles == FileActions.Copy)
{
this.initialized = false;
if (this.ErrorEvent != null)
this.ErrorEvent(new ArgumentException("defaultActionForDifferentFiles is not correct"), null);
}
this.defMissing1 = defMissingInFolder1;
this.defMissing2 = defMissingInFolder2;
this.defSize = defDifferentFiles;
this.folderName1 = folderName1;
this.folderName2 = folderName2;
this.diff = new FolderDiff(this.folderName1, this.folderName2);
this.diff.CompareEvent += new CompareDelegate(Compared);
}
/// <summary>
/// Cancels all activity now, immediately, without waiting a femtosecond (Without exageration).
/// </summary>
public void CancelNow()
{
diff.CancelNow();
}
// This is called by diff.CompareEvent
private void Compared(ComparisonResult result, FileSystemInfo[] files, bool isADir)
{
#region SizeDifferent
if (result == ComparisonResult.SizeDifferent) // Can only be files, not dirs
{
FileActions action = this.defSize;
if (action == FileActions.Ask)
action = this.AskWhatToDo(files, isADir, -1); // Need to ask user if
// default action is Ask
if (action == FileActions.CancelCopy) // user choice: Cancel
{
this.CancelNow();
return;
}
switch (action)
{
case FileActions.Ignore: // Do nothing
break;
case FileActions.Delete: // The file(s) must be deleted
if (files[0].Exists)
{
files[0].Delete();
}
else
{
files[1].Delete();
}
break;
// Copy by looking at the dates *************************************
case FileActions.OverwriteNewer: // D
this.OverWriteDate((FileInfo)files[0], (FileInfo)files[1], false); //
break; // A
//
case FileActions.OverwriteOlder: // T
this.OverWriteDate((FileInfo)files[0], (FileInfo)files[1], true); //
break; // E
//
//********************************************************************
case FileActions.Write1to2: // Writes the file to folder 2 (the file should exist)
try
{
((FileInfo)files[0]).CopyTo(files[1].FullName, true);
}
catch (Exception e) // This should NOT happen (and it doesn't, usually...)
{
string[] f = new string[2];
f[0] = files[0].FullName;
f[1] = files[1].FullName;
this.ErrorEvent(e, f);
}
break;
case FileActions.Write2to1: // Writes the file to folder 1 (the file should exist)
try
{
((FileInfo)files[1]).CopyTo(files[0].FullName, true);
}
catch (Exception e) // This should NOT happen (and it doesn't, usually...)
{
string[] f = new string[2];
f[0] = files[0].FullName;
f[1] = files[1].FullName;
this.ErrorEvent(e, f);
}
break;
}
}
#endregion
#region MissingInFolderx
if (result == ComparisonResult.MissingInFolder1 | result == ComparisonResult.MissingInFolder2)
{
FileActions action = FileActions.Ask;
int missingIndex = 0; // used only for the AskWhatToDo event
// if default action is Ask
if (result == ComparisonResult.MissingInFolder1)
{
action = this.defMissing1;
missingIndex = 1;
}
if (result == ComparisonResult.MissingInFolder2)
{
action = this.defMissing2;
missingIndex = 2;
}
if (action == FileActions.Ask)
action = this.AskWhatToDo(files, isADir, missingIndex);
if (action == FileActions.CancelCopy)
{
this.CancelNow();
return;
}
switch (action)
{
case FileActions.Ignore:
break;
case FileActions.Copy: // Copy the missing file or dir
if (!isADir) // It's not a dir (incredible!)
{
int missingFileIndex = missingIndex - 1; // missingFileIndex has to be 0-based
int presentFileIndex = Math.Abs(missingFileIndex - 1);
try
{
((FileInfo)files[presentFileIndex]).CopyTo(files[missingFileIndex].FullName, false);
}
catch (IOException e) // This should not happen because files[presentIndex] should not exist
{
string[] f = new string[2];
f[0] = files[0].FullName;
f[1] = files[1].FullName;
this.ErrorEvent(e, f);
}
}
else if (isADir) // It's a dir (wow!)
{
int missingFolderIndex = missingIndex - 1;
int presentFolderIndex = Math.Abs(missingFolderIndex - 1);
RecursiveCopy rCopy = new RecursiveCopy(files[presentFolderIndex].FullName, files[missingFolderIndex].FullName, false);
rCopy.ErrorEvent += this.ErrorEvent;
rCopy.Copy();
}
break;
case FileActions.Delete: // The existing file or dir will be deleted
if (isADir)
{
if (files[0].Exists)
((DirectoryInfo)files[0]).Delete(true);
else if (files[1].Exists)
((DirectoryInfo)files[1]).Delete(true);
}
else
{
if (files[0].Exists)
((FileInfo)files[0]).Delete();
else if (files[1].Exists)
((FileInfo)files[1]).Delete();
}
break;
case FileActions.Write1to2: // Shall write the file or dir from folder index 0 to folder index 1
if (files[0].Exists & isADir)
{
RecursiveCopy rCopy = new RecursiveCopy(files[0].FullName, files[1].FullName, false);
rCopy.ErrorEvent += this.ErrorEvent;
rCopy.Copy();
}
else if (files[0].Exists & !isADir)
{
try
{
((FileInfo)files[0]).CopyTo(files[1].FullName, false); // Copies the file
}
catch (Exception e)
{
string[] f = new string[2];
f[0] = files[0].FullName;
f[1] = files[1].FullName;
this.ErrorEvent(e, f);
}
}
break;
case FileActions.Write2to1: // Shall write the file or dir from folder index 1 to folder index 0
if (files[1].Exists & isADir)
{
RecursiveCopy rCopy = new RecursiveCopy(files[1].FullName, files[0].FullName, false);
rCopy.ErrorEvent += this.ErrorEvent;
rCopy.Copy();
}
else if (files[1].Exists & !isADir)
{
try
{
((FileInfo)files[1]).CopyTo(files[0].FullName, false);
}
catch (Exception e)
{
string[] f = new string[2];
f[0] = files[0].FullName;
f[1] = files[1].FullName;
this.ErrorEvent(e, f);
}
}
break;
}
}
#endregion
}
/// <summary>
/// Begins synchronisation.
/// </summary>
public void Sync()
{
if ((this.defMissing1 == FileActions.Ask | this.defMissing2 == FileActions.Ask
| this.defSize == FileActions.Ask) & this.AskWhatToDo == null)
return;
if (this.initialized & this.ErrorEvent != null)
diff.Compare();
}
/// <summary>
/// Copies one file over another. Looks for the last modification date to know which file
/// to overwrite.
/// </summary>
/// <param name="file1">the first file</param>
/// <param name="file2">the second file</param>
/// <param name="deleteOlder">true deletes the older file, false the newer</param>
private void OverWriteDate(FileInfo file1, FileInfo file2, bool deleteOlder)
{
long fileModDate1 = file1.LastWriteTime.Ticks;
long fileModDate2 = file2.LastWriteTime.Ticks;
// Ticks bigger => file newer
if (deleteOlder ^ (fileModDate1 < fileModDate2))
{
// delete file 2 ==> Copy 1 -> 2
try
{
file1.CopyTo(file2.FullName, true);
}
catch (IOException e)
{
string[] f = new string[2];
f[0] = file1.FullName;
f[1] = file2.FullName ;
this.ErrorEvent(e,f);
}
}
else
{
try
{
// delete file 1 ==> Copy 2 -> 2
file2.CopyTo(file1.FullName, true);
}
catch (IOException e)
{
string[] f = new string[2];
f[0] = file1.FullName;
f[1] = file2.FullName ;
this.ErrorEvent(e,f);
}
}
}
}
/// <summary>
/// Can copy dirs recursively (That's magic)
/// </summary>
public class RecursiveCopy
{
private string sourceFolder;
public string SourceFolder { get { return this.sourceFolder; } }
private string destinationFolder;
public string DestinationFolder { get { return this.destinationFolder; } }
private bool overwrite;
public bool Overwrite { get { return this.overwrite; } }
private bool cancelAll = false;
private bool isReady = false;
public event ErrorDelegate ErrorEvent;
/// <summary>
/// Copies a directory to another. Recursively.
/// </summary>
/// <param name="sourceFolder">Source Dir</param>
/// <param name="destinationFolder">Destination dir.</param>
/// <param name="overwrite">Specifies if a existing dir shall be overwritten. Existing files will not be deleted</param>
public RecursiveCopy(string sourceFolder, string destinationFolder, bool overwrite)
{
this.sourceFolder = sourceFolder;
this.destinationFolder = destinationFolder;
this.overwrite = true;
if (Directory.Exists(this.destinationFolder) & !overwrite)
{
this.ErrorEvent(new ApplicationException("The destination directory exists and overwrite is false!"), null);
}
isReady = true;
}
/// <summary>
/// Cancels all copying
/// </summary>
public void CancelAll()
{
this.cancelAll = true;
}
/// <summary>
/// Begins the copy process.
/// </summary>
public void Copy()
{
if (!isReady)
return;
DirectoryInfo sourceDir = new DirectoryInfo(this.sourceFolder);
DirectoryInfo destDir = new DirectoryInfo(this.destinationFolder);
Directory.CreateDirectory(this.destinationFolder);
Copy(sourceDir, destDir);
}
private void Copy(DirectoryInfo sourceDir, DirectoryInfo destDir)
{
DirectoryInfo[] subDirs = sourceDir.GetDirectories();
FileInfo[] files = sourceDir.GetFiles();
foreach (FileInfo file in files)
{
if (cancelAll)
return;
try
{
file.CopyTo(destDir.FullName + "\\" + file.Name, this.overwrite);
}
catch (IOException e)
{
string[] f= new string[1];
f[0] = file.FullName;
this.ErrorEvent(e, f);
}
}
foreach (DirectoryInfo dir in subDirs)
{
if (cancelAll)
return;
Directory.CreateDirectory(destDir.FullName + @"\" + dir.Name);
Copy(dir, new DirectoryInfo(destDir.FullName + @"\" + dir.Name));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using xsc = DotNetXmlSwfChart;
namespace testWeb.tests
{
public class ParallelColumn3DOne : ChartTestBase
{
#region ChartInclude
public override xsc.ChartHTML ChartInclude
{
get
{
DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML();
chartHtml.height = 300;
chartHtml.bgColor = "ffaa88";
chartHtml.flashFile = "charts/charts.swf";
chartHtml.libraryPath = "charts/charts_library";
chartHtml.xmlSource = "xmlData.aspx";
return chartHtml;
}
}
#endregion
#region Chart
public override xsc.Chart Chart
{
get
{
xsc.Chart c = new xsc.Chart();
c.AddChartType(xsc.XmlSwfChartType.ColumnParallel3d);
c.AxisCategory = SetAxisCategory(c.ChartType[0]);
c.AxisTicks = SetAxisTicks();
c.AxisValue = SetAxisValue();
c.ChartBorder = SetChartBorder();
c.Data = SetChartData();
c.ChartGridH = SetChartGridH();
c.ChartPreferences = SetChartPreferences(c.ChartType[0]);
c.ChartRectangle = SetChartRectangle();
c.ChartValue = SetChartValue();
c.AddDrawImage(CreateDrawImage());
c.LegendRectangle = SetLegendRectangle();
c.LinkAreas = SetLinkAreas();
c.AddSeriesColor("666666");
c.AddSeriesColor("768bb3");
c.AddSeriesColor("884400");
c.SeriesGap = SetSeriesGap();
return c;
}
}
#endregion
#region Helpers
#region SetAxisCategory(xsc.XmlSwfChartType xmlSwfChartType)
private xsc.AxisCategory SetAxisCategory(xsc.XmlSwfChartType xmlSwfChartType)
{
xsc.AxisCategory ac = new xsc.AxisCategory(xmlSwfChartType);
ac.Size = 10;
ac.Color = "000000";
ac.Alpha = 75;
ac.Skip = 0;
ac.Orientation = "horizontal";
return ac;
}
#endregion
#region SetAxisTicks()
private xsc.AxisTicks SetAxisTicks()
{
xsc.AxisTicks at = new xsc.AxisTicks();
at.ValueTicks = false;
at.CategoryTicks = false;
return at;
}
#endregion
#region SetAxisValue()
private xsc.AxisValue SetAxisValue()
{
xsc.AxisValue av = new xsc.AxisValue();
av.Alpha = 0;
av.Max = 220;
return av;
}
#endregion
#region SetChartBorder()
private xsc.ChartBorder SetChartBorder()
{
xsc.ChartBorder cb = new xsc.ChartBorder();
cb.TopThickness = 0;
cb.BottomThickness = 0;
cb.LeftThickness = 0;
cb.RightThickness = 0;
return cb;
}
#endregion
#region SetChartData()
private xsc.ChartData SetChartData()
{
xsc.ChartData cd = new xsc.ChartData();
cd.AddDataPoint("region 1", "2005", 90);
cd.AddDataPoint("region 1", "2006", 50);
cd.AddDataPoint("region 1", "2007", 40);
cd.AddDataPoint("region 2", "2005", 150);
cd.AddDataPoint("region 2", "2006", 100);
cd.AddDataPoint("region 2", "2007", 70);
cd.AddDataPoint("region 3", "2005", 200);
cd.AddDataPoint("region 3", "2006", 160);
cd.AddDataPoint("region 3", "2007", 90);
return cd;
}
#endregion
#region SetChartGridH()
private xsc.ChartGrid SetChartGridH()
{
xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal);
cg.Color = "000000";
cg.Thickness = 0;
cg.Alpha = 5;
return cg;
}
#endregion
#region SetChartPreferences(xsc.XmlSwfChartType xmlSwfChartType)
private xsc.ChartPreferences SetChartPreferences(xsc.XmlSwfChartType xmlSwfChartType)
{
xsc.ChartPreferences cp = new xsc.ChartPreferences(xmlSwfChartType);
cp.RotationX = 30;
cp.RotationY = 30;
return cp;
}
#endregion
#region SetChartRectangle()
private xsc.ChartRectangle SetChartRectangle()
{
xsc.ChartRectangle cr = new xsc.ChartRectangle();
cr.X = 50;
cr.Y = 50;
cr.Width = 300;
cr.Height = 200;
cr.PositiveColor = "888888";
cr.PositiveAlpha = 10;
return cr;
}
#endregion
#region SetChartValue()
private xsc.ChartValue SetChartValue()
{
xsc.ChartValue cv = new xsc.ChartValue();
cv.HideZero = true;
cv.Color = "ffffff";
cv.Alpha = 90;
cv.Font = "Arial";
cv.Bold = true;
cv.Size = 12;
cv.Position = "cursor";
cv.Prefix = "";
cv.Suffix = "";
cv.Decimals = 0;
cv.Separator = "";
cv.AsPercentage = true;
return cv;
}
#endregion
#region CreateDrawImage()
private xsc.DrawImage CreateDrawImage()
{
xsc.DrawImage di = new xsc.DrawImage();
di.Url = "images/cursor.swf";
di.X = 0;
di.Y = 0;
di.Width = 401;
di.Height = 301;
di.Rotation = 0;
return di;
}
#endregion
#region SetLegendRectangle()
private xsc.LegendRectangle SetLegendRectangle()
{
xsc.LegendRectangle lr = new xsc.LegendRectangle();
lr.X = -100;
lr.Y = -100;
lr.Width = 10;
lr.Height = 10;
return lr;
}
#endregion
#region SetLinkAreas()
private List<xsc.LinkArea> SetLinkAreas()
{
List<xsc.LinkArea> list = new List<xsc.LinkArea>();
xsc.LinkArea la = new xsc.LinkArea();
la.X = 180;
la.Y = 0;
la.Width = 40;
la.Height = 35;
la.Url = "xmlData.aspx?test=parallelcolumn3d1";
la.Target = "live_update";
list.Add(la);
la = new xsc.LinkArea();
la.X = 180;
la.Y = 265;
la.Width = 40;
la.Height = 35;
la.Url = "xmlData.aspx?test=parallelcolumn3d1";
la.Target = "live_update";
list.Add(la);
la = new xsc.LinkArea();
la.X = 0;
la.Y = 130;
la.Width = 35;
la.Height = 40;
la.Url = "xmlData.aspx?test=parallelcolumn3d1";
la.Target = "live_update";
list.Add(la);
la = new xsc.LinkArea();
la.X = 365;
la.Y = 130;
la.Width = 35;
la.Height = 40;
la.Url = "xmlData.aspx?test=parallelcolumn3d1";
la.Target = "live_update";
list.Add(la);
return list;
}
#endregion
#region SetSeriesGap()
private xsc.SeriesGap SetSeriesGap()
{
xsc.SeriesGap sg = new xsc.SeriesGap();
sg.BarGap = 30;
sg.SetGap = 30;
return sg;
}
#endregion
#endregion
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public enum FBTestEnum
{
VALUE_0,
VALUE_1
}
public struct FBTestStruct
{
public int m_Int;
public FBTestEnum m_FBTestEnum;
}
public class FieldBuilderSetConstant
{
private TypeBuilder TypeBuilder
{
get
{
if (null == _typeBuilder)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName("FieldBuilderSetConstant_Assembly"), AssemblyBuilderAccess.Run);
ModuleBuilder module = TestLibrary.Utilities.GetModuleBuilder(assembly, "FieldBuilderSetConstant_Module");
_typeBuilder = module.DefineType("FieldBuilderSetConstant_Type", TypeAttributes.Abstract);
}
return _typeBuilder;
}
}
private TypeBuilder _typeBuilder;
[Fact]
public void TestForBool()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest1", typeof(Boolean), FieldAttributes.Public);
// set default value
field.SetConstant(false);
// change default value
field.SetConstant(true);
}
[Fact]
public void TestForSByte()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest2", typeof(sbyte), FieldAttributes.Public);
// set default value
field.SetConstant(SByte.MinValue);
// change default value
field.SetConstant(SByte.MaxValue);
}
[Fact]
public void TestForShort()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest3", typeof(short), FieldAttributes.Public);
// set default value
field.SetConstant(Int16.MaxValue);
// change default value
field.SetConstant(Int16.MinValue);
}
[Fact]
public void TestForInt()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest4", typeof(int), FieldAttributes.Public);
// set default value
field.SetConstant(int.MinValue);
// change default value
field.SetConstant(int.MaxValue);
}
[Fact]
public void TestForLong()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest5", typeof(long), FieldAttributes.Public);
// set default value
field.SetConstant(long.MaxValue);
// change default value
field.SetConstant(long.MinValue);
}
[Fact]
public void TestForByte()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest6", typeof(byte), FieldAttributes.Public);
// set default value
field.SetConstant(byte.MinValue);
// change default value
field.SetConstant(byte.MaxValue);
}
[Fact]
public void TestForUShort()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest7", typeof(ushort), FieldAttributes.Public);
// set default value
field.SetConstant(ushort.MaxValue);
// change default value
field.SetConstant(ushort.MinValue);
}
[Fact]
public void TestForUInt()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest8", typeof(uint), FieldAttributes.Public);
// set default value
field.SetConstant(uint.MaxValue);
// change default value
field.SetConstant(uint.MinValue);
}
[Fact]
public void TestForULong()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest9", typeof(ulong), FieldAttributes.Public);
// set default value
field.SetConstant(ulong.MaxValue);
// change default value
field.SetConstant(ulong.MinValue);
}
[Fact]
public void TestForFloat()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest10", typeof(float), FieldAttributes.Public);
// set default value
field.SetConstant(float.MaxValue);
// change default value
field.SetConstant(float.NaN);
}
[Fact]
public void TestForDouble()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest11", typeof(double), FieldAttributes.Public);
// set default value
field.SetConstant(double.PositiveInfinity);
// change default value
field.SetConstant(double.NegativeInfinity);
}
[Fact]
public void TestForDateTime()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest12", typeof(DateTime), FieldAttributes.Public);
// set default value
field.SetConstant(DateTime.MinValue);
// change default value
field.SetConstant(DateTime.MaxValue);
}
[Fact]
public void TestForChar()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest13", typeof(Char), FieldAttributes.Public);
// set default value
field.SetConstant(Char.MaxValue);
// change default value
field.SetConstant(Char.MinValue);
}
[Fact]
public void TestForString()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest14", typeof(string), FieldAttributes.Public);
// set default value
field.SetConstant(null);
// change default value
field.SetConstant(TestLibrary.Generator.GetString(false, 1, 30));
}
[Fact]
public void TestForCustomType()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest15", typeof(FBTestEnum), FieldAttributes.Public);
// set default value
field.SetConstant(FBTestEnum.VALUE_0);
// change default value
field.SetConstant(FBTestEnum.VALUE_1);
}
[Fact]
public void TestForObject()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest17", typeof(object), FieldAttributes.Public);
// set default value
field.SetConstant(null);
}
[Fact]
public void TestForNullOnCustomType()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest18", typeof(FieldBuilderSetConstant), FieldAttributes.Public);
// set default value
field.SetConstant(null);
}
[Fact]
public void TestThrowsExceptionOnCreateTypeCalled()
{
FieldBuilder field = TypeBuilder.DefineField("Field_NegTest1", typeof(int), FieldAttributes.Public);
TypeBuilder.CreateTypeInfo().AsType();
Assert.Throws<InvalidOperationException>(() => { field.SetConstant(0); });
}
[Fact]
public void TestThrowsExceptionForInvalidValueOnFieldType()
{
FieldBuilder field = TypeBuilder.DefineField("Field_NegTest2_Boolean", typeof(Boolean), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_int", typeof(int), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_SByte", typeof(SByte), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Int16", typeof(Int16), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Int64", typeof(long), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Byte", typeof(byte), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_UInt16", typeof(ushort), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_UInt32", typeof(uint), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_UInt64", typeof(ulong), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Single", typeof(float), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Double", typeof(double), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_DateTime", typeof(DateTime), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Char", typeof(Char), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_String", typeof(string), FieldAttributes.Public);
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_FBTestEnum", typeof(FBTestEnum), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Decimal", typeof(Decimal), FieldAttributes.Public);
VerificationHelper(field, new object(), typeof(ArgumentException));
field = TypeBuilder.DefineField("Field_NegTest2_Object", typeof(object), FieldAttributes.Public);
VerificationHelper(field, new object(), typeof(ArgumentException));
}
[Fact]
public void TestThrowsExceptionForStruct()
{
FieldBuilder field = TypeBuilder.DefineField("Field_NegTest3", typeof(FBTestStruct), FieldAttributes.Public);
VerificationHelper(field, null, typeof(ArgumentException));
}
[Fact]
public void TestThrowsExceptionForDecimal()
{
FieldBuilder field = TypeBuilder.DefineField("Field_PosTest16", typeof(Decimal), FieldAttributes.Public);
VerificationHelper(field, decimal.One, typeof(ArgumentException));
}
private void VerificationHelper(FieldBuilder field, object value, Type expected)
{
Assert.Throws(expected, () => { field.SetConstant(value); });
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Fabric.Internal.Editor.ThirdParty.xcodeapi
{
internal class DeviceTypeRequirement
{
public static readonly string Key = "idiom";
public static readonly string Any = "universal";
public static readonly string iPhone = "iphone";
public static readonly string iPad = "ipad";
public static readonly string Mac = "mac";
public static readonly string iWatch = "watch";
}
internal class MemoryRequirement
{
public static readonly string Key = "memory";
public static readonly string Any = "";
public static readonly string Mem1GB = "1GB";
public static readonly string Mem2GB = "2GB";
}
internal class GraphicsRequirement
{
public static readonly string Key = "graphics-feature-set";
public static readonly string Any = "";
public static readonly string Metal1v2 = "metal1v2";
public static readonly string Metal2v2 = "metal2v2";
}
// only used for image sets
internal class SizeClassRequirement
{
public static readonly string HeightKey = "height-class";
public static readonly string WidthKey = "width-class";
public static readonly string Any = "";
public static readonly string Compact = "compact";
public static readonly string Regular = "regular";
}
// only used for image sets
internal class ScaleRequirement
{
public static readonly string Key = "scale";
public static readonly string Any = ""; // vector image
public static readonly string X1 = "1x";
public static readonly string X2 = "2x";
public static readonly string X3 = "3x";
}
internal class DeviceRequirement
{
internal Dictionary<string, string> values = new Dictionary<string, string>();
public DeviceRequirement AddDevice(string device)
{
AddCustom(DeviceTypeRequirement.Key, device);
return this;
}
public DeviceRequirement AddMemory(string memory)
{
AddCustom(MemoryRequirement.Key, memory);
return this;
}
public DeviceRequirement AddGraphics(string graphics)
{
AddCustom(GraphicsRequirement.Key, graphics);
return this;
}
public DeviceRequirement AddWidthClass(string sizeClass)
{
AddCustom(SizeClassRequirement.WidthKey, sizeClass);
return this;
}
public DeviceRequirement AddHeightClass(string sizeClass)
{
AddCustom(SizeClassRequirement.HeightKey, sizeClass);
return this;
}
public DeviceRequirement AddScale(string scale)
{
AddCustom(ScaleRequirement.Key, scale);
return this;
}
public DeviceRequirement AddCustom(string key, string value)
{
if (values.ContainsKey(key))
values.Remove(key);
values.Add(key, value);
return this;
}
public DeviceRequirement()
{
values.Add("idiom", DeviceTypeRequirement.Any);
}
}
internal class AssetCatalog
{
AssetFolder m_Root;
public string path { get { return m_Root.path; } }
public AssetFolder root { get { return m_Root; } }
public AssetCatalog(string path, string authorId)
{
if (Path.GetExtension(path) != ".xcassets")
throw new Exception("Asset catalogs must have xcassets extension");
m_Root = new AssetFolder(path, null, authorId);
}
AssetFolder OpenFolderForResource(string relativePath)
{
var pathItems = PBX.Utils.SplitPath(relativePath).ToList();
// remove path filename
pathItems.RemoveAt(pathItems.Count - 1);
AssetFolder folder = root;
foreach (var pathItem in pathItems)
folder = folder.OpenFolder(pathItem);
return folder;
}
// Checks if a dataset at the given path exists and returns it if it does.
// Otherwise, creates a new dataset. Parent folders are created if needed.
// Note: the path is filesystem path, not logical asset name formed
// only from names of the folders that have "provides namespace" attribute.
// If you want to put certain resources in folders with namespace, first
// manually create the folders and then set the providesNamespace attribute.
// OpenNamespacedFolder may help to do this.
public AssetDataSet OpenDataSet(string relativePath)
{
var folder = OpenFolderForResource(relativePath);
return folder.OpenDataSet(Path.GetFileName(relativePath));
}
public AssetImageSet OpenImageSet(string relativePath)
{
var folder = OpenFolderForResource(relativePath);
return folder.OpenImageSet(Path.GetFileName(relativePath));
}
public AssetImageStack OpenImageStack(string relativePath)
{
var folder = OpenFolderForResource(relativePath);
return folder.OpenImageStack(Path.GetFileName(relativePath));
}
// Checks if a folder with given path exists and returns it if it does.
// Otherwise, creates a new folder. Parent folders are created if needed.
public AssetFolder OpenFolder(string relativePath)
{
if (relativePath == null)
return root;
var pathItems = PBX.Utils.SplitPath(relativePath);
if (pathItems.Length == 0)
return root;
AssetFolder folder = root;
foreach (var pathItem in pathItems)
folder = folder.OpenFolder(pathItem);
return folder;
}
// Creates a directory structure with "provides namespace" attribute.
// First, retrieves or creates the directory at relativeBasePath, creating parent
// directories if needed. Effectively calls OpenFolder(relativeBasePath).
// Then, relative to this directory, creates namespacePath directories with "provides
// namespace" attribute set. Fails if the attribute can't be set.
public AssetFolder OpenNamespacedFolder(string relativeBasePath, string namespacePath)
{
var folder = OpenFolder(relativeBasePath);
var pathItems = PBX.Utils.SplitPath(namespacePath);
foreach (var pathItem in pathItems)
{
folder = folder.OpenFolder(pathItem);
folder.providesNamespace = true;
}
return folder;
}
public void Write()
{
m_Root.Write();
}
}
internal abstract class AssetCatalogItem
{
public readonly string name;
public readonly string authorId;
public string path { get { return m_Path; } }
protected Dictionary<string, string> m_Properties = new Dictionary<string, string>();
protected string m_Path;
public AssetCatalogItem(string name, string authorId)
{
if (name != null && name.Contains("/"))
throw new Exception("Asset catalog item must not have slashes in name");
this.name = name;
this.authorId = authorId;
}
protected JsonElementDict WriteInfoToJson(JsonDocument doc)
{
var info = doc.root.CreateDict("info");
info.SetInteger("version", 1);
info.SetString("author", authorId);
return info;
}
public abstract void Write();
}
internal class AssetFolder : AssetCatalogItem
{
List<AssetCatalogItem> m_Items = new List<AssetCatalogItem>();
bool m_ProvidesNamespace = false;
public bool providesNamespace
{
get { return m_ProvidesNamespace; }
set {
if (m_Items.Count > 0 && value != m_ProvidesNamespace)
throw new Exception("Asset folder namespace providing status can't be "+
"changed after items have been added");
m_ProvidesNamespace = value;
}
}
internal AssetFolder(string parentPath, string name, string authorId) : base(name, authorId)
{
if (name != null)
m_Path = Path.Combine(parentPath, name);
else
m_Path = parentPath;
}
// Checks if a folder with given name exists and returns it if it does.
// Otherwise, creates a new folder.
public AssetFolder OpenFolder(string name)
{
var item = GetChild(name);
if (item != null)
{
if (item is AssetFolder)
return item as AssetFolder;
throw new Exception("The given path is already occupied with an asset");
}
var folder = new AssetFolder(m_Path, name, authorId);
m_Items.Add(folder);
return folder;
}
T GetExistingItemWithType<T>(string name) where T : class
{
var item = GetChild(name);
if (item != null)
{
if (item is T)
return item as T;
throw new Exception("The given path is already occupied with an asset");
}
return null;
}
// Checks if a dataset with given name exists and returns it if it does.
// Otherwise, creates a new data set.
public AssetDataSet OpenDataSet(string name)
{
var item = GetExistingItemWithType<AssetDataSet>(name);
if (item != null)
return item;
var dataset = new AssetDataSet(m_Path, name, authorId);
m_Items.Add(dataset);
return dataset;
}
// Checks if an imageset with given name exists and returns it if it does.
// Otherwise, creates a new image set.
public AssetImageSet OpenImageSet(string name)
{
var item = GetExistingItemWithType<AssetImageSet>(name);
if (item != null)
return item;
var imageset = new AssetImageSet(m_Path, name, authorId);
m_Items.Add(imageset);
return imageset;
}
// Checks if a image stack with given name exists and returns it if it does.
// Otherwise, creates a new image stack.
public AssetImageStack OpenImageStack(string name)
{
var item = GetExistingItemWithType<AssetImageStack>(name);
if (item != null)
return item;
var imageStack = new AssetImageStack(m_Path, name, authorId);
m_Items.Add(imageStack);
return imageStack;
}
// Returns the requested item or null if not found
public AssetCatalogItem GetChild(string name)
{
foreach (var item in m_Items)
{
if (item.name == name)
return item;
}
return null;
}
void WriteJson()
{
if (!providesNamespace)
return; // json is optional when namespace is not provided
var doc = new JsonDocument();
WriteInfoToJson(doc);
var props = doc.root.CreateDict("properties");
props.SetBoolean("provides-namespace", providesNamespace);
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
public override void Write()
{
if (Directory.Exists(m_Path))
Directory.Delete(m_Path, true); // ensure we start from clean state
Directory.CreateDirectory(m_Path);
WriteJson();
foreach (var item in m_Items)
item.Write();
}
}
abstract class AssetCatalogItemWithVariants : AssetCatalogItem
{
protected List<VariantData> m_Variants = new List<VariantData>();
protected List<string> m_ODRTags = new List<string>();
protected AssetCatalogItemWithVariants(string name, string authorId) :
base(name, authorId)
{
}
protected class VariantData
{
public DeviceRequirement requirement;
public string path;
public VariantData(DeviceRequirement requirement, string path)
{
this.requirement = requirement;
this.path = path;
}
}
public bool HasVariant(DeviceRequirement requirement)
{
foreach (var item in m_Variants)
{
if (item.requirement.values == requirement.values)
return true;
}
return false;
}
public void AddOnDemandResourceTag(string tag)
{
if (!m_ODRTags.Contains(tag))
m_ODRTags.Add(tag);
}
protected void AddVariant(VariantData newItem)
{
foreach (var item in m_Variants)
{
if (item.requirement.values == newItem.requirement.values)
throw new Exception("The given requirement has been already added");
if (Path.GetFileName(item.path) == Path.GetFileName(path))
throw new Exception("Two items within the same set must not have the same file name");
}
if (Path.GetFileName(newItem.path) == "Contents.json")
throw new Exception("The file name must not be equal to Contents.json");
m_Variants.Add(newItem);
}
protected void WriteODRTagsToJson(JsonElementDict info)
{
if (m_ODRTags.Count > 0)
{
var tags = info.CreateArray("on-demand-resource-tags");
foreach (var tag in m_ODRTags)
tags.AddString(tag);
}
}
protected void WriteRequirementsToJson(JsonElementDict item, DeviceRequirement req)
{
foreach (var kv in req.values)
{
if (kv.Value != null && kv.Value != "")
item.SetString(kv.Key, kv.Value);
}
}
}
internal class AssetDataSet : AssetCatalogItemWithVariants
{
class DataSetVariant : VariantData
{
public string id;
public DataSetVariant(DeviceRequirement requirement, string path, string id) : base(requirement, path)
{
this.id = id;
}
}
internal AssetDataSet(string parentPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(parentPath, name + ".dataset");
}
// an exception is thrown is two equivalent requirements are added.
// The same asset dataset must not have paths with equivalent filenames.
// The identifier allows to identify which data variant is actually loaded (use
// the typeIdentifer property of the NSDataAsset that was created from the data set)
public void AddVariant(DeviceRequirement requirement, string path, string typeIdentifier)
{
foreach (DataSetVariant item in m_Variants)
{
if (item.id != null && typeIdentifier != null && item.id == typeIdentifier)
throw new Exception("Two items within the same dataset must not have the same id");
}
AddVariant(new DataSetVariant(requirement, path, typeIdentifier));
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
var info = WriteInfoToJson(doc);
WriteODRTagsToJson(info);
var data = doc.root.CreateArray("data");
foreach (DataSetVariant item in m_Variants)
{
var filename = Path.GetFileName(item.path);
File.Copy(item.path, Path.Combine(m_Path, filename));
var docItem = data.AddDict();
docItem.SetString("filename", filename);
WriteRequirementsToJson(docItem, item.requirement);
if (item.id != null)
docItem.SetString("universal-type-identifier", item.id);
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
internal class ImageAlignment
{
public int left = 0, right = 0, top = 0, bottom = 0;
}
internal class ImageResizing
{
public enum SlicingType
{
Horizontal,
Vertical,
HorizontalAndVertical
}
public enum ResizeMode
{
Stretch,
Tile
}
public SlicingType type = SlicingType.HorizontalAndVertical;
public int left = 0; // only valid for horizontal slicing
public int right = 0; // only valid for horizontal slicing
public int top = 0; // only valid for vertical slicing
public int bottom = 0; // only valid for vertical slicing
public ResizeMode centerResizeMode = ResizeMode.Stretch;
public int centerWidth = 0; // only valid for vertical slicing
public int centerHeight = 0; // only valid for horizontal slicing
}
// TODO: rendering intent property
internal class AssetImageSet : AssetCatalogItemWithVariants
{
internal AssetImageSet(string assetCatalogPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(assetCatalogPath, name + ".imageset");
}
class ImageSetVariant : VariantData
{
public ImageAlignment alignment = null;
public ImageResizing resizing = null;
public ImageSetVariant(DeviceRequirement requirement, string path) : base(requirement, path)
{
}
}
public void AddVariant(DeviceRequirement requirement, string path)
{
AddVariant(new ImageSetVariant(requirement, path));
}
public void AddVariant(DeviceRequirement requirement, string path, ImageAlignment alignment, ImageResizing resizing)
{
var imageset = new ImageSetVariant(requirement, path);
imageset.alignment = alignment;
imageset.resizing = resizing;
AddVariant(imageset);
}
void WriteAlignmentToJson(JsonElementDict item, ImageAlignment alignment)
{
var docAlignment = item.CreateDict("alignment-insets");
docAlignment.SetInteger("top", alignment.top);
docAlignment.SetInteger("bottom", alignment.bottom);
docAlignment.SetInteger("left", alignment.left);
docAlignment.SetInteger("right", alignment.right);
}
static string GetSlicingMode(ImageResizing.SlicingType mode)
{
switch (mode)
{
case ImageResizing.SlicingType.Horizontal: return "3-part-horizontal";
case ImageResizing.SlicingType.Vertical: return "3-part-vertical";
case ImageResizing.SlicingType.HorizontalAndVertical: return "9-part";
}
return "";
}
static string GetCenterResizeMode(ImageResizing.ResizeMode mode)
{
switch (mode)
{
case ImageResizing.ResizeMode.Stretch: return "stretch";
case ImageResizing.ResizeMode.Tile: return "tile";
}
return "";
}
void WriteResizingToJson(JsonElementDict item, ImageResizing resizing)
{
var docResizing = item.CreateDict("resizing");
docResizing.SetString("mode", GetSlicingMode(resizing.type));
var docCenter = docResizing.CreateDict("center");
docCenter.SetString("mode", GetCenterResizeMode(resizing.centerResizeMode));
docCenter.SetInteger("width", resizing.centerWidth);
docCenter.SetInteger("height", resizing.centerHeight);
var docInsets = docResizing.CreateDict("cap-insets");
docInsets.SetInteger("top", resizing.top);
docInsets.SetInteger("bottom", resizing.bottom);
docInsets.SetInteger("left", resizing.left);
docInsets.SetInteger("right", resizing.right);
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
var info = WriteInfoToJson(doc);
WriteODRTagsToJson(info);
var images = doc.root.CreateArray("images");
foreach (ImageSetVariant item in m_Variants)
{
var filename = Path.GetFileName(item.path);
File.Copy(item.path, Path.Combine(m_Path, filename));
var docItem = images.AddDict();
docItem.SetString("filename", filename);
WriteRequirementsToJson(docItem, item.requirement);
if (item.alignment != null)
WriteAlignmentToJson(docItem, item.alignment);
if (item.resizing != null)
WriteResizingToJson(docItem, item.resizing);
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
/* A stack layer may either contain an image set or reference another imageset
*/
class AssetImageStackLayer : AssetCatalogItem
{
internal AssetImageStackLayer(string assetCatalogPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(assetCatalogPath, name + ".imagestacklayer");
m_Imageset = new AssetImageSet(m_Path, "Content", authorId);
}
AssetImageSet m_Imageset = null;
string m_ReferencedName = null;
public void SetReference(string name)
{
m_Imageset = null;
m_ReferencedName = name;
}
public string ReferencedName()
{
return m_ReferencedName;
}
public AssetImageSet GetImageSet()
{
return m_Imageset;
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
WriteInfoToJson(doc);
if (m_ReferencedName != null)
{
var props = doc.root.CreateDict("properties");
var reference = props.CreateDict("content-reference");
reference.SetString("type", "image-set");
reference.SetString("name", m_ReferencedName);
reference.SetString("matching-style", "fully-qualified-name");
}
if (m_Imageset != null)
m_Imageset.Write();
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
class AssetImageStack : AssetCatalogItem
{
List<AssetImageStackLayer> m_Layers = new List<AssetImageStackLayer>();
internal AssetImageStack(string assetCatalogPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(assetCatalogPath, name + ".imagestack");
}
public AssetImageStackLayer AddLayer(string name)
{
foreach (var layer in m_Layers)
{
if (layer.name == name)
throw new Exception("A layer with given name already exists");
}
var newLayer = new AssetImageStackLayer(m_Path, name, authorId);
m_Layers.Add(newLayer);
return newLayer;
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
WriteInfoToJson(doc);
var docLayers = doc.root.CreateArray("layers");
foreach (var layer in m_Layers)
{
layer.Write();
var docLayer = docLayers.AddDict();
docLayer.SetString("filename", Path.GetFileName(layer.path));
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
} // namespace UnityEditor.iOS.Xcode
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using Validation;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable unordered hash set implementation.
/// </summary>
/// <typeparam name="T">The type of elements in the set.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableHashSetDebuggerProxy<>))]
public sealed partial class ImmutableHashSet<T> : IImmutableSet<T>, IHashKeyCollection<T>, IReadOnlyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator>
{
/// <summary>
/// An empty immutable hash set with the default comparer for <typeparamref name="T"/>.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0);
/// <summary>
/// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen.
/// </summary>
private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze();
/// <summary>
/// The equality comparer used to hash the elements in the collection.
/// </summary>
private readonly IEqualityComparer<T> _equalityComparer;
/// <summary>
/// The number of elements in this collection.
/// </summary>
private readonly int _count;
/// <summary>
/// The sorted dictionary that this hash set wraps. The key is the hash code and the value is the bucket of all items that hashed to it.
/// </summary>
private readonly SortedInt32KeyNode<HashBucket> _root;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet{T}"/> class.
/// </summary>
/// <param name="equalityComparer">The equality comparer.</param>
internal ImmutableHashSet(IEqualityComparer<T> equalityComparer)
: this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet{T}"/> class.
/// </summary>
/// <param name="root">The sorted set that this set wraps.</param>
/// <param name="equalityComparer">The equality comparer used by this instance.</param>
/// <param name="count">The number of elements in this collection.</param>
private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count)
{
Requires.NotNull(root, "root");
Requires.NotNull(equalityComparer, "equalityComparer");
root.Freeze(s_FreezeBucketAction);
_root = root;
_count = count;
_equalityComparer = equalityComparer;
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public ImmutableHashSet<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>().IsEmpty);
return this.IsEmpty ? this : ImmutableHashSet<T>.Empty.WithComparer(_equalityComparer);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public bool IsEmpty
{
get { return this.Count == 0; }
}
#region IHashKeyCollection<T> Properties
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public IEqualityComparer<T> KeyComparer
{
get { return _equalityComparer; }
}
#endregion
#region IImmutableSet<T> Properties
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Clear()
{
return this.Clear();
}
#endregion
#region ICollection Properties
/// <summary>
/// See <see cref="ICollection"/>.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// See the <see cref="ICollection"/> interface.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal IBinaryTree Root
{
get { return _root; }
}
/// <summary>
/// Gets a data structure that captures the current state of this map, as an input into a query or mutating function.
/// </summary>
private MutationInput Origin
{
get { return new MutationInput(this); }
}
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> Add(T item)
{
Requires.NotNullAllowStructs(item, "item");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Add(item, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public ImmutableHashSet<T> Remove(T item)
{
Requires.NotNullAllowStructs(item, "item");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Remove(item, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="equalValue">The value to search for.</param>
/// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// a value that has more complete data than the value you currently have, although their
/// comparer functions indicate they are equal.
/// </remarks>
[Pure]
public bool TryGetValue(T equalValue, out T actualValue)
{
Requires.NotNullAllowStructs(equalValue, "value");
int hashCode = _equalityComparer.GetHashCode(equalValue);
HashBucket bucket;
if (_root.TryGetValue(hashCode, out bucket))
{
return bucket.TryExchange(equalValue, _equalityComparer, out actualValue);
}
actualValue = equalValue;
return false;
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> Union(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
return this.Union(other, avoidWithComparer: false);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> Intersect(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Intersect(other, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public ImmutableHashSet<T> Except(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
var result = Except(other, _equalityComparer, _root);
return result.Finalize(this);
}
/// <summary>
/// Produces a set that contains elements either in this set or a given sequence, but not both.
/// </summary>
/// <param name="other">The other sequence of items.</param>
/// <returns>The new set.</returns>
[Pure]
public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
Contract.Ensures(Contract.Result<IImmutableSet<T>>() != null);
var result = SymmetricExcept(other, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// Checks whether a given sequence of items entirely describe the contents of this set.
/// </summary>
/// <param name="other">The sequence of items to check against this set.</param>
/// <returns>A value indicating whether the sets are equal.</returns>
[Pure]
public bool SetEquals(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
if (object.ReferenceEquals(this, other))
{
return true;
}
return SetEquals(other, this.Origin);
}
/// <summary>
/// Determines whether the current set is a property (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of <paramref name="other"/>; otherwise, false.</returns>
[Pure]
public bool IsProperSubsetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsProperSubsetOf(other, this.Origin);
}
/// <summary>
/// Determines whether the current set is a correct superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct superset of <paramref name="other"/>; otherwise, false.</returns>
[Pure]
public bool IsProperSupersetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsProperSupersetOf(other, this.Origin);
}
/// <summary>
/// Determines whether a set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of <paramref name="other"/>; otherwise, false.</returns>
[Pure]
public bool IsSubsetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsSubsetOf(other, this.Origin);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of <paramref name="other"/>; otherwise, false.</returns>
[Pure]
public bool IsSupersetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsSupersetOf(other, this.Origin);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and <paramref name="other"/> share at least one common element; otherwise, false.</returns>
[Pure]
public bool Overlaps(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return Overlaps(other, this.Origin);
}
#endregion
#region IImmutableSet<T> Methods
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Add(T item)
{
return this.Add(item);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Remove(T item)
{
return this.Remove(item);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other)
{
return this.Union(other);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other)
{
return this.Intersect(other);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other)
{
return this.Except(other);
}
/// <summary>
/// Produces a set that contains elements either in this set or a given sequence, but not both.
/// </summary>
/// <param name="other">The other sequence of items.</param>
/// <returns>The new set.</returns>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other)
{
return this.SymmetricExcept(other);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public bool Contains(T item)
{
Requires.NotNullAllowStructs(item, "item");
return Contains(item, this.Origin);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> WithComparer(IEqualityComparer<T> equalityComparer)
{
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
if (equalityComparer == null)
{
equalityComparer = EqualityComparer<T>.Default;
}
if (equalityComparer == _equalityComparer)
{
return this;
}
else
{
var result = new ImmutableHashSet<T>(equalityComparer);
result = result.Union(this, avoidWithComparer: true);
return result;
}
}
#endregion
#region ISet<T> Members
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
bool ISet<T>.Add(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.ExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.IntersectWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.SymmetricExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.UnionWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<T> members
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (T item in this)
{
array[arrayIndex++] = item;
}
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (T item in this)
{
array.SetValue(item, arrayIndex++);
}
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_root);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Static query and manipulator methods
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (!Contains(item, origin))
{
return false;
}
}
return true;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Add(T item, MutationInput origin)
{
Requires.NotNullAllowStructs(item, "item");
OperationResult result;
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket = origin.Root.GetValueOrDefault(hashCode);
var newBucket = bucket.Add(item, origin.EqualityComparer, out result);
if (result == OperationResult.NoChangeRequired)
{
return new MutationResult(origin.Root, 0);
}
var newRoot = UpdateRoot(origin.Root, hashCode, newBucket);
Debug_.Assert(result == OperationResult.SizeChanged);
return new MutationResult(newRoot, 1 /*result == OperationResult.SizeChanged ? 1 : 0*/);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Remove(T item, MutationInput origin)
{
Requires.NotNullAllowStructs(item, "item");
var result = OperationResult.NoChangeRequired;
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket;
var newRoot = origin.Root;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
var newBucket = bucket.Remove(item, origin.EqualityComparer, out result);
if (result == OperationResult.NoChangeRequired)
{
return new MutationResult(origin.Root, 0);
}
newRoot = UpdateRoot(origin.Root, hashCode, newBucket);
}
return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool Contains(T item, MutationInput origin)
{
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
return bucket.Contains(item, origin.EqualityComparer);
}
return false;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Union(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
int count = 0;
var newRoot = origin.Root;
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket = newRoot.GetValueOrDefault(hashCode);
OperationResult result;
var newBucket = bucket.Add(item, origin.EqualityComparer, out result);
if (result == OperationResult.SizeChanged)
{
newRoot = UpdateRoot(newRoot, hashCode, newBucket);
count++;
}
}
return new MutationResult(newRoot, count);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool Overlaps(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return false;
}
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (Contains(item, origin))
{
return true;
}
}
return false;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool SetEquals(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
if (origin.Count != otherSet.Count)
{
return false;
}
int matches = 0;
foreach (T item in otherSet)
{
if (!Contains(item, origin))
{
return false;
}
matches++;
}
return matches == origin.Count;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket)
{
bool mutated;
if (newBucket.IsEmpty)
{
return root.Remove(hashCode, out mutated);
}
else
{
bool replacedExistingValue;
return root.SetItem(hashCode, newBucket, EqualityComparer<HashBucket>.Default, out replacedExistingValue, out mutated);
}
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
var newSet = SortedInt32KeyNode<HashBucket>.EmptyNode;
int count = 0;
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (Contains(item, origin))
{
var result = Add(item, new MutationInput(newSet, origin.EqualityComparer, count));
newSet = result.Root;
count += result.Count;
}
}
return new MutationResult(newSet, count, CountType.FinalValue);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, SortedInt32KeyNode<HashBucket> root)
{
Requires.NotNull(other, "other");
Requires.NotNull(equalityComparer, "equalityComparer");
Requires.NotNull(root, "root");
int count = 0;
var newRoot = root;
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
int hashCode = equalityComparer.GetHashCode(item);
HashBucket bucket;
if (newRoot.TryGetValue(hashCode, out bucket))
{
OperationResult result;
HashBucket newBucket = bucket.Remove(item, equalityComparer, out result);
if (result == OperationResult.SizeChanged)
{
count--;
newRoot = UpdateRoot(newRoot, hashCode, newBucket);
}
}
}
return new MutationResult(newRoot, count);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
[Pure]
private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
var otherAsSet = ImmutableHashSet.CreateRange(origin.EqualityComparer, other);
int count = 0;
var result = SortedInt32KeyNode<HashBucket>.EmptyNode;
foreach (T item in new NodeEnumerable(origin.Root))
{
if (!otherAsSet.Contains(item))
{
var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count));
result = mutationResult.Root;
count += mutationResult.Count;
}
}
foreach (T item in otherAsSet)
{
if (!Contains(item, origin))
{
var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count));
result = mutationResult.Root;
count += mutationResult.Count;
}
}
return new MutationResult(result, count, CountType.FinalValue);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return other.Any();
}
// To determine whether everything we have is also in another sequence,
// we enumerate the sequence and "tag" whether it's in this collection,
// then consider whether every element in this collection was tagged.
// Since this collection is immutable we cannot directly tag. So instead
// we simply count how many "hits" we have and ensure it's equal to the
// size of this collection. Of course for this to work we need to ensure
// the uniqueness of items in the given sequence, so we create a set based
// on the sequence first.
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
if (origin.Count >= otherSet.Count)
{
return false;
}
int matches = 0;
bool extraFound = false;
foreach (T item in otherSet)
{
if (Contains(item, origin))
{
matches++;
}
else
{
extraFound = true;
}
if (matches == origin.Count && extraFound)
{
return true;
}
}
return false;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return false;
}
int matchCount = 0;
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
matchCount++;
if (!Contains(item, origin))
{
return false;
}
}
return origin.Count > matchCount;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return true;
}
// To determine whether everything we have is also in another sequence,
// we enumerate the sequence and "tag" whether it's in this collection,
// then consider whether every element in this collection was tagged.
// Since this collection is immutable we cannot directly tag. So instead
// we simply count how many "hits" we have and ensure it's equal to the
// size of this collection. Of course for this to work we need to ensure
// the uniqueness of items in the given sequence, so we create a set based
// on the sequence first.
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
int matches = 0;
foreach (T item in otherSet)
{
if (Contains(item, origin))
{
matches++;
}
}
return matches == origin.Count;
}
#endregion
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <param name="count">The number of elements in the data structure.</param>
/// <returns>The immutable collection.</returns>
private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count)
{
Requires.NotNull(root, "root");
Requires.NotNull(equalityComparer, "equalityComparer");
Requires.Range(count >= 0, "count");
return new ImmutableHashSet<T>(root, equalityComparer, count);
}
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param>
/// <returns>The immutable collection.</returns>
private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot)
{
return (root != _root) ? new ImmutableHashSet<T>(root, _equalityComparer, adjustedCountIfDifferentRoot) : this;
}
/// <summary>
/// Bulk adds entries to the set.
/// </summary>
/// <param name="items">The entries to add.</param>
/// <param name="avoidWithComparer"><c>true</c> when being called from <see cref="WithComparer"/> to avoid <see cref="T:System.StackOverflowException"/>.</param>
[Pure]
private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer)
{
Requires.NotNull(items, "items");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
// Some optimizations may apply if we're an empty set.
if (this.IsEmpty && !avoidWithComparer)
{
// If the items being added actually come from an ImmutableHashSet<T>,
// reuse that instance if possible.
var other = items as ImmutableHashSet<T>;
if (other != null)
{
return other.WithComparer(this.KeyComparer);
}
}
var result = Union(items, this.Origin);
return result.Finalize(this);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function initializeRiverEditor()
{
echo(" % - Initializing River Editor");
exec( "./riverEditor.cs" );
exec( "./riverEditorGui.gui" );
exec( "./riverEditorToolbar.gui" );
exec( "./riverEditorGui.cs" );
// Add ourselves to EditorGui, where all the other tools reside
RiverEditorGui.setVisible( false );
RiverEditorToolbar.setVisible(false);
RiverEditorOptionsWindow.setVisible( false );
RiverEditorTreeWindow.setVisible( false );
EditorGui.add( RiverEditorGui );
EditorGui.add( RiverEditorToolbar );
EditorGui.add( RiverEditorOptionsWindow );
EditorGui.add( RiverEditorTreeWindow );
new ScriptObject( RiverEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = RiverEditorGui;
};
%map = new ActionMap();
%map.bindCmd( keyboard, "backspace", "RiverEditorGui.deleteNode();", "" );
%map.bindCmd( keyboard, "1", "RiverEditorGui.prepSelectionMode();", "" );
%map.bindCmd( keyboard, "2", "ToolsPaletteArray->RiverEditorMoveMode.performClick();", "" );
%map.bindCmd( keyboard, "3", "ToolsPaletteArray->RiverEditorRotateMode.performClick();", "" );
%map.bindCmd( keyboard, "4", "ToolsPaletteArray->RiverEditorScaleMode.performClick();", "" );
%map.bindCmd( keyboard, "5", "ToolsPaletteArray->RiverEditorAddRiverMode.performClick();", "" );
%map.bindCmd( keyboard, "=", "ToolsPaletteArray->RiverEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->RiverEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "-", "ToolsPaletteArray->RiverEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->RiverEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "z", "RiverEditorShowSplineBtn.performClick();", "" );
%map.bindCmd( keyboard, "x", "RiverEditorWireframeBtn.performClick();", "" );
%map.bindCmd( keyboard, "v", "RiverEditorShowRoadBtn.performClick();", "" );
RiverEditorPlugin.map = %map;
RiverEditorPlugin.initSettings();
}
function destroyRiverEditor()
{
}
function RiverEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "River Editor", "", RiverEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "River Editor (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "RiverEditorPlugin", "RiverEditorPalette", expandFilename("tools/worldEditor/images/toolbar/river-editor"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( RiverEditorOptionsWindow, RiverEditorTreeWindow);
// Add ourselves to the Editor Settings window
exec( "./RiverEditorSettingsTab.gui" );
ESettingsWindow.addTabPage( ERiverEditorSettingsPage );
}
function RiverEditorPlugin::onActivated( %this )
{
%this.readSettings();
$River::EditorOpen = true;
ToolsPaletteArray->RiverEditorAddRiverMode.performClick();
EditorGui.bringToFront( RiverEditorGui );
RiverEditorGui.setVisible(true);
RiverEditorGui.makeFirstResponder( true );
RiverEditorToolbar.setVisible(true);
RiverEditorOptionsWindow.setVisible( true );
RiverEditorTreeWindow.setVisible( true );
RiverTreeView.open(ServerRiverSet,true);
%this.map.push();
// Store this on a dynamic field
// in order to restore whatever setting
// the user had before.
%this.prevGizmoAlignment = GlobalGizmoProfile.alignment;
// The DecalEditor always uses Object alignment.
GlobalGizmoProfile.alignment = "Object";
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo("River editor.");
EditorGuiStatusBar.setSelection("");
// Allow the Gui to setup.
RiverEditorGui.onEditorActivated();
Parent::onActivated(%this);
}
function RiverEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
$River::EditorOpen = false;
RiverEditorGui.setVisible(false);
RiverEditorToolbar.setVisible(false);
RiverEditorOptionsWindow.setVisible( false );
RiverEditorTreeWindow.setVisible( false );
%this.map.pop();
// Restore the previous Gizmo
// alignment settings.
GlobalGizmoProfile.alignment = %this.prevGizmoAlignment;
// Allow the Gui to cleanup.
RiverEditorGui.onEditorDeactivated();
Parent::onDeactivated(%this);
}
function RiverEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if( isObject( RiverEditorGui.river ) )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, false ); // Deselect
}
function RiverEditorPlugin::handleDelete( %this )
{
RiverEditorGui.deleteNode();
}
function RiverEditorPlugin::handleEscape( %this )
{
return RiverEditorGui.onEscapePressed();
}
function RiverEditorPlugin::isDirty( %this )
{
return RiverEditorGui.isDirty;
}
function RiverEditorPlugin::onSaveMission( %this, %missionFile )
{
if( RiverEditorGui.isDirty )
{
MissionGroup.save( %missionFile );
RiverEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function RiverEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "RiverEditor", true );
EditorSettings.setDefaultValue( "DefaultWidth", "10" );
EditorSettings.setDefaultValue( "DefaultDepth", "5" );
EditorSettings.setDefaultValue( "DefaultNormal", "0 0 1" );
EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" );
EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" );
EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used
EditorSettings.endGroup();
}
function RiverEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "RiverEditor", true );
RiverEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth");
RiverEditorGui.DefaultDepth = EditorSettings.value("DefaultDepth");
RiverEditorGui.DefaultNormal = EditorSettings.value("DefaultNormal");
RiverEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor");
RiverEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor");
RiverEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor");
EditorSettings.endGroup();
}
function RiverEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "RiverEditor", true );
EditorSettings.setValue( "DefaultWidth", RiverEditorGui.DefaultWidth );
EditorSettings.setValue( "DefaultDepth", RiverEditorGui.DefaultDepth );
EditorSettings.setValue( "DefaultNormal", RiverEditorGui.DefaultNormal );
EditorSettings.setValue( "HoverSplineColor", RiverEditorGui.HoverSplineColor );
EditorSettings.setValue( "SelectedSplineColor", RiverEditorGui.SelectedSplineColor );
EditorSettings.setValue( "HoverNodeColor", RiverEditorGui.HoverNodeColor );
EditorSettings.endGroup();
}
| |
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using Tester;
using UnitTests.GrainInterfaces;
using UnitTests.Tester;
using Xunit;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace UnitTests.StreamingTests
{
[TestCategory("Streaming")]
public class SampleSmsStreamingTests : OrleansTestingBase, IClassFixture<SampleSmsStreamingTests.Fixture>
{
public class Fixture : BaseTestClusterFixture
{
protected override TestCluster CreateTestCluster()
{
var options = new TestClusterOptions(2);
options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore");
options.ClusterConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false);
options.ClientConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false);
return new TestCluster(options);
}
}
private const string StreamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task SampleStreamingTests_1()
{
logger.Info("************************ SampleStreamingTests_1 *********************************");
var runner = new SampleStreamingTests(StreamProvider, logger);
await runner.StreamingTests_Consumer_Producer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task SampleStreamingTests_2()
{
logger.Info("************************ SampleStreamingTests_2 *********************************");
var runner = new SampleStreamingTests(StreamProvider, logger);
await runner.StreamingTests_Producer_Consumer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task SampleStreamingTests_3()
{
logger.Info("************************ SampleStreamingTests_3 *********************************");
var runner = new SampleStreamingTests(StreamProvider, logger);
await runner.StreamingTests_Producer_InlineConsumer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task MultipleImplicitSubscriptionTest()
{
logger.Info("************************ MultipleImplicitSubscriptionTest *********************************");
var streamId = Guid.NewGuid();
const int nRedEvents = 5, nBlueEvents = 3;
var provider = GrainClient.GetStreamProvider(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME);
var redStream = provider.GetStream<int>(streamId, "red");
var blueStream = provider.GetStream<int>(streamId, "blue");
for (int i = 0; i < nRedEvents; i++)
await redStream.OnNextAsync(i);
for (int i = 0; i < nBlueEvents; i++)
await blueStream.OnNextAsync(i);
var grain = GrainClient.GrainFactory.GetGrain<IMultipleImplicitSubscriptionGrain>(streamId);
var counters = await grain.GetCounters();
Assert.AreEqual(nRedEvents, counters.Item1);
Assert.AreEqual(nBlueEvents, counters.Item2);
}
}
[TestCategory("Streaming")]
public class SampleAzureQueueStreamingTests : TestClusterPerTest
{
private const string StreamProvider = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
public override TestCluster CreateTestCluster()
{
TestUtils.CheckForAzureStorage();
var options = new TestClusterOptions(2);
options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore");
options.ClusterConfiguration.AddAzureQueueStreamProvider(StreamProvider);
return new TestCluster(options);
}
public override void Dispose()
{
var deploymentId = HostedCluster.DeploymentId;
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(StreamProvider, deploymentId, StorageTestConstants.DataConnectionString).Wait();
}
[Fact, TestCategory("Functional")]
public async Task SampleStreamingTests_4()
{
logger.Info("************************ SampleStreamingTests_4 *********************************");
var runner = new SampleStreamingTests(StreamProvider, logger);
await runner.StreamingTests_Consumer_Producer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task SampleStreamingTests_5()
{
logger.Info("************************ SampleStreamingTests_5 *********************************");
var runner = new SampleStreamingTests(StreamProvider, logger);
await runner.StreamingTests_Producer_Consumer(Guid.NewGuid());
}
}
public class SampleStreamingTests
{
private const string StreamNamespace = "SampleStreamNamespace";
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
private readonly string streamProvider;
private readonly Logger logger;
public SampleStreamingTests( string streamProvider, Logger logger)
{
this.streamProvider = streamProvider;
this.logger = logger;
}
public async Task StreamingTests_Consumer_Producer(Guid streamId)
{
// consumer joins first, producer later
var consumer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
public async Task StreamingTests_Producer_Consumer(Guid streamId)
{
// producer joins first, consumer later
var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
var consumer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
//int numProduced = await producer.NumberProduced;
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
public async Task StreamingTests_Producer_InlineConsumer(Guid streamId)
{
// producer joins first, consumer later
var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
var consumer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_InlineConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
//int numProduced = await producer.NumberProduced;
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, ISampleStreaming_ConsumerGrain consumer, bool assertIsTrue)
{
var numProduced = await producer.GetNumberProduced();
var numConsumed = await consumer.GetNumberConsumed();
logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed);
if (assertIsTrue)
{
Assert.AreEqual(numProduced, numConsumed, String.Format("numProduced = {0}, numConsumed = {1}", numProduced, numConsumed));
return true;
}
else
{
return numProduced == numConsumed;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.