context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//#define USE_GENERICS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
using UnitTests.StreamingTests;
namespace UnitTests.Grains
{
[Serializable]
[GenerateSerializer]
public class StreamReliabilityTestGrainState
{
// For producer and consumer
// -- only need to store because of how we run our unit tests against multiple providers
[Id(0)]
public string StreamProviderName { get; set; }
// For producer only.
#if USE_GENERICS
public IAsyncStream<T> Stream { get; set; }
#else
[Id(1)]
public IAsyncStream<int> Stream { get; set; }
#endif
[Id(2)]
public bool IsProducer { get; set; }
// For consumer only.
#if USE_GENERICS
public HashSet<StreamSubscriptionHandle<T>> ConsumerSubscriptionHandles { get; set; }
public StreamReliabilityTestGrainState()
{
ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<T>>();
}
#else
[Id(3)]
public HashSet<StreamSubscriptionHandle<int>> ConsumerSubscriptionHandles { get; set; }
public StreamReliabilityTestGrainState()
{
ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<int>>();
}
#endif
}
[Orleans.Providers.StorageProvider(ProviderName = "AzureStore")]
#if USE_GENERICS
public class StreamReliabilityTestGrain<T> : Grain<IStreamReliabilityTestGrainState>, IStreamReliabilityTestGrain<T>
#else
public class StreamReliabilityTestGrain : Grain<StreamReliabilityTestGrainState>, IStreamReliabilityTestGrain
#endif
{
[NonSerialized]
private ILogger logger;
#if USE_GENERICS
private IAsyncStream<T> Stream { get; set; }
private IAsyncObserver<T> Producer { get; set; }
private Dictionary<StreamSubscriptionHandle<T>, MyStreamObserver<T>> Observers { get; set; }
#else
private IAsyncStream<int> Stream { get { return State.Stream; } }
private IAsyncObserver<int> Producer { get; set; }
private Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>> Observers { get; set; }
#endif
private const string StreamNamespace = StreamTestsConstants.StreamReliabilityNamespace;
public StreamReliabilityTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override async Task OnActivateAsync()
{
logger.Info(String.Format("OnActivateAsync IsProducer = {0}, IsConsumer = {1}.",
State.IsProducer, State.ConsumerSubscriptionHandles != null && State.ConsumerSubscriptionHandles.Count > 0));
if (Observers == null)
#if USE_GENERICS
Observers = new Dictionary<StreamSubscriptionHandle<T>, MyStreamObserver<T>>();
#else
Observers = new Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>>();
#endif
if (State.Stream != null && State.StreamProviderName != null)
{
//TryInitStream(State.Stream, State.StreamProviderName);
if (State.ConsumerSubscriptionHandles.Count > 0)
{
var handles = State.ConsumerSubscriptionHandles.ToArray();
State.ConsumerSubscriptionHandles.Clear();
await ReconnectConsumerHandles(handles);
}
if (State.IsProducer)
{
//await BecomeProducer(State.StreamId, State.StreamProviderName);
Producer = Stream;
State.IsProducer = true;
await WriteStateAsync();
}
}
else
{
logger.Info("No stream yet.");
}
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return base.OnDeactivateAsync();
}
public Task<int> GetConsumerCount()
{
int numConsumers = State.ConsumerSubscriptionHandles.Count;
logger.Info("ConsumerCount={0}", numConsumers);
return Task.FromResult(numConsumers);
}
public Task<int> GetReceivedCount()
{
int numReceived = Observers.Sum(o => o.Value.NumItems);
logger.Info("ReceivedCount={0}", numReceived);
return Task.FromResult(numReceived);
}
public Task<int> GetErrorsCount()
{
int numErrors = Observers.Sum(o => o.Value.NumErrors);
logger.Info("ErrorsCount={0}", numErrors);
return Task.FromResult(numErrors);
}
public Task Ping()
{
logger.Info("Ping");
return Task.CompletedTask;
}
#if USE_GENERICS
public async Task<StreamSubscriptionHandle<T>> AddConsumer(Guid streamId, string providerName)
#else
public async Task<StreamSubscriptionHandle<int>> AddConsumer(Guid streamId, string providerName)
#endif
{
logger.Info("AddConsumer StreamId={0} StreamProvider={1} Grain={2}", streamId, providerName, this.AsReference<IStreamReliabilityTestGrain>());
TryInitStream(streamId, providerName);
#if USE_GENERICS
var observer = new MyStreamObserver<T>();
#else
var observer = new MyStreamObserver<int>(logger);
#endif
var subsHandle = await Stream.SubscribeAsync(observer);
Observers.Add(subsHandle, observer);
State.ConsumerSubscriptionHandles.Add(subsHandle);
await WriteStateAsync();
return subsHandle;
}
#if USE_GENERICS
public async Task RemoveConsumer(Guid streamId, string providerName, StreamSubscriptionHandle<T> subsHandle)
#else
public async Task RemoveConsumer(Guid streamId, string providerName, StreamSubscriptionHandle<int> subsHandle)
#endif
{
logger.Info("RemoveConsumer StreamId={0} StreamProvider={1}", streamId, providerName);
if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer");
await subsHandle.UnsubscribeAsync();
Observers.Remove(subsHandle);
State.ConsumerSubscriptionHandles.Remove(subsHandle);
await WriteStateAsync();
}
public async Task RemoveAllConsumers()
{
logger.Info("RemoveAllConsumers: State.ConsumerSubscriptionHandles.Count={0}", State.ConsumerSubscriptionHandles.Count);
if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer");
var handles = State.ConsumerSubscriptionHandles.ToArray();
foreach (var handle in handles)
{
await handle.UnsubscribeAsync();
}
//Observers.Remove(subsHandle);
State.ConsumerSubscriptionHandles.Clear();
await WriteStateAsync();
}
public async Task BecomeProducer(Guid streamId, string providerName)
{
logger.Info("BecomeProducer StreamId={0} StreamProvider={1}", streamId, providerName);
TryInitStream(streamId, providerName);
Producer = Stream;
State.IsProducer = true;
await WriteStateAsync();
}
public async Task RemoveProducer(Guid streamId, string providerName)
{
logger.Info("RemoveProducer StreamId={0} StreamProvider={1}", streamId, providerName);
if (!State.IsProducer) throw new InvalidOperationException("Not a Producer");
Producer = null;
State.IsProducer = false;
await WriteStateAsync();
}
public async Task ClearGrain()
{
logger.Info("ClearGrain.");
State.ConsumerSubscriptionHandles.Clear();
State.IsProducer = false;
Observers.Clear();
State.Stream = null;
await ClearStateAsync();
}
public Task<bool> IsConsumer()
{
bool isConsumer = State.ConsumerSubscriptionHandles.Count > 0;
logger.Info("IsConsumer={0}", isConsumer);
return Task.FromResult(isConsumer);
}
public Task<bool> IsProducer()
{
bool isProducer = State.IsProducer;
logger.Info("IsProducer={0}", isProducer);
return Task.FromResult(isProducer);
}
public Task<int> GetConsumerHandlesCount()
{
return Task.FromResult(State.ConsumerSubscriptionHandles.Count);
}
public async Task<int> GetConsumerObserversCount()
{
#if USE_GENERICS
var consumer = (StreamConsumer<T>)Stream;
#else
var consumer = (StreamConsumer<int>)Stream;
#endif
return await consumer.DiagGetConsumerObserversCount();
}
#if USE_GENERICS
public async Task SendItem(T item)
#else
public async Task SendItem(int item)
#endif
{
logger.Info("SendItem Item={0}", item);
await Producer.OnNextAsync(item);
}
public Task<SiloAddress> GetLocation()
{
SiloAddress siloAddress = Data.Address.Silo;
logger.Info("GetLocation SiloAddress={0}", siloAddress);
return Task.FromResult(siloAddress);
}
private void TryInitStream(Guid streamId, string providerName)
{
if (providerName == null) throw new ArgumentNullException(nameof(providerName));
State.StreamProviderName = providerName;
if (State.Stream == null)
{
logger.Info("InitStream StreamId={0} StreamProvider={1}", streamId, providerName);
IStreamProvider streamProvider = this.GetStreamProvider(providerName);
#if USE_GENERICS
State.Stream = streamProvider.GetStream<T>(streamId);
#else
State.Stream = streamProvider.GetStream<int>(streamId, StreamNamespace);
#endif
}
}
#if USE_GENERICS
private async Task ReconnectConsumerHandles(StreamSubscriptionHandle<T>[] subscriptionHandles)
#else
private async Task ReconnectConsumerHandles(StreamSubscriptionHandle<int>[] subscriptionHandles)
#endif
{
logger.Info("ReconnectConsumerHandles SubscriptionHandles={0} Grain={1}", Utils.EnumerableToString(subscriptionHandles), this.AsReference<IStreamReliabilityTestGrain>());
foreach (var subHandle in subscriptionHandles)
{
#if USE_GENERICS
// var stream = GetStreamProvider(State.StreamProviderName).GetStream<T>(subHandle.StreamId);
var stream = subHandle.Stream;
var observer = new MyStreamObserver<T>();
#else
var observer = new MyStreamObserver<int>(logger);
#endif
var subsHandle = await subHandle.ResumeAsync(observer);
Observers.Add(subsHandle, observer);
State.ConsumerSubscriptionHandles.Add(subsHandle);
}
await WriteStateAsync();
}
}
//[Serializable]
//public class MyStreamObserver<T> : IAsyncObserver<T>
//{
// internal int NumItems { get; private set; }
// internal int NumErrors { get; private set; }
// private readonly Logger logger;
// internal MyStreamObserver(Logger logger)
// {
// this.logger = logger;
// }
// public Task OnNextAsync(T item, StreamSequenceToken token)
// {
// NumItems++;
// if (logger.IsVerbose)
// logger.Verbose("Received OnNextAsync - Item={0} - Total Items={1} Errors={2}", item, NumItems, NumErrors);
// return Task.CompletedTask;
// }
// public Task OnCompletedAsync()
// {
// logger.Info("Receive OnCompletedAsync - Total Items={0} Errors={1}", NumItems, NumErrors);
// return Task.CompletedTask;
// }
// public Task OnErrorAsync(Exception ex)
// {
// NumErrors++;
// logger.Warn(1, "Received OnErrorAsync - Exception={0} - Total Items={1} Errors={2}", ex, NumItems, NumErrors);
// return Task.CompletedTask;
// }
//}
[Orleans.Providers.StorageProvider(ProviderName = "AzureStore")]
public class StreamUnsubscribeTestGrain : Grain<StreamReliabilityTestGrainState>, IStreamUnsubscribeTestGrain
{
[NonSerialized]
private ILogger logger;
private const string StreamNamespace = StreamTestsConstants.StreamReliabilityNamespace;
public StreamUnsubscribeTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info(String.Format("OnActivateAsync IsProducer = {0}, IsConsumer = {1}.",
State.IsProducer, State.ConsumerSubscriptionHandles != null && State.ConsumerSubscriptionHandles.Count > 0));
return Task.CompletedTask;
}
public async Task Subscribe(Guid streamId, string providerName)
{
logger.Info("Subscribe StreamId={0} StreamProvider={1} Grain={2}", streamId, providerName, this.AsReference<IStreamUnsubscribeTestGrain>());
State.StreamProviderName = providerName;
if (State.Stream == null)
{
logger.Info("InitStream StreamId={0} StreamProvider={1}", streamId, providerName);
IStreamProvider streamProvider = this.GetStreamProvider(providerName);
State.Stream = streamProvider.GetStream<int>(streamId, StreamNamespace);
}
var observer = new MyStreamObserver<int>(logger);
var consumer = State.Stream;
var subsHandle = await consumer.SubscribeAsync(observer);
State.ConsumerSubscriptionHandles.Add(subsHandle);
await WriteStateAsync();
}
public async Task UnSubscribeFromAllStreams()
{
logger.Info("UnSubscribeFromAllStreams: State.ConsumerSubscriptionHandles.Count={0}", State.ConsumerSubscriptionHandles.Count);
if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer");
var handles = State.ConsumerSubscriptionHandles.ToArray();
foreach (var handle in handles)
{
await handle.UnsubscribeAsync();
}
State.ConsumerSubscriptionHandles.Clear();
await WriteStateAsync();
}
}
}
| |
//
// TeamExplorerPad.cs
//
// Author:
// Ventsislav Mladenov <vmladenov.mladenov@gmail.com>
//
// Copyright (c) 2013 Ventsislav Mladenov
//
// 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 MonoDevelop.Ide.Gui;
using Xwt;
using MonoDevelop.Components.Commands;
using MonoDevelop.VersionControl.TFS.Commands;
using MonoDevelop.Ide;
using Microsoft.TeamFoundation.Client;
using System.Linq;
using System;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client.Objects;
using MonoDevelop.VersionControl.TFS.GUI.VersionControl;
using MonoDevelop.VersionControl.TFS.GUI.WorkItems;
namespace MonoDevelop.VersionControl.TFS.GUI
{
public class TeamExplorerPad : IPadContent
{
private enum NodeType
{
Server,
ProjectCollection,
Project,
SourceControl,
WorkItems,
WorkItemQueryType,
WorkItemQuery,
Exception
}
private readonly VBox _content = new VBox();
private readonly TreeView _treeView = new TreeView();
private readonly DataField<string> _name = new DataField<string>();
private readonly DataField<NodeType> _type = new DataField<NodeType>();
private readonly DataField<object> _item = new DataField<object>();
private readonly TreeStore _treeStore;
private System.Action onServersChanged;
public TeamExplorerPad()
{
_treeStore = new TreeStore(_name, _type, _item);
}
#region IPadContent implementation
public void Initialize(IPadWindow window)
{
var toolBar = window.GetToolbar(Gtk.PositionType.Top);
CommandToolButton button = new CommandToolButton(TFSCommands.ConnectToServer, IdeApp.CommandService) { StockId = Gtk.Stock.Add };
toolBar.Add(button);
_treeView.Columns.Add(new ListViewColumn(string.Empty, new TextCellView(_name)));
_treeView.DataSource = _treeStore;
_content.PackStart(_treeView, true, true);
UpdateData();
onServersChanged = DispatchService.GuiDispatch<System.Action>(UpdateData);
TFSVersionControlService.Instance.OnServersChange += onServersChanged;
_treeView.RowActivated += OnRowClicked;
}
public void RedrawContent()
{
UpdateData();
}
public Gtk.Widget Control { get { return (Gtk.Widget)Toolkit.CurrentEngine.GetNativeWidget(_content); } }
#endregion
#region IDisposable implementation
public void Dispose()
{
TFSVersionControlService.Instance.OnServersChange -= onServersChanged;
_treeView.Dispose();
_treeStore.Dispose();
_content.Dispose();
}
#endregion
private void UpdateData()
{
_treeStore.Clear();
foreach (var server in TFSVersionControlService.Instance.Servers)
{
var node = _treeStore.AddNode().SetValue(_name, server.Name)
.SetValue(_type, NodeType.Server)
.SetValue(_item, server);
try
{
foreach (var pc in server.ProjectCollections)
{
node.AddChild().SetValue(_name, pc.Name)
.SetValue(_type, NodeType.ProjectCollection)
.SetValue(_item, pc);
var workItemManager = new WorkItemManager(pc);
foreach (var projectInfo in pc.Projects.OrderBy(x => x.Name))
{
node.AddChild().SetValue(_name, projectInfo.Name).SetValue(_type, NodeType.Project).SetValue(_item, projectInfo);
var workItemProject = workItemManager.GetByGuid(projectInfo.Guid);
if (workItemProject != null)
{
node.AddChild().SetValue(_name, "Work Items").SetValue(_type, NodeType.WorkItems);
var privateQueries = workItemManager.GetMyQueries(workItemProject);
if (privateQueries.Any())
{
node.AddChild().SetValue(_name, "My Queries").SetValue(_type, NodeType.WorkItemQueryType);
foreach (var query in privateQueries)
{
node.AddChild().SetValue(_name, query.QueryName).SetValue(_type, NodeType.WorkItemQuery).SetValue(_item, query);
node.MoveToParent();
}
node.MoveToParent();
}
var publicQueries = workItemManager.GetPublicQueries(workItemProject);
if (publicQueries.Any())
{
node.AddChild().SetValue(_name, "Public").SetValue(_type, NodeType.WorkItemQueryType);
foreach (var query in publicQueries)
{
node.AddChild().SetValue(_name, query.QueryName).SetValue(_type, NodeType.WorkItemQuery).SetValue(_item, query);
node.MoveToParent();
}
node.MoveToParent();
}
node.MoveToParent();
}
node.AddChild().SetValue(_name, "Source Control").SetValue(_type, NodeType.SourceControl);
node.MoveToParent();
node.MoveToParent();
}
node.MoveToParent();
}
}
catch (Exception ex)
{
node.AddChild().SetValue(_name, ex.Message).SetValue(_type, NodeType.Exception);
}
}
ExpandServers();
}
private void ExpandServers()
{
var node = _treeStore.GetFirstNode();
if (node.CurrentPosition == null)
return;
_treeView.ExpandRow(node.CurrentPosition, false);
while (node.MoveNext())
{
_treeView.ExpandRow(node.CurrentPosition, false);
}
}
#region Tree Events
private void OnRowClicked(object sender, TreeViewRowEventArgs e)
{
var node = _treeStore.GetNavigatorAt(e.Position);
var nodeType = node.GetValue(_type);
switch (nodeType)
{
case NodeType.SourceControl:
node.MoveToParent();
var project = (ProjectInfo)node.GetValue(_item);
SourceControlExplorerView.Open(project);
break;
case NodeType.WorkItemQuery:
var query = (StoredQuery)node.GetValue(_item);
WorkItemsView.Open(query);
break;
default:
break;
}
}
#endregion
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* 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 pb.locationIntelligence.Model
{
/// <summary>
/// StudentEthnicity
/// </summary>
[DataContract]
public partial class StudentEthnicity : IEquatable<StudentEthnicity>
{
/// <summary>
/// Initializes a new instance of the <see cref="StudentEthnicity" /> class.
/// </summary>
/// <param name="IndianAlaskaNative">IndianAlaskaNative.</param>
/// <param name="Asian">Asian.</param>
/// <param name="Hispanic">Hispanic.</param>
/// <param name="Black">Black.</param>
/// <param name="White">White.</param>
/// <param name="HawaiianPacificlslander">HawaiianPacificlslander.</param>
/// <param name="TwoOrMoreRaces">TwoOrMoreRaces.</param>
public StudentEthnicity(string IndianAlaskaNative = null, string Asian = null, string Hispanic = null, string Black = null, string White = null, string HawaiianPacificlslander = null, string TwoOrMoreRaces = null)
{
this.IndianAlaskaNative = IndianAlaskaNative;
this.Asian = Asian;
this.Hispanic = Hispanic;
this.Black = Black;
this.White = White;
this.HawaiianPacificlslander = HawaiianPacificlslander;
this.TwoOrMoreRaces = TwoOrMoreRaces;
}
/// <summary>
/// Gets or Sets IndianAlaskaNative
/// </summary>
[DataMember(Name="indianAlaskaNative", EmitDefaultValue=false)]
public string IndianAlaskaNative { get; set; }
/// <summary>
/// Gets or Sets Asian
/// </summary>
[DataMember(Name="asian", EmitDefaultValue=false)]
public string Asian { get; set; }
/// <summary>
/// Gets or Sets Hispanic
/// </summary>
[DataMember(Name="hispanic", EmitDefaultValue=false)]
public string Hispanic { get; set; }
/// <summary>
/// Gets or Sets Black
/// </summary>
[DataMember(Name="black", EmitDefaultValue=false)]
public string Black { get; set; }
/// <summary>
/// Gets or Sets White
/// </summary>
[DataMember(Name="white", EmitDefaultValue=false)]
public string White { get; set; }
/// <summary>
/// Gets or Sets HawaiianPacificlslander
/// </summary>
[DataMember(Name="hawaiianPacificlslander", EmitDefaultValue=false)]
public string HawaiianPacificlslander { get; set; }
/// <summary>
/// Gets or Sets TwoOrMoreRaces
/// </summary>
[DataMember(Name="twoOrMoreRaces", EmitDefaultValue=false)]
public string TwoOrMoreRaces { 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 StudentEthnicity {\n");
sb.Append(" IndianAlaskaNative: ").Append(IndianAlaskaNative).Append("\n");
sb.Append(" Asian: ").Append(Asian).Append("\n");
sb.Append(" Hispanic: ").Append(Hispanic).Append("\n");
sb.Append(" Black: ").Append(Black).Append("\n");
sb.Append(" White: ").Append(White).Append("\n");
sb.Append(" HawaiianPacificlslander: ").Append(HawaiianPacificlslander).Append("\n");
sb.Append(" TwoOrMoreRaces: ").Append(TwoOrMoreRaces).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 StudentEthnicity);
}
/// <summary>
/// Returns true if StudentEthnicity instances are equal
/// </summary>
/// <param name="other">Instance of StudentEthnicity to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(StudentEthnicity other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.IndianAlaskaNative == other.IndianAlaskaNative ||
this.IndianAlaskaNative != null &&
this.IndianAlaskaNative.Equals(other.IndianAlaskaNative)
) &&
(
this.Asian == other.Asian ||
this.Asian != null &&
this.Asian.Equals(other.Asian)
) &&
(
this.Hispanic == other.Hispanic ||
this.Hispanic != null &&
this.Hispanic.Equals(other.Hispanic)
) &&
(
this.Black == other.Black ||
this.Black != null &&
this.Black.Equals(other.Black)
) &&
(
this.White == other.White ||
this.White != null &&
this.White.Equals(other.White)
) &&
(
this.HawaiianPacificlslander == other.HawaiianPacificlslander ||
this.HawaiianPacificlslander != null &&
this.HawaiianPacificlslander.Equals(other.HawaiianPacificlslander)
) &&
(
this.TwoOrMoreRaces == other.TwoOrMoreRaces ||
this.TwoOrMoreRaces != null &&
this.TwoOrMoreRaces.Equals(other.TwoOrMoreRaces)
);
}
/// <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.IndianAlaskaNative != null)
hash = hash * 59 + this.IndianAlaskaNative.GetHashCode();
if (this.Asian != null)
hash = hash * 59 + this.Asian.GetHashCode();
if (this.Hispanic != null)
hash = hash * 59 + this.Hispanic.GetHashCode();
if (this.Black != null)
hash = hash * 59 + this.Black.GetHashCode();
if (this.White != null)
hash = hash * 59 + this.White.GetHashCode();
if (this.HawaiianPacificlslander != null)
hash = hash * 59 + this.HawaiianPacificlslander.GetHashCode();
if (this.TwoOrMoreRaces != null)
hash = hash * 59 + this.TwoOrMoreRaces.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk;
namespace PowerShellLibrary.Crm.CmdletProviders
{
[DataContract]
[Microsoft.Xrm.Sdk.Client.EntityLogicalName("sdkmessagepair")]
[GeneratedCode("CrmSvcUtil", "7.1.0001.3108")]
public class SdkMessagePair : Entity, INotifyPropertyChanging, INotifyPropertyChanged
{
public const string EntityLogicalName = "sdkmessagepair";
public const int EntityTypeCode = 4613;
[AttributeLogicalName("createdby")]
public EntityReference CreatedBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdby");
}
}
[AttributeLogicalName("createdon")]
public DateTime? CreatedOn
{
get
{
return this.GetAttributeValue<DateTime?>("createdon");
}
}
[AttributeLogicalName("createdonbehalfby")]
public EntityReference CreatedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdonbehalfby");
}
}
[AttributeLogicalName("customizationlevel")]
public int? CustomizationLevel
{
get
{
return this.GetAttributeValue<int?>("customizationlevel");
}
}
[AttributeLogicalName("endpoint")]
public string Endpoint
{
get
{
return this.GetAttributeValue<string>("endpoint");
}
set
{
this.OnPropertyChanging("Endpoint");
this.SetAttributeValue("endpoint", (object) value);
this.OnPropertyChanged("Endpoint");
}
}
[AttributeLogicalName("modifiedby")]
public EntityReference ModifiedBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedby");
}
}
[AttributeLogicalName("modifiedon")]
public DateTime? ModifiedOn
{
get
{
return this.GetAttributeValue<DateTime?>("modifiedon");
}
}
[AttributeLogicalName("modifiedonbehalfby")]
public EntityReference ModifiedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedonbehalfby");
}
}
[AttributeLogicalName("namespace")]
public string Namespace
{
get
{
return this.GetAttributeValue<string>("namespace");
}
set
{
this.OnPropertyChanging("Namespace");
this.SetAttributeValue("namespace", (object) value);
this.OnPropertyChanged("Namespace");
}
}
[AttributeLogicalName("organizationid")]
public EntityReference OrganizationId
{
get
{
return this.GetAttributeValue<EntityReference>("organizationid");
}
}
[AttributeLogicalName("sdkmessagebindinginformation")]
public string SdkMessageBindingInformation
{
get
{
return this.GetAttributeValue<string>("sdkmessagebindinginformation");
}
set
{
this.OnPropertyChanging("SdkMessageBindingInformation");
this.SetAttributeValue("sdkmessagebindinginformation", (object) value);
this.OnPropertyChanged("SdkMessageBindingInformation");
}
}
[AttributeLogicalName("sdkmessageid")]
public EntityReference SdkMessageId
{
get
{
return this.GetAttributeValue<EntityReference>("sdkmessageid");
}
}
[AttributeLogicalName("sdkmessagepairid")]
public Guid? SdkMessagePairId
{
get
{
return this.GetAttributeValue<Guid?>("sdkmessagepairid");
}
set
{
this.OnPropertyChanging("SdkMessagePairId");
this.SetAttributeValue("sdkmessagepairid", (object) value);
if (value.HasValue)
base.Id = value.Value;
else
base.Id = Guid.Empty;
this.OnPropertyChanged("SdkMessagePairId");
}
}
[AttributeLogicalName("sdkmessagepairid")]
public override Guid Id
{
get
{
return base.Id;
}
set
{
this.SdkMessagePairId = new Guid?(value);
}
}
[AttributeLogicalName("sdkmessagepairidunique")]
public Guid? SdkMessagePairIdUnique
{
get
{
return this.GetAttributeValue<Guid?>("sdkmessagepairidunique");
}
}
[AttributeLogicalName("versionnumber")]
public long? VersionNumber
{
get
{
return this.GetAttributeValue<long?>("versionnumber");
}
}
[RelationshipSchemaName("messagepair_sdkmessagerequest")]
public IEnumerable<SdkMessageRequest> messagepair_sdkmessagerequest
{
get
{
return this.GetRelatedEntities<SdkMessageRequest>("messagepair_sdkmessagerequest", new EntityRole?());
}
set
{
this.OnPropertyChanging("messagepair_sdkmessagerequest");
this.SetRelatedEntities<SdkMessageRequest>("messagepair_sdkmessagerequest", new EntityRole?(), value);
this.OnPropertyChanged("messagepair_sdkmessagerequest");
}
}
[AttributeLogicalName("createdby")]
[RelationshipSchemaName("createdby_sdkmessagepair")]
public SystemUser createdby_sdkmessagepair
{
get
{
return this.GetRelatedEntity<SystemUser>("createdby_sdkmessagepair", new EntityRole?());
}
}
[RelationshipSchemaName("lk_sdkmessagepair_createdonbehalfby")]
[AttributeLogicalName("createdonbehalfby")]
public SystemUser lk_sdkmessagepair_createdonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_sdkmessagepair_createdonbehalfby", new EntityRole?());
}
}
[AttributeLogicalName("modifiedonbehalfby")]
[RelationshipSchemaName("lk_sdkmessagepair_modifiedonbehalfby")]
public SystemUser lk_sdkmessagepair_modifiedonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_sdkmessagepair_modifiedonbehalfby", new EntityRole?());
}
}
[RelationshipSchemaName("message_sdkmessagepair")]
[AttributeLogicalName("sdkmessageid")]
public SdkMessage message_sdkmessagepair
{
get
{
return this.GetRelatedEntity<SdkMessage>("message_sdkmessagepair", new EntityRole?());
}
}
[AttributeLogicalName("modifiedby")]
[RelationshipSchemaName("modifiedby_sdkmessagepair")]
public SystemUser modifiedby_sdkmessagepair
{
get
{
return this.GetRelatedEntity<SystemUser>("modifiedby_sdkmessagepair", new EntityRole?());
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public SdkMessagePair()
: base("sdkmessagepair")
{
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged == null)
return;
this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanging(string propertyName)
{
if (this.PropertyChanging == null)
return;
this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName));
}
}
}
| |
namespace ControlzEx.Helpers
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ControlzEx.Controls.Internal;
using ControlzEx.Internal;
public static class GlowWindowBitmapGenerator
{
public static RenderTargetBitmap GenerateBitmapSource(GlowBitmapPart part, int glowDepth, bool useRadialGradientForCorners)
{
var size = GetSize(part, glowDepth);
var drawingVisual = new DrawingVisual();
using (var drawingContext = drawingVisual.RenderOpen())
{
if (glowDepth > 1)
{
var gradientBrush = CreateGradientBrush(part, useRadialGradientForCorners);
gradientBrush.Freeze();
drawingContext.DrawRectangle(gradientBrush, null, new Rect(0, 0, size.Width, size.Height));
drawingContext.DrawRectangle(Brushes.Black, null, GetBlackRect(part, glowDepth));
}
else
{
drawingContext.DrawRectangle(Brushes.Black, null, new Rect(0, 0, size.Width, size.Height));
}
}
var targetBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
targetBitmap.Render(drawingVisual);
return targetBitmap;
}
private static Rect GetBlackRect(GlowBitmapPart part, int glowDepth)
{
switch (part)
{
case GlowBitmapPart.CornerTopLeft:
return new Rect(new Point(glowDepth - 1, glowDepth - 1), new Size(1, 1));
case GlowBitmapPart.CornerTopRight:
return new Rect(new Point(0, glowDepth - 1), new Size(1, 1));
case GlowBitmapPart.CornerBottomLeft:
return new Rect(new Point(glowDepth - 1, 0), new Size(1, 1));
case GlowBitmapPart.CornerBottomRight:
return new Rect(new Point(0, 0), new Size(1, 1));
case GlowBitmapPart.TopLeft:
case GlowBitmapPart.Top:
case GlowBitmapPart.TopRight:
return new Rect(new Point(0, glowDepth - 1), new Size(glowDepth, 1));
case GlowBitmapPart.LeftTop:
case GlowBitmapPart.Left:
case GlowBitmapPart.LeftBottom:
return new Rect(new Point(glowDepth - 1, 0), new Size(1, glowDepth));
case GlowBitmapPart.BottomLeft:
case GlowBitmapPart.Bottom:
case GlowBitmapPart.BottomRight:
return new Rect(new Point(0, 0), new Size(glowDepth, 1));
case GlowBitmapPart.RightTop:
case GlowBitmapPart.Right:
case GlowBitmapPart.RightBottom:
return new Rect(new Point(0, 0), new Size(1, glowDepth));
default:
throw new ArgumentOutOfRangeException(nameof(part), part, null);
}
}
private static Size GetSize(GlowBitmapPart part, int glowDepth)
{
switch (part)
{
case GlowBitmapPart.CornerTopLeft:
case GlowBitmapPart.CornerTopRight:
case GlowBitmapPart.CornerBottomLeft:
case GlowBitmapPart.CornerBottomRight:
return new Size(glowDepth, glowDepth);
case GlowBitmapPart.Top:
case GlowBitmapPart.Bottom:
return new Size(1, glowDepth);
case GlowBitmapPart.TopLeft:
case GlowBitmapPart.TopRight:
case GlowBitmapPart.BottomLeft:
case GlowBitmapPart.BottomRight:
return new Size(Math.Min(glowDepth, 6), glowDepth);
case GlowBitmapPart.Left:
case GlowBitmapPart.Right:
return new Size(glowDepth, 1);
case GlowBitmapPart.LeftTop:
case GlowBitmapPart.LeftBottom:
case GlowBitmapPart.RightTop:
case GlowBitmapPart.RightBottom:
return new Size(glowDepth, Math.Min(glowDepth, 6));
default:
throw new ArgumentOutOfRangeException(nameof(part), part, null);
}
}
private static GradientBrush CreateGradientBrush(GlowBitmapPart part, bool useRadialGradientForCorners)
{
var startAndEndPoint = GetStartAndEndPoint(part);
var gradientStops = GetGradientStops(part, useRadialGradientForCorners);
var gradientStopCollection = new GradientStopCollection(gradientStops);
if (useRadialGradientForCorners == false)
{
return new LinearGradientBrush(gradientStopCollection, startAndEndPoint.Start, startAndEndPoint.End);
}
switch (part)
{
case GlowBitmapPart.CornerTopLeft:
case GlowBitmapPart.CornerTopRight:
case GlowBitmapPart.CornerBottomLeft:
case GlowBitmapPart.CornerBottomRight:
return new RadialGradientBrush(gradientStopCollection)
{
GradientOrigin = startAndEndPoint.Start,
Center = new Point(startAndEndPoint.Start.X.AreClose(0) ? 0.2 : 0.8, startAndEndPoint.Start.Y.AreClose(0) ? 0.2 : 0.8),
RadiusX = 1,
RadiusY = 1
};
case GlowBitmapPart.TopLeft:
case GlowBitmapPart.Top:
case GlowBitmapPart.TopRight:
case GlowBitmapPart.LeftTop:
case GlowBitmapPart.Left:
case GlowBitmapPart.LeftBottom:
case GlowBitmapPart.BottomLeft:
case GlowBitmapPart.Bottom:
case GlowBitmapPart.BottomRight:
case GlowBitmapPart.RightTop:
case GlowBitmapPart.Right:
case GlowBitmapPart.RightBottom:
return new LinearGradientBrush(gradientStopCollection, startAndEndPoint.Start, startAndEndPoint.End);
default:
throw new ArgumentOutOfRangeException(nameof(part), part, null);
}
}
private static StartAndEndPoint GetStartAndEndPoint(GlowBitmapPart part)
{
switch (part)
{
case GlowBitmapPart.CornerTopLeft:
return new(new Point(1, 1), new Point(0, 0));
case GlowBitmapPart.CornerTopRight:
return new(new Point(0, 1), new Point(1, 0));
case GlowBitmapPart.CornerBottomLeft:
return new(new Point(1, 0), new Point(0, 1));
case GlowBitmapPart.CornerBottomRight:
return new(new Point(0, 0), new Point(1, 1));
case GlowBitmapPart.TopLeft:
return new(new Point(0.6, 1), new Point(0.5, 0));
case GlowBitmapPart.Top:
return new(new Point(0.5, 1), new Point(0.5, 0));
case GlowBitmapPart.TopRight:
return new(new Point(0.4, 1), new Point(0.5, 0));
case GlowBitmapPart.LeftTop:
return new(new Point(1, 0.1), new Point(0, 0));
case GlowBitmapPart.Left:
return new(new Point(1, 0), new Point(0, 0));
case GlowBitmapPart.LeftBottom:
return new(new Point(1, 0), new Point(0, 0.1));
case GlowBitmapPart.BottomLeft:
return new(new Point(0.6, 0), new Point(0.5, 1));
case GlowBitmapPart.Bottom:
return new(new Point(0.5, 0), new Point(0.5, 1));
case GlowBitmapPart.BottomRight:
return new(new Point(0.4, 0), new Point(0.5, 1));
case GlowBitmapPart.RightTop:
return new(new Point(0, 0.1), new Point(1, 0));
case GlowBitmapPart.Right:
return new(new Point(0, 0), new Point(1, 0));
case GlowBitmapPart.RightBottom:
return new(new Point(0, 0), new Point(1, 0.1));
default:
throw new ArgumentOutOfRangeException(nameof(part), part, null);
}
}
private static IEnumerable<GradientStop> GetGradientStops(GlowBitmapPart part, bool useRadialGradientForCorners)
{
switch (part)
{
case GlowBitmapPart.CornerBottomLeft:
case GlowBitmapPart.CornerBottomRight:
case GlowBitmapPart.CornerTopLeft:
case GlowBitmapPart.CornerTopRight:
if (useRadialGradientForCorners)
{
yield return new GradientStop(ColorFromString("#55838383"), 0);
yield return new GradientStop(ColorFromString("#02838383"), 0.5);
yield return new GradientStop(ColorFromString("#00000000"), 1);
}
else
{
yield return new GradientStop(ColorFromString("#55838383"), 0);
yield return new GradientStop(ColorFromString("#02838383"), 0.3);
yield return new GradientStop(ColorFromString("#00000000"), 1);
}
break;
default:
yield return new GradientStop(ColorFromString("#55838383"), 0);
yield return new GradientStop(ColorFromString("#02838383"), 0.6);
yield return new GradientStop(ColorFromString("#00000000"), 1);
break;
}
}
private static Color ColorFromString(string input)
{
return (Color)ColorConverter.ConvertFromString(input);
}
private readonly struct StartAndEndPoint
{
public StartAndEndPoint(Point start, Point end)
{
this.Start = start;
this.End = end;
}
public Point Start { get; }
public Point End { get; }
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Moq;
using NUnit.Framework;
using QuantConnect.Brokerages;
using QuantConnect.Brokerages.Zerodha;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Tests.Common.Securities;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace QuantConnect.Tests.Brokerages.Zerodha
{
[TestFixture, Ignore("This test requires a configured and active Zerodha account")]
public class ZerodhaBrokerageTests
{
private static IOrderProperties orderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
private IBrokerage _brokerage;
private OrderProvider _orderProvider;
private SecurityProvider _securityProvider;
[SetUp]
public void Setup()
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- SETUP ---");
Log.Trace("");
Log.Trace("");
// we want to regenerate these for each test
_brokerage = null;
_orderProvider = null;
_securityProvider = null;
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateZerodhaHoldings();
Thread.Sleep(1000);
}
[TearDown]
public void Teardown()
{
try
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- TEARDOWN ---");
Log.Trace("");
Log.Trace("");
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateZerodhaHoldings();
Thread.Sleep(1000);
}
finally
{
if (_brokerage != null)
{
DisposeBrokerage(_brokerage);
}
}
}
/// <summary>
/// Disposes of the brokerage and any external resources started in order to create it
/// </summary>
/// <param name="brokerage">The brokerage instance to be disposed of</param>
protected virtual void DisposeBrokerage(IBrokerage brokerage)
{
brokerage.Disconnect();
}
public IBrokerage Brokerage
{
get
{
if (_brokerage == null)
{
_brokerage = InitializeBrokerage();
}
return _brokerage;
}
}
private IBrokerage InitializeBrokerage()
{
Log.Trace("");
Log.Trace("- INITIALIZING BROKERAGE -");
Log.Trace("");
var brokerage = CreateBrokerage(OrderProvider, SecurityProvider);
brokerage.Connect();
if (!brokerage.IsConnected)
{
Assert.Fail("Failed to connect to brokerage");
}
Log.Trace("");
Log.Trace("GET OPEN ORDERS");
Log.Trace("");
foreach (var openOrder in brokerage.GetOpenOrders())
{
OrderProvider.Add(openOrder);
}
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
foreach (var accountHolding in brokerage.GetAccountHoldings())
{
// these securities don't need to be real, just used for the ISecurityProvider impl, required
// by brokerages to track holdings
SecurityProvider[accountHolding.Symbol] = CreateSecurity(accountHolding.Symbol);
}
brokerage.OrderStatusChanged += (sender, args) =>
{
Log.Trace("");
Log.Trace("ORDER STATUS CHANGED: " + args);
Log.Trace("");
// we need to keep this maintained properly
if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled)
{
Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString());
Security security;
if (_securityProvider.TryGetValue(args.Symbol, out security))
{
var holding = _securityProvider[args.Symbol].Holdings;
holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity);
}
else
{
_securityProvider[args.Symbol] = CreateSecurity(args.Symbol);
_securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity);
}
Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]);
// update order mapping
var order = _orderProvider.GetOrderById(args.OrderId);
order.Status = args.Status;
}
};
return brokerage;
}
internal static Security CreateSecurity(Symbol symbol)
{
return new Security(
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(
typeof(TradeBar),
symbol,
Resolution.Minute,
TimeZones.NewYork,
TimeZones.NewYork,
false,
false,
false
),
new Cash(Currencies.USD, 0, 1m),
SymbolProperties.GetDefault(Currencies.USD),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache()
);
}
public OrderProvider OrderProvider
{
get { return _orderProvider ?? (_orderProvider = new OrderProvider()); }
}
public SecurityProvider SecurityProvider
{
get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); }
}
/// <summary>
/// This is used to ensure each test starts with a clean, known state.
/// </summary>
protected void LiquidateZerodhaHoldings()
{
Log.Trace("");
Log.Trace("LIQUIDATE HOLDINGS");
Log.Trace("");
var holdings = Brokerage.GetAccountHoldings();
foreach (var holding in holdings)
{
if (holding.Quantity == 0) continue;
Log.Trace("Liquidating: " + holding);
var order = new MarketOrder(holding.Symbol, -holding.Quantity, DateTime.UtcNow,properties:orderProperties);
_orderProvider.Add(order);
PlaceZerodhaOrderWaitForStatus(order, OrderStatus.Filled);
}
}
/// <summary>
/// Provides the data required to test each order type in various cases
/// </summary>
private static TestCaseData[] OrderParameters()
{
return new[]
{
new TestCaseData(new MarketOrderTestParameters(Symbols.IDEA,orderProperties)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(Symbols.IDEA, 9.00m, 9.30m,orderProperties)).SetName("LimitOrder"),
new TestCaseData(new StopMarketOrderTestParameters(Symbols.IDEA, 10.50m, 9.50m,orderProperties)).SetName("StopMarketOrder"),
//new TestCaseData(new StopLimitOrderTestParameters(Symbols.IDEA, 9.00m, 10.50m,orderProperties)).SetName("StopLimitOrder")
};
}
/// <summary>
/// Creates the brokerage under test
/// </summary>
/// <returns>A connected brokerage instance</returns>
protected IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
{
var securities = new SecurityManager(new TimeKeeper(DateTime.UtcNow, TimeZones.Kolkata))
{
{ Symbol, CreateSecurity(Symbol) }
};
var transactions = new SecurityTransactionManager(null, securities);
transactions.SetOrderProcessor(new FakeOrderProcessor());
var algorithm = new Mock<IAlgorithm>();
algorithm.Setup(a => a.Transactions).Returns(transactions);
algorithm.Setup(a => a.BrokerageModel).Returns(new ZerodhaBrokerageModel());
algorithm.Setup(a => a.Portfolio).Returns(new SecurityPortfolioManager(securities, transactions));
var accessToken = Config.Get("zerodha-access-token");
var apiKey = Config.Get("zerodha-api-key");
var tradingSegment = Config.Get("zerodha-trading-segment");
var productType = Config.Get("zerodha-product-type");
var zerodha = new ZerodhaBrokerage(tradingSegment, productType, apiKey, accessToken, algorithm.Object, algorithm.Object.Portfolio, new AggregationManager());
return zerodha;
}
/// <summary>
/// Gets the symbol to be traded, must be shortable
/// </summary>
protected Symbol Symbol => Symbols.IDEA;
/// <summary>
/// Gets the security type associated with the <see cref="BrokerageTests.Symbol"/>
/// </summary>
protected SecurityType SecurityType => SecurityType.Equity;
/// <summary>
/// Returns wether or not the brokers order methods implementation are async
/// </summary>
protected bool IsAsync()
{
return false;
}
/// <summary>
/// Gets the default order quantity
/// </summary>
protected virtual decimal GetDefaultQuantity()
{
return 1;
}
/// <summary>
/// Gets the current market price of the specified security
/// </summary>
protected decimal GetAskPrice(Symbol symbol)
{
var zerodha = (ZerodhaBrokerage)Brokerage;
var quotes = zerodha.GetQuote(symbol);
return quotes.LastPrice;
}
[Test]
public void ShortIdea()
{
PlaceZerodhaOrderWaitForStatus(new MarketOrder(Symbols.IDEA, -1, DateTime.Now, properties: orderProperties), OrderStatus.Submitted, allowFailedSubmission: true);
// wait for output to be generated
Thread.Sleep(20 * 1000);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public void CancelOrders(OrderTestParameters parameters)
{
const int secondsTimeout = 20;
Log.Trace("");
Log.Trace("CANCEL ORDERS");
Log.Trace("");
var order = PlaceZerodhaOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
var canceledOrderStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> orderStatusCallback = (sender, fill) =>
{
if (fill.Status == OrderStatus.Canceled)
{
canceledOrderStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += orderStatusCallback;
var cancelResult = false;
try
{
cancelResult = Brokerage.CancelOrder(order);
}
catch (Exception exception)
{
Log.Error(exception);
}
Assert.AreEqual(IsCancelAsync() || parameters.ExpectedCancellationResult, cancelResult);
if (parameters.ExpectedCancellationResult)
{
// We expect the OrderStatus.Canceled event
canceledOrderStatusEvent.WaitOneAssertFail(1000 * secondsTimeout, "Order timedout to cancel");
}
var openOrders = Brokerage.GetOpenOrders();
var cancelledOrder = openOrders.FirstOrDefault(x => x.Id == order.Id);
Assert.IsNull(cancelledOrder);
//canceledOrderStatusEvent.Reset();
//var cancelResultSecondTime = false;
//try
//{
// cancelResultSecondTime = Brokerage.CancelOrder(order);
//}
//catch (Exception exception)
//{
// Log.Error(exception);
//}
//Assert.AreEqual(IsCancelAsync(), cancelResultSecondTime);
//// We do NOT expect the OrderStatus.Canceled event
//Assert.IsFalse(canceledOrderStatusEvent.WaitOne(new TimeSpan(0, 0, 10)));
//Brokerage.OrderStatusChanged -= orderStatusCallback;
}
[Test]
public void ValidateStopLimitOrders()
{
var zerodha = (ZerodhaBrokerage)Brokerage;
var symbol = Symbol;
var lastPrice = GetAskPrice(symbol.Value);
// Buy StopLimit order below market TODO: This might not work because of the Zerodha structure. Verify this.
//var stopPrice = lastPrice - 0.10m;
//var limitPrice = stopPrice + 0.10m;
//var order = new StopLimitOrder(symbol, 1, stopPrice, limitPrice, DateTime.UtcNow, properties: orderProperties);
//Assert.IsTrue(zerodha.PlaceOrder(order));
// Buy StopLimit order above market
var stopPrice = lastPrice + 0.20m;
var limitPrice = stopPrice + 0.25m;
var order = new StopLimitOrder(symbol, 1, stopPrice, limitPrice, DateTime.UtcNow, properties: orderProperties);
Assert.IsTrue(zerodha.PlaceOrder(order));
// In case there is no position, the following sell orders would not be placed
// So build a position for them.
var marketOrder = new MarketOrder(symbol, 2, DateTime.UtcNow, properties: orderProperties);
Assert.IsTrue(zerodha.PlaceOrder(marketOrder));
Thread.Sleep(20000);
// Sell StopLimit order below market
stopPrice = lastPrice - 0.25m;
limitPrice = stopPrice - 0.5m;
order = new StopLimitOrder(symbol, -1, stopPrice, limitPrice, DateTime.UtcNow, properties: orderProperties);
Assert.IsTrue(zerodha.PlaceOrder(order));
// Sell StopLimit order above market. TODO: This might not work because of the Zerodha structure. Verify this
//stopPrice = lastPrice + 0.5m;
//limitPrice = stopPrice - 0.25m ;
//order = new StopLimitOrder(symbol, -1, stopPrice, limitPrice, DateTime.UtcNow, properties: orderProperties);
//Assert.IsTrue(zerodha.PlaceOrder(order));
}
[Test, TestCaseSource(nameof(OrderParameters))]
public void LongFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM ZERO");
Log.Trace("");
PlaceZerodhaOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public void CloseFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM LONG");
Log.Trace("");
// first go long
PlaceZerodhaOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceZerodhaOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public void ShortFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM ZERO");
Log.Trace("");
PlaceZerodhaOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public virtual void CloseFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM SHORT");
Log.Trace("");
// first go short
PlaceZerodhaOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceZerodhaOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public virtual void ShortFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM LONG");
Log.Trace("");
// first go long
PlaceZerodhaOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()));
// now go net short
var order = PlaceZerodhaOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerage")]
public void PartialFills()
{
var manualResetEvent = new ManualResetEvent(false);
var qty = 1000000m;
var remaining = qty;
var sync = new object();
Brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
lock (sync)
{
remaining -= orderEvent.FillQuantity;
Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity);
if (orderEvent.Status == OrderStatus.Filled)
{
manualResetEvent.Set();
}
}
};
// pick a security with low, but some, volume
var symbol = Symbols.EURUSD;
var order = new MarketOrder(symbol, qty, DateTime.UtcNow) { Id = 1 };
OrderProvider.Add(order);
Brokerage.PlaceOrder(order);
// pause for a while to wait for fills to come in
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
Console.WriteLine("Remaining: " + remaining);
Assert.AreEqual(0, remaining);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public virtual void LongFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM SHORT");
Log.Trace("");
// first fo short
PlaceZerodhaOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled);
// now go long
var order = PlaceZerodhaOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test]
public void GetCashBalanceContainsSomething()
{
Log.Trace("");
Log.Trace("GET CASH BALANCE");
Log.Trace("");
var balance = Brokerage.GetCashBalance();
Assert.IsTrue(balance.Any());
}
[Test]
public void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetAccountHoldings();
PlaceZerodhaOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.UtcNow,properties:orderProperties));
Thread.Sleep(3000);
var after = Brokerage.GetAccountHoldings();
var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol);
var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol);
var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity;
var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity;
Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity);
}
[Test]
public void IsConnected()
{
Assert.IsTrue(Brokerage.IsConnected);
}
/// <summary>
/// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event.
/// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID.
/// </summary>
/// <param name="order">The order to be submitted</param>
/// <param name="expectedStatus">The status to wait for</param>
/// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param>
/// <param name="allowFailedSubmission">Allow failed order submission</param>
/// <returns>The same order that was submitted.</returns>
protected Order PlaceZerodhaOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled,
double secondsTimeout = 10.0, bool allowFailedSubmission = false)
{
var requiredStatusEvent = new ManualResetEvent(false);
var desiredStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
// no matter what, every order should fire at least one of these
if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid)
{
Log.Trace("");
Log.Trace("SUBMITTED: " + args);
Log.Trace("");
requiredStatusEvent.Set();
}
// make sure we fire the status we're expecting
if (args.Status == expectedStatus)
{
Log.Trace("");
Log.Trace("EXPECTED: " + args);
Log.Trace("");
desiredStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
OrderProvider.Add(order);
if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission)
{
Assert.Fail("Brokerage failed to place the order: " + order);
}
requiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "Expected every order to fire a submitted or invalid status event");
desiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout. Order Id:" + order.Id);
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
return order;
}
protected void CancelOpenOrders()
{
Log.Trace("");
Log.Trace("CANCEL OPEN ORDERS");
Log.Trace("");
var openOrders = Brokerage.GetOpenOrders();
foreach (var openOrder in openOrders)
{
Log.Trace("Canceling: " + openOrder);
Brokerage.CancelOrder(openOrder);
}
}
/// <summary>
/// Updates the specified order in the brokerage until it fills or reaches a timeout
/// </summary>
/// <param name="order">The order to be modified</param>
/// <param name="parameters">The order test parameters that define how to modify the order</param>
/// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param>
protected void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
{
if (order.Status == OrderStatus.Filled)
{
return;
}
var filledResetEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
if (args.Status == OrderStatus.Filled)
{
filledResetEvent.Set();
}
if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid)
{
Log.Trace("ModifyOrderUntilFilled(): " + order);
Assert.Fail("Unexpected order status: " + args.Status);
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
Log.Trace("");
Log.Trace("MODIFY UNTIL FILLED: " + order);
Log.Trace("");
var stopwatch = Stopwatch.StartNew();
while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout)
{
filledResetEvent.Reset();
if (order.Status == OrderStatus.PartiallyFilled) continue;
var marketPrice = GetAskPrice(order.Symbol);
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice);
var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice);
if (updateOrder)
{
if (order.Status == OrderStatus.Filled) break;
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order);
if (!Brokerage.UpdateOrder(order))
{
Assert.Fail("Brokerage failed to update the order");
}
}
}
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
}
/// <summary>
/// Returns whether or not the brokers order cancel method implementation is async
/// </summary>
protected bool IsCancelAsync()
{
return false;
}
}
}
| |
// <copyright file="Preprocessor.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using BeanIO.Internal.Config;
using BeanIO.Internal.Util;
namespace BeanIO.Internal.Compiler
{
/// <summary>
/// A Pre-processer is responsible for validating a stream configuration, setting
/// default configuration values, and populating any calculated values before the
/// <see cref="ParserFactorySupport"/> compiles the configuration into parser components.
/// </summary>
internal class Preprocessor : ProcessorSupport
{
private static readonly Settings _settings = Settings.Instance;
private static readonly bool SORT_XML_COMPONENTS = Settings.Instance.GetBoolean(Settings.SORT_XML_COMPONENTS_BY_POSITION);
private readonly StreamConfig _stream;
private bool _recordIgnored;
public Preprocessor(StreamConfig stream)
{
_stream = stream;
}
/// <summary>
/// Gets the stream configuration
/// </summary>
protected StreamConfig Stream => _stream;
protected PropertyConfig PropertyRoot { get; set; }
protected override void InitializeStream(StreamConfig stream)
{
if (stream.MinOccurs == null)
stream.MinOccurs = 0;
if (stream.MaxOccurs == null)
stream.MaxOccurs = 1;
if (stream.MaxOccurs <= 0)
throw new BeanIOConfigurationException("Maximum occurrences must be greater than 0");
InitializeGroup(stream);
}
/// <summary>
/// Finalizes a stream configuration after its children have been processed
/// </summary>
/// <param name="stream">the stream configuration to finalize</param>
protected override void FinalizeStream(StreamConfig stream)
{
FinalizeGroup(stream);
bool sortingRequired = SORT_XML_COMPONENTS || !string.Equals("xml", stream.Format, StringComparison.Ordinal);
if (sortingRequired)
stream.Sort(new ComponentConfigComparer());
}
/// <summary>
/// Initializes a group configuration before its children have been processed
/// </summary>
/// <param name="group">the group configuration to process</param>
protected override void InitializeGroup(GroupConfig group)
{
if (group.MinOccurs == null)
group.MinOccurs = _settings.GetInt(Settings.DEFAULT_GROUP_MIN_OCCURS, 0);
if (group.MaxOccurs == null)
group.MaxOccurs = int.MaxValue;
if (group.MaxOccurs <= 0)
throw new BeanIOConfigurationException("Maximum occurrences must be greater than 0");
if (group.MaxOccurs < group.MinOccurs)
throw new BeanIOConfigurationException("Maximum occurences cannot be less than mininum occurences");
// validate both 'class' and 'target' aren't set
if (group.Type != null && group.Target != null)
throw new BeanIOConfigurationException("Cannot set both 'class' and 'value'");
if (PropertyRoot != null)
{
group.IsBound = true;
if (group.Collection != null && group.Type == null)
throw new BeanIOConfigurationException("Class required if collection is set");
if (group.Type != null
&& (group.MaxOccurs == null || group.MaxOccurs > 1)
&& group.Collection == null)
{
throw new BeanIOConfigurationException("Collection required when maxOccurs is greater than 1 and class is set");
}
if (group.IsRepeating && group.Collection == null)
group.IsBound = false;
}
if (PropertyRoot == null && (group.Type != null || group.Target != null))
PropertyRoot = group;
if (Parent != null && group.ValidateOnMarshal == null)
group.ValidateOnMarshal = Parent.ValidateOnMarshal;
}
/// <summary>
/// Finalizes a group configuration after its children have been processed
/// </summary>
/// <param name="group">the group configuration to finalize</param>
protected override void FinalizeGroup(GroupConfig group)
{
// order must be set for all group children, or for none of them
// if order is specified...
// -validate group children are in ascending order
// otherwise if order is not specified...
// -if strict, all children have current order incremented
// -if not, all children have order set to 1
var lastOrder = 0;
bool? orderSet = null;
foreach (var child in group.Children.Cast<ISelectorConfig>())
{
string typeDescription = child.ComponentType == ComponentType.Record ? "record" : "group";
if (child.Order != null && child.Order < 0)
throw new BeanIOConfigurationException("Order must be 1 or greater");
if (orderSet == null)
{
orderSet = child.Order != null;
}
else if (orderSet.Value ^ (child.Order != null))
{
throw new BeanIOConfigurationException("Order must be set all children at a group level, or none at all");
}
if (orderSet.Value)
{
if (child.Order < lastOrder)
throw new BeanIOConfigurationException($"'{child.Name}' {typeDescription} configuration is out of order");
lastOrder = child.Order.Value;
}
else
{
if (_stream.IsStrict)
{
child.Order = ++lastOrder;
}
else
{
child.Order = 1;
}
}
}
if (PropertyRoot == group)
PropertyRoot = null;
}
/// <summary>
/// Initializes a record configuration before its children have been processed
/// </summary>
/// <param name="record">the record configuration to process</param>
protected override void InitializeRecord(RecordConfig record)
{
// a record is ignored if a 'class' was not set and the property root is null
// or the record repeats
_recordIgnored = false;
if (record.Type == null && record.Target == null)
{
if (PropertyRoot == null || record.IsRepeating)
_recordIgnored = true;
}
// assign default min and max occurs
if (record.MinOccurs == null)
record.MinOccurs = _settings.GetInt(Settings.DEFAULT_RECORD_MIN_OCCURS, 0);
if (record.MaxOccurs == null)
record.MaxOccurs = int.MaxValue;
if (record.MaxOccurs <= 0)
throw new BeanIOConfigurationException("Maximum occurrences must be greater than 0");
if (PropertyRoot == null)
{
PropertyRoot = record;
if (record.IsLazy)
throw new BeanIOConfigurationException("Lazy cannot be true for unbound records");
}
InitializeSegment(record);
}
/// <summary>
/// Finalizes a record configuration after its children have been processed
/// </summary>
/// <param name="record">the record configuration to finalize</param>
protected override void FinalizeRecord(RecordConfig record)
{
FinalizeSegment(record);
if (PropertyRoot == record)
PropertyRoot = null;
}
/// <summary>
/// Initializes a segment configuration before its children have been processed
/// </summary>
/// <param name="segment">the segment configuration to process</param>
protected override void InitializeSegment(SegmentConfig segment)
{
if (segment.Name == null)
throw new BeanIOConfigurationException("name must be set");
if (segment.Label == null)
segment.Label = segment.Name;
// validate both 'class' and 'target' aren't set
if (segment.Type != null && segment.Target != null)
throw new BeanIOConfigurationException("Cannot set both 'class' and 'value'");
// set default occurrences and validate
if (segment.MinOccurs == null)
segment.MinOccurs = segment.OccursRef != null ? 0 : 1;
if (segment.MaxOccurs == null)
segment.MaxOccurs = segment.OccursRef != null ? int.MaxValue : 1;
if (segment.MaxOccurs <= 0)
throw new BeanIOConfigurationException("Maximum occurrences must be greater than 0");
if (segment.MaxOccurs < segment.MinOccurs)
throw new BeanIOConfigurationException("Maximum occurrences cannot be less than minimum occurrences");
if (segment.Key != null && segment.Collection == null)
throw new BeanIOConfigurationException("Unexpected key value when collection not set");
if (segment.Collection != null && segment.Type == null && segment.Target == null)
throw new BeanIOConfigurationException("Class or value required if collection is set");
if (Parent != null && segment.ValidateOnMarshal == null)
segment.ValidateOnMarshal = Parent.ValidateOnMarshal;
if (PropertyRoot == null || PropertyRoot != segment)
{
segment.IsBound = true;
if ((segment.MaxOccurs == null || segment.MaxOccurs > 1) && segment.Collection == null)
{
if (segment.Type != null || segment.Target != null)
throw new BeanIOConfigurationException("Collection required when maxOccurs is greater than 1 and class or value is set");
}
if (segment.ComponentType == ComponentType.Record
&& segment.IsRepeating
&& segment.Type == null
&& segment.Target == null)
{
segment.IsBound = false;
}
}
else if (segment.Collection != null)
{
throw new BeanIOConfigurationException("Collection cannot be set on unbound record or segment.");
}
}
/// <summary>
/// Finalizes a segment configuration after its children have been processed
/// </summary>
/// <param name="segment">the segment configuration to finalize</param>
protected override void FinalizeSegment(SegmentConfig segment)
{
if (segment.PropertyList.Any(x => x.IsIdentifier))
segment.IsIdentifier = true;
}
/// <summary>
/// Processes a field configuration
/// </summary>
/// <param name="field">the field configuration to process</param>
protected override void HandleField(FieldConfig field)
{
// ignore fields that belong to ignored records
if (_recordIgnored)
field.IsBound = false;
if (field.Name == null)
throw new BeanIOConfigurationException("name is required");
if (field.Label == null)
field.Label = field.Name;
// set and validate occurrences
if (field.MinOccurs == null)
{
field.MinOccurs =
field.OccursRef != null
? 0
: _settings.GetInt($"{Settings.DEFAULT_FIELD_MIN_OCCURS}.{_stream.Format}", 0);
}
if (field.MaxOccurs == null)
field.MaxOccurs = field.OccursRef != null ? int.MaxValue : Math.Max(field.MinOccurs.Value, 1);
if (field.MaxOccurs != null)
{
if (field.MaxOccurs <= 0)
throw new BeanIOConfigurationException("Maximum occurrences must be greater than 0");
if (field.MaxOccurs < field.MinOccurs)
throw new BeanIOConfigurationException("Maximum occurrences cannot be less than minimum occurrences");
}
// set and validate min and max length
if (field.MinLength == null)
field.MinLength = 0;
if (field.MaxLength == null)
field.MaxLength = int.MaxValue;
if (field.MaxLength < field.MinLength)
throw new BeanIOConfigurationException("maxLength must be greater than or equal to minLength");
if (field.Literal != null)
{
var literalLength = field.Literal.Length;
if (literalLength < field.MinLength)
throw new BeanIOConfigurationException("literal text length is less than minLength");
if (field.MaxLength != null && literalLength > field.MaxLength)
throw new BeanIOConfigurationException("literal text length is greater than maxLength");
}
if (field.IsRepeating && field.IsIdentifier)
throw new BeanIOConfigurationException("repeating fields cannot be used as identifiers");
if (field.IsBound && field.IsRepeating && field.Collection == null)
throw new BeanIOConfigurationException("collection not set");
if (Parent != null && field.ValidateOnMarshal == null)
field.ValidateOnMarshal = Parent.ValidateOnMarshal;
if (field.IsIdentifier)
ValidateRecordIdentifyingCriteria(field);
}
/// <summary>
/// Processes a constant configuration
/// </summary>
/// <param name="constant">the constant configuration to process</param>
protected override void HandleConstant(ConstantConfig constant)
{
constant.IsBound = true;
if (constant.Name == null)
throw new BeanIOConfigurationException("Missing property name");
}
/// <summary>
/// This method validates a record identifying field has a literal or regular expression
/// configured for identifying a record.
/// </summary>
/// <param name="field">the record identifying field configuration to validate</param>
protected virtual void ValidateRecordIdentifyingCriteria(FieldConfig field)
{
// validate regex or literal is configured for record identifying fields
if (field.Literal == null && field.RegEx == null)
throw new BeanIOConfigurationException("Literal or regex pattern required for identifying fields");
}
private class ComponentConfigComparer : IComparer<ComponentConfig>
{
public int Compare(ComponentConfig x, ComponentConfig y)
{
var p1 = GetPosition(x);
var p2 = GetPosition(y);
if (p1 == null)
return p2 == null ? 0 : 1;
if (p2 == null)
return -1;
return p1.Value.CompareTo(p2.Value);
}
private int? GetPosition(ComponentConfig config)
{
int? result = null;
switch (config.ComponentType)
{
case ComponentType.Field:
case ComponentType.Segment:
result = ((PropertyConfig)config).Position;
break;
case ComponentType.Record:
result = ((RecordConfig)config).Order;
break;
case ComponentType.Group:
result = ((GroupConfig)config).Order;
break;
}
if (result != null && result < 0)
result = int.MaxValue + result;
return result;
}
}
}
}
| |
//
// LiteTestCase.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Router;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Sharpen;
namespace Couchbase.Lite
{
public abstract class LiteTestCase : TestCase
{
public const string Tag = "LiteTestCase";
private static bool initializedUrlHandler = false;
protected internal ObjectWriter mapper = new ObjectWriter();
protected internal Manager manager = null;
protected internal Database database = null;
protected internal string DefaultTestDb = "cblite-test";
/// <exception cref="System.Exception"></exception>
protected override void SetUp()
{
Log.V(Tag, "setUp");
base.SetUp();
//for some reason a traditional static initializer causes junit to die
if (!initializedUrlHandler)
{
URLStreamHandlerFactory.RegisterSelfIgnoreError();
initializedUrlHandler = true;
}
LoadCustomProperties();
StartCBLite();
StartDatabase();
}
protected internal virtual InputStream GetAsset(string name)
{
return this.GetType().GetResourceAsStream("/assets/" + name);
}
protected internal virtual FilePath GetRootDirectory()
{
string rootDirectoryPath = Runtime.GetProperty("user.dir");
FilePath rootDirectory = new FilePath(rootDirectoryPath);
rootDirectory = new FilePath(rootDirectory, "data/data/com.couchbase.cblite.test/files"
);
return rootDirectory;
}
protected internal virtual string GetServerPath()
{
string filesDir = GetRootDirectory().GetAbsolutePath();
return filesDir;
}
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void StartCBLite()
{
string serverPath = GetServerPath();
FilePath serverPathFile = new FilePath(serverPath);
FileDirUtils.DeleteRecursive(serverPathFile);
serverPathFile.Mkdir();
manager = new Manager(new FilePath(GetRootDirectory(), "test"), Manager.DefaultOptions
);
}
protected internal virtual void StopCBLite()
{
if (manager != null)
{
manager.Close();
}
}
protected internal virtual Database StartDatabase()
{
database = EnsureEmptyDatabase(DefaultTestDb);
return database;
}
protected internal virtual void StopDatabse()
{
if (database != null)
{
database.Close();
}
}
protected internal virtual Database EnsureEmptyDatabase(string dbName)
{
Database db = manager.GetExistingDatabase(dbName);
if (db != null)
{
bool status = db.Delete();
NUnit.Framework.Assert.IsTrue(status);
}
db = manager.GetDatabase(dbName);
return db;
}
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void LoadCustomProperties()
{
Properties systemProperties = Runtime.GetProperties();
InputStream mainProperties = GetAsset("test.properties");
if (mainProperties != null)
{
systemProperties.Load(mainProperties);
}
try
{
InputStream localProperties = GetAsset("local-test.properties");
if (localProperties != null)
{
systemProperties.Load(localProperties);
}
}
catch (IOException)
{
Log.W(Tag, "Error trying to read from local-test.properties, does this file exist?"
);
}
}
protected internal virtual string GetReplicationProtocol()
{
return Runtime.GetProperty("replicationProtocol");
}
protected internal virtual string GetReplicationServer()
{
return Runtime.GetProperty("replicationServer");
}
protected internal virtual int GetReplicationPort()
{
return System.Convert.ToInt32(Runtime.GetProperty("replicationPort"));
}
protected internal virtual string GetReplicationAdminUser()
{
return Runtime.GetProperty("replicationAdminUser");
}
protected internal virtual string GetReplicationAdminPassword()
{
return Runtime.GetProperty("replicationAdminPassword");
}
protected internal virtual string GetReplicationDatabase()
{
return Runtime.GetProperty("replicationDatabase");
}
protected internal virtual Uri GetReplicationURL()
{
try
{
if (GetReplicationAdminUser() != null && GetReplicationAdminUser().Trim().Length
> 0)
{
return new Uri(string.Format("%s://%s:%s@%s:%d/%s", GetReplicationProtocol(), GetReplicationAdminUser
(), GetReplicationAdminPassword(), GetReplicationServer(), GetReplicationPort(),
GetReplicationDatabase()));
}
else
{
return new Uri(string.Format("%s://%s:%d/%s", GetReplicationProtocol(), GetReplicationServer
(), GetReplicationPort(), GetReplicationDatabase()));
}
}
catch (UriFormatException e)
{
throw new ArgumentException(e);
}
}
/// <exception cref="System.UriFormatException"></exception>
protected internal virtual Uri GetReplicationURLWithoutCredentials()
{
return new Uri(string.Format("%s://%s:%d/%s", GetReplicationProtocol(), GetReplicationServer
(), GetReplicationPort(), GetReplicationDatabase()));
}
/// <exception cref="System.Exception"></exception>
protected override void TearDown()
{
Log.V(Tag, "tearDown");
base.TearDown();
StopDatabse();
StopCBLite();
}
protected internal virtual IDictionary<string, object> UserProperties(IDictionary
<string, object> properties)
{
IDictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in properties.Keys)
{
if (!key.StartsWith("_"))
{
result.Put(key, properties.Get(key));
}
}
return result;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetReplicationAuthParsedJson()
{
string authJson = "{\n" + " \"facebook\" : {\n" + " \"email\" : \"jchris@couchbase.com\"\n"
+ " }\n" + " }\n";
ObjectWriter mapper = new ObjectWriter();
IDictionary<string, object> authProperties = mapper.ReadValue(authJson, new _TypeReference_192
());
return authProperties;
}
private sealed class _TypeReference_192 : TypeReference<Dictionary<string, object
>>
{
public _TypeReference_192()
{
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetPushReplicationParsedJson()
{
IDictionary<string, object> authProperties = GetReplicationAuthParsedJson();
IDictionary<string, object> targetProperties = new Dictionary<string, object>();
targetProperties.Put("url", GetReplicationURL().ToExternalForm());
targetProperties.Put("auth", authProperties);
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("source", DefaultTestDb);
properties.Put("target", targetProperties);
return properties;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetPullReplicationParsedJson()
{
IDictionary<string, object> authProperties = GetReplicationAuthParsedJson();
IDictionary<string, object> sourceProperties = new Dictionary<string, object>();
sourceProperties.Put("url", GetReplicationURL().ToExternalForm());
sourceProperties.Put("auth", authProperties);
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("source", sourceProperties);
properties.Put("target", DefaultTestDb);
return properties;
}
protected internal virtual URLConnection SendRequest(string method, string path,
IDictionary<string, string> headers, object bodyObj)
{
try
{
Uri url = new Uri("cblite://" + path);
URLConnection conn = (URLConnection)url.OpenConnection();
conn.SetDoOutput(true);
conn.SetRequestMethod(method);
if (headers != null)
{
foreach (string header in headers.Keys)
{
conn.SetRequestProperty(header, headers.Get(header));
}
}
IDictionary<string, IList<string>> allProperties = conn.GetRequestProperties();
if (bodyObj != null)
{
conn.SetDoInput(true);
ByteArrayInputStream bais = new ByteArrayInputStream(mapper.WriteValueAsBytes(bodyObj
));
conn.SetRequestInputStream(bais);
}
Couchbase.Lite.Router.Router router = new Couchbase.Lite.Router.Router(manager, conn
);
router.Start();
return conn;
}
catch (UriFormatException)
{
Fail();
}
catch (IOException)
{
Fail();
}
return null;
}
protected internal virtual object ParseJSONResponse(URLConnection conn)
{
object result = null;
Body responseBody = conn.GetResponseBody();
if (responseBody != null)
{
byte[] json = responseBody.GetJson();
string jsonString = null;
if (json != null)
{
jsonString = Sharpen.Runtime.GetStringForBytes(json);
try
{
result = mapper.ReadValue<object>(jsonString);
}
catch (Exception)
{
Fail();
}
}
}
return result;
}
protected internal virtual object SendBody(string method, string path, object bodyObj
, int expectedStatus, object expectedResult)
{
URLConnection conn = SendRequest(method, path, null, bodyObj);
object result = ParseJSONResponse(conn);
Log.V(Tag, string.Format("%s %s --> %d", method, path, conn.GetResponseCode()));
NUnit.Framework.Assert.AreEqual(expectedStatus, conn.GetResponseCode());
if (expectedResult != null)
{
NUnit.Framework.Assert.AreEqual(expectedResult, result);
}
return result;
}
protected internal virtual object Send(string method, string path, int expectedStatus
, object expectedResult)
{
return SendBody(method, path, null, expectedStatus, expectedResult);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Msagl.Core;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.GraphAlgorithms;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.Incremental;
using Microsoft.Msagl.Routing;
using Node = Microsoft.Msagl.Core.Layout.Node;
namespace Microsoft.Msagl.Layout.Incremental {
/// <summary>
/// Fast incremental layout is a force directed layout strategy with approximate computation of long-range node-node repulsive forces to achieve O(n log n) running time per iteration.
/// It can be invoked on an existing layout (for example, as computed by MDS) to beautify it. See docs for CalculateLayout method (below) to see how to use it incrementally.
///
/// Note that in debug mode lots of numerical checking is applied, which slows things down considerably. So, run in Release mode unless you're actually debugging!
/// </summary>
public class FastIncrementalLayout : AlgorithmBase {
readonly BasicGraph<FiEdge> basicGraph;
readonly List<FiNode[]> components;
internal readonly Dictionary<int, List<IConstraint>> constraints = new Dictionary<int, List<IConstraint>>();
readonly List<FiEdge> edges = new List<FiEdge>();
/// <summary>
/// Returns the derivative of the cost function calculated in the most recent iteration.
/// It's a volatile float so that we can potentially access it from other threads safely,
/// for example during test.
/// </summary>
internal volatile float energy;
readonly GeometryGraph graph;
readonly AxisSolver horizontalSolver;
/// <summary>
/// Construct a graph by adding nodes and edges to these lists
/// </summary>
readonly FiNode[] nodes;
int progress;
readonly FastIncrementalLayoutSettings settings;
double stepSize;
readonly AxisSolver verticalSolver;
readonly Func<Cluster, LayoutAlgorithmSettings> clusterSettings;
List<Edge> clusterEdges = new List<Edge>();
/// <summary>
/// Create the graph data structures.
/// </summary>
/// <param name="geometryGraph"></param>
/// <param name="settings">The settings for the algorithm.</param>
/// <param name="initialConstraintLevel">initialize at this constraint level</param>
/// <param name="clusterSettings">settings by cluster</param>
internal FastIncrementalLayout(GeometryGraph geometryGraph, FastIncrementalLayoutSettings settings,
int initialConstraintLevel,
Func<Cluster, LayoutAlgorithmSettings> clusterSettings) {
graph = geometryGraph;
this.settings = settings;
this.clusterSettings = clusterSettings;
int i = 0;
ICollection<Node> allNodes = graph.Nodes;
nodes = new FiNode[allNodes.Count];
foreach (Node v in allNodes) {
v.AlgorithmData = nodes[i] = new FiNode(i, v);
i++;
}
clusterEdges.Clear();
edges.Clear();
foreach (Edge e in graph.Edges) {
if (e.Source is Cluster || e.Target is Cluster)
clusterEdges.Add(e);
else
edges.Add(new FiEdge(e));
foreach (var l in e.Labels)
l.InnerPoints = l.OuterPoints = null;
}
SetLockNodeWeights();
components = new List<FiNode[]>();
if (!settings.InterComponentForces) {
basicGraph = new BasicGraph<FiEdge>(edges, nodes.Length);
foreach (var componentNodes in ConnectedComponentCalculator<FiEdge>.GetComponents(basicGraph)) {
var vs = new FiNode[componentNodes.Count()];
int vi = 0;
foreach (int v in componentNodes) {
vs[vi++] = nodes[v];
}
components.Add(vs);
}
}
else // just one big component (regardless of actual edges)
components.Add(nodes);
horizontalSolver = new AxisSolver(true, nodes, new[] {geometryGraph.RootCluster}, settings.AvoidOverlaps,
settings.MinConstraintLevel, clusterSettings) {
OverlapRemovalParameters =
new OverlapRemovalParameters {
AllowDeferToVertical = true,
// use "ProportionalOverlap" mode only when iterative apply forces layout is being used.
// it is not necessary otherwise.
ConsiderProportionalOverlap = settings.ApplyForces
}
};
verticalSolver = new AxisSolver(false, nodes, new[] {geometryGraph.RootCluster}, settings.AvoidOverlaps,
settings.MinConstraintLevel, clusterSettings);
SetupConstraints();
geometryGraph.RootCluster.ComputeWeight();
foreach (
Cluster c in geometryGraph.RootCluster.AllClustersDepthFirst().Where(c => c.RectangularBoundary == null)
) {
c.RectangularBoundary = new RectangularClusterBoundary();
}
CurrentConstraintLevel = initialConstraintLevel;
}
void SetupConstraints() {
AddConstraintLevel(0);
if (settings.AvoidOverlaps) {
AddConstraintLevel(2);
}
foreach (IConstraint c in settings.StructuralConstraints) {
AddConstraintLevel(c.Level);
if (c is VerticalSeparationConstraint) {
verticalSolver.AddStructuralConstraint(c);
}
else if (c is HorizontalSeparationConstraint) {
horizontalSolver.AddStructuralConstraint(c);
}
else {
AddConstraint(c);
}
}
EdgeConstraintGenerator.GenerateEdgeConstraints(graph.Edges, settings.IdealEdgeLength, horizontalSolver,
verticalSolver);
}
int currentConstraintLevel;
/// <summary>
/// Controls which constraints are applied in CalculateLayout. Setter enforces feasibility at that level.
/// </summary>
internal int CurrentConstraintLevel {
get { return currentConstraintLevel; }
set {
currentConstraintLevel = value;
horizontalSolver.ConstraintLevel = value;
verticalSolver.ConstraintLevel = value;
Feasibility.Enforce(settings, value, nodes, horizontalSolver.structuralConstraints,
verticalSolver.structuralConstraints, new[] {graph.RootCluster}, clusterSettings);
settings.Unconverge();
}
}
/// <summary>
/// Add constraint to constraints lists. Warning, no check that dictionary alread holds a list for the level.
/// Make sure you call AddConstraintLevel first (perf).
/// </summary>
/// <param name="c"></param>
void AddConstraint(IConstraint c) {
if (!constraints.ContainsKey(c.Level)) {
constraints[c.Level] = new List<IConstraint>();
}
constraints[c.Level].Add(c);
}
/// <summary>
/// Check for constraint level in dictionary, if it doesn't exist add the list at that level.
/// </summary>
/// <param name="level"></param>
void AddConstraintLevel(int level) {
if (!constraints.ContainsKey(level)) {
constraints[level] = new List<IConstraint>();
}
}
internal void SetLockNodeWeights() {
foreach (LockPosition l in settings.locks) {
l.SetLockNodeWeight();
}
}
internal void ResetNodePositions() {
foreach (FiNode v in nodes) {
v.ResetBounds();
}
foreach (var e in edges) {
foreach (var l in e.mEdge.Labels) {
l.InnerPoints = l.OuterPoints = null;
}
}
}
void AddRepulsiveForce(FiNode v, Point repulsion) {
// scale repulsion
v.force = 10.0*settings.RepulsiveForceConstant*repulsion;
}
void AddLogSpringForces(FiEdge e, Point duv, double d) {
double l = duv.Length,
f = 0.0007*settings.AttractiveForceConstant*l*Math.Log((l + 0.1)/(d + 0.1));
e.source.force += f*duv;
e.target.force -= f*duv;
}
void AddSquaredSpringForces(FiEdge e, Point duv, double d) {
double l = duv.Length,
d2 = d*d + 0.1,
f = settings.AttractiveForceConstant*(l - d)/d2;
e.source.force += f*duv;
e.target.force -= f*duv;
}
static void CalculateMultiPorts(FiEdge e) {
var sourceLocation = e.source.Center;
var targetLocation = e.target.Center;
var sourceMultiPort = e.mEdge.SourcePort as MultiLocationFloatingPort;
if (sourceMultiPort != null) {
sourceMultiPort.SetClosestLocation(targetLocation);
}
var targetMultiPort = e.mEdge.TargetPort as MultiLocationFloatingPort;
if (targetMultiPort != null) {
targetMultiPort.SetClosestLocation(sourceLocation);
}
}
void AddSpringForces(FiEdge e) {
Point duv;
if (settings.RespectEdgePorts) {
var sourceLocation = e.source.Center;
var targetLocation = e.target.Center;
var sourceFloatingPort = e.mEdge.SourcePort as FloatingPort;
if (sourceFloatingPort != null) {
sourceLocation = sourceFloatingPort.Location;
}
var targetFloatingPort = e.mEdge.TargetPort as FloatingPort;
if (targetFloatingPort != null) {
targetLocation = targetFloatingPort.Location;
}
duv = sourceLocation - targetLocation;
}
else {
duv = e.vector();
}
if (settings.LogScaleEdgeForces) {
AddLogSpringForces(e, duv, e.mEdge.Length);
}
else {
AddSquaredSpringForces(e, duv, e.mEdge.Length);
}
}
static void AddGravityForce(Point origin, double gravity, FiNode v) {
// compute and add gravity
v.force -= 0.0001*gravity*(origin - v.Center);
}
void ComputeRepulsiveForces(FiNode[] vs) {
int n = vs.Length;
if (n > 16 && settings.ApproximateRepulsion) {
var ps = new KDTree.Particle[vs.Length];
// before calculating forces we perturb each center by a small vector in a unique
// but deterministic direction (by walking around a circle in n steps) - this allows
// the KD-tree to decompose even when some nodes are at exactly the same position
double angle = 0, angleDelta = 2.0*Math.PI/n;
for (int i = 0; i < n; ++i) {
ps[i] = new KDTree.Particle(vs[i].Center + 1e-5*new Point(Math.Cos(angle), Math.Sin(angle)));
angle += angleDelta;
}
var kdTree = new KDTree(ps, 8);
kdTree.ComputeForces(5);
for (int i = 0; i < vs.Length; ++i) {
AddRepulsiveForce(vs[i], ps[i].force);
}
}
else {
foreach (FiNode u in vs) {
var fu = new Point();
foreach (FiNode v in vs) {
if (u != v) {
fu += MultipoleCoefficients.Force(u.Center, v.Center);
}
}
AddRepulsiveForce(u, fu);
}
}
}
void AddClusterForces(Cluster root) {
if (root == null)
return;
// SetBarycenter is recursive.
root.SetBarycenter();
// The cluster edges draw the barycenters of the connected clusters together
foreach (var e in clusterEdges) {
// foreach cluster keep a force vector. Replace ForEachNode calls below with a simple
// addition to this force vector. Traverse top down, tallying up force vectors of children
// to be the sum of their parents.
var c1 = e.Source as Cluster;
var c2 = e.Target as Cluster;
var n1 = e.Source.AlgorithmData as FiNode;
var n2 = e.Target.AlgorithmData as FiNode;
Point center1 = c1 != null ? c1.Barycenter : n1.Center;
Point center2 = c2 != null ? c2.Barycenter : n2.Center;
Point duv = center1 - center2;
double l = duv.Length,
f = 1e-8*settings.AttractiveInterClusterForceConstant*l*Math.Log(l + 0.1);
if (c1 != null) {
c1.ForEachNode(v => {
var fv = v.AlgorithmData as FiNode;
fv.force += f*duv;
});
}
else {
n1.force += f*duv;
}
if (c2 != null) {
c2.ForEachNode(v => {
var fv = v.AlgorithmData as FiNode;
fv.force -= f*duv;
});
}
else {
n2.force -= f*duv;
}
}
foreach (Cluster c in root.AllClustersDepthFirst())
if (c != root) {
c.ForEachNode(v => AddGravityForce(c.Barycenter, settings.ClusterGravity, (FiNode) v.AlgorithmData));
}
}
/// <summary>
/// Aggregate all the forces affecting each node
/// </summary>
void ComputeForces() {
if (components != null) {
components.ForEach(ComputeRepulsiveForces);
}
else {
ComputeRepulsiveForces(nodes);
}
edges.ForEach(AddSpringForces);
foreach (var c in components) {
var origin = new Point();
for (int i = 0; i < c.Length; ++i) {
origin += c[i].Center;
}
origin /= (double) c.Length;
double maxForce = double.NegativeInfinity;
for (int i = 0; i < c.Length; ++i) {
FiNode v = c[i];
AddGravityForce(origin, settings.GravityConstant, v);
if (v.force.Length > maxForce) {
maxForce = v.force.Length;
}
}
if (maxForce > 100.0) {
for (int i = 0; i < c.Length; ++i) {
c[i].force *= 100.0/maxForce;
}
}
}
// This is the only place where ComputeForces (and hence verletIntegration) considers clusters.
// It's just adding a "gravity" force on nodes inside each cluster towards the barycenter of the cluster.
AddClusterForces(graph.RootCluster);
}
void SatisfyConstraints() {
for (int i = 0; i < settings.ProjectionIterations; ++i) {
foreach (var level in constraints.Keys) {
if (level > CurrentConstraintLevel) {
break;
}
foreach (var c in constraints[level]) {
c.Project();
// c.Project operates only on MSAGL nodes, so need to update the local FiNode.Centers
foreach (var v in c.Nodes) {
((FiNode) v.AlgorithmData).Center = v.Center;
}
}
}
foreach (LockPosition l in settings.locks) {
l.Project();
// again, project operates only on MSAGL nodes, we'll also update FiNode.PreviousPosition since we don't want any inertia in this case
foreach (var v in l.Nodes) {
FiNode fiNode = v.AlgorithmData as FiNode;
// the locks should have had their AlgorithmData updated, but if (for some reason)
// the locks list is out of date we don't want to null ref here.
if (fiNode != null && v.AlgorithmData != null) {
fiNode.ResetBounds();
}
}
}
}
}
/// <summary>
/// Checks if solvers need to be applied, i.e. if there are user constraints or
/// generated constraints (such as non-overlap) that need satisfying
/// </summary>
/// <returns></returns>
bool NeedSolve() {
return horizontalSolver.NeedSolve || verticalSolver.NeedSolve;
}
/// <summary>
/// Force directed layout is basically an iterative approach to solving a bunch of differential equations.
/// Different integration schemes are possible for applying the forces iteratively. Euler is the simplest:
/// v_(i+1) = v_i + a dt
/// x_(i+1) = x_i + v_(i+1) dt
///
/// Verlet is much more stable (and not really much more complicated):
/// x_(i+1) = x_i + (x_i - x_(i-1)) + a dt dt
/// </summary>
double VerletIntegration() {
// The following sets the Centers of all nodes to a (not necessarily feasible) configuration that reduces the cost (forces)
float energy0 = energy;
energy = (float) ComputeDescentDirection(1.0);
UpdateStepSize(energy0);
SolveSeparationConstraints();
double displacementSquared = 0;
for (int i = 0; i < nodes.Length; ++i) {
FiNode v = nodes[i];
displacementSquared += (v.Center - v.previousCenter).LengthSquared;
}
return displacementSquared;
}
void SolveSeparationConstraints() {
if (this.NeedSolve()) {
// Increasing the padding effectively increases the size of the rectangle, so it will lead to more overlaps,
// and therefore tighter packing once the overlap is removed and therefore more apparent "columnarity".
// We don't want to drastically change the shape of the rectangles, just increase them ever so slightly so that
// there is a bit more space in the horizontal than vertical direction, thus reducing the likelihood that
// the vertical constraint generation will detect spurious overlaps, which should allow the nodes to slide
// smoothly around each other. ConGen padding args are: First pad is in direction of the constraints being
// generated, second pad is in the perpendicular direction.
double dblVpad = settings.NodeSeparation;
double dblHpad = dblVpad + Feasibility.Pad;
double dblCVpad = settings.ClusterMargin;
double dblCHpad = dblCVpad + Feasibility.Pad;
// The centers are our desired positions, but we need to find a feasible configuration
foreach (FiNode v in nodes) {
v.desiredPosition = v.Center;
}
// Set up horizontal non-overlap constraints based on the (feasible) starting configuration
horizontalSolver.Initialize(dblHpad, dblVpad, dblCHpad, dblCVpad, v => v.previousCenter);
horizontalSolver.SetDesiredPositions();
horizontalSolver.Solve();
// generate y constraints
verticalSolver.Initialize(dblHpad, dblVpad, dblCHpad, dblCVpad, v => v.Center);
verticalSolver.SetDesiredPositions();
verticalSolver.Solve();
// If we have multiple locks (hence multiple high-weight nodes), there can still be some
// movement of the locked variables - so update all lock positions.
foreach (LockPosition l in settings.locks.Where(l => !l.Sticky)) {
l.Bounds = l.node.BoundingBox;
}
}
}
double ComputeDescentDirection(double alpha) {
ResetForceVectors();
// velocity is the distance travelled last time step
if (settings.ApplyForces) {
ComputeForces();
}
//System.Console.WriteLine("Iteration = {0}, Energy = {1}, StepSize = {2}", settings.maxIterations - settings.RemainingIterations, energy, stepSize);
double lEnergy = 0;
foreach (FiNode v in nodes) {
lEnergy += v.force.LengthSquared;
Point dx = v.Center - v.previousCenter;
v.previousCenter = v.Center;
dx *= settings.Friction;
Point a = -stepSize*alpha*v.force;
Debug.Assert(!double.IsNaN(a.X), "!double.IsNaN(a.X)");
Debug.Assert(!double.IsNaN(a.Y), "!double.IsNaN(a.Y)");
Debug.Assert(!double.IsInfinity(a.X), "!double.IsInfinity(a.X)");
Debug.Assert(!double.IsInfinity(a.Y), "!double.IsInfinity(a.Y)");
dx += a;
dx /= v.stayWeight;
v.Center += dx;
}
//System.Console.WriteLine("Iteration = {0}, Energy = {1}, StepSize = {2}", settings.maxIterations - settings.RemainingIterations, energy, stepSize);
//UpdateStepSize(energy, energy0);
SatisfyConstraints();
return lEnergy;
}
// end VerletIntegration()
void ResetForceVectors() {
foreach (var v in nodes) {
v.force = new Point();
}
}
/// <summary>
/// Adapt StepSize based on change in energy.
/// Five sequential improvements in energy mean we increase the stepsize.
/// Any increase in energy means we reduce the stepsize.
/// </summary>
/// <param name="energy0"></param>
void UpdateStepSize(float energy0) {
if (energy < energy0) {
if (++progress >= 3) {
progress = 0;
stepSize /= settings.Decay;
}
}
else {
progress = 0;
stepSize *= settings.Decay;
}
}
double RungeKuttaIntegration() {
var y0 = new Point[nodes.Length];
var k1 = new Point[nodes.Length];
var k2 = new Point[nodes.Length];
var k3 = new Point[nodes.Length];
var k4 = new Point[nodes.Length];
float energy0 = energy;
SatisfyConstraints();
for (int i = 0; i < nodes.Length; ++i) {
y0[i] = nodes[i].previousCenter = nodes[i].Center;
}
const double alpha = 3;
ComputeDescentDirection(alpha);
for (int i = 0; i < nodes.Length; ++i) {
k1[i] = nodes[i].Center - nodes[i].previousCenter;
nodes[i].Center = y0[i] + 0.5*k1[i];
}
ComputeDescentDirection(alpha);
for (int i = 0; i < nodes.Length; ++i) {
k2[i] = nodes[i].Center - nodes[i].previousCenter;
nodes[i].previousCenter = y0[i];
nodes[i].Center = y0[i] + 0.5*k2[i];
}
ComputeDescentDirection(alpha);
for (int i = 0; i < nodes.Length; ++i) {
k3[i] = nodes[i].Center - nodes[i].previousCenter;
nodes[i].previousCenter = y0[i];
nodes[i].Center = y0[i] + k3[i];
}
energy = (float) ComputeDescentDirection(alpha);
for (int i = 0; i < nodes.Length; ++i) {
k4[i] = nodes[i].Center - nodes[i].previousCenter;
nodes[i].previousCenter = y0[i];
Point dx = (k1[i] + 2.0*k2[i] + 2.0*k3[i] + k4[i])/6.0;
nodes[i].Center = y0[i] + dx;
}
UpdateStepSize(energy0);
//System.Console.WriteLine("energy0={0}, energy={1}, progress={2}, stepsize={3}", energy0, energy, progress, stepSize);
SolveSeparationConstraints();
return this.nodes.Sum(v => (v.Center - v.previousCenter).LengthSquared);
}
/// <summary>
/// Apply a small number of iterations of the layout.
/// The idea of incremental layout is that settings.minorIterations should be a small number (e.g. 3) and
/// CalculateLayout should be invoked in a loop, e.g.:
///
/// while(settings.RemainingIterations > 0) {
/// fastIncrementalLayout.CalculateLayout();
/// InvokeYourProcedureToRedrawTheGraphOrHandleInteractionEtc();
/// }
///
/// In the verletIntegration step above, the RemainingIterations is used to control damping.
/// </summary>
protected override void RunInternal() {
settings.Converged = false;
settings.EdgeRoutesUpToDate = false;
if (settings.Iterations++ == 0) {
stepSize = settings.InitialStepSize;
energy = float.MaxValue;
progress = 0;
}
this.StartListenToLocalProgress(settings.MinorIterations);
for (int i = 0; i < settings.MinorIterations; ++i) {
if (settings.RespectEdgePorts) {
edges.ForEach(CalculateMultiPorts);
}
double d2 = settings.RungeKuttaIntegration ? RungeKuttaIntegration() : VerletIntegration();
if (d2 < settings.DisplacementThreshold || settings.Iterations > settings.MaxIterations) {
settings.Converged = true;
this.ProgressComplete();
break;
}
ProgressStep();
}
FinalizeClusterBoundaries();
}
/// <summary>
/// Simply does a depth first traversal of the cluster hierarchies fitting Rectangles to the contents of the cluster
/// or updating the cluster BoundingBox to the already calculated RectangularBoundary
/// </summary>
void FinalizeClusterBoundaries() {
foreach (var c in graph.RootCluster.AllClustersDepthFirst()) {
if (c == graph.RootCluster) continue;
if (!this.NeedSolve() && settings.UpdateClusterBoundariesFromChildren) {
// if we are not using the solver (e.g. when constraintLevel == 0) then we need to get the cluster bounds manually
c.CalculateBoundsFromChildren(this.settings.ClusterMargin);
}
else {
c.BoundingBox = c.RectangularBoundary.Rect;
}
c.RaiseLayoutDoneEvent();
}
}
}
}
| |
//===============================================================================
// Code Associate Data Access Block for .NET
// DataAccessCore.cs
//
//===============================================================================
// Copyright (C) 2002-2014 Ravin Enterprises Ltd.
// All rights reserved.
// THIS CODE AND INFORMATION IS 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.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Text;
using CA.Blocks.DataAccess.Paging;
namespace CA.Blocks.DataAccess
{
/// <summary>
/// Provides a SQL server implementation for DataAccessCore
/// </summary>
/// <remarks>
/// <p>source code:</p>
/// <code outlining="true" source="..\CANC\Blocks\DataAccess\SqlServerDataAccess.cs" lang="cs"/>
/// </remarks>
public class SqlServerDataAccess : DataAccessCore
{
public const string FILTER_REPLACE_STRING = "/*##FILTER##*/";
//public const string JOIN_REPLACE_STRING = "/*##JOIN##*/";
public SqlServerDataAccess(string connectionString) : base(connectionString)
{
}
protected virtual string GetConnectionContext()
{
return null;
}
public void SetCommandContext(SqlConnection sqlConnection)
{
string context = GetConnectionContext();
if (!String.IsNullOrWhiteSpace(context))
{
var cmd = CreateTextCommand("SET CONTEXT_INFO @AppContext");
cmd.Parameters.Add(Encoding.ASCII.GetBytes(context).ToSqlParameter("@AppContext"));
cmd.Connection = sqlConnection;
cmd.ExecuteNonQuery();
}
}
protected override bool PrepCommand(IDbCommand cmd)
{
SqlConnection sqlConnection = new SqlConnection(ConnectionString);
sqlConnection.Open();
SetCommandContext(sqlConnection);
cmd.Connection = sqlConnection;
return true;
}
protected override DbDataAdapter GetDataAdapter(IDbCommand cmd)
{
return (new SqlDataAdapter((SqlCommand)cmd));
}
#region StoredProcedureHelpers
protected SqlCommand CreateBlankStoredProcedureCommand(string strStoredProcedureName, bool bolIncludeReturnValue = false)
{
SqlCommand sqlcmd = new SqlCommand
{
CommandText = strStoredProcedureName,
CommandType = CommandType.StoredProcedure
};
if (bolIncludeReturnValue)
{
SqlParameter sqlparam = sqlcmd.CreateParameter();
sqlparam.ParameterName = "Return";
sqlparam.SqlDbType = SqlDbType.Int;
sqlparam.Direction = ParameterDirection.ReturnValue;
sqlcmd.Parameters.Add(sqlparam);
}
return (sqlcmd);
}
protected int GetStoredProcedureReturnValue(SqlCommand sqlcmd)
{
int result = -1;
SqlParameter sqlparam = sqlcmd.Parameters["Return"];
if (sqlparam != null)
{
if (sqlparam.Value != null)
result = (int) sqlparam.Value;
}
return result;
}
#endregion StoredProcedureHelpers
#region TextCommandType Helpers
protected SqlCommand CreateTextCommand(string sql)
{
SqlCommand sqlcmd = new SqlCommand
{
CommandText = sql,
CommandType = CommandType.Text
};
return (sqlcmd);
}
protected SqlCommand CreateTextCommand(string sqlTemplate, string mainFilter)
{
string sql = sqlTemplate.Replace(FILTER_REPLACE_STRING, mainFilter);
return CreateTextCommand(sql);
}
/* Bad idea taking it out before it grows into a wild thing.
protected SqlCommand CreateTextCommand(string sqlTemplate, string mainFilter, string mainJoin)
{
string sql = sqlTemplate.Replace(JOIN_REPLACE_STRING, mainJoin);
return CreateTextCommand(sql,mainFilter);
}*/
protected SqlCommand CreateTableSelectCommand(string tableName, string filter)
{
return CreateTextCommand(string.Format("SELECT * FROM {0} {1}", tableName, filter));
}
protected SqlCommand CreateTableSelectCommand(string tableName, string filter, string orderBy)
{
return CreateTextCommand(string.Format("SELECT * FROM {0} {1} Order By {2}", tableName, filter, orderBy));
}
#endregion StoredProcedureHelpers
#region ParemeterHelpers
protected SqlParameter AddInputParamCommand(SqlCommand cmd, string strParameterName, object objParameterValue, DbType odbType, int maxParamSize)
{
SqlParameter sqlparam = new SqlParameter(strParameterName, odbType);
sqlparam.Direction = ParameterDirection.Input;
if (maxParamSize > 0) sqlparam.Size = maxParamSize;
if ((objParameterValue == null || objParameterValue == DBNull.Value))
{
sqlparam.Value = DBNull.Value;
//Added the following as sometimes the type is changed to int32
sqlparam.DbType = odbType;
}
else
sqlparam.Value = objParameterValue;
cmd.Parameters.Add(sqlparam);
return (sqlparam);
}
protected SqlParameter AddInputParamCommand(SqlCommand cmd, string strParameterName, object objParameterValue, SqlDbType odbType, int maxParamSize)
{
SqlParameter sqlparam = new SqlParameter(strParameterName, odbType);
sqlparam.Direction = ParameterDirection.Input;
if (maxParamSize > 0) sqlparam.Size = maxParamSize;
if ((objParameterValue == null || objParameterValue == DBNull.Value))
{
sqlparam.Value = DBNull.Value;
//Added the following as sometimes the type is changed to int32
sqlparam.SqlDbType = odbType;
}
else
sqlparam.Value = objParameterValue;
cmd.Parameters.Add(sqlparam);
return (sqlparam);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsInt(SqlCommand cmd, string strParameterName, int? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Int, 4);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsShort(SqlCommand cmd, string strParameterName, short? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.SmallInt, 2);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsLong(SqlCommand cmd, string strParameterName, long? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.BigInt, 8);
}
//protected SqlParameter AddInputParamCommandAsDeciaml(SqlCommand cmd, string strParameterName, decimal? objParameterValue)
//{
// return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Decimal, 38);
//}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsGuid(SqlCommand cmd, string strParameterName, Guid? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.UniqueIdentifier, 16);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsByte(SqlCommand cmd, string strParameterName, byte? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.TinyInt, 1);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsBinary(SqlCommand cmd, string strParameterName, byte[] objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.VarBinary, -1);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsBit(SqlCommand cmd, string strParameterName, bool objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Bit, 1);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsString(SqlCommand cmd, string strParameterName, string objParameterValue, int maxSize)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.VarChar, maxSize);
}
// dont care about the size of the object this assumes the check as been done already else SQL will raise an error
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsString(SqlCommand cmd, string strParameterName, string objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.VarChar, -1 );
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsBool(SqlCommand cmd, string strParameterName, bool? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Bit, 1);
}
[System.Obsolete("Do Conversion to Y ? N Outside then use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsCharBool(SqlCommand cmd, string strParameterName, bool objParameterValue)
{
char DBValue = objParameterValue ? 'Y' : 'N';
return AddInputParamCommand(cmd, strParameterName, DBValue, SqlDbType.Char, 1);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsChar(SqlCommand cmd, string strParameterName, char? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Char, 1);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsDateTime(SqlCommand cmd, string strParameterName, DateTime? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.DateTime, 8);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsDateTime2(SqlCommand cmd, string strParameterName, DateTime? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.DateTime2, 8);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsSmallDateTime(SqlCommand cmd, string strParameterName, DateTime? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.SmallDateTime, 4);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsMoney(SqlCommand cmd, string strParameterName, Decimal? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Money, 0);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsDecimal(SqlCommand cmd, string strParameterName, Decimal? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Decimal, 0);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsFloat(SqlCommand cmd, string strParameterName, Double? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Float, 0);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsDouble(SqlCommand cmd, string strParameterName, Double? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Float, 0);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsTimeSpan(SqlCommand cmd, string strParameterName, TimeSpan? objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.Time, 0);
}
[System.Obsolete("Please use the ToSqlParameter Extension Method")]
protected SqlParameter AddInputParamCommandAsStringMax(SqlCommand cmd, string strParameterName, string objParameterValue)
{
return AddInputParamCommand(cmd, strParameterName, objParameterValue, SqlDbType.VarChar, int.MaxValue);
}
protected SqlParameter AddOutputParamCommand(SqlCommand cmd, string strParameterName, DbType odbType, Int32 maxParamSize)
{
SqlParameter sqlparam = new SqlParameter(strParameterName, odbType);
sqlparam.Direction = ParameterDirection.Output;
if (maxParamSize > 0)
sqlparam.Size = maxParamSize;
cmd.Parameters.Add(sqlparam);
return (sqlparam);
}
protected SqlParameter AddOutputParamCommand(SqlCommand cmd, string strParameterName, SqlDbType odbType, Int32 maxParamSize)
{
SqlParameter sqlparam = new SqlParameter(strParameterName, odbType);
sqlparam.Direction = ParameterDirection.Output;
if (maxParamSize > 0)
sqlparam.Size = maxParamSize;
cmd.Parameters.Add(sqlparam);
return (sqlparam);
}
protected SqlParameter AddAdapterInputParamCommand(SqlCommand cmd, string strParameterName, string sourceColName, DataTable sourceDataTable)
{
SqlParameter sqlparam;
if (sourceDataTable.Columns.Contains(sourceColName))
{
DataColumn dc = sourceDataTable.Columns[sourceColName];
sqlparam = new SqlParameter(strParameterName, dc.DataType);
sqlparam.Direction = ParameterDirection.Input;
sqlparam.SourceColumn = sourceColName;
sqlparam.SourceVersion = DataRowVersion.Current;
cmd.Parameters.Add(sqlparam);
}
else
{
throw new Exception(string.Format("SourceColName {0} does not exist in the SourceDataTable as such cannot be added as a parameter!", sourceColName));
}
return (sqlparam);
}
protected SqlParameter AddAdapterInputParamCommand(SqlCommand cmd, string strParameterName, DataTable sourceDataTable)
{
return
AddAdapterInputParamCommand(cmd, strParameterName, strParameterName.Replace("@", string.Empty),
sourceDataTable);
}
#endregion ParemeterHelpers
#region SQLType Helpers
/// <summary>
/// This is usefull when you dont know the sql datatype but you do know the physical type example is datatable
/// DataColumn dc = ??
/// AddInputParamCommand(cmd, dc.ColumnName, dr[dc], GetDBType(dc.DataType), dc.MaxLength);
/// </summary>
/// <param name="theType"></param>
/// <returns></returns>
protected SqlDbType GetDBType(Type theType)
{
SqlParameter p1 = new SqlParameter();
TypeConverter tc = TypeDescriptor.GetConverter(p1.DbType);
if (tc.CanConvertFrom(theType))
{
tc.ConvertFrom(theType.Name);
p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
}
else
{
//Try brute force
try
{
p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
}
catch
{
//Do Nothing
}
}
return p1.SqlDbType;
}
#endregion
#region SQL Bulk Update Methods
protected SqlDataAdapter CreateBulkInsertAdapter(string storedProcedureName, int batchSize)
{
SqlDataAdapter result = new SqlDataAdapter();
result.UpdateBatchSize = batchSize;
SqlCommand cmd = CreateBlankStoredProcedureCommand(storedProcedureName, false);
cmd.UpdatedRowSource = UpdateRowSource.None;
result.InsertCommand = cmd;
return result;
}
// gets the first col which has an expression on.
// This will need to be refactored if you have expressions based on expressions as you will need to be aware of dependency order
// if no expressions are found it will return null.
private DataColumn GetColunmWithExpression(DataTable dt)
{
DataColumn result = null;
foreach (DataColumn dcloop in dt.Columns)
{
if (!string.IsNullOrEmpty(dcloop.Expression))
{
result = dcloop;
break;
}
}
return result;
}
protected void CementExpressionsAsValues(DataTable dt)
{
DataColumn colWithExpression = GetColunmWithExpression(dt);
int excapeCounter = 0;
while (colWithExpression != null && excapeCounter < dt.Columns.Count)
{
string tempColName = colWithExpression.ColumnName + Guid.NewGuid().ToString();
dt.Columns.Add(tempColName, colWithExpression.DataType);
foreach(DataRow dr in dt.Rows)
{
dr[tempColName] = dr[colWithExpression.ColumnName];
}
dt.Columns.Remove(colWithExpression);
dt.Columns[tempColName].ColumnName = colWithExpression.ColumnName;
colWithExpression = GetColunmWithExpression(dt);
excapeCounter++;
}
}
protected void ExecuteBulkInsertAdapter(SqlDataAdapter bulkAdapter, DataTable dt)
{
try
{
PrepCommand(bulkAdapter.InsertCommand);
// possibly move this function out as it nos not really belong here
CementExpressionsAsValues(dt);
bulkAdapter.Update(dt);
}
finally
{
WrapUp(bulkAdapter.InsertCommand.Connection, true);
}
}
#endregion SQL Bulk Update Methods
#region
// With SQL 2012 we can use syntax OFFSET x ROWS FETCH NEXT y ROWS ONLY.. but this will only work with 2012. for now leave as is.
public DataTable ExecuteDataTable(SqlCommand cmd, PagingRequest page)
{
// this is sql server specific and only for direct quries
string sortOrder = page.GetOrderBy();
string sqlSelect = string.Format(" ROW_NUMBER() Over (Order By {0}) As RowNumber, ", sortOrder);
cmd.CommandText = WrapPagingQuery(cmd.CommandText, sqlSelect);
cmd.Parameters.Add((page.Skip + 1).ToSqlParameter("@PagingRowNumberFrom"));
cmd.Parameters.Add((page.Skip + page.Take).ToSqlParameter("@PagingRowNumberTo"));
return ExecuteDataTable(cmd);
}
protected string WrapPagingQuery(string sourceQuery, string orderOver)
{
sourceQuery = sourceQuery.Trim();
if (sourceQuery.StartsWith("Select", StringComparison.CurrentCultureIgnoreCase))
{
sourceQuery = "Select " + orderOver + sourceQuery.Substring(6);
string pagingWrapperSQL = @"With PagingWrapper As
(
{0}
)
Select PagingWrapper.*
from PagingWrapper
Where PagingWrapper.RowNumber Between @PagingRowNumberFrom AND @PagingRowNumberTo
Order By PagingWrapper.RowNumber Asc";
return string.Format(pagingWrapperSQL, sourceQuery);
}
else
{
throw new ApplicationException("To Execute ExecuteDataTable using a PagingRequest the Command must be text query and start with 'Select' ");
}
}
#endregion
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
namespace Orleans.Internal
{
public static class OrleansTaskExtentions
{
internal static readonly Task<object> CanceledTask = TaskFromCanceled<object>();
internal static readonly Task<object> CompletedTask = Task.FromResult(default(object));
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task"/>.
/// </summary>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask(this Task task)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return CompletedTask;
case TaskStatus.Faulted:
return TaskFromFaulted(task);
case TaskStatus.Canceled:
return CanceledTask;
default:
return ConvertAsync(task);
}
async Task<object> ConvertAsync(Task asyncTask)
{
await asyncTask;
return null;
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>.
/// </summary>
/// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask<T>(this Task<T> task)
{
if (typeof(T) == typeof(object))
return task as Task<object>;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((object)GetResult(task));
case TaskStatus.Faulted:
return TaskFromFaulted(task);
case TaskStatus.Canceled:
return CanceledTask;
default:
return ConvertAsync(task);
}
async Task<object> ConvertAsync(Task<T> asyncTask)
{
return await asyncTask.ConfigureAwait(false);
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>.
/// </summary>
/// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam>
/// <param name="task">The task.</param>
internal static Task<T> ToTypedTask<T>(this Task<object> task)
{
if (typeof(T) == typeof(object))
return task as Task<T>;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((T)GetResult(task));
case TaskStatus.Faulted:
return TaskFromFaulted<T>(task);
case TaskStatus.Canceled:
return TaskFromCanceled<T>();
default:
return ConvertAsync(task);
}
async Task<T> ConvertAsync(Task<object> asyncTask)
{
var result = await asyncTask.ConfigureAwait(false);
if (result is null)
{
if (!NullabilityHelper<T>.IsNullableType)
{
ThrowInvalidTaskResultType(typeof(T));
}
return default;
}
return (T)result;
}
}
private static class NullabilityHelper<T>
{
/// <summary>
/// True if <typeparamref name="T" /> is an instance of a nullable type (a reference type or <see cref="Nullable{T}"/>), otherwise false.
/// </summary>
public static readonly bool IsNullableType = !typeof(T).IsValueType || typeof(T).IsConstructedGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidTaskResultType(Type type)
{
var message = $"Expected result of type {type} but encountered a null value. This may be caused by a grain call filter swallowing an exception.";
throw new InvalidOperationException(message);
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{Object}"/>.
/// </summary>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask(this Task<object> task)
{
return task;
}
private static Task<object> TaskFromFaulted(Task task)
{
var completion = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
private static Task<T> TaskFromFaulted<T>(Task task)
{
var completion = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
private static Task<T> TaskFromCanceled<T>()
{
var completion = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
completion.SetCanceled();
return completion.Task;
}
public static async Task LogException(this Task task, ILogger logger, ErrorCode errorCode, string message)
{
try
{
await task;
}
catch (Exception exc)
{
_ = task.Exception; // Observe exception
logger.Error(errorCode, message, exc);
throw;
}
}
// Executes an async function such as Exception is never thrown but rather always returned as a broken task.
public static async Task SafeExecute(Func<Task> action)
{
await action();
}
public static async Task ExecuteAndIgnoreException(Func<Task> action)
{
try
{
await action();
}
catch (Exception)
{
// dont re-throw, just eat it.
}
}
internal static String ToString(this Task t)
{
return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status));
}
internal static String ToString<T>(this Task<T> t)
{
return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status));
}
public static void WaitWithThrow(this Task task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException($"Task.WaitWithThrow has timed out after {timeout}.");
}
}
internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException($"Task<T>.WaitForResultWithThrow has timed out after {timeout}.");
}
return task.Result;
}
/// <summary>
/// This will apply a timeout delay to the task, allowing us to exit early
/// </summary>
/// <param name="taskToComplete">The task we will timeout after timeSpan</param>
/// <param name="timeout">Amount of time to wait before timing out</param>
/// <param name="exceptionMessage">Text to put into the timeout exception message</param>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The completed task</returns>
public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout, string exceptionMessage = null)
{
if (taskToComplete.IsCompleted)
{
await taskToComplete;
return;
}
var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
// We got done before the timeout, or were able to complete before this code ran, return the result
if (taskToComplete == completedTask)
{
timeoutCancellationTokenSource.Cancel();
// Await this so as to propagate the exception correctly
await taskToComplete;
return;
}
// We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur
taskToComplete.Ignore();
var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeout}";
throw new TimeoutException(errorMessage);
}
/// <summary>
/// This will apply a timeout delay to the task, allowing us to exit early
/// </summary>
/// <param name="taskToComplete">The task we will timeout after timeSpan</param>
/// <param name="timeSpan">Amount of time to wait before timing out</param>
/// <param name="exceptionMessage">Text to put into the timeout exception message</param>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The value of the completed task</returns>
public static async Task<T> WithTimeout<T>(this Task<T> taskToComplete, TimeSpan timeSpan, string exceptionMessage = null)
{
if (taskToComplete.IsCompleted)
{
return await taskToComplete;
}
var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeSpan, timeoutCancellationTokenSource.Token));
// We got done before the timeout, or were able to complete before this code ran, return the result
if (taskToComplete == completedTask)
{
timeoutCancellationTokenSource.Cancel();
// Await this so as to propagate the exception correctly
return await taskToComplete;
}
// We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur
taskToComplete.Ignore();
var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeSpan}";
throw new TimeoutException(errorMessage);
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <param name="message">Message to set in the exception</param>
/// <returns></returns>
internal static async Task WithCancellation(
this Task taskToComplete,
CancellationToken cancellationToken,
string message)
{
try
{
await taskToComplete.WithCancellation(cancellationToken);
}
catch (TaskCanceledException ex)
{
throw new TaskCanceledException(message, ex);
}
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <returns></returns>
internal static Task WithCancellation(this Task taskToComplete, CancellationToken cancellationToken)
{
if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled)
{
return taskToComplete;
}
else if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<object>(cancellationToken);
}
else
{
return MakeCancellable(taskToComplete, cancellationToken);
}
}
private static async Task MakeCancellable(Task task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
using (cancellationToken.Register(() =>
tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false))
{
var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (firstToComplete != task)
{
task.Ignore();
}
await firstToComplete.ConfigureAwait(false);
}
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <param name="message">Message to set in the exception</param>
/// <returns></returns>
internal static async Task<T> WithCancellation<T>(
this Task<T> taskToComplete,
CancellationToken cancellationToken,
string message)
{
try
{
return await taskToComplete.WithCancellation(cancellationToken);
}
catch (TaskCanceledException ex)
{
throw new TaskCanceledException(message, ex);
}
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <returns></returns>
internal static Task<T> WithCancellation<T>(this Task<T> taskToComplete, CancellationToken cancellationToken)
{
if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled)
{
return taskToComplete;
}
else if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<T>(cancellationToken);
}
else
{
return MakeCancellable(taskToComplete, cancellationToken);
}
}
private static async Task<T> MakeCancellable<T>(Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
using (cancellationToken.Register(() =>
tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false))
{
var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (firstToComplete != task)
{
task.Ignore();
}
return await firstToComplete.ConfigureAwait(false);
}
}
internal static Task WrapInTask(Action action)
{
try
{
action();
return Task.CompletedTask;
}
catch (Exception exc)
{
return Task.FromException<object>(exc);
}
}
internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task)
{
if (task == null) return Task.FromResult(default(T));
var resolver = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
if (task.Status == TaskStatus.RanToCompletion)
{
resolver.TrySetResult(task.Result);
}
else if (task.IsFaulted)
{
resolver.TrySetException(task.Exception.InnerExceptions);
}
else if (task.IsCanceled)
{
resolver.TrySetException(new TaskCanceledException(task));
}
else
{
if (task.Status == TaskStatus.Created) task.Start();
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
resolver.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
resolver.TrySetException(new TaskCanceledException(t));
}
else
{
resolver.TrySetResult(t.GetResult());
}
});
}
return resolver.Task;
}
//The rationale for GetAwaiter().GetResult() instead of .Result
//is presented at https://github.com/aspnet/Security/issues/59.
internal static T GetResult<T>(this Task<T> task)
{
return task.GetAwaiter().GetResult();
}
internal static void GetResult(this Task task)
{
task.GetAwaiter().GetResult();
}
internal static Task WhenCancelled(this CancellationToken token)
{
if (token.IsCancellationRequested)
{
return Task.CompletedTask;
}
var waitForCancellation = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
token.Register(obj =>
{
var tcs = (TaskCompletionSource<object>)obj;
tcs.TrySetResult(null);
}, waitForCancellation);
return waitForCancellation.Task;
}
}
}
namespace Orleans
{
/// <summary>
/// A special void 'Done' Task that is already in the RunToCompletion state.
/// Equivalent to Task.FromResult(1).
/// </summary>
public static class TaskDone
{
/// <summary>
/// A special 'Done' Task that is already in the RunToCompletion state
/// </summary>
[Obsolete("Use Task.CompletedTask")]
public static Task Done => Task.CompletedTask;
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2017 Jesse Sweetland
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Platibus.Filesystem;
using Platibus.Http;
namespace Platibus.Diagnostics
{
/// <summary>
/// A base class for <see cref="IDiagnosticService"/> implementations based on the Graylog
/// Extended Log Format (GELF)
/// </summary>
public abstract class GelfLoggingSink : IDiagnosticEventSink
{
private readonly JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
/// <inheritdoc />
public void Consume(DiagnosticEvent @event)
{
var gelfMessage = new GelfMessage();
PopulateGelfMessage(gelfMessage, @event);
var json = JsonConvert.SerializeObject(gelfMessage, _jsonSerializerSettings);
Process(json);
// Allow exceptions to propagate to the IDiagnosticService where they will be caught
// and handled by registered DiagnosticSinkExceptionHandlers
}
/// <inheritdoc />
public async Task ConsumeAsync(DiagnosticEvent @event, CancellationToken cancellationToken = new CancellationToken())
{
var gelfMessage = new GelfMessage();
PopulateGelfMessage(gelfMessage, @event);
var json = JsonConvert.SerializeObject(gelfMessage, _jsonSerializerSettings);
await ProcessAsync(json, cancellationToken);
// Allow exceptions to propagate to the IDiagnosticService where they will be caught
// and handled by registered DiagnosticSinkExceptionHandlers
}
/// <summary>
/// Processes the specified GELF formatted string by writing it to a file or sending it to
/// a network endpoint
/// </summary>
/// <param name="gelfMessage">The JSON serialized GELF message to process</param>
/// <returns>Returns a task that will complete when the GELF message has been processed</returns>
public abstract void Process(string gelfMessage);
/// <summary>
/// Processes the specified GELF formatted string by writing it to a file or sending it to
/// a network endpoint
/// </summary>
/// <param name="gelfMessage">The JSON serialized GELF message to process</param>
/// <param name="cancellationToken">(Optional) A cancellation token that can be provided
/// by the caller to interrupt processing of the GELF message</param>
/// <returns>Returns a task that will complete when the GELF message has been processed</returns>
public abstract Task ProcessAsync(string gelfMessage, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Serializes the specified <paramref name="gelfMessage"/> to a JSON string
/// </summary>
/// <param name="gelfMessage">The GELF message to serialize</param>
/// <returns>Returns the JSON serialized <paramref name="gelfMessage"/></returns>
protected string Serialize(GelfMessage gelfMessage)
{
if (gelfMessage == null) throw new ArgumentNullException(nameof(gelfMessage));
return JsonConvert.SerializeObject(gelfMessage, _jsonSerializerSettings);
}
/// <summary>
/// Sets the standard and common additional GELF fields with values from the specified
/// diagnostic <paramref name="event"/>.
/// </summary>
/// <param name="gelfMessage">The GELF message to populate</param>
/// <param name="event">The diagnostic event</param>
/// <returns>The GELF formatted string</returns>
protected virtual void PopulateGelfMessage(GelfMessage gelfMessage, DiagnosticEvent @event)
{
var source = @event.Source;
gelfMessage.Facility = source == null ? "Platibus" : source.GetType().FullName;
gelfMessage.Level = GetSyslogLevel(@event.Type.Level);
gelfMessage.Timestamp = @event.Timestamp;
gelfMessage.EventType = @event.Type;
gelfMessage.Queue = @event.Queue;
gelfMessage.Topic = @event.Topic;
if (MessageTooLong(@event.Detail, out string shortMessage))
{
gelfMessage.ShortMessage = shortMessage;
gelfMessage.FullMessage = @event.Detail;
}
else
{
gelfMessage.ShortMessage = @event.Detail;
}
if (string.IsNullOrWhiteSpace(gelfMessage.ShortMessage))
{
// Short message is required. Default to the event type.
gelfMessage.ShortMessage = @event.Type;
}
if (@event.Exception != null)
{
gelfMessage.Exception = @event.Exception.ToString();
}
PopulateMessageFields(gelfMessage, @event);
PopulateHttpFields(gelfMessage, @event as HttpEvent);
PopulateFilesystemFields(gelfMessage, @event as FilesystemEvent);
}
/// <summary>
/// Populates fields on the GELF message that correspond to the properties of the
/// <see cref="DiagnosticEvent.Message"/>
/// </summary>
/// <param name="gelfMessage">The GELF message to populate</param>
/// <param name="event">The diagnostic event</param>
protected virtual void PopulateMessageFields(GelfMessage gelfMessage, DiagnosticEvent @event)
{
if (@event.Message == null) return;
var headers = @event.Message.Headers;
gelfMessage.MessageId = headers.MessageId;
gelfMessage.MessageName = headers.MessageName;
gelfMessage.RelatedTo = headers.RelatedTo == default(MessageId)
? null
: headers.MessageId.ToString();
if (headers.Origination != null)
{
gelfMessage.Origination = headers.Origination.ToString();
}
if (headers.Destination != null)
{
gelfMessage.Destination = headers.Destination.ToString();
}
if (headers.ReplyTo != null)
{
gelfMessage.Destination = headers.ReplyTo.ToString();
}
}
/// <summary>
/// Populates fields on the GELF message that correspond to properties on an
/// <see cref="HttpEvent"/>
/// </summary>
/// <param name="gelfMessage">The GELF message to populate</param>
/// <param name="httpEvent">The HTTP diagnostic event</param>
protected virtual void PopulateHttpFields(GelfMessage gelfMessage, HttpEvent httpEvent)
{
if (httpEvent == null) return;
gelfMessage.Remote = httpEvent.Remote;
gelfMessage.HttpMethod = httpEvent.Method;
gelfMessage.HttpStatus = httpEvent.Status;
if (httpEvent.Uri != null)
{
gelfMessage.Uri = httpEvent.Uri.ToString();
}
}
/// <summary>
/// Populates fields on the GELF message that correspond to properties on an
/// <see cref="FilesystemEvent"/>
/// </summary>
/// <param name="gelfMessage">The GELF message to populate</param>
/// <param name="fsEvent">The filesystem diagnostic event</param>
protected virtual void PopulateFilesystemFields(GelfMessage gelfMessage, FilesystemEvent fsEvent)
{
if (fsEvent == null) return;
gelfMessage.Path = fsEvent.Path;
}
private static readonly IDictionary<DiagnosticEventLevel, int> SyslogLevels = new Dictionary<DiagnosticEventLevel, int>
{
{ DiagnosticEventLevel.Trace, 7 },
{ DiagnosticEventLevel.Debug, 7 },
{ DiagnosticEventLevel.Info, 6 },
{ DiagnosticEventLevel.Warn, 4 },
{ DiagnosticEventLevel.Error, 3 }
};
/// <summary>
/// Returns the syslog level corresponding to the specified diagnostic event
/// <paramref name="level"/>
/// </summary>
/// <param name="level">The diagnostic event level</param>
/// <returns>Returns the syslog level corresponding to the specified diagnostic event
/// level</returns>
protected int GetSyslogLevel(DiagnosticEventLevel level)
{
return SyslogLevels.TryGetValue(level, out int syslogLevel) ? syslogLevel : 7;
}
/// <summary>
/// Determines whether the <paramref name="fullMessage"/> is too long to use for the GELF
/// <c>short_message</c> field, parsing out an appropriate substring to use as the short
/// message that is the case.
/// </summary>
/// <param name="fullMessage">The full message</param>
/// <param name="shortMessage">A variable that will receive a substring of the
/// <paramref name="fullMessage"/> that is appropriate to use for the <c>short_message</c>
/// if the <paramref name="fullMessage"/> is too long</param>
/// <returns>Returns <c>true</c> if the <paramref name="fullMessage"/> is too long and
/// a separate <paramref name="shortMessage"/> is needed; <c>false</c> otherwise</returns>
protected virtual bool MessageTooLong(string fullMessage, out string shortMessage)
{
if (string.IsNullOrWhiteSpace(fullMessage))
{
shortMessage = fullMessage;
return false;
}
const int maxShortMessageLength = 100;
const string trailingEllipses = "...";
if (fullMessage.Length > maxShortMessageLength)
{
var cutoffPoint = maxShortMessageLength - trailingEllipses.Length;
var lastWhitespace = fullMessage.LastIndexOf(" ", cutoffPoint, StringComparison.OrdinalIgnoreCase);
if (lastWhitespace > 0)
{
cutoffPoint = lastWhitespace;
}
shortMessage = fullMessage.Substring(0, cutoffPoint) + trailingEllipses;
return true;
}
shortMessage = fullMessage;
return false;
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using SquabPie.Mono.Cecil.Cil;
using NUnit.Framework;
using SquabPie.Mono.Cecil.PE;
namespace SquabPie.Mono.Cecil.Tests {
public abstract class BaseTestFixture {
protected static void IgnoreOnMono ()
{
if (Platform.OnMono)
Assert.Ignore ();
}
public static string GetResourcePath (string name, Assembly assembly)
{
return Path.Combine (FindResourcesDirectory (assembly), name);
}
public static string GetAssemblyResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("assemblies", name), assembly);
}
public static string GetCSharpResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("cs", name), assembly);
}
public static string GetILResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("il", name), assembly);
}
public ModuleDefinition GetResourceModule (string name)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly));
}
public ModuleDefinition GetResourceModule (string name, ReaderParameters parameters)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), parameters);
}
public ModuleDefinition GetResourceModule (string name, ReadingMode mode)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), new ReaderParameters (mode));
}
internal Image GetResourceImage (string name)
{
using (var fs = new FileStream (GetAssemblyResourcePath (name, GetType ().Assembly), FileMode.Open, FileAccess.Read))
return ImageReader.ReadImageFrom (fs);
}
public ModuleDefinition GetCurrentModule ()
{
return ModuleDefinition.ReadModule (GetType ().Module.FullyQualifiedName);
}
public ModuleDefinition GetCurrentModule (ReaderParameters parameters)
{
return ModuleDefinition.ReadModule (GetType ().Module.FullyQualifiedName, parameters);
}
public static string FindResourcesDirectory (Assembly assembly)
{
var path = Path.GetDirectoryName (new Uri (assembly.CodeBase).LocalPath);
while (!Directory.Exists (Path.Combine (path, "Resources"))) {
var old = path;
path = Path.GetDirectoryName (path);
Assert.AreNotEqual (old, path);
}
return Path.Combine (path, "Resources");
}
public static void TestModule (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null)
{
Run (new ModuleTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider));
}
public static void TestCSharp (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null)
{
Run (new CSharpTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider));
}
public static void TestIL (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null)
{
Run (new ILTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider));
}
private static void Run (TestCase testCase)
{
var runner = new TestRunner (testCase, TestCaseType.ReadDeferred);
runner.RunTest ();
runner = new TestRunner (testCase, TestCaseType.ReadImmediate);
runner.RunTest ();
if (testCase.ReadOnly)
return;
runner = new TestRunner (testCase, TestCaseType.WriteFromDeferred);
runner.RunTest();
runner = new TestRunner (testCase, TestCaseType.WriteFromImmediate);
runner.RunTest();
}
}
abstract class TestCase {
public readonly bool Verify;
public readonly bool ReadOnly;
public readonly Type SymbolReaderProvider;
public readonly Type SymbolWriterProvider;
public readonly Action<ModuleDefinition> Test;
public abstract string ModuleLocation { get; }
protected Assembly Assembly { get { return Test.Method.Module.Assembly; } }
protected TestCase (Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider)
{
Test = test;
Verify = verify;
ReadOnly = readOnly;
SymbolReaderProvider = symbolReaderProvider;
SymbolWriterProvider = symbolWriterProvider;
}
}
class ModuleTestCase : TestCase {
public readonly string Module;
public ModuleTestCase (string module, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider)
: base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider)
{
Module = module;
}
public override string ModuleLocation
{
get { return BaseTestFixture.GetAssemblyResourcePath (Module, Assembly); }
}
}
class CSharpTestCase : TestCase {
public readonly string File;
public CSharpTestCase (string file, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider)
: base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider)
{
File = file;
}
public override string ModuleLocation
{
get
{
return CompilationService.CompileResource (BaseTestFixture.GetCSharpResourcePath (File, Assembly));
}
}
}
class ILTestCase : TestCase {
public readonly string File;
public ILTestCase (string file, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider)
: base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider)
{
File = file;
}
public override string ModuleLocation
{
get
{
return CompilationService.CompileResource (BaseTestFixture.GetILResourcePath (File, Assembly)); ;
}
}
}
class TestRunner {
readonly TestCase test_case;
readonly TestCaseType type;
public TestRunner (TestCase testCase, TestCaseType type)
{
this.test_case = testCase;
this.type = type;
}
ModuleDefinition GetModule ()
{
var location = test_case.ModuleLocation;
var directory = Path.GetDirectoryName (location);
var resolver = new DefaultAssemblyResolver ();
resolver.AddSearchDirectory (directory);
var parameters = new ReaderParameters {
SymbolReaderProvider = GetSymbolReaderProvider (),
AssemblyResolver = resolver,
};
switch (type) {
case TestCaseType.ReadImmediate:
parameters.ReadingMode = ReadingMode.Immediate;
return ModuleDefinition.ReadModule (location, parameters);
case TestCaseType.ReadDeferred:
parameters.ReadingMode = ReadingMode.Deferred;
return ModuleDefinition.ReadModule (location, parameters);
case TestCaseType.WriteFromImmediate:
parameters.ReadingMode = ReadingMode.Immediate;
return RoundTrip (location, parameters, "cecil-irt");
case TestCaseType.WriteFromDeferred:
parameters.ReadingMode = ReadingMode.Deferred;
return RoundTrip (location, parameters, "cecil-drt");
default:
return null;
}
}
ISymbolReaderProvider GetSymbolReaderProvider ()
{
if (test_case.SymbolReaderProvider == null)
return null;
return (ISymbolReaderProvider) Activator.CreateInstance (test_case.SymbolReaderProvider);
}
ISymbolWriterProvider GetSymbolWriterProvider ()
{
if (test_case.SymbolReaderProvider == null)
return null;
return (ISymbolWriterProvider) Activator.CreateInstance (test_case.SymbolWriterProvider);
}
ModuleDefinition RoundTrip (string location, ReaderParameters reader_parameters, string folder)
{
var module = ModuleDefinition.ReadModule (location, reader_parameters);
var rt_folder = Path.Combine (Path.GetTempPath (), folder);
if (!Directory.Exists (rt_folder))
Directory.CreateDirectory (rt_folder);
var rt_module = Path.Combine (rt_folder, Path.GetFileName (location));
var writer_parameters = new WriterParameters {
SymbolWriterProvider = GetSymbolWriterProvider (),
};
test_case.Test (module);
module.Write (rt_module, writer_parameters);
if (test_case.Verify)
CompilationService.Verify (rt_module);
return ModuleDefinition.ReadModule (rt_module, reader_parameters);
}
public void RunTest ()
{
var module = GetModule ();
if (module == null)
return;
test_case.Test(module);
}
}
enum TestCaseType {
ReadImmediate,
ReadDeferred,
WriteFromImmediate,
WriteFromDeferred,
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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;
namespace SharpDX.XAudio2
{
public partial class Voice
{
/// <summary>
/// Enables the effect at a given position in the effect chain of the voice.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect in the effect chain of the voice. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::EnableEffect([None] UINT32 EffectIndex,[None] UINT32 OperationSet)</unmanaged>
public void EnableEffect(int effectIndex)
{
EnableEffect(effectIndex, 0);
}
/// <summary>
/// Disables the effect at a given position in the effect chain of the voice.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect in the effect chain of the voice. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::DisableEffect([None] UINT32 EffectIndex,[None] UINT32 OperationSet)</unmanaged>
public void DisableEffect(int effectIndex)
{
DisableEffect(effectIndex, 0);
}
/// <summary>
/// Sets parameters for a given effect in the voice's effect chain.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param>
/// <returns>Returns the current values of the effect-specific parameters.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged>
public T GetEffectParameters<T>(int effectIndex) where T : struct
{
unsafe
{
var effectParameter = default(T);
byte* pEffectParameter = stackalloc byte[Utilities.SizeOf<T>()];
GetEffectParameters(effectIndex, (IntPtr)pEffectParameter, Utilities.SizeOf<T>());
Utilities.Read((IntPtr)pEffectParameter, ref effectParameter);
return effectParameter;
}
}
/// <summary>
/// Returns the current effect-specific parameters of a given effect in the voice's effect chain.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param>
/// <param name="effectParameters">[out] Returns the current values of the effect-specific parameters. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::GetEffectParameters([None] UINT32 EffectIndex,[Out, Buffer] void* pParameters,[None] UINT32 ParametersByteSize)</unmanaged>
public void GetEffectParameters(int effectIndex, byte[] effectParameters)
{
unsafe
{
fixed (void* pEffectParameter = &effectParameters[0])
GetEffectParameters(effectIndex, (IntPtr)pEffectParameter, effectParameters.Length);
}
}
/// <summary>
/// Sets parameters for a given effect in the voice's effect chain.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param>
/// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged>
public void SetEffectParameters(int effectIndex, byte[] effectParameter)
{
SetEffectParameters(effectIndex, effectParameter, 0);
}
/// <summary>
/// Sets parameters for a given effect in the voice's effect chain.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param>
/// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param>
/// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged>
public void SetEffectParameters(int effectIndex, byte[] effectParameter, int operationSet)
{
unsafe
{
fixed (void* pEffectParameter = &effectParameter[0])
SetEffectParameters(effectIndex, (IntPtr)pEffectParameter, effectParameter.Length, operationSet);
}
}
/// <summary>
/// Sets parameters for a given effect in the voice's effect chain.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param>
/// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged>
public void SetEffectParameters<T>(int effectIndex, T effectParameter) where T : struct
{
this.SetEffectParameters<T>(effectIndex, effectParameter, 0);
}
/// <summary>
/// Sets parameters for a given effect in the voice's effect chain.
/// </summary>
/// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param>
/// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param>
/// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged>
public void SetEffectParameters<T>(int effectIndex, T effectParameter, int operationSet) where T : struct
{
unsafe
{
byte* pEffectParameter = stackalloc byte[Utilities.SizeOf<T>()];
Utilities.Write((IntPtr)pEffectParameter, ref effectParameter);
SetEffectParameters(effectIndex, (IntPtr) pEffectParameter, Utilities.SizeOf<T>(), operationSet);
}
}
/// <summary>
/// Replaces the effect chain of the voice.
/// </summary>
/// <param name="effectDescriptors">[in, optional] an array of <see cref="SharpDX.XAudio2.EffectDescriptor"/> structure that describes the new effect chain to use. If NULL is passed, the current effect chain is removed. If array is non null, its length must be at least of 1. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetEffectChain([In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged>
public void SetEffectChain(params EffectDescriptor[] effectDescriptors)
{
unsafe
{
if (effectDescriptors != null)
{
var tempSendDescriptor = new EffectChain();
var effectDescriptorNatives = new EffectDescriptor.__Native[effectDescriptors.Length];
for (int i = 0; i < effectDescriptorNatives.Length; i++)
effectDescriptors[i].__MarshalTo(ref effectDescriptorNatives[i]);
tempSendDescriptor.EffectCount = effectDescriptorNatives.Length;
fixed (void* pEffectDescriptors = &effectDescriptorNatives[0])
{
tempSendDescriptor.EffectDescriptorPointer = (IntPtr)pEffectDescriptors;
SetEffectChain(tempSendDescriptor);
}
}
else
{
SetEffectChain((EffectChain?) null);
}
}
}
/// <summary>
/// Designates a new set of submix or mastering voices to receive the output of the voice.
/// </summary>
/// <param name="outputVoices">[in] Array of <see cref="VoiceSendDescriptor"/> structure pointers to destination voices. If outputVoices is NULL, the voice will send its output to the current mastering voice. To set the voice to not send its output anywhere set an array of length 0. All of the voices in a send list must have the same input sample rate, see {{XAudio2 Sample Rate Conversions}} for additional information. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetOutputVoices([In, Optional] const XAUDIO2_VOICE_SENDS* pSendList)</unmanaged>
public void SetOutputVoices(params VoiceSendDescriptor[] outputVoices)
{
unsafe
{
if (outputVoices != null)
{
var tempSendDescriptor = new VoiceSendDescriptors {SendCount = outputVoices.Length};
if(outputVoices.Length > 0)
{
fixed(void* pVoiceSendDescriptors = &outputVoices[0])
{
tempSendDescriptor.SendPointer = (IntPtr)pVoiceSendDescriptors;
SetOutputVoices(tempSendDescriptor);
}
}
else
{
tempSendDescriptor.SendPointer = IntPtr.Zero;
}
}
else
{
SetOutputVoices((VoiceSendDescriptors?) null);
}
}
}
/// <summary>
/// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice.
/// </summary>
/// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param>
/// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param>
/// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged>
public void SetOutputMatrix(int sourceChannels, int destinationChannels, float[] levelMatrixRef)
{
this.SetOutputMatrix(sourceChannels, destinationChannels, levelMatrixRef, 0);
}
/// <summary>
/// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice.
/// </summary>
/// <param name="destinationVoiceRef">[in] Pointer to a destination <see cref="SharpDX.XAudio2.Voice"/> for which to set volume levels. Note If the voice sends to a single target voice then specifying NULL will cause SetOutputMatrix to operate on that target voice. </param>
/// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param>
/// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param>
/// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged>
public void SetOutputMatrix(SharpDX.XAudio2.Voice destinationVoiceRef, int sourceChannels, int destinationChannels, float[] levelMatrixRef)
{
this.SetOutputMatrix(destinationVoiceRef, sourceChannels, destinationChannels, levelMatrixRef, 0);
}
/// <summary>
/// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice.
/// </summary>
/// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param>
/// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param>
/// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param>
/// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param>
/// <returns>No documentation.</returns>
/// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged>
public void SetOutputMatrix(int sourceChannels, int destinationChannels, float[] levelMatrixRef, int operationSet)
{
this.SetOutputMatrix(null, sourceChannels, destinationChannels, levelMatrixRef, operationSet);
}
}
}
| |
#define COUNT_ACTIVATE_DEACTIVATE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Providers;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
[Serializable]
public class StreamLifecycleTestGrainState
{
// For producer and consumer
// -- only need to store this because of how we run our unit tests against multiple providers
public string StreamProviderName { get; set; }
// For producer only.
public IAsyncStream<int> Stream { get; set; }
public bool IsProducer { get; set; }
public int NumMessagesSent { get; set; }
public int NumErrors { get; set; }
// For consumer only.
public HashSet<StreamSubscriptionHandle<int>> ConsumerSubscriptionHandles { get; set; }
public StreamLifecycleTestGrainState()
{
ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<int>>();
}
}
public class GenericArg
{
public string A { get; private set; }
public int B { get; private set; }
public GenericArg(string a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
var item = obj as GenericArg;
if (item == null)
{
return false;
}
return A.Equals(item.A) && B.Equals(item.B);
}
public override int GetHashCode()
{
return (B * 397) ^ (A != null ? A.GetHashCode() : 0);
}
}
public class AsyncObserverArg : GenericArg
{
public AsyncObserverArg(string a, int b) : base(a, b) { }
}
public class AsyncObservableArg : GenericArg
{
public AsyncObservableArg(string a, int b) : base(a, b) { }
}
public class AsyncStreamArg : GenericArg
{
public AsyncStreamArg(string a, int b) : base(a, b) { }
}
public class StreamSubscriptionHandleArg : GenericArg
{
public StreamSubscriptionHandleArg(string a, int b) : base(a, b) { }
}
public class StreamLifecycleTestGrainBase : Grain<StreamLifecycleTestGrainState>
{
protected ILogger logger;
protected string _lastProviderName;
protected IStreamProvider _streamProvider;
#if COUNT_ACTIVATE_DEACTIVATE
private IActivateDeactivateWatcherGrain watcher;
#endif
public StreamLifecycleTestGrainBase(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
protected Task RecordActivate()
{
#if COUNT_ACTIVATE_DEACTIVATE
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
return watcher.RecordActivateCall(IdentityString);
#else
return Task.CompletedTask;
#endif
}
protected Task RecordDeactivate()
{
#if COUNT_ACTIVATE_DEACTIVATE
return watcher.RecordDeactivateCall(IdentityString);
#else
return Task.CompletedTask;
#endif
}
protected void InitStream(StreamId streamId, string providerToUse)
{
if (providerToUse == null) throw new ArgumentNullException("providerToUse", "Can't have null stream provider name");
if (State.Stream != null && !State.Stream.StreamId.Equals(streamId))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Stream already exists for StreamId={0} StreamProvider={1} - Resetting", State.Stream, providerToUse);
// Note: in this test, we are deliberately not doing Unsubscribe consumers, just discard old stream and let auto-cleanup functions do their thing.
State.ConsumerSubscriptionHandles.Clear();
State.IsProducer = false;
State.NumMessagesSent = 0;
State.NumErrors = 0;
State.Stream = null;
}
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("InitStream StreamId={0} StreamProvider={1}", streamId, providerToUse);
if (providerToUse != _lastProviderName)
{
_streamProvider = this.GetStreamProvider(providerToUse);
_lastProviderName = providerToUse;
}
IAsyncStream<int> stream = _streamProvider.GetStream<int>(streamId);
State.Stream = stream;
State.StreamProviderName = providerToUse;
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("InitStream returning with Stream={0} with ref type = {1}", State.Stream, State.Stream.GetType().FullName);
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
internal class StreamLifecycleConsumerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleConsumerGrain
{
protected readonly InsideRuntimeClient runtimeClient;
protected readonly IStreamProviderRuntime streamProviderRuntime;
public StreamLifecycleConsumerGrain(InsideRuntimeClient runtimeClient, IStreamProviderRuntime streamProviderRuntime, ILoggerFactory loggerFactory) : base(loggerFactory)
{
this.runtimeClient = runtimeClient;
this.streamProviderRuntime = streamProviderRuntime;
}
protected IDictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>> Observers { get; set; }
public override async Task OnActivateAsync()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnActivateAsync");
await RecordActivate();
if (Observers == null)
{
Observers = new Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>>();
}
if (State.Stream != null && State.StreamProviderName != null)
{
if (State.ConsumerSubscriptionHandles.Count > 0)
{
var handles = State.ConsumerSubscriptionHandles.ToArray();
logger.Info("ReconnectConsumerHandles SubscriptionHandles={0} Grain={1}", Utils.EnumerableToString(handles), this.AsReference<IStreamLifecycleConsumerGrain>());
foreach (var handle in handles)
{
var observer = new MyStreamObserver<int>(this.logger);
StreamSubscriptionHandle<int> subsHandle = await handle.ResumeAsync(observer);
Observers.Add(subsHandle, observer);
}
}
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Not conected to stream yet.");
}
}
public override async Task OnDeactivateAsync()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnDeactivateAsync");
await RecordDeactivate();
}
public Task<int> GetReceivedCount()
{
int numReceived = Observers.Sum(o => o.Value.NumItems);
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("ReceivedCount={0}", numReceived);
return Task.FromResult(numReceived);
}
public Task<int> GetErrorsCount()
{
int numErrors = Observers.Sum(o => o.Value.NumErrors);
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("ErrorsCount={0}", numErrors);
return Task.FromResult(numErrors);
}
public Task Ping()
{
logger.Info("Ping");
return Task.CompletedTask;
}
public virtual async Task BecomeConsumer(StreamId streamId, string providerToUse)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("BecomeConsumer StreamId={0} StreamProvider={1} Grain={2}", streamId, providerToUse, this.AsReference<IStreamLifecycleConsumerGrain>());
InitStream(streamId, providerToUse);
var observer = new MyStreamObserver<int>(logger);
var subsHandle = await State.Stream.SubscribeAsync(observer);
State.ConsumerSubscriptionHandles.Add(subsHandle);
Observers.Add(subsHandle, observer);
await WriteStateAsync();
}
public virtual async Task TestBecomeConsumerSlim(StreamId streamId, string providerName)
{
InitStream(streamId, providerName);
var observer = new MyStreamObserver<int>(logger);
//var subsHandle = await State.Stream.SubscribeAsync(observer);
var context = this.Data;
var (myExtension, myExtensionReference) = this.streamProviderRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(
() => new StreamConsumerExtension(streamProviderRuntime));
string extKey = providerName + "_" + Encoding.UTF8.GetString(State.Stream.StreamId.Namespace.ToArray());
var id = new InternalStreamId(providerName, streamId);
IPubSubRendezvousGrain pubsub = GrainFactory.GetGrain<IPubSubRendezvousGrain>(id.ToString());
GuidId subscriptionId = GuidId.GetNewGuidId();
await pubsub.RegisterConsumer(subscriptionId, ((StreamImpl<int>)State.Stream).InternalStreamId, myExtensionReference, null);
myExtension.SetObserver(subscriptionId, ((StreamImpl<int>)State.Stream), observer, null, null, null);
}
public async Task RemoveConsumer(StreamId streamId, string providerName, StreamSubscriptionHandle<int> subsHandle)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("RemoveConsumer StreamId={0} StreamProvider={1}", streamId, providerName);
if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer");
await subsHandle.UnsubscribeAsync();
Observers.Remove(subsHandle);
State.ConsumerSubscriptionHandles.Remove(subsHandle);
await WriteStateAsync();
}
public async Task ClearGrain()
{
logger.Info("ClearGrain");
var subsHandles = State.ConsumerSubscriptionHandles.ToArray();
foreach (var handle in subsHandles)
{
await handle.UnsubscribeAsync();
}
State.ConsumerSubscriptionHandles.Clear();
State.Stream = null;
State.IsProducer = false;
Observers.Clear();
await ClearStateAsync();
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class StreamLifecycleProducerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleProducerGrain
{
public StreamLifecycleProducerGrain(ILoggerFactory loggerFactory) : base(loggerFactory)
{
}
public override async Task OnActivateAsync()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnActivateAsync");
await RecordActivate();
if (State.Stream != null && State.StreamProviderName != null)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Reconnected to stream {0}", State.Stream);
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Not connected to stream yet.");
}
}
public override async Task OnDeactivateAsync()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnDeactivateAsync");
await RecordDeactivate();
}
public Task<int> GetSendCount()
{
int result = State.NumMessagesSent;
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("GetSendCount={0}", result);
return Task.FromResult(result);
}
public Task<int> GetErrorsCount()
{
int result = State.NumErrors;
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("GetErrorsCount={0}", result);
return Task.FromResult(result);
}
public Task Ping()
{
logger.Info("Ping");
return Task.CompletedTask;
}
public async Task SendItem(int item)
{
if (!State.IsProducer || State.Stream == null) throw new InvalidOperationException("Not a Producer");
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("SendItem Item={0}", item);
Exception error = null;
try
{
await State.Stream.OnNextAsync(item);
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Successful SendItem " + item);
State.NumMessagesSent++;
}
catch (Exception exc)
{
logger.Error(0, "Error from SendItem " + item, exc);
State.NumErrors++;
error = exc;
}
await WriteStateAsync(); // Update counts in persisted state
if (error != null)
{
throw new AggregateException(error);
}
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Finished SendItem for Item={0}", item);
}
public async Task BecomeProducer(StreamId streamId, string providerName)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("BecomeProducer StreamId={0} StreamProvider={1}", streamId, providerName);
InitStream(streamId, providerName);
State.IsProducer = true;
// Send an initial message to ensure we are properly initialized as a Producer.
await State.Stream.OnNextAsync(0);
State.NumMessagesSent++;
await WriteStateAsync();
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Finished BecomeProducer for StreamId={0} StreamProvider={1}", streamId, providerName);
}
public async Task ClearGrain()
{
logger.Info("ClearGrain");
State.IsProducer = false;
State.Stream = null;
await ClearStateAsync();
}
public async Task DoDeactivateNoClose()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("DoDeactivateNoClose");
State.IsProducer = false;
State.Stream = null;
await WriteStateAsync();
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Calling DeactivateOnIdle");
DeactivateOnIdle();
}
}
[Serializable]
public class MyStreamObserver<T> : IAsyncObserver<T>
{
internal int NumItems { get; private set; }
internal int NumErrors { get; private set; }
private readonly ILogger logger;
internal MyStreamObserver(ILogger logger)
{
this.logger = logger;
}
public Task OnNextAsync(T item, StreamSequenceToken token)
{
NumItems++;
if (logger != null && logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Received OnNextAsync - Item={0} - Total Items={1} Errors={2}", item, NumItems, NumErrors);
}
return Task.CompletedTask;
}
public Task OnCompletedAsync()
{
if (logger != null)
{
logger.Info("Receive OnCompletedAsync - Total Items={0} Errors={1}", NumItems, NumErrors);
}
return Task.CompletedTask;
}
public Task OnErrorAsync(Exception ex)
{
NumErrors++;
if (logger != null)
{
logger.Warn(1, "Received OnErrorAsync - Exception={0} - Total Items={1} Errors={2}", ex, NumItems, NumErrors);
}
return Task.CompletedTask;
}
}
public class ClosedTypeStreamObserver : MyStreamObserver<AsyncObserverArg>
{
public ClosedTypeStreamObserver(ILogger logger) : base(logger)
{
}
}
public interface IClosedTypeAsyncObservable : IAsyncObservable<AsyncObservableArg> { }
public interface IClosedTypeAsyncStream : IAsyncStream<AsyncStreamArg> { }
internal class ClosedTypeStreamSubscriptionHandle : StreamSubscriptionHandleImpl<StreamSubscriptionHandleArg>
{
public ClosedTypeStreamSubscriptionHandle() : base(null, null) { /* not a subject to the creation */ }
}
}
| |
using System.Runtime.InteropServices;
namespace Ets2SdkClient
{
[StructLayout(LayoutKind.Explicit)]
public struct Ets2SdkData
{
[FieldOffset(0)]
public uint time;
[FieldOffset(4)]
public uint paused;
[FieldOffset(8)]
public uint ets2_telemetry_plugin_revision;
[FieldOffset(12)]
public uint ets2_version_major;
[FieldOffset(16)]
public uint ets2_version_minor;
// ***** REVISION 1 ****** //
[FieldOffset(20)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] flags;
// vehicle dynamics
[FieldOffset(24)]
public float speed;
[FieldOffset(28)]
public float accelerationX;
[FieldOffset(32)]
public float accelerationY;
[FieldOffset(36)]
public float accelerationZ;
[FieldOffset(40)]
public float coordinateX;
[FieldOffset(44)]
public float coordinateY;
[FieldOffset(48)]
public float coordinateZ;
[FieldOffset(52)]
public float rotationX;
[FieldOffset(56)]
public float rotationY;
[FieldOffset(60)]
public float rotationZ;
// drivetrain essentials
[FieldOffset(64)]
public int gear;
[FieldOffset(68)]
public int gears;
[FieldOffset(72)]
public int gearRanges;
[FieldOffset(76)]
public int gearRangeActive;
[FieldOffset(80)]
public float engineRpm;
[FieldOffset(84)]
public float engineRpmMax;
[FieldOffset(88)]
public float fuel;
[FieldOffset(92)]
public float fuelCapacity;
[FieldOffset(96)]
public float fuelRate;
[FieldOffset(100)]
public float fuelAvgConsumption;
// user input
[FieldOffset(104)]
public float userSteer;
[FieldOffset(108)]
public float userThrottle;
[FieldOffset(112)]
public float userBrake;
[FieldOffset(116)]
public float userClutch;
[FieldOffset(120)]
public float gameSteer;
[FieldOffset(124)]
public float gameThrottle;
[FieldOffset(128)]
public float gameBrake;
[FieldOffset(132)]
public float gameClutch;
// truck & trailer
[FieldOffset(136)]
public float truckWeight;
[FieldOffset(140)]
public float trailerWeight;
[FieldOffset(144)]
public int modelOffset;
[FieldOffset(148)]
public int modelLength;
[FieldOffset(152)]
public int trailerOffset;
[FieldOffset(156)]
public int trailerLength;
// ***** REVISION 2 ****** //
[FieldOffset(160)]
public int timeAbsolute;
[FieldOffset(164)]
public int gearsReverse;
[FieldOffset(168)]
public float trailerMass;
[FieldOffset(172)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] trailerId;
[FieldOffset(236)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] trailerName;
[FieldOffset(300)]
public int jobIncome;
[FieldOffset(304)]
public int jobDeadline;
[FieldOffset(308)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] jobCitySource;
[FieldOffset(372)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] jobCityDestination;
[FieldOffset(436)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] jobCompanySource;
[FieldOffset(500)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] jobCompanyDestination;
// ***** REVISION 3 ****** //
[FieldOffset(564)]
public int retarderBrake;
[FieldOffset(568)]
public int shifterSlot;
[FieldOffset(572)]
public int shifterToggle;
//[FieldOffset(576)]
//public int fill;
[FieldOffset(580)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
public byte[] aux;
[FieldOffset(604)]
public float airPressure;
[FieldOffset(608)]
public float brakeTemperature;
[FieldOffset(612)]
public int fuelWarning;
[FieldOffset(616)]
public float adblue;
[FieldOffset(620)]
public float adblueConsumption;
[FieldOffset(624)]
public float oilPressure;
[FieldOffset(628)]
public float oilTemperature;
[FieldOffset(632)]
public float waterTemperature;
[FieldOffset(636)]
public float batteryVoltage;
[FieldOffset(640)]
public float lightsDashboard;
[FieldOffset(644)]
public float wearEngine;
[FieldOffset(648)]
public float wearTransmission;
[FieldOffset(652)]
public float wearCabin;
[FieldOffset(656)]
public float wearChassis;
[FieldOffset(660)]
public float wearWheels;
[FieldOffset(664)]
public float wearTrailer;
[FieldOffset(668)]
public float truckOdometer;
[FieldOffset(672)]
public float cruiseControlSpeed;
[FieldOffset(676)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] truckMake;
[FieldOffset(740)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] truckMakeId;
[FieldOffset(804)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] truckModel;
// ***** REVISION 4 ****** //
[FieldOffset(868)]
public float speedLimit;
[FieldOffset(872)]
public float routeDistance;
[FieldOffset(876)]
public float routeTime;
[FieldOffset(880)]
public float fuelRange;
[FieldOffset(884)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
public float[] gearRatioForward;
[FieldOffset(980)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public float[] gearRatioReverse;
[FieldOffset(1012)]
public float gearRatioDifferential;
[FieldOffset(1016)]
public int gearDashboard;
[FieldOffset(1020)] public byte onJob;
[FieldOffset(1021)] public byte jobFinished;
public bool GetBool(Ets2SdkBoolean i)
{
if (i == Ets2SdkBoolean.TrailerAttached)
return flags[1] > 0;
return aux[(int)i] > 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Shipping;
using Nop.Core.Plugins;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Events;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Orders;
using Nop.Services.Shipping.Pickup;
namespace Nop.Services.Shipping
{
/// <summary>
/// Shipping service
/// </summary>
public partial class ShippingService : IShippingService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : warehouse ID
/// </remarks>
private const string WAREHOUSES_BY_ID_KEY = "Nop.warehouse.id-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string WAREHOUSES_PATTERN_KEY = "Nop.warehouse.";
#endregion
#region Fields
private readonly IRepository<ShippingMethod> _shippingMethodRepository;
private readonly IRepository<Warehouse> _warehouseRepository;
private readonly ILogger _logger;
private readonly IProductService _productService;
private readonly IProductAttributeParser _productAttributeParser;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ILocalizationService _localizationService;
private readonly IAddressService _addressService;
private readonly ShippingSettings _shippingSettings;
private readonly IPluginFinder _pluginFinder;
private readonly IStoreContext _storeContext;
private readonly IEventPublisher _eventPublisher;
private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="shippingMethodRepository">Shipping method repository</param>
/// <param name="warehouseRepository">Warehouse repository</param>
/// <param name="logger">Logger</param>
/// <param name="productService">Product service</param>
/// <param name="productAttributeParser">Product attribute parser</param>
/// <param name="checkoutAttributeParser">Checkout attribute parser</param>
/// <param name="genericAttributeService">Generic attribute service</param>
/// <param name="localizationService">Localization service</param>
/// <param name="addressService">Address service</param>
/// <param name="shippingSettings">Shipping settings</param>
/// <param name="pluginFinder">Plugin finder</param>
/// <param name="storeContext">Store context</param>
/// <param name="eventPublisher">Event published</param>
/// <param name="shoppingCartSettings">Shopping cart settings</param>
/// <param name="cacheManager">Cache manager</param>
public ShippingService(IRepository<ShippingMethod> shippingMethodRepository,
IRepository<Warehouse> warehouseRepository,
ILogger logger,
IProductService productService,
IProductAttributeParser productAttributeParser,
ICheckoutAttributeParser checkoutAttributeParser,
IGenericAttributeService genericAttributeService,
ILocalizationService localizationService,
IAddressService addressService,
ShippingSettings shippingSettings,
IPluginFinder pluginFinder,
IStoreContext storeContext,
IEventPublisher eventPublisher,
ShoppingCartSettings shoppingCartSettings,
ICacheManager cacheManager)
{
this._shippingMethodRepository = shippingMethodRepository;
this._warehouseRepository = warehouseRepository;
this._logger = logger;
this._productService = productService;
this._productAttributeParser = productAttributeParser;
this._checkoutAttributeParser = checkoutAttributeParser;
this._genericAttributeService = genericAttributeService;
this._localizationService = localizationService;
this._addressService = addressService;
this._shippingSettings = shippingSettings;
this._pluginFinder = pluginFinder;
this._storeContext = storeContext;
this._eventPublisher = eventPublisher;
this._shoppingCartSettings = shoppingCartSettings;
this._cacheManager = cacheManager;
}
#endregion
#region Utilities
/// <summary>
/// Check whether there are multiple package items in the cart for the delivery
/// </summary>
/// <param name="items">Package items</param>
/// <returns>True if there are multiple items; otherwise false</returns>
protected bool AreMultipleItems(IList<GetShippingOptionRequest.PackageItem> items)
{
//no items
if (!items.Any())
return false;
//more than one
if (items.Count > 1)
return true;
//or single item
var singleItem = items.First();
//but quantity more than one
if (singleItem.GetQuantity() > 1)
return true;
//one item with quantity is one and without attributes
if (string.IsNullOrEmpty(singleItem.ShoppingCartItem.AttributesXml))
return false;
//find associated products of item
var associatedAttributeValues = _productAttributeParser.ParseProductAttributeValues(singleItem.ShoppingCartItem.AttributesXml)
.Where(attributeValue => attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct);
//whether to ship associated products
return associatedAttributeValues.Any(attributeValue =>
_productService.GetProductById(attributeValue.AssociatedProductId).Return(product => product.IsShipEnabled, false));
}
#endregion
#region Methods
#region Shipping rate computation methods
/// <summary>
/// Load active shipping rate computation methods
/// </summary>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Shipping rate computation methods</returns>
public virtual IList<IShippingRateComputationMethod> LoadActiveShippingRateComputationMethods(Customer customer = null, int storeId = 0)
{
return LoadAllShippingRateComputationMethods(customer, storeId)
.Where(provider => _shippingSettings.ActiveShippingRateComputationMethodSystemNames
.Contains(provider.PluginDescriptor.SystemName, StringComparer.InvariantCultureIgnoreCase)).ToList();
}
/// <summary>
/// Load shipping rate computation method by system name
/// </summary>
/// <param name="systemName">System name</param>
/// <returns>Found Shipping rate computation method</returns>
public virtual IShippingRateComputationMethod LoadShippingRateComputationMethodBySystemName(string systemName)
{
var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IShippingRateComputationMethod>(systemName);
if (descriptor != null)
return descriptor.Instance<IShippingRateComputationMethod>();
return null;
}
/// <summary>
/// Load all shipping rate computation methods
/// </summary>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Shipping rate computation methods</returns>
public virtual IList<IShippingRateComputationMethod> LoadAllShippingRateComputationMethods(Customer customer = null, int storeId = 0)
{
return _pluginFinder.GetPlugins<IShippingRateComputationMethod>(customer: customer, storeId: storeId).ToList();
}
#endregion
#region Shipping methods
/// <summary>
/// Deletes a shipping method
/// </summary>
/// <param name="shippingMethod">The shipping method</param>
public virtual void DeleteShippingMethod(ShippingMethod shippingMethod)
{
if (shippingMethod == null)
throw new ArgumentNullException("shippingMethod");
_shippingMethodRepository.Delete(shippingMethod);
//event notification
_eventPublisher.EntityDeleted(shippingMethod);
}
/// <summary>
/// Gets a shipping method
/// </summary>
/// <param name="shippingMethodId">The shipping method identifier</param>
/// <returns>Shipping method</returns>
public virtual ShippingMethod GetShippingMethodById(int shippingMethodId)
{
if (shippingMethodId == 0)
return null;
return _shippingMethodRepository.GetById(shippingMethodId);
}
/// <summary>
/// Gets all shipping methods
/// </summary>
/// <param name="filterByCountryId">The country indentifier to filter by</param>
/// <returns>Shipping methods</returns>
public virtual IList<ShippingMethod> GetAllShippingMethods(int? filterByCountryId = null)
{
if (filterByCountryId.HasValue && filterByCountryId.Value > 0)
{
var query1 = from sm in _shippingMethodRepository.Table
where
sm.RestrictedCountries.Select(c => c.Id).Contains(filterByCountryId.Value)
select sm.Id;
var query2 = from sm in _shippingMethodRepository.Table
where !query1.Contains(sm.Id)
orderby sm.DisplayOrder, sm.Id
select sm;
var shippingMethods = query2.ToList();
return shippingMethods;
}
else
{
var query = from sm in _shippingMethodRepository.Table
orderby sm.DisplayOrder, sm.Id
select sm;
var shippingMethods = query.ToList();
return shippingMethods;
}
}
/// <summary>
/// Inserts a shipping method
/// </summary>
/// <param name="shippingMethod">Shipping method</param>
public virtual void InsertShippingMethod(ShippingMethod shippingMethod)
{
if (shippingMethod == null)
throw new ArgumentNullException("shippingMethod");
_shippingMethodRepository.Insert(shippingMethod);
//event notification
_eventPublisher.EntityInserted(shippingMethod);
}
/// <summary>
/// Updates the shipping method
/// </summary>
/// <param name="shippingMethod">Shipping method</param>
public virtual void UpdateShippingMethod(ShippingMethod shippingMethod)
{
if (shippingMethod == null)
throw new ArgumentNullException("shippingMethod");
_shippingMethodRepository.Update(shippingMethod);
//event notification
_eventPublisher.EntityUpdated(shippingMethod);
}
#endregion
#region Warehouses
/// <summary>
/// Deletes a warehouse
/// </summary>
/// <param name="warehouse">The warehouse</param>
public virtual void DeleteWarehouse(Warehouse warehouse)
{
if (warehouse == null)
throw new ArgumentNullException("warehouse");
_warehouseRepository.Delete(warehouse);
//clear cache
_cacheManager.RemoveByPattern(WAREHOUSES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(warehouse);
}
/// <summary>
/// Gets a warehouse
/// </summary>
/// <param name="warehouseId">The warehouse identifier</param>
/// <returns>Warehouse</returns>
public virtual Warehouse GetWarehouseById(int warehouseId)
{
if (warehouseId == 0)
return null;
string key = string.Format(WAREHOUSES_BY_ID_KEY, warehouseId);
return _cacheManager.Get(key, () => _warehouseRepository.GetById(warehouseId));
}
/// <summary>
/// Gets all warehouses
/// </summary>
/// <returns>Warehouses</returns>
public virtual IList<Warehouse> GetAllWarehouses()
{
var query = from wh in _warehouseRepository.Table
orderby wh.Name
select wh;
var warehouses = query.ToList();
return warehouses;
}
/// <summary>
/// Inserts a warehouse
/// </summary>
/// <param name="warehouse">Warehouse</param>
public virtual void InsertWarehouse(Warehouse warehouse)
{
if (warehouse == null)
throw new ArgumentNullException("warehouse");
_warehouseRepository.Insert(warehouse);
//clear cache
_cacheManager.RemoveByPattern(WAREHOUSES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(warehouse);
}
/// <summary>
/// Updates the warehouse
/// </summary>
/// <param name="warehouse">Warehouse</param>
public virtual void UpdateWarehouse(Warehouse warehouse)
{
if (warehouse == null)
throw new ArgumentNullException("warehouse");
_warehouseRepository.Update(warehouse);
//clear cache
_cacheManager.RemoveByPattern(WAREHOUSES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(warehouse);
}
#endregion
#region Pickup points
/// <summary>
/// Load active pickup point providers
/// </summary>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Pickup point providers</returns>
public virtual IList<IPickupPointProvider> LoadActivePickupPointProviders(Customer customer = null, int storeId = 0)
{
return LoadAllPickupPointProviders(customer, storeId).Where(provider => _shippingSettings.ActivePickupPointProviderSystemNames
.Contains(provider.PluginDescriptor.SystemName, StringComparer.InvariantCultureIgnoreCase)).ToList();
}
/// <summary>
/// Load pickup point provider by system name
/// </summary>
/// <param name="systemName">System name</param>
/// <returns>Found pickup point provider</returns>
public virtual IPickupPointProvider LoadPickupPointProviderBySystemName(string systemName)
{
var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IPickupPointProvider>(systemName);
if (descriptor != null)
return descriptor.Instance<IPickupPointProvider>();
return null;
}
/// <summary>
/// Load all pickup point providers
/// </summary>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Pickup point providers</returns>
public virtual IList<IPickupPointProvider> LoadAllPickupPointProviders(Customer customer = null, int storeId = 0)
{
return _pluginFinder.GetPlugins<IPickupPointProvider>(customer: customer, storeId: storeId).ToList();
}
#endregion
#region Workflow
/// <summary>
/// Gets shopping cart item weight (of one item)
/// </summary>
/// <param name="shoppingCartItem">Shopping cart item</param>
/// <returns>Shopping cart item weight</returns>
public virtual decimal GetShoppingCartItemWeight(ShoppingCartItem shoppingCartItem)
{
if (shoppingCartItem == null)
throw new ArgumentNullException("shoppingCartItem");
if (shoppingCartItem.Product == null)
return decimal.Zero;
//attribute weight
decimal attributesTotalWeight = decimal.Zero;
if (_shippingSettings.ConsiderAssociatedProductsDimensions && !String.IsNullOrEmpty(shoppingCartItem.AttributesXml))
{
var attributeValues = _productAttributeParser.ParseProductAttributeValues(shoppingCartItem.AttributesXml);
foreach (var attributeValue in attributeValues)
{
switch (attributeValue.AttributeValueType)
{
case AttributeValueType.Simple:
{
//simple attribute
attributesTotalWeight += attributeValue.WeightAdjustment;
}
break;
case AttributeValueType.AssociatedToProduct:
{
//bundled product
var associatedProduct = _productService.GetProductById(attributeValue.AssociatedProductId);
if (associatedProduct != null && associatedProduct.IsShipEnabled)
{
attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;
}
}
break;
}
}
}
var weight = shoppingCartItem.Product.Weight + attributesTotalWeight;
return weight;
}
/// <summary>
/// Gets shopping cart weight
/// </summary>
/// <param name="request">Request</param>
/// <param name="includeCheckoutAttributes">A value indicating whether we should calculate weights of selected checkotu attributes</param>
/// <returns>Total weight</returns>
public virtual decimal GetTotalWeight(GetShippingOptionRequest request, bool includeCheckoutAttributes = true)
{
if (request == null)
throw new ArgumentNullException("request");
Customer customer = request.Customer;
decimal totalWeight = decimal.Zero;
//shopping cart items
foreach (var packageItem in request.Items)
totalWeight += GetShoppingCartItemWeight(packageItem.ShoppingCartItem) * packageItem.GetQuantity();
//checkout attributes
if (customer != null && includeCheckoutAttributes)
{
var checkoutAttributesXml = customer.GetAttribute<string>(SystemCustomerAttributeNames.CheckoutAttributes, _genericAttributeService, _storeContext.CurrentStore.Id);
if (!String.IsNullOrEmpty(checkoutAttributesXml))
{
var attributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(checkoutAttributesXml);
foreach (var attributeValue in attributeValues)
totalWeight += attributeValue.WeightAdjustment;
}
}
return totalWeight;
}
/// <summary>
/// Get dimensions of associated products (for quantity 1)
/// </summary>
/// <param name="shoppingCartItem">Shopping cart item</param>
/// <param name="width">Width</param>
/// <param name="length">Length</param>
/// <param name="height">Height</param>
public virtual void GetAssociatedProductDimensions(ShoppingCartItem shoppingCartItem,
out decimal width, out decimal length, out decimal height)
{
if (shoppingCartItem == null)
throw new ArgumentNullException("shoppingCartItem");
width = length = height = decimal.Zero;
//don't consider associated products dimensions
if (!_shippingSettings.ConsiderAssociatedProductsDimensions)
return;
//attributes
if (String.IsNullOrEmpty(shoppingCartItem.AttributesXml))
return;
//bundled products (associated attributes)
var attributeValues = _productAttributeParser.ParseProductAttributeValues(shoppingCartItem.AttributesXml)
.Where(x => x.AttributeValueType == AttributeValueType.AssociatedToProduct)
.ToList();
foreach (var attributeValue in attributeValues)
{
var associatedProduct = _productService.GetProductById(attributeValue.AssociatedProductId);
if (associatedProduct != null && associatedProduct.IsShipEnabled)
{
width += associatedProduct.Width*attributeValue.Quantity;
length += associatedProduct.Length * attributeValue.Quantity;
height += associatedProduct.Height*attributeValue.Quantity;
}
}
}
/// <summary>
/// Get total dimensions
/// </summary>
/// <param name="packageItems">Package items</param>
/// <param name="width">Width</param>
/// <param name="length">Length</param>
/// <param name="height">Height</param>
public virtual void GetDimensions(IList<GetShippingOptionRequest.PackageItem> packageItems,
out decimal width, out decimal length, out decimal height)
{
if (packageItems == null)
throw new ArgumentNullException("packageItems");
//calculate cube root of volume, in case if the number of items more than 1
if (_shippingSettings.UseCubeRootMethod && AreMultipleItems(packageItems))
{
//find max dimensions of items
var maxWidth = packageItems.Max(item => item.ShoppingCartItem.Product.Width);
var maxLength = packageItems.Max(item => item.ShoppingCartItem.Product.Length);
var maxHeight = packageItems.Max(item => item.ShoppingCartItem.Product.Height);
//get total volume
var totalVolume = packageItems.Sum(packageItem =>
{
//product volume
var productVolume = packageItem.ShoppingCartItem.Product.Width *
packageItem.ShoppingCartItem.Product.Length * packageItem.ShoppingCartItem.Product.Height;
//associated products volume
if (_shippingSettings.ConsiderAssociatedProductsDimensions && !string.IsNullOrEmpty(packageItem.ShoppingCartItem.AttributesXml))
{
productVolume += _productAttributeParser.ParseProductAttributeValues(packageItem.ShoppingCartItem.AttributesXml)
.Where(attributeValue => attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct).Sum(attributeValue =>
{
var associatedProduct = _productService.GetProductById(attributeValue.AssociatedProductId);
if (associatedProduct == null || !associatedProduct.IsShipEnabled)
return 0;
//adjust max dimensions
maxWidth = Math.Max(maxWidth, associatedProduct.Width);
maxLength = Math.Max(maxLength, associatedProduct.Length);
maxHeight = Math.Max(maxHeight, associatedProduct.Height);
return attributeValue.Quantity * associatedProduct.Width * associatedProduct.Length * associatedProduct.Height;
});
}
//total volume of item
return productVolume * packageItem.GetQuantity();
});
//set dimensions as cube root of volume
width = length = height = Convert.ToDecimal(Math.Pow(Convert.ToDouble(totalVolume), (1.0 / 3.0)));
//sometimes we have products with sizes like 1x1x20
//that's why let's ensure that a maximum dimension is always preserved
//otherwise, shipping rate computation methods can return low rates
width = Math.Max(width, maxWidth);
length = Math.Max(length, maxLength);
height = Math.Max(height, maxHeight);
}
else
{
//summarize all values (very inaccurate with multiple items)
width = length = height = decimal.Zero;
foreach (var packageItem in packageItems)
{
//associated products
decimal associatedProductsWidth;
decimal associatedProductsLength;
decimal associatedProductsHeight;
GetAssociatedProductDimensions(packageItem.ShoppingCartItem,
out associatedProductsWidth, out associatedProductsLength, out associatedProductsHeight);
var quantity = packageItem.GetQuantity();
width += (packageItem.ShoppingCartItem.Product.Width + associatedProductsWidth) * quantity;
length += (packageItem.ShoppingCartItem.Product.Length + associatedProductsLength) * quantity;
height += (packageItem.ShoppingCartItem.Product.Height + associatedProductsHeight) * quantity;
}
}
}
/// <summary>
/// Get the nearest warehouse for the specified address
/// </summary>
/// <param name="address">Address</param>
/// <param name="warehouses">List of warehouses, if null all warehouses are used.</param>
/// <returns></returns>
public virtual Warehouse GetNearestWarehouse(Address address, IList<Warehouse> warehouses = null)
{
warehouses = warehouses ?? GetAllWarehouses();
//no address specified. return any
if (address == null)
return warehouses.FirstOrDefault();
//of course, we should use some better logic to find nearest warehouse
//but we don't have a built-in geographic database which supports "distance" functionality
//that's why we simply look for exact matches
//find by country
var matchedByCountry = new List<Warehouse>();
foreach (var warehouse in warehouses)
{
var warehouseAddress = _addressService.GetAddressById(warehouse.AddressId);
if (warehouseAddress != null)
if (warehouseAddress.CountryId == address.CountryId)
matchedByCountry.Add(warehouse);
}
//no country matches. return any
if (!matchedByCountry.Any())
return warehouses.FirstOrDefault();
//find by state
var matchedByState = new List<Warehouse>();
foreach (var warehouse in matchedByCountry)
{
var warehouseAddress = _addressService.GetAddressById(warehouse.AddressId);
if (warehouseAddress != null)
if (warehouseAddress.StateProvinceId == address.StateProvinceId)
matchedByState.Add(warehouse);
}
if (matchedByState.Any())
return matchedByState.FirstOrDefault();
//no state matches. return any
return matchedByCountry.FirstOrDefault();
}
/// <summary>
/// Create shipment packages (requests) from shopping cart
/// </summary>
/// <param name="cart">Shopping cart</param>
/// <param name="shippingAddress">Shipping address</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <param name="shippingFromMultipleLocations">Value indicating whether shipping is done from multiple locations (warehouses)</param>
/// <returns>Shipment packages (requests)</returns>
public virtual IList<GetShippingOptionRequest> CreateShippingOptionRequests(IList<ShoppingCartItem> cart,
Address shippingAddress, int storeId, out bool shippingFromMultipleLocations)
{
//if we always ship from the default shipping origin, then there's only one request
//if we ship from warehouses ("ShippingSettings.UseWarehouseLocation" enabled),
//then there could be several requests
//key - warehouse identifier (0 - default shipping origin)
//value - request
var requests = new Dictionary<int, GetShippingOptionRequest>();
//a list of requests with products which should be shipped separately
var separateRequests = new List<GetShippingOptionRequest>();
foreach (var sci in cart)
{
if (!sci.IsShipEnabled)
continue;
var product = sci.Product;
//warehouses
Warehouse warehouse = null;
if (_shippingSettings.UseWarehouseLocation)
{
if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
product.UseMultipleWarehouses)
{
var allWarehouses = new List<Warehouse>();
//multiple warehouses supported
foreach (var pwi in product.ProductWarehouseInventory)
{
//TODO validate stock quantity when backorder is not allowed?
var tmpWarehouse = GetWarehouseById(pwi.WarehouseId);
if (tmpWarehouse != null)
allWarehouses.Add(tmpWarehouse);
}
warehouse = GetNearestWarehouse(shippingAddress, allWarehouses);
}
else
{
//multiple warehouses are not supported
warehouse = GetWarehouseById(product.WarehouseId);
}
}
int warehouseId = warehouse != null ? warehouse.Id : 0;
if (requests.ContainsKey(warehouseId) && !product.ShipSeparately)
{
//add item to existing request
requests[warehouseId].Items.Add(new GetShippingOptionRequest.PackageItem(sci));
}
else
{
//create a new request
var request = new GetShippingOptionRequest();
//store
request.StoreId = storeId;
//add item
request.Items.Add(new GetShippingOptionRequest.PackageItem(sci));
//customer
request.Customer = cart.GetCustomer();
//ship to
request.ShippingAddress = shippingAddress;
//ship from
Address originAddress = null;
if (warehouse != null)
{
//warehouse address
originAddress = _addressService.GetAddressById(warehouse.AddressId);
request.WarehouseFrom = warehouse;
}
if (originAddress == null)
{
//no warehouse address. in this case use the default shipping origin
originAddress = _addressService.GetAddressById(_shippingSettings.ShippingOriginAddressId);
}
if (originAddress != null)
{
request.CountryFrom = originAddress.Country;
request.StateProvinceFrom = originAddress.StateProvince;
request.ZipPostalCodeFrom = originAddress.ZipPostalCode;
request.CityFrom = originAddress.City;
request.AddressFrom = originAddress.Address1;
}
if (product.ShipSeparately)
{
//ship separately
separateRequests.Add(request);
}
else
{
//usual request
requests.Add(warehouseId, request);
}
}
}
//multiple locations?
//currently we just compare warehouses
//but we should also consider cases when several warehouses are located in the same address
shippingFromMultipleLocations = requests.Select(x => x.Key).Distinct().Count() > 1;
var result = requests.Values.ToList();
result.AddRange(separateRequests);
return result;
}
/// <summary>
/// Gets available shipping options
/// </summary>
/// <param name="cart">Shopping cart</param>
/// <param name="shippingAddress">Shipping address</param>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="allowedShippingRateComputationMethodSystemName">Filter by shipping rate computation method identifier; null to load shipping options of all shipping rate computation methods</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Shipping options</returns>
public virtual GetShippingOptionResponse GetShippingOptions(IList<ShoppingCartItem> cart,
Address shippingAddress, Customer customer = null, string allowedShippingRateComputationMethodSystemName = "",
int storeId = 0)
{
if (cart == null)
throw new ArgumentNullException("cart");
var result = new GetShippingOptionResponse();
//create a package
bool shippingFromMultipleLocations;
var shippingOptionRequests = CreateShippingOptionRequests(cart, shippingAddress, storeId, out shippingFromMultipleLocations);
result.ShippingFromMultipleLocations = shippingFromMultipleLocations;
var shippingRateComputationMethods = LoadActiveShippingRateComputationMethods(customer, storeId);
//filter by system name
if (!String.IsNullOrWhiteSpace(allowedShippingRateComputationMethodSystemName))
{
shippingRateComputationMethods = shippingRateComputationMethods
.Where(srcm => allowedShippingRateComputationMethodSystemName.Equals(srcm.PluginDescriptor.SystemName, StringComparison.InvariantCultureIgnoreCase))
.ToList();
}
if (!shippingRateComputationMethods.Any())
//throw new NopException("Shipping rate computation method could not be loaded");
return result;
//request shipping options from each shipping rate computation methods
foreach (var srcm in shippingRateComputationMethods)
{
//request shipping options (separately for each package-request)
IList<ShippingOption> srcmShippingOptions = null;
foreach (var shippingOptionRequest in shippingOptionRequests)
{
var getShippingOptionResponse = srcm.GetShippingOptions(shippingOptionRequest);
if (getShippingOptionResponse.Success)
{
//success
if (srcmShippingOptions == null)
{
//first shipping option request
srcmShippingOptions = getShippingOptionResponse.ShippingOptions;
}
else
{
//get shipping options which already exist for prior requested packages for this scrm (i.e. common options)
srcmShippingOptions = srcmShippingOptions
.Where(existingso => getShippingOptionResponse.ShippingOptions.Any(newso => newso.Name == existingso.Name))
.ToList();
//and sum the rates
foreach (var existingso in srcmShippingOptions)
{
existingso.Rate += getShippingOptionResponse
.ShippingOptions
.First(newso => newso.Name == existingso.Name)
.Rate;
}
}
}
else
{
//errors
foreach (string error in getShippingOptionResponse.Errors)
{
result.AddError(error);
_logger.Warning(string.Format("Shipping ({0}). {1}", srcm.PluginDescriptor.FriendlyName, error));
}
//clear the shipping options in this case
srcmShippingOptions = new List<ShippingOption>();
break;
}
}
//add this scrm's options to the result
if (srcmShippingOptions != null)
{
foreach (var so in srcmShippingOptions)
{
//set system name if not set yet
if (String.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName))
so.ShippingRateComputationMethodSystemName = srcm.PluginDescriptor.SystemName;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
so.Rate = RoundingHelper.RoundPrice(so.Rate);
result.ShippingOptions.Add(so);
}
}
}
if (_shippingSettings.ReturnValidOptionsIfThereAreAny)
{
//return valid options if there are any (no matter of the errors returned by other shipping rate compuation methods).
if (result.ShippingOptions.Any() && result.Errors.Any())
result.Errors.Clear();
}
//no shipping options loaded
if (!result.ShippingOptions.Any() && !result.Errors.Any())
result.Errors.Add(_localizationService.GetResource("Checkout.ShippingOptionCouldNotBeLoaded"));
return result;
}
/// <summary>
/// Gets available pickup points
/// </summary>
/// <param name="address">Address</param>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="providerSystemName">Filter by provider identifier; null to load pickup points of all providers</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Pickup points</returns>
public virtual GetPickupPointsResponse GetPickupPoints(Address address, Customer customer = null, string providerSystemName = null, int storeId = 0)
{
var result = new GetPickupPointsResponse();
var pickupPointsProviders = LoadActivePickupPointProviders(customer, storeId);
if (!string.IsNullOrEmpty(providerSystemName))
pickupPointsProviders = pickupPointsProviders
.Where(x => x.PluginDescriptor.SystemName.Equals(providerSystemName, StringComparison.InvariantCultureIgnoreCase)).ToList();
if (pickupPointsProviders.Count == 0)
return result;
var allPickupPoints = new List<PickupPoint>();
foreach (var provider in pickupPointsProviders)
{
var pickPointsResponse = provider.GetPickupPoints(address);
if (pickPointsResponse.Success)
allPickupPoints.AddRange(pickPointsResponse.PickupPoints);
else
{
foreach (string error in pickPointsResponse.Errors)
{
result.AddError(error);
_logger.Warning(string.Format("PickupPoints ({0}). {1}", provider.PluginDescriptor.FriendlyName, error));
}
}
}
//any pickup points is enough
if (allPickupPoints.Count > 0)
{
result.Errors.Clear();
result.PickupPoints = allPickupPoints;
}
return result;
}
#endregion
#endregion
}
}
| |
/*
* Muhimbi PDF
*
* Convert, Merge, Watermark, Secure and OCR files.
*
* OpenAPI spec version: 9.15
*
* 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;
namespace Muhimbi.PDF.Online.Client.Model
{
/// <summary>
/// Response data for OCRText operation
/// </summary>
[DataContract]
public partial class OcrOperationResponse : IEquatable<OcrOperationResponse>, IValidatableObject
{
/// <summary>
/// Operation result code.
/// </summary>
/// <value>Operation result code.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum ResultCodeEnum
{
/// <summary>
/// Enum Success for "Success"
/// </summary>
[EnumMember(Value = "Success")]
Success,
/// <summary>
/// Enum ProcessingError for "ProcessingError"
/// </summary>
[EnumMember(Value = "ProcessingError")]
ProcessingError,
/// <summary>
/// Enum SubscriptionNotFound for "SubscriptionNotFound"
/// </summary>
[EnumMember(Value = "SubscriptionNotFound")]
SubscriptionNotFound,
/// <summary>
/// Enum SubscriptionExpired for "SubscriptionExpired"
/// </summary>
[EnumMember(Value = "SubscriptionExpired")]
SubscriptionExpired,
/// <summary>
/// Enum ActivationPending for "ActivationPending"
/// </summary>
[EnumMember(Value = "ActivationPending")]
ActivationPending,
/// <summary>
/// Enum TrialExpired for "TrialExpired"
/// </summary>
[EnumMember(Value = "TrialExpired")]
TrialExpired,
/// <summary>
/// Enum OperationSizeExceeded for "OperationSizeExceeded"
/// </summary>
[EnumMember(Value = "OperationSizeExceeded")]
OperationSizeExceeded,
/// <summary>
/// Enum OperationsExceeded for "OperationsExceeded"
/// </summary>
[EnumMember(Value = "OperationsExceeded")]
OperationsExceeded,
/// <summary>
/// Enum InputFileTypeNotSupported for "InputFileTypeNotSupported"
/// </summary>
[EnumMember(Value = "InputFileTypeNotSupported")]
InputFileTypeNotSupported,
/// <summary>
/// Enum OutputFileTypeNotSupported for "OutputFileTypeNotSupported"
/// </summary>
[EnumMember(Value = "OutputFileTypeNotSupported")]
OutputFileTypeNotSupported,
/// <summary>
/// Enum OperationNotSupported for "OperationNotSupported"
/// </summary>
[EnumMember(Value = "OperationNotSupported")]
OperationNotSupported,
/// <summary>
/// Enum Accepted for "Accepted"
/// </summary>
[EnumMember(Value = "Accepted")]
Accepted,
/// <summary>
/// Enum AccessDenied for "AccessDenied"
/// </summary>
[EnumMember(Value = "AccessDenied")]
AccessDenied,
/// <summary>
/// Enum InvalidExtension for "InvalidExtension"
/// </summary>
[EnumMember(Value = "InvalidExtension")]
InvalidExtension
}
/// <summary>
/// Operation result code.
/// </summary>
/// <value>Operation result code.</value>
[DataMember(Name="result_code", EmitDefaultValue=false)]
public ResultCodeEnum? ResultCode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="OcrOperationResponse" /> class.
/// </summary>
/// <param name="OutText">Extracted OCRed text in plain text..</param>
/// <param name="BaseFileName">Name of the input file without the extension..</param>
/// <param name="ResultCode">Operation result code..</param>
/// <param name="ResultDetails">Operation result details..</param>
public OcrOperationResponse(string OutText = default(string), string BaseFileName = default(string), ResultCodeEnum? ResultCode = default(ResultCodeEnum?), string ResultDetails = default(string))
{
this.OutText = OutText;
this.BaseFileName = BaseFileName;
this.ResultCode = ResultCode;
this.ResultDetails = ResultDetails;
}
/// <summary>
/// Extracted OCRed text in plain text.
/// </summary>
/// <value>Extracted OCRed text in plain text.</value>
[DataMember(Name="out_text", EmitDefaultValue=false)]
public string OutText { get; set; }
/// <summary>
/// Name of the input file without the extension.
/// </summary>
/// <value>Name of the input file without the extension.</value>
[DataMember(Name="base_file_name", EmitDefaultValue=false)]
public string BaseFileName { get; set; }
/// <summary>
/// Operation result details.
/// </summary>
/// <value>Operation result details.</value>
[DataMember(Name="result_details", EmitDefaultValue=false)]
public string ResultDetails { 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 OcrOperationResponse {\n");
sb.Append(" OutText: ").Append(OutText).Append("\n");
sb.Append(" BaseFileName: ").Append(BaseFileName).Append("\n");
sb.Append(" ResultCode: ").Append(ResultCode).Append("\n");
sb.Append(" ResultDetails: ").Append(ResultDetails).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 OcrOperationResponse);
}
/// <summary>
/// Returns true if OcrOperationResponse instances are equal
/// </summary>
/// <param name="other">Instance of OcrOperationResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OcrOperationResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.OutText == other.OutText ||
this.OutText != null &&
this.OutText.Equals(other.OutText)
) &&
(
this.BaseFileName == other.BaseFileName ||
this.BaseFileName != null &&
this.BaseFileName.Equals(other.BaseFileName)
) &&
(
this.ResultCode == other.ResultCode ||
this.ResultCode != null &&
this.ResultCode.Equals(other.ResultCode)
) &&
(
this.ResultDetails == other.ResultDetails ||
this.ResultDetails != null &&
this.ResultDetails.Equals(other.ResultDetails)
);
}
/// <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.OutText != null)
hash = hash * 59 + this.OutText.GetHashCode();
if (this.BaseFileName != null)
hash = hash * 59 + this.BaseFileName.GetHashCode();
if (this.ResultCode != null)
hash = hash * 59 + this.ResultCode.GetHashCode();
if (this.ResultDetails != null)
hash = hash * 59 + this.ResultDetails.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Signum.Engine.Linq
{
internal class GroupEntityCleaner : DbExpressionVisitor
{
public static Expression Clean(Expression source)
{
GroupEntityCleaner pc = new GroupEntityCleaner();
return pc.Visit(source);
}
public override Expression Visit(Expression exp)
{
if (exp == null)
return null!;
if (exp.Type == typeof(Type))
return VisitType(exp);
else
return base.Visit(exp);
}
private Expression VisitType(Expression exp)
{
if (exp.NodeType == ExpressionType.Constant)
return exp;
return new TypeImplementedByAllExpression(QueryBinder.ExtractTypeId(exp));
}
protected internal override Expression VisitEntity(EntityExpression entity)
{
var newID = (PrimaryKeyExpression)Visit(entity.ExternalId);
return new EntityExpression(entity.Type, newID, null, null, null, null, null, entity.AvoidExpandOnRetrieving); // remove bindings
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.Coalesce)
{
if (node.Left.Type.IsLite() || node.Right.Type.IsLite())
return this.Visit(new LiteReferenceExpression(node.Type,
Expression.Coalesce(GetLiteEntity(node.Left), GetLiteEntity(node.Right)), null, false, false));
if (typeof(IEntity).IsAssignableFrom(node.Left.Type) || typeof(IEntity).IsAssignableFrom(node.Right.Type))
{
return this.CombineEntities(node.Left, node.Right, node.Type,
(l, r) => Expression.Coalesce(l, r),
(l, r) => Expression.Condition(Expression.NotEqual(node.Left, Expression.Constant(null, node.Left.Type)), l, r));
}
}
return base.VisitBinary(node);
}
protected override Expression VisitConditional(ConditionalExpression node)
{
if (node.IfTrue.Type.IsLite() || node.IfTrue.Type.IsLite())
return this.Visit(new LiteReferenceExpression(node.Type,
Expression.Condition(node.Test, GetLiteEntity(node.IfTrue), GetLiteEntity(node.IfFalse)), null, false, false));
if (typeof(IEntity).IsAssignableFrom(node.IfTrue.Type) || typeof(IEntity).IsAssignableFrom(node.IfFalse.Type))
{
return this.CombineEntities(node.IfTrue, node.IfFalse, node.Type,
(t, f) => Expression.Condition(node.Test, t, f));
}
return base.VisitConditional(node);
}
Expression CombineEntities(Expression a, Expression b, Type type, Func<Expression, Expression, Expression> combiner, Func<Expression, Expression, Expression>? combinerIB = null)
{
if (a is ImplementedByAllExpression || b is ImplementedByAllExpression)
return CombineIBA(ToIBA(a, type), ToIBA(b, type), type, combiner);
if (a is ImplementedByExpression || b is ImplementedByExpression)
return CombineIB(ToIB(a, type), ToIB(b, type), type, combinerIB ?? combiner);
if (a is EntityExpression || b is EntityExpression)
{
if (a.Type == b.Type)
return CombineEntity(ToEntity(a, type), ToEntity(b, type), type, combiner);
else
return CombineIB(ToIB(a, type), ToIB(b, type), type, combiner);
}
if (a.IsNull() || b.IsNull())
return a;
throw new UnexpectedValueException(a);
}
private ImplementedByAllExpression CombineIBA(ImplementedByAllExpression a, ImplementedByAllExpression b, Type type, Func<Expression, Expression, Expression> combiner)
{
return new ImplementedByAllExpression(type, combiner(a.Id, b.Id),
new TypeImplementedByAllExpression(new PrimaryKeyExpression(combiner(a.TypeId.TypeColumn, b.TypeId.TypeColumn))), null);
}
private ImplementedByExpression CombineIB(ImplementedByExpression a, ImplementedByExpression b, Type type, Func<Expression, Expression, Expression> combiner)
{
return new ImplementedByExpression(type, a.Strategy,
a.Implementations.OuterJoinDictionaryCC(b.Implementations,
(t, ia, ib) => CombineEntity(ia ?? NullEntity(t), ib ?? NullEntity(t), t, combiner)
));
}
private EntityExpression CombineEntity(EntityExpression a, EntityExpression b, Type type, Func<Expression, Expression, Expression> combiner)
{
return new EntityExpression(type, new PrimaryKeyExpression(combiner(a.ExternalId.Value, b.ExternalId.Value)), null, null, null, null, null, a.AvoidExpandOnRetrieving || b.AvoidExpandOnRetrieving);
}
ImplementedByAllExpression ToIBA(Expression node, Type type)
{
if (node.IsNull())
return new ImplementedByAllExpression(type,
Expression.Constant(null, typeof(string)),
new TypeImplementedByAllExpression(new PrimaryKeyExpression(Expression.Constant(null, PrimaryKey.Type(typeof(TypeEntity))))), null);
if (node is EntityExpression e)
return new ImplementedByAllExpression(type,
new SqlCastExpression(typeof(string), e.ExternalId.Value),
new TypeImplementedByAllExpression(new PrimaryKeyExpression(QueryBinder.TypeConstant(e.Type))), null);
if (node is ImplementedByExpression ib)
return new ImplementedByAllExpression(type,
new PrimaryKeyExpression(QueryBinder.Coalesce(ib.Implementations.Values.Select(a => a.ExternalId.ValueType.Nullify()).Distinct().SingleEx(), ib.Implementations.Select(e => e.Value.ExternalId))),
new TypeImplementedByAllExpression(new PrimaryKeyExpression(
ib.Implementations.Select(imp => new When(imp.Value.ExternalId.NotEqualsNulll(), QueryBinder.TypeConstant(imp.Key))).ToList()
.ToCondition(PrimaryKey.Type(typeof(TypeEntity)).Nullify()))), null);
if (node is ImplementedByAllExpression iba)
return iba;
throw new UnexpectedValueException(node);
}
ImplementedByExpression ToIB(Expression node, Type type)
{
if (node.IsNull())
return new ImplementedByExpression(type, CombineStrategy.Case, new Dictionary<Type, EntityExpression>());
if (node is EntityExpression e)
return new ImplementedByExpression(type, CombineStrategy.Case, new Dictionary<Type, EntityExpression> { { e.Type, e } });
if (node is ImplementedByExpression ib)
return ib;
throw new UnexpectedValueException(node);
}
EntityExpression ToEntity(Expression node, Type type)
{
if (node.IsNull())
return NullEntity(type);
if (node is EntityExpression e)
return e;
throw new UnexpectedValueException(node);
}
private static EntityExpression NullEntity(Type type)
{
return new EntityExpression(type, new PrimaryKeyExpression(Expression.Constant(null, PrimaryKey.Type(type).Nullify())), null, null, null, null, null, false);
}
private Expression GetLiteEntity(Expression lite)
{
if (lite is LiteReferenceExpression l)
return l.Reference;
if (lite.IsNull())
return Expression.Constant(null, lite.Type.CleanType());
if (lite is ConditionalExpression c)
return Expression.Condition(c.Test, GetLiteEntity(c.IfTrue), GetLiteEntity(c.IfFalse));
if (lite is BinaryExpression b && b.NodeType == ExpressionType.Coalesce)
return Expression.Coalesce(GetLiteEntity(b.Left), GetLiteEntity(b.Right));
throw new UnexpectedValueException(lite);
}
}
internal class DistinctEntityCleaner : DbExpressionVisitor
{
public static Expression Clean(Expression source)
{
DistinctEntityCleaner pc = new DistinctEntityCleaner();
return pc.Visit(source);
}
bool inLite = false;
protected internal override Expression VisitLiteReference(LiteReferenceExpression lite)
{
var oldInLite = inLite;
inLite = true;
var result = base.VisitLiteReference(lite);
inLite = oldInLite;
return result;
}
public override Expression Visit(Expression exp)
{
if (exp == null)
return null!;
if (exp.Type == typeof(Type))
return VisitType(exp);
else
return base.Visit(exp);
}
private Expression VisitType(Expression exp)
{
if (!inLite)
return exp;
if (exp.NodeType == ExpressionType.Constant)
return exp;
return new TypeImplementedByAllExpression(QueryBinder.ExtractTypeId(exp));
}
protected internal override Expression VisitEntity(EntityExpression entity)
{
if (!inLite)
return base.VisitEntity(entity);
var newID = (PrimaryKeyExpression)Visit(entity.ExternalId);
return new EntityExpression(entity.Type, newID, null, null, null, null, null, entity.AvoidExpandOnRetrieving); // remove bindings
}
}
}
| |
using System;
using Foundation;
using UIKit;
using System.CodeDom.Compiler;
using MessageUI;
using Microsoft.Office365.OutlookServices;
using FiveMinuteMeeting.Shared.ViewModels;
using CoreGraphics;
using CoreGraphics;
using FiveMinuteMeeting.Shared;
using SDWebImage;
namespace FiveMinuteMeeting.iOS
{
partial class ContactDetailViewController : UIViewController
{
public ContactDetailViewController(IntPtr handle)
: base(handle)
{
}
public DetailsViewModel ViewModel
{
get;
set;
}
UIBarButtonItem save;
public override void ViewDidLoad()
{
base.ViewDidLoad();
NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;
save = new UIBarButtonItem(UIBarButtonSystemItem.Save,
async (sender, args) =>
{
ViewModel.FirstName = TextFirst.Text.Trim();
ViewModel.LastName = TextLast.Text.Trim();
ViewModel.Email = TextEmail.Text.Trim();
ViewModel.Phone = TextPhone.Text.Trim();
BigTed.BTProgressHUD.Show("Saving contact...");
await ViewModel.SaveContact();
BigTed.BTProgressHUD.Dismiss();
NavigationController.PopToRootViewController(true);
});
TextEmail.ShouldReturn += ShouldReturn;
TextFirst.ShouldReturn += ShouldReturn;
TextPhone.ShouldReturn += ShouldReturn;
TextLast.ShouldReturn += ShouldReturn;
TextEmail.ValueChanged += (sender, args) =>
{
ImagePhoto.SetImage(
url: new NSUrl(Gravatar.GetURL(TextEmail.Text, 172)),
placeholder: UIImage.FromBundle("missing.png")
);
};
var color = new CGColor(17.0F / 255.0F, 113.0F / 255.0F, 197.0F / 255F);
TextEmail.Layer.BorderColor = color;
TextFirst.Layer.BorderColor = color;
TextPhone.Layer.BorderColor = color;
TextLast.Layer.BorderColor = color;
ButtonCall.Clicked += (sender, args) => PlaceCall();
NSNotificationCenter.DefaultCenter.AddObserver
(UIKeyboard.DidShowNotification, KeyBoardUpNotification);
// Keyboard Down
NSNotificationCenter.DefaultCenter.AddObserver
(UIKeyboard.WillHideNotification, KeyBoardDownNotification);
double min = Math.Min((float)ImagePhoto.Frame.Width, (float)ImagePhoto.Frame.Height);
ImagePhoto.Layer.CornerRadius = (float)(min / 2.0);
ImagePhoto.Layer.MasksToBounds = false;
ImagePhoto.Layer.BorderColor = new CGColor(1, 1, 1);
ImagePhoto.Layer.BorderWidth = 3;
ImagePhoto.ClipsToBounds = true;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (ViewModel == null)
{
ViewModel = new DetailsViewModel();
NavigationItem.RightBarButtonItem = save;
}
else
{
this.Title = ViewModel.FirstName;
TextEmail.Text = ViewModel.Email;
TextFirst.Text = ViewModel.FirstName;
TextLast.Text = ViewModel.LastName;
TextPhone.Text = ViewModel.Phone;
ImagePhoto.SetImage(
url: new NSUrl(Gravatar.GetURL(ViewModel.Contact.EmailAddresses[0].Address, 172)),
placeholder: UIImage.FromBundle("missing.png")
);
NavigationItem.RightBarButtonItem = null;
}
}
private bool ShouldReturn(UITextField field)
{
field.ResignFirstResponder();
return true;
}
private void PlaceCall()
{
var alertPrompt = new UIAlertView("Dial Number?",
"Do you want to call " + TextPhone.Text + "?",
null, "No", "Yes");
alertPrompt.Dismissed += (sender, e) =>
{
if ((int)e.ButtonIndex >= (int)alertPrompt.FirstOtherButtonIndex)
{
var url = new NSUrl("tel:" + TextPhone.Text);
if (!UIApplication.SharedApplication.OpenUrl(url))
{
var av = new UIAlertView("Not supported",
"Scheme 'tel:' is not supported on this device",
null,
"OK",
null);
av.Show();
}
else
{
UIApplication.SharedApplication.OpenUrl(url);
}
}
};
alertPrompt.Show();
}
/*private async void SendEmail()
{
var mailController = new MFMailComposeViewController();
mailController.SetToRecipients(new string[] { TextEmail.Text });
mailController.SetSubject("5 Minute Meeting");
mailController.SetMessageBody("We are having a 5 minute stand up tomorrow at this time! Check your calendar.", false);
mailController.Finished += (object s, MFComposeResultEventArgs args) =>
{
Console.WriteLine(args.Result.ToString());
args.Controller.DismissViewController(true, (Action)null);
};
PresentViewControllerAsync(mailController, true);
}*/
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
switch(segue.Identifier)
{
case "email":
{
var vc = segue.DestinationViewController as SendEmailViewController;
vc.ViewModel.FirstName = ViewModel.FirstName;
vc.ViewModel.LastName = ViewModel.LastName;
vc.ViewModel.Email = ViewModel.Email;
}
break;
case "meeting":
{
var vc = segue.DestinationViewController as NewEventDurationViewController;
vc.ViewModel.FirstName = ViewModel.FirstName;
vc.ViewModel.LastName = ViewModel.LastName;
vc.ViewModel.Email = ViewModel.Email;
}
break;
}
}
#region Keyboard
private UIView activeview; // Controller that activated the keyboard
private float scrollamount; // amount to scroll
private float bottom; // bottom point
private const float Offset = 68.0f; // extra offset
private bool moveViewUp; // which direction are we moving
private void KeyBoardDownNotification(NSNotification notification)
{
if (moveViewUp) { ScrollTheView(false); }
}
private void ScrollTheView(bool move)
{
// scroll the view up or down
UIView.BeginAnimations(string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration(0.3);
CGRect frame = (CGRect)View.Frame;
if (move)
{
frame.Y -= scrollamount;
}
else
{
frame.Y += scrollamount;
scrollamount = 0;
}
View.Frame = frame;
UIView.CommitAnimations();
}
private void KeyBoardUpNotification(NSNotification notification)
{
// get the keyboard size
var r = (CGRect)UIKeyboard.FrameBeginFromNotification((NSNotification)notification);
// Find what opened the keyboard
foreach (UIView view in this.View.Subviews)
{
if (view.IsFirstResponder)
activeview = view;
}
// Bottom of the controller = initial position + height + offset
bottom = ((float)activeview.Frame.Y + (float)activeview.Frame.Height + Offset);
// Calculate how far we need to scroll
scrollamount = ((float)r.Height - ((float)View.Frame.Size.Height - bottom));
// Perform the scrolling
if (scrollamount > 0)
{
moveViewUp = true;
ScrollTheView(moveViewUp);
}
else
{
moveViewUp = false;
}
}
#endregion
}
}
| |
// ***********************************************************************
// Assembly : OptimizationToolbox
// Author : campmatt
// Created : 01-28-2021
//
// Last Modified By : campmatt
// Last Modified On : 04-21-2021
// ***********************************************************************
// <copyright file="partiswarm.cs" company="OptimizationToolbox">
// Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using StarMathLib;
//Ref/Source: http://msdn.microsoft.com/en-us/magazine/hh335067.aspx
namespace OptimizationToolbox
{
/// <summary>
/// Class partiswarm.
/// Implements the <see cref="OptimizationToolbox.abstractOptMethod" />
/// </summary>
/// <seealso cref="OptimizationToolbox.abstractOptMethod" />
public class partiswarm : abstractOptMethod
{
//fields
/// <summary>
/// Gets the neighbor generator.
/// </summary>
/// <value>The neighbor generator.</value>
public abstractGenerator neighborGenerator { get; private set; }
/// <summary>
/// Gets the selector.
/// </summary>
/// <value>The selector.</value>
public abstractSelector selector { get; private set; }
/// <summary>
/// The number particles
/// </summary>
private readonly int numberParticles = 10;
/// <summary>
/// The number iterations
/// </summary>
private readonly int numberIterations = 100;
/// <summary>
/// The minimum x
/// </summary>
private readonly double minX = -25;
/// <summary>
/// The maximum x
/// </summary>
private readonly double maxX = 25;
/// <summary>
/// The best global fitness
/// </summary>
private double bestGlobalFitness = double.MaxValue;
/// <summary>
/// The x stars
/// </summary>
private List<double[]> xStars = new List<double[]>();
/// <summary>
/// The trial values
/// </summary>
private List<double[]> trialValues = new List<double[]>();
/// <summary>
/// The x d
/// </summary>
private double x_d = 0.0;
/// <summary>
/// The y d
/// </summary>
private double y_d = 0.0;
/// <summary>
/// The sliderindices
/// </summary>
private List<int> sliderindices = new List<int>();
/// <summary>
/// The minimum alpha step ratio
/// </summary>
private const double minAlphaStepRatio = 1e-6;
/// <summary>
/// The alpha star
/// </summary>
private double alphaStar;
/// <summary>
/// The dk
/// </summary>
private double[] dk;
/* fk is the value of f(xk). */
/// <summary>
/// The fk
/// </summary>
private double fk;
/// <summary>
/// The iteration
/// </summary>
private int iteration = 0;
/// <summary>
/// The trial trial
/// </summary>
private static SomeFunctions.Values trial_trial;
/// <summary>
/// The f value
/// </summary>
private static SomeFunctions.Values f_val;
/// <summary>
/// Initializes a new instance of the <see cref="partiswarm"/> class.
/// </summary>
public partiswarm()
{
RequiresObjectiveFunction = true;
ConstraintsSolvedWithPenalties = true;
InequalitiesConvertedToEqualities = false;
RequiresSearchDirectionMethod = false;
RequiresAnInitialPoint = true;
RequiresConvergenceCriteria = true;
RequiresFeasibleStartPoint = false;
RequiresDiscreteSpaceDescriptor = false;
RequiresLineSearchMethod = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="partiswarm"/> class.
/// </summary>
/// <param name="numberParticles">The number particles.</param>
/// <param name="numberIterations">The number iterations.</param>
/// <param name="maxX">The maximum x.</param>
/// <param name="minX">The minimum x.</param>
/// <param name="xStars">The x stars.</param>
/// <param name="trialValues">The trial values.</param>
/// <param name="bestGlobalFitness">The best global fitness.</param>
public partiswarm(int numberParticles, int numberIterations, double maxX, double minX, List<double[]> xStars, List<double[]> trialValues, double bestGlobalFitness = double.MaxValue)
: this()
{
this.numberIterations = numberIterations;
this.numberParticles = numberParticles;
this.maxX = maxX;
this.minX = minX;
this.bestGlobalFitness = bestGlobalFitness;
this.xStars = xStars; this.trialValues = trialValues;
}
/// <summary>
/// Initializes a new instance of the <see cref="partiswarm"/> class.
/// </summary>
/// <param name="numberParticles">The number particles.</param>
/// <param name="numberIterations">The number iterations.</param>
/// <param name="maxX">The maximum x.</param>
/// <param name="minX">The minimum x.</param>
/// <param name="x_d">The x d.</param>
/// <param name="y_d">The y d.</param>
/// <param name="sliderindices">The sliderindices.</param>
public partiswarm(int numberParticles, int numberIterations, double maxX, double minX, double x_d, double y_d, List<int> sliderindices)
: this()
{
this.numberIterations = numberIterations;
this.numberParticles = numberParticles;
this.maxX = maxX;
this.minX = minX;
this.x_d = x_d;
this.y_d = y_d;
this.sliderindices = sliderindices;
}
/// <summary>
/// Runs the specified optimization method. This includes the details
/// of the optimization method.
/// </summary>
/// <param name="xStar">The x star.</param>
/// <returns>System.Double.</returns>
protected override double run(out double[] xStar)
{
Particle[] swarm = new Particle[numberParticles];
trial_trial = new SomeFunctions.Values(x[0]);
trial_trial.addtoValues(x);
double[] bestGlobalPosition = new double[x.Length];
x.CopyTo(bestGlobalPosition, 0);
double minV = -1.0 * maxX;
double maxV = maxX;
Random ran = new Random();
var conjugateDirections = new List<double[]>();
for (int ij = 0; ij < n; ij++)
{
var direction = new double[n];
direction[ij] = 1;
conjugateDirections.Add(direction);
}
for (int i = 0; i < swarm.Length; ++i)
{ // initialize each Particle in the swarm
double[] randomPosition = new double[x.Length];
if (xStars.Count > 0)
{
if (i == 0)
x.CopyTo(randomPosition, 0);
else
{
for (int j = 0; j < randomPosition.Length; ++j)
{
double lo = minX;
double hi = maxX;
randomPosition[j] = (hi - lo) * x[j] + lo;
//randomPosition [j] = x [j]+(hi-lo)*ran.NextDouble();
randomPosition[j] = (hi - lo) * ran.NextDouble() + lo;
}
}
}
else
{
if (i == 0)
x.CopyTo(randomPosition, 0);
else
{
for (int j = 0; j < randomPosition.Length; ++j)
{
double lo = minX;
double hi = maxX;
//randomPosition [j] = (hi - lo) * x [j] + lo;
//randomPosition [j] = x [j]+(hi-lo)*ran.NextDouble();
randomPosition[j] = (hi - lo) * ran.NextDouble() + lo;
}
}
}
double fitness = calc_f(randomPosition);
f_val = new SomeFunctions.Values(fitness);
double[] randomVelocity = new double[x.Length];
for (int j = 0; j < randomVelocity.Length; ++j)
{
double lo = -1.0 * Math.Abs(maxX - minX);
double hi = Math.Abs(maxX - minX);
randomVelocity[j] = (hi - lo) * ran.NextDouble() + lo;
//randomVelocity [j] = (hi - lo) * x[j] + lo;
}
swarm[i] = new Particle(randomPosition, fitness, randomVelocity, randomPosition, fitness);
// does current Particle have global best position/solution?
if (swarm[i].fitness < bestGlobalFitness)
{
bestGlobalFitness = swarm[i].fitness;
swarm[i].position.CopyTo(bestGlobalPosition, 0);
}
}
double w = 0.729; // inertia weight. see http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=00870279
double c1 = 1.49445; // cognitive/local weight 1.49445
double c2 = 1.49445; // social/global weight
double r1, r2; // cognitive and social randomizations
while (notConverged(iteration, numEvals, bestGlobalFitness, bestGlobalPosition))
{
//SearchIO.output (iteration);
++iteration;
double[] newVelocity = new double[x.Length];
double[] newPosition = new double[x.Length];
double newFitness;
for (int i = 0; i < swarm.Length; ++i)
{ // each Particle
Particle currP = swarm[i];
for (int j = 0; j < currP.velocity.Length; ++j)
{ // each x value of the velocity
r1 = ran.NextDouble();
r2 = ran.NextDouble();
newVelocity[j] = w * (currP.velocity[j]) +
(c1 * r1 * (currP.bestPosition[j] - currP.position[j])) +
(c2 * r2 * (bestGlobalPosition[j] - currP.position[j]));
if (newVelocity[j] < (minV - 50.0))
//newVelocity [j] = minV;
newVelocity[j] = (maxV - minV) * ran.NextDouble() + minV;
else if (newVelocity[j] > (maxV + 50.0))
//newVelocity [j] = maxV;
newVelocity[j] = (maxV - minV) * ran.NextDouble() + minV;
}
newVelocity.CopyTo(currP.velocity, 0);
for (int j = 0; j < currP.position.Length; ++j)
{
newPosition[j] = currP.position[j] + newVelocity[j];
if (newPosition[j] < (minX - 50.0))
//newPosition [j] = minX;
newPosition[j] = (maxX - minX) * ran.NextDouble() + minX;
else if (newPosition[j] > (maxX + 50.0))
//newPosition [j] = maxX;
newPosition[j] = (maxX - minX) * ran.NextDouble() + minX;
}
// var trial = finddesiredPathrepeats (newPosition, x_d, y_d,sliderindices);
// trial.CopyTo (newPosition, 0);
newPosition.CopyTo(currP.position, 0);
newFitness = calc_f(newPosition);
f_val.addtoValues(newFitness);
//
currP.fitness = newFitness;
trial_trial.addtoValues(newPosition);
if (newFitness < currP.bestFitness)
{
newPosition.CopyTo(currP.bestPosition, 0);
currP.bestFitness = newFitness;
//SearchIO.output ("better than best fitness: " + newFitness);
}
if (newFitness < bestGlobalFitness)
{
newPosition.CopyTo(bestGlobalPosition, 0);
bestGlobalFitness = newFitness;
//SearchIO.output ("before golden section new fitness obtained : " + newFitness);
}
/*if (newFitness > bestGlobalFitness)*/
else
{
// var conjugateDirections1 = new List<double[]> ();
//
// for (int ij = 0; ij < n; ij++) {
// var direction = new double[n];
// direction [ij] = 1;
// conjugateDirections1.Add (direction);
//
// }
// var xinner11 = (double[])newPosition.Clone ();
// for (int ij = 0; ij < n; ij++) {
//
// var dk1 = conjugateDirections1 [ij];
// var xinner1 = xinner11;
// alphaStar = lineSearchMethod.findAlphaStar (xinner1, dk1, true);
// xinner1 = StarMath.add (xinner1, StarMath.multiply (alphaStar, dk1));
//
//
//
// //I have the new position, try to update the velocity now now
//
//
// for (int j = 0; j < newPosition.Length; ++j) {
// r1 = ran.NextDouble ();
// r2 = ran.NextDouble ();
//
// newVelocity [j] = w * (currP.velocity [j]) +
// (c1 * r1 * (currP.bestPosition [j] - xinner1 [j])) +
// (c2 * r2 * (bestGlobalPosition [j] - xinner1 [j]));
//
// if (newVelocity [j] < minV)
// newVelocity [j] = minV;
// else if (newVelocity [j] > maxV)
// newVelocity [j] = maxV;
// }
//
//
// var fNew = calc_f (xinner1);
// trial_trial.addtoValues (newPosition);
//
// if (fNew < newFitness) {
// newPosition.CopyTo (currP.position, 0);
// currP.fitness = fNew;
//
//
// if (fNew < currP.bestFitness) {
// xinner1.CopyTo (currP.bestPosition, 0);
// currP.bestFitness = fNew;
//
// //SearchIO.output ("Last after golden sectiom new fitness obtained : " + fNew);
// }
//
// if (fNew < bestGlobalFitness) {
// xinner1.CopyTo (bestGlobalPosition, 0);
// bestGlobalFitness = fNew;
//
// //SearchIO.output ("Last after golden sectiom new fitness obtained : " + fNew);
//
//
// }
// }
//
// }
// var initPoints11 = (double[])currP.position.Clone ();
// var new_tral11 = xStars;
// for (int l = 0; l < xStars.Count; l++) {
// new_tral11 [l] = StarMath.add (initPoints11, xStars [l]);
// }
////
// for (int j = 0; j < new_tral11.Count; j++) {
// //var trial = NelderMead (new_tral1 [j]);
// var f_star = calc_f (new_tral11 [j]);
// trial_trial.addtoValues (new_tral11 [j]);
//// new_tral11 [j].CopyTo (currP.position, 0);
//// currP.fitness = f_star;
// //trial_trial.addtoValues (trial);
//
// if (f_star < currP.bestFitness) {
// new_tral11 [j].CopyTo (currP.bestPosition, 0);
// currP.bestFitness = f_star;
// new_tral11 [j].CopyTo (currP.position, 0);
// currP.fitness = f_star;
// SearchIO.output ("neighbour search new currP best fitness obtained : " + f_star);
//// trial.CopyTo (currP.position, 0);
//// currP.fitness = f_star;
//
// }
////
// if (f_star < bestGlobalFitness) {
// new_tral11 [j].CopyTo (bestGlobalPosition, 0);
// bestGlobalFitness = f_star;
// new_tral11 [j].CopyTo (currP.position, 0);
// currP.fitness = f_star;
// SearchIO.output ("neighbour search best new global fitness obtained : " + f_star);
//// trial.CopyTo (currP.position, 0);
//// currP.fitness = f_star;
//
// }
////
//// }
//
// }
}
}
Console.WriteLine("bestGlobalFitness:" + bestGlobalFitness);
}
xStar = bestGlobalPosition;
fStar = bestGlobalFitness;
return fStar;
}
/// <summary>
/// Finddesireds the pathrepeats.
/// </summary>
/// <param name="vector">The vector.</param>
/// <param name="x_d">The x d.</param>
/// <param name="y_d">The y d.</param>
/// <param name="sliderindices">The sliderindices.</param>
/// <returns>System.Double[].</returns>
public double[] finddesiredPathrepeats(double[] vector, double x_d, double y_d, List<int> sliderindices)
{
var newPoints = new double[vector.GetLength(0)];
List<double> newvector = new List<double>();
for (int i = 0; i < vector.GetLength(0); i++)
{
bool isInList = sliderindices.IndexOf(i) != -1;
if (!isInList)
{
newvector.Add(vector[i]);
}
}
var vector1 = newvector.ToArray();
var numbercoord = (vector1.GetLength(0)) / 2;
var k = 0;
var x_coord = new double[numbercoord];
var y_coord = new double[numbercoord];
vector1.CopyTo(newPoints, 0);
Random rna = new Random();
for (int j = 0; j < vector1.GetLength(0); j = j + 2)
{
x_coord[k] = vector1[j];
y_coord[k] = vector1[j + 1];
k++;
}
k = 0;
//now I have the x-coor and y-coord separately
for (int j = 0; j < x_coord.GetLength(0); j++)
{
if (x_coord[j] == x_d)
{
if (y_coord[j] == y_d)
{
//then we have to form a different set of numbers
newPoints[j * 2] = (maxX - minX) * rna.NextDouble() + minX;
newPoints[j * 2 + 1] = (maxX - minX) * rna.NextDouble() + minX;
k = 1;
}
}
}
if (k == 1)
{
//have to copy to the original format
int p = 0;
List<double> newVector = new List<double>();
for (int i = 0; i < vector.GetLength(0); i++)
{
bool isInList = sliderindices.IndexOf(i) != -1;
if (!isInList)
{
newVector.Add(newPoints[p++]);
}
else
{
newVector.Add(vector[sliderindices[i]]);
}
}
var trialarray = newVector.ToArray();
return trialarray;
}
else
return vector;
}
/// <summary>
/// Gets or sets the trials.
/// </summary>
/// <value>The trials.</value>
public static SomeFunctions.Values Trials
{
get { return trial_trial; }
set { trial_trial = value; }
}
/// <summary>
/// Gets or sets the f value.
/// </summary>
/// <value>The f value.</value>
public static SomeFunctions.Values FVal
{
get { return f_val; }
set { f_val = value; }
}
}
/// <summary>
/// Class SomeFunctions. this is a stand-in for an adaptation of particle swarm from someone
/// else's rendition. Need to re-develop for use in OOT
/// </summary>
public class SomeFunctions
{
/// <summary>
/// Class Values.
/// </summary>
public class Values
{
/// <summary>
/// The fitness
/// </summary>
private double fitness;
/// <summary>
/// Initializes a new instance of the <see cref="Values"/> class.
/// </summary>
/// <param name="fitness">The fitness.</param>
public Values(double fitness)
{
this.fitness = fitness;
}
/// <summary>
/// Addtoes the values.
/// </summary>
/// <param name="newPosition">The new position.</param>
/// <exception cref="NotImplementedException"></exception>
internal void addtoValues(double[] newPosition)
{
throw new NotImplementedException();
}
/// <summary>
/// Addtoes the values.
/// </summary>
/// <param name="newFitness">The new fitness.</param>
/// <exception cref="NotImplementedException"></exception>
internal void addtoValues(double newFitness)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Class MyClass.
/// </summary>
internal class MyClass
{
/// <summary>
/// Generates the neighbors.
/// </summary>
/// <param name="xCopy">The x copy.</param>
/// <param name="meshSize">Size of the mesh.</param>
/// <param name="stepsize">The stepsize.</param>
/// <returns>IList<System.Double[]>.</returns>
/// <exception cref="NotImplementedException"></exception>
internal IList<double[]> generateNeighbors(double[] xCopy, double meshSize, double stepsize)
{
throw new NotImplementedException();
}
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections.Generic;
using Axiom.MathLib;
using Axiom.Graphics;
namespace Axiom.Animating {
/// <summary>
/// A key frame in an animation sequence defined by an AnimationTrack.
/// </summary>
/// <remarks>
/// This class can be used as a basis for all kinds of key frames.
/// The unifying principle is that multiple KeyFrames define an
/// animation sequence, with the exact state of the animation being an
/// interpolation between these key frames.
/// </remarks>
public class KeyFrame {
#region Protected member variables
/// <summary>
/// Time of this keyframe.
/// </summary>
public float time;
/// <summary>
/// Animation track that this key frame belongs to.
/// </summary>
protected AnimationTrack parentTrack;
#endregion Protected member variables
#region Constructors
/// <summary>
/// Creates a new keyframe with the specified time.
/// Should really be created by <see cref="AnimationTrack.CreateKeyFrame"/> instead.
/// </summary>
/// <param name="parent">Animation track that this keyframe belongs to.</param>
/// <param name="time">Time at which this keyframe begins.</param>
public KeyFrame(AnimationTrack parent, float time) {
this.parentTrack = parent;
this.time = time;
}
#endregion Constructors
#region Public properties
/// <summary>
/// Gets the time of this keyframe in the animation sequence.
/// </summary>
public float Time {
get {
return time;
}
}
#endregion
}
/// <summary>Specialised KeyFrame which stores any numeric value.</summary>
public class NumericKeyFrame : KeyFrame {
#region Protected member variables
/// <summary>
/// Object holding the numeric value
/// </summary>
protected Object numericValue;
#endregion Protected member variables
#region Constructors
/// <summary>
/// Creates a new keyframe with the specified time.
/// Should really be created by <see cref="AnimationTrack.CreateKeyFrame"/> instead.
/// </summary>
/// <param name="parent">Animation track that this keyframe belongs to.</param>
/// <param name="time">Time at which this keyframe begins.</param>
public NumericKeyFrame(AnimationTrack parent, float time) : base(parent, time) {}
#endregion
#region Public properties
/// <summary>
/// Gets the time of this keyframe in the animation sequence.
/// </summary>
public Object NumericValue {
get {
return numericValue;
}
set {
// hack for python scripting, which insists on passing in a double
NumericAnimationTrack tmpParent = parentTrack as NumericAnimationTrack;
if (tmpParent != null)
{
if (tmpParent.TargetAnimable.Type == AnimableType.Float)
{
if (value is double)
{
double d = (double)value;
float tmp = (float)d;
value = tmp;
}
else if (value is int)
{
int i = (int)value;
float tmp = (float)i;
value = tmp;
}
}
}
numericValue = value;
}
}
#endregion Public Properties
}
/// <summary>Specialised KeyFrame which stores a full transform.
/// The members are public, but any client that assigns to a
/// member instead of using the setter must call Changed()
/// </summary>
public class TransformKeyFrame : KeyFrame {
#region Protected member variables
/// <summary>
/// Translation at this keyframe.
/// </summary>
public Vector3 translate;
/// <summary>
/// Scale factor at this keyframe.
/// </summary>
public Vector3 scale;
/// <summary>
/// Rotation at this keyframe.
/// </summary>
public Quaternion rotation;
#endregion Protected member variables
#region Constructors
/// <summary>
/// Creates a new keyframe with the specified time.
/// Should really be created by <see cref="AnimationTrack.CreateKeyFrame"/> instead.
/// </summary>
/// <param name="parent">Animation track that this keyframe belongs to.</param>
/// <param name="time">Time at which this keyframe begins.</param>
public TransformKeyFrame(AnimationTrack parent, float time) : base(parent, time) {
translate.x = 0f;
translate.y = 0f;
translate.z = 0f;
scale.x = 1f;
scale.y = 1f;
scale.z = 1f;
rotation.w = 1f;
rotation.x = 1f;
rotation.y = 1f;
rotation.z = 1f;
}
#endregion Constructors
#region Public properties
/// <summary>
/// Sets the rotation applied by this keyframe.
/// Use Quaternion methods to convert from angle/axis or Matrix3 if
/// you don't like using Quaternions directly.
/// </summary>
public Quaternion Rotation {
get {
return rotation;
}
set {
rotation = value;
if(parentTrack != null) {
parentTrack.OnKeyFrameDataChanged();
}
}
}
/// <summary>
/// Sets the scaling factor applied by this keyframe to the animable
/// object at its time index.
/// beware of supplying zero values for any component of this
/// vector, it will scale the object to zero dimensions.
/// </summary>
public Vector3 Scale {
get {
return scale;
}
set {
scale = value;
if(parentTrack != null) {
parentTrack.OnKeyFrameDataChanged();
}
}
}
/// <summary>
/// Sets the translation associated with this keyframe.
/// </summary>
/// <remarks>
/// The translation factor affects how much the keyframe translates (moves) its animable
/// object at it's time index.
/// </remarks>
public Vector3 Translate {
get {
return translate;
}
set {
translate = value;
if(parentTrack != null) {
parentTrack.OnKeyFrameDataChanged();
}
}
}
/// <summary>
/// Let's the parentTrack know the frame has changed.
/// </summary>
public void Changed() {
if(parentTrack != null) {
parentTrack.OnKeyFrameDataChanged();
}
}
#endregion Public Properties
}
/// <summary>Reference to a pose at a given influence level</summary>
/// <remarks>
/// Each keyframe can refer to many poses each at a given influence level.
/// </remarks>
public struct PoseRef {
/// <summary>The linked pose index.</summary>
/// <remarks>
/// The Mesh contains all poses for all vertex data in one list, both
/// for the shared vertex data and the dedicated vertex data on submeshes.
/// The 'target' on the parent track must match the 'target' on the
/// linked pose.
/// </remarks>
public ushort poseIndex;
/// <summary>
/// Influence level of the linked pose.
/// 1.0 for full influence (full offset), 0.0 for no influence.
/// </summary>
public float influence;
public PoseRef(ushort poseIndex, float influence) {
this.poseIndex = poseIndex;
this.influence = influence;
}
public ushort PoseIndex {
get {
return poseIndex;
}
set {
poseIndex = value;
}
}
public float Influence {
get {
return influence;
}
set {
influence = value;
}
}
}
public class VertexMorphKeyFrame : KeyFrame {
#region Protected member variables
/// <summary>
/// A list of the pose references for this frame
/// </summary>
protected HardwareVertexBuffer vertexBuffer;
#endregion Protected member variables
#region Constructors
/// <summary>
/// Creates a new keyframe with the specified time.
/// Should really be created by <see cref="AnimationTrack.CreateKeyFrame"/> instead.
/// </summary>
/// <param name="parent">Animation track that this keyframe belongs to.</param>
/// <param name="time">Time at which this keyframe begins.</param>
public VertexMorphKeyFrame(AnimationTrack parent, float time) : base(parent, time) {}
#endregion Constructors
#region Public properties
/// <summary>
/// Gets or sets the vertex buffer
/// </summary>
public HardwareVertexBuffer VertexBuffer {
get {
return vertexBuffer;
}
set {
vertexBuffer = value;
}
}
#endregion
}
public class VertexPoseKeyFrame : KeyFrame {
#region Protected member variables
/// <summary>
/// A list of the pose references for this frame
/// </summary>
protected List<PoseRef> poseRefs = new List<PoseRef>();
#endregion Protected member variables
#region Constructors
/// <summary>
/// Creates a new keyframe with the specified time.
/// Should really be created by <see cref="AnimationTrack.CreateKeyFrame"/> instead.
/// </summary>
/// <param name="parent">Animation track that this keyframe belongs to.</param>
/// <param name="time">Time at which this keyframe begins.</param>
public VertexPoseKeyFrame(AnimationTrack parent, float time) : base(parent, time) {}
#endregion Constructors
#region Public properties
/// <summary>
/// Gets the time of this keyframe in the animation sequence.
/// </summary>
public List<PoseRef> PoseRefs {
get {
return poseRefs;
}
}
#endregion
#region Public Methods
/// <summary>Add a new pose reference.</summary>
public void AddPoseReference(ushort poseIndex, float influence) {
poseRefs.Add(new PoseRef(poseIndex, influence));
}
/// <summary>Update the influence of a pose reference.</summary>
public void UpdatePoseReference(ushort poseIndex, float influence) {
// Unfortunately, I can't modify PoseRef since it is a struct,
// and when I access the list elements, I get a copy.
// Because of this limitation, I remove and re-add the PoseRef
RemovePoseReference(poseIndex);
AddPoseReference(poseIndex, influence);
}
/// <summary>Remove reference to a given pose.</summary>
/// <param name="poseIndex">The pose index (not the index of the reference)</param>
public void RemovePoseReference(ushort poseIndex) {
for(int i=0; i<poseRefs.Count; i++) {
if (poseRefs[i].poseIndex == poseIndex) {
poseRefs.RemoveAt(i);
return;
}
}
}
/// <summary>Remove all pose references.</summary>
public void RemoveAllPoseReferences() {
poseRefs.Clear();
}
#endregion Public Methods
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client.Transport.Mqtt
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs.Mqtt.Packets;
using DotNetty.Transport.Channels;
using Microsoft.Azure.Devices.Client.Common;
using Microsoft.Azure.Devices.Client.Extensions;
static class Util
{
static class PacketIdGenerator
{
static ushort current = (ushort)new Random((int)DateTime.UtcNow.ToFileTimeUtc()).Next(0, ushort.MaxValue);
public static int Next()
{
unchecked
{
return current++;
}
}
}
static class IotHubWirePropertyNames
{
public const string AbsoluteExpiryTime = "$.exp";
public const string CorrelationId = "$.cid";
public const string MessageId = "$.mid";
public const string To = "$.to";
public const string UserId = "$.uid";
}
static class MessageSystemPropertyNames
{
public const string MessageId = "message-id";
public const string To = "to";
public const string ExpiryTimeUtc = "absolute-expiry-time";
public const string CorrelationId = "correlation-id";
public const string UserId = "user-id";
public const string Operation = "iothub-operation";
public const string Ack = "iothub-ack";
}
static readonly Dictionary<string, string> ToSystemPropertiesMap = new Dictionary<string, string>
{
{IotHubWirePropertyNames.AbsoluteExpiryTime, MessageSystemPropertyNames.ExpiryTimeUtc},
{IotHubWirePropertyNames.CorrelationId, MessageSystemPropertyNames.CorrelationId},
{IotHubWirePropertyNames.MessageId, MessageSystemPropertyNames.MessageId},
{IotHubWirePropertyNames.To, MessageSystemPropertyNames.To},
{IotHubWirePropertyNames.UserId, MessageSystemPropertyNames.UserId},
{MessageSystemPropertyNames.Operation, MessageSystemPropertyNames.Operation},
{MessageSystemPropertyNames.Ack, MessageSystemPropertyNames.Ack}
};
static readonly Dictionary<string, string> FromSystemPropertiesMap = new Dictionary<string, string>
{
{MessageSystemPropertyNames.ExpiryTimeUtc, IotHubWirePropertyNames.AbsoluteExpiryTime},
{MessageSystemPropertyNames.CorrelationId, IotHubWirePropertyNames.CorrelationId},
{MessageSystemPropertyNames.MessageId, IotHubWirePropertyNames.MessageId},
{MessageSystemPropertyNames.To, IotHubWirePropertyNames.To},
{MessageSystemPropertyNames.UserId, IotHubWirePropertyNames.UserId},
{MessageSystemPropertyNames.Operation, MessageSystemPropertyNames.Operation},
{MessageSystemPropertyNames.Ack, MessageSystemPropertyNames.Ack}
};
const char SegmentSeparatorChar = '/';
const char SingleSegmentWildcardChar = '+';
const char MultiSegmentWildcardChar = '#';
static readonly char[] WildcardChars = { MultiSegmentWildcardChar, SingleSegmentWildcardChar };
const string IotHubTrueString = "true";
const string SegmentSeparator = "/";
const int MaxPayloadSize = 0x3ffff;
public static bool CheckTopicFilterMatch(string topicName, string topicFilter)
{
int topicFilterIndex = 0;
int topicNameIndex = 0;
while (topicNameIndex < topicName.Length && topicFilterIndex < topicFilter.Length)
{
int wildcardIndex = topicFilter.IndexOfAny(WildcardChars, topicFilterIndex);
if (wildcardIndex == -1)
{
int matchLength = Math.Max(topicFilter.Length - topicFilterIndex, topicName.Length - topicNameIndex);
return string.Compare(topicFilter, topicFilterIndex, topicName, topicNameIndex, matchLength, StringComparison.Ordinal) == 0;
}
else
{
if (topicFilter[wildcardIndex] == MultiSegmentWildcardChar)
{
if (wildcardIndex == 0) // special case -- any topic name would match
{
return true;
}
else
{
int matchLength = wildcardIndex - topicFilterIndex - 1;
if (string.Compare(topicFilter, topicFilterIndex, topicName, topicNameIndex, matchLength, StringComparison.Ordinal) == 0
&& (topicName.Length == topicNameIndex + matchLength || (topicName.Length > topicNameIndex + matchLength && topicName[topicNameIndex + matchLength] == SegmentSeparatorChar)))
{
// paths match up till wildcard and either it is parent topic in hierarchy (one level above # specified) or any child topic under a matching parent topic
return true;
}
else
{
return false;
}
}
}
else
{
// single segment wildcard
int matchLength = wildcardIndex - topicFilterIndex;
if (matchLength > 0 && string.Compare(topicFilter, topicFilterIndex, topicName, topicNameIndex, matchLength, StringComparison.Ordinal) != 0)
{
return false;
}
topicNameIndex = topicName.IndexOf(SegmentSeparatorChar, topicNameIndex + matchLength);
topicFilterIndex = wildcardIndex + 1;
if (topicNameIndex == -1)
{
// there's no more segments following matched one
return topicFilterIndex == topicFilter.Length;
}
}
}
}
return topicFilterIndex == topicFilter.Length && topicNameIndex == topicName.Length;
}
public static QualityOfService DeriveQos(Message message, MqttTransportSettings config)
{
QualityOfService qos;
string qosValue;
if (message.Properties.TryGetValue(config.QoSPropertyName, out qosValue))
{
int qosAsInt;
if (int.TryParse(qosValue, out qosAsInt))
{
qos = (QualityOfService)qosAsInt;
if (qos > QualityOfService.ExactlyOnce)
{
qos = config.PublishToServerQoS;
}
}
else
{
qos = config.PublishToServerQoS;
}
}
else
{
qos = config.PublishToServerQoS;
}
return qos;
}
public static Message CompleteMessageFromPacket(Message message, PublishPacket packet, MqttTransportSettings mqttTransportSettings)
{
message.MessageId = Guid.NewGuid().ToString("N");
if (packet.RetainRequested)
{
message.Properties[mqttTransportSettings.RetainPropertyName] = IotHubTrueString;
}
if (packet.Duplicate)
{
message.Properties[mqttTransportSettings.DupPropertyName] = IotHubTrueString;
}
return message;
}
public static async Task<PublishPacket> ComposePublishPacketAsync(IChannelHandlerContext context, Message message, QualityOfService qos, string topicName)
{
var packet = new PublishPacket(qos, false, false);
packet.TopicName = PopulateMessagePropertiesFromMessage(topicName, message);
if (qos > QualityOfService.AtMostOnce)
{
int packetId = GetNextPacketId();
switch (qos)
{
case QualityOfService.AtLeastOnce:
packetId &= 0x7FFF; // clear 15th bit
break;
case QualityOfService.ExactlyOnce:
packetId |= 0x8000; // set 15th bit
break;
default:
throw new ArgumentOutOfRangeException(nameof(qos), qos, null);
}
packet.PacketId = packetId;
}
using (Stream payloadStream = message.GetBodyStream())
{
long streamLength = payloadStream.Length;
if (streamLength > MaxPayloadSize)
{
throw new InvalidOperationException($"Message size ({streamLength} bytes) is too big to process. Maximum allowed payload size is {MaxPayloadSize}");
}
int length = (int)streamLength;
IByteBuffer buffer = context.Channel.Allocator.Buffer(length, length);
await buffer.WriteBytesAsync(payloadStream, length);
Contract.Assert(buffer.ReadableBytes == length);
packet.Payload = buffer;
}
return packet;
}
public static async Task WriteMessageAsync(IChannelHandlerContext context, object message, Func<IChannelHandlerContext, Exception, bool> exceptionHandler)
{
try
{
await context.WriteAndFlushAsync(message);
}
catch (Exception ex)
{
if (!exceptionHandler(context, ex))
{
throw;
}
}
}
public static void PopulateMessagePropertiesFromPacket(Message message, PublishPacket publish)
{
message.LockToken = publish.QualityOfService == QualityOfService.AtLeastOnce ? publish.PacketId.ToString() : null;
Dictionary<string, string> properties = UrlEncodedDictionarySerializer.Deserialize(publish.TopicName, publish.TopicName.NthIndexOf('/', 0, 4));
foreach (KeyValuePair<string, string> property in properties)
{
string propertyName;
if (ToSystemPropertiesMap.TryGetValue(property.Key, out propertyName))
{
message.SystemProperties[propertyName] = ConvertToSystemProperty(property);
}
else
{
message.Properties[property.Key] = property.Value;
}
}
}
static string PopulateMessagePropertiesFromMessage(string topicName, Message message)
{
var systemProperties = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> property in message.SystemProperties)
{
string propertyName;
if (FromSystemPropertiesMap.TryGetValue(property.Key, out propertyName))
{
systemProperties[propertyName] = ConvertFromSystemProperties(property.Value);
}
}
string properties = UrlEncodedDictionarySerializer.Serialize(new ReadOnlyMergeDictionary<string, string>(systemProperties, message.Properties));
return topicName.EndsWith(SegmentSeparator, StringComparison.Ordinal) ? topicName + properties + SegmentSeparator : topicName + SegmentSeparator + properties;
}
static string ConvertFromSystemProperties(object systemProperty)
{
if (systemProperty is string)
{
return (string)systemProperty;
}
if (systemProperty is DateTime)
{
return ((DateTime)systemProperty).ToString("o", CultureInfo.InvariantCulture);
}
return systemProperty?.ToString();
}
static object ConvertToSystemProperty(KeyValuePair<string, string> property)
{
if (string.IsNullOrEmpty(property.Value))
{
return property.Value;
}
if (property.Key == IotHubWirePropertyNames.AbsoluteExpiryTime)
{
return DateTime.ParseExact(property.Value, "o", CultureInfo.InvariantCulture);
}
if (property.Key == MessageSystemPropertyNames.Ack)
{
return (DeliveryAcknowledgement)Enum.Parse(typeof(DeliveryAcknowledgement), property.Value, true);
}
return property.Value;
}
public static int GetNextPacketId()
{
return PacketIdGenerator.Next();
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace SFML
{
namespace Audio
{
////////////////////////////////////////////////////////////
/// <summary>
/// SoundStream is a streamed sound, ie. samples are acquired
/// while the sound is playing. Use it for big sounds that would
/// require hundreds of MB in memory (see Music),
/// or for streaming sound from the network
/// </summary>
////////////////////////////////////////////////////////////
public abstract class SoundStream : ObjectBase
{
////////////////////////////////////////////////////////////
/// <summary>
/// Default constructor
/// </summary>
////////////////////////////////////////////////////////////
public SoundStream() :
base(IntPtr.Zero)
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Play the sound stream
/// </summary>
////////////////////////////////////////////////////////////
public void Play()
{
sfSoundStream_Play(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Pause the sound stream
/// </summary>
////////////////////////////////////////////////////////////
public void Pause()
{
sfSoundStream_Pause(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Stop the sound stream
/// </summary>
////////////////////////////////////////////////////////////
public void Stop()
{
sfSoundStream_Stop(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Samples rate, in samples per second
/// </summary>
////////////////////////////////////////////////////////////
public uint SampleRate
{
get { return sfSoundStream_GetSampleRate(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Number of channels (1 = mono, 2 = stereo)
/// </summary>
////////////////////////////////////////////////////////////
public uint ChannelsCount
{
get { return sfSoundStream_GetChannelsCount(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Current status of the sound stream (see SoundStatus enum)
/// </summary>
////////////////////////////////////////////////////////////
public SoundStatus Status
{
get { return sfSoundStream_GetStatus(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Loop state of the sound stream. Default value is false
/// </summary>
////////////////////////////////////////////////////////////
public bool Loop
{
get { return sfSoundStream_GetLoop(This); }
set { sfSoundStream_SetLoop(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Pitch of the sound stream. Default value is 1
/// </summary>
////////////////////////////////////////////////////////////
public float Pitch
{
get { return sfSoundStream_GetPitch(This); }
set { sfSoundStream_SetPitch(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Volume of the sound stream, in range [0, 100]. Default value is 100
/// </summary>
////////////////////////////////////////////////////////////
public float Volume
{
get { return sfSoundStream_GetVolume(This); }
set { sfSoundStream_SetVolume(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// 3D position of the sound stream. Default value is (0, 0, 0)
/// </summary>
////////////////////////////////////////////////////////////
public Vector3 Position
{
get { Vector3 v; sfSoundStream_GetPosition(This, out v.X, out v.Y, out v.Z); return v; }
set { sfSoundStream_SetPosition(This, value.X, value.Y, value.Z); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Is the sound stream's position relative to the listener's position,
/// or is it absolute?
/// Default value is false (absolute)
/// </summary>
////////////////////////////////////////////////////////////
public bool RelativeToListener
{
get { return sfSoundStream_IsRelativeToListener(This); }
set { sfSoundStream_SetRelativeToListener(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Minimum distance of the sound stream. Closer than this distance,
/// the listener will hear the sound at its maximum volume.
/// The default value is 1
/// </summary>
////////////////////////////////////////////////////////////
public float MinDistance
{
get { return sfSoundStream_GetMinDistance(This); }
set { sfSoundStream_SetMinDistance(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Attenuation factor. The higher the attenuation, the
/// more the sound will be attenuated with distance from listener.
/// The default value is 1
/// </summary>
////////////////////////////////////////////////////////////
public float Attenuation
{
get { return sfSoundStream_GetAttenuation(This); }
set { sfSoundStream_SetAttenuation(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Current playing position, in seconds
/// </summary>
////////////////////////////////////////////////////////////
public float PlayingOffset
{
get { return sfSoundStream_GetPlayingOffset(This); }
set { sfSoundStream_SetPlayingOffset(This, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[SoundStream]" +
" SampleRate(" + SampleRate + ")" +
" ChannelsCount(" + ChannelsCount + ")" +
" Status(" + Status + ")" +
" Loop(" + Loop + ")" +
" Pitch(" + Pitch + ")" +
" Volume(" + Volume + ")" +
" Position(" + Position + ")" +
" RelativeToListener(" + RelativeToListener + ")" +
" MinDistance(" + MinDistance + ")" +
" Attenuation(" + Attenuation + ")" +
" PlayingOffset(" + PlayingOffset + ")";
}
////////////////////////////////////////////////////////////
/// <summary>
/// Set the audio stream parameters, you must call it before Play()
/// </summary>
/// <param name="sampleRate">Number of channels</param>
/// <param name="channelsCount">Sample rate, in samples per second</param>
////////////////////////////////////////////////////////////
protected void Initialize(uint channelsCount, uint sampleRate)
{
myGetDataCallback = new GetDataCallbackType(GetData);
mySeekCallback = new SeekCallbackType(Seek);
SetThis(sfSoundStream_Create(myGetDataCallback, mySeekCallback, channelsCount, sampleRate, IntPtr.Zero));
}
////////////////////////////////////////////////////////////
/// <summary>
/// Virtual function called each time new audio data is needed to feed the stream
/// </summary>
/// <param name="samples">Array of samples to fill for the stream</param>
/// <returns>True to continue playback, false to stop</returns>
////////////////////////////////////////////////////////////
protected abstract bool OnGetData(out short[] samples);
////////////////////////////////////////////////////////////
/// <summary>
/// Virtual function called to seek into the stream
/// </summary>
/// <param name="timeOffset">New position, expressed in seconds</param>
////////////////////////////////////////////////////////////
protected abstract void OnSeek(float timeOffset);
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfSoundStream_Destroy(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Structure mapping the C library arguments passed to the data callback
/// </summary>
////////////////////////////////////////////////////////////
[StructLayout(LayoutKind.Sequential)]
private struct Chunk
{
unsafe public short* samplesPtr;
public uint samplesCount;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Called each time new audio data is needed to feed the stream
/// </summary>
/// <param name="dataChunk">Data chunk to fill with new audio samples</param>
/// <param name="userData">User data -- unused</param>
/// <returns>True to continue playback, false to stop</returns>
////////////////////////////////////////////////////////////
private bool GetData(ref Chunk dataChunk, IntPtr userData)
{
if (OnGetData(out myTempBuffer))
{
unsafe
{
fixed (short* samplesPtr = myTempBuffer)
{
dataChunk.samplesPtr = samplesPtr;
dataChunk.samplesCount = (uint)myTempBuffer.Length;
}
}
return true;
}
else
{
return false;
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Called to seek in the stream
/// </summary>
/// <param name="timeOffset">New position, expressed in seconds</param>
/// <param name="userData">User data -- unused</param>
/// <returns>If false is returned, the playback is aborted</returns>
////////////////////////////////////////////////////////////
private void Seek(float timeOffset, IntPtr userData)
{
OnSeek(timeOffset);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool GetDataCallbackType(ref Chunk dataChunk, IntPtr UserData);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SeekCallbackType(float timeOffset, IntPtr UserData);
private GetDataCallbackType myGetDataCallback;
private SeekCallbackType mySeekCallback;
private short[] myTempBuffer;
#region Imports
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfSoundStream_Create(GetDataCallbackType OnGetData, SeekCallbackType OnSeek, uint ChannelsCount, uint SampleRate, IntPtr UserData);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_Destroy(IntPtr SoundStreamStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_Play(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_Pause(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_Stop(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern SoundStatus sfSoundStream_GetStatus(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfSoundStream_GetChannelsCount(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfSoundStream_GetSampleRate(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetLoop(IntPtr SoundStream, bool Loop);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetPitch(IntPtr SoundStream, float Pitch);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetVolume(IntPtr SoundStream, float Volume);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetPosition(IntPtr SoundStream, float X, float Y, float Z);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetRelativeToListener(IntPtr SoundStream, bool Relative);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetMinDistance(IntPtr SoundStream, float MinDistance);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetAttenuation(IntPtr SoundStream, float Attenuation);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_SetPlayingOffset(IntPtr SoundStream, float TimeOffset);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfSoundStream_GetLoop(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfSoundStream_GetPitch(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfSoundStream_GetVolume(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundStream_GetPosition(IntPtr SoundStream, out float X, out float Y, out float Z);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfSoundStream_IsRelativeToListener(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfSoundStream_GetMinDistance(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfSoundStream_GetAttenuation(IntPtr SoundStream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfSoundStream_GetPlayingOffset(IntPtr SoundStream);
#endregion
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using System.Diagnostics;
using Generator.Enums;
namespace Generator.Tables {
/// <summary>
/// Operand encoding and kind
/// </summary>
enum OperandEncoding {
/// <summary>
/// Not an operand
/// </summary>
None,
/// <summary>
/// Signed {8,16,32}-bit relative branch
/// </summary>
NearBranch,
/// <summary>
/// <c>XBEGIN</c> signed {16,32}-bit relative branch
/// </summary>
Xbegin,
/// <summary>
/// <c>JMPE</c> unsigned {16,32}-bit offset branch (not a near relative branch)
/// </summary>
AbsNearBranch,
/// <summary>
/// Far branch (unsigned {16,32}-bit offset + unsigned 16-bit segment/selector)
/// </summary>
FarBranch,
/// <summary>
/// {8,16,32,64}-bit immediate that may or may not be sign extended
/// </summary>
Immediate,
/// <summary>
/// Implied constant (eg. <c>1</c>) and not encoded in the instruction
/// </summary>
ImpliedConst,
/// <summary>
/// Implied register (eg. <c>AX</c>) and not encoded in the instruction
/// </summary>
ImpliedRegister,
/// <summary>
/// <c>seg:[rBX]</c> memory operand. The base register depends on the effective address size and can be overridden with the <c>67h</c> prefix.
/// </summary>
SegRBX,
/// <summary>
/// <c>seg:[rSI]</c> memory operand. The base register depends on the effective address size and can be overridden with the <c>67h</c> prefix.
/// </summary>
SegRSI,
/// <summary>
/// <c>seg:[rDI]</c> memory operand. The base register depends on the effective address size and can be overridden with the <c>67h</c> prefix.
/// </summary>
SegRDI,
/// <summary>
/// <c>ES:[rDI]</c> memory operand. The base register depends on the effective address size and can be overridden with the <c>67h</c> prefix.
/// </summary>
ESRDI,
/// <summary>
/// <c>/is4</c> and <c>/is5</c> operand: the register operand is stored in the upper 4 bits of an 8-bit immediate
/// </summary>
RegImm,
/// <summary>
/// The register operand is encoded in the low 3 bits of the opcode (64-bit: REX.B is the 4th bit)
/// </summary>
RegOpCode,
/// <summary>
/// The register operand is encoded in <c>modrm.reg</c> (64-bit: REX.R is the 4th bit)
/// </summary>
RegModrmReg,
/// <summary>
/// The register operand is encoded in <c>modrm.mod==11b</c> + <c>modrm.rm</c> (no mem operand allowed) (64-bit: REX.B is the 4th bit)
/// </summary>
RegModrmRm,
/// <summary>
/// The register/memory operand is encoded in <c>modrm.mod</c> + <c>modrm.rm</c> (64-bit: REX.B is the 4th bit)
/// </summary>
RegMemModrmRm,
/// <summary>
/// The register operand is encoded in <c>V'vvvv</c>
/// </summary>
RegVvvvv,
/// <summary>
/// The memory operand is encoded in <c>modrm.mod!=11b</c> + <c>modrm.rm</c> (no register operand allowed)
/// </summary>
MemModrmRm,
/// <summary>
/// The memory operand is an unsigned {16,32,64}-bit offset (no modrm byte). The size of the offset depends on the effective
/// address size and can be overridden with the <c>67h</c> prefix.
/// </summary>
MemOffset,
}
[Flags]
enum OpCodeOperandKindDefFlags : uint {
/// <summary>
/// No bit is set
/// </summary>
None = 0,
/// <summary>
/// The <c>LOCK</c> bit can be used as an extra register bit
/// </summary>
LockBit = 0x00000001,
/// <summary>
/// 2 regs are used (bit <c>[0]</c> is ignored) (eg. <c>k1+1</c>)
/// </summary>
RegPlus1 = 0x00000002,
/// <summary>
/// 4 regs are used (bits <c>[1:0]</c> are ignored) (eg. <c>xmm1+3</c>)
/// </summary>
RegPlus3 = 0x00000004,
/// <summary>
/// It's a memory operand
/// </summary>
Memory = 0x00000008,
/// <summary>
/// MPX memory operand. Must be 32-bit addressing in 16/32-bit mode and is forced to be 64-bit addressing in 64-bit mode. RIP-relative memory operands aren't allowed.
/// </summary>
MPX = 0x00000010,
/// <summary>
/// MIB memory operand. Must be 32-bit addressing in 16/32-bit mode and is forced to be 64-bit addressing in 64-bit mode. RIP-relative memory operands aren't allowed.
/// </summary>
MIB = 0x00000020,
/// <summary>
/// A SIB byte must be present
/// </summary>
SibRequired = 0x00000040,
/// <summary>
/// It's a VSIB32 memory operand
/// </summary>
Vsib32 = 0x00000080,
/// <summary>
/// It's a VSIB64 memory operand
/// </summary>
Vsib64 = 0x00000100,
/// <summary>
/// It's encoded in the modrm byte
/// </summary>
Modrm = 0x00000200,
/// <summary>
/// <c>/is5</c> instructions: 4-bit immediate stored in the low 4 bits of an 8-bit immediate (upper 4 bits is the
/// register bits, see <see cref="OperandEncoding.RegImm"/>)
/// </summary>
M2Z = 0x00000400,
/// <summary>
/// (if <see cref="OperandEncoding.RegImm"/>): <c>/is5</c> register operand, else <c>/is4</c>
/// </summary>
Is5 = 0x00000800,
}
[DebuggerDisplay("{EnumValue.RawName} {OperandEncoding} {Flags}")]
sealed class OpCodeOperandKindDef {
public EnumValue EnumValue { get; }
public OpCodeOperandKindDefFlags Flags { get; }
public OperandEncoding OperandEncoding { get; }
public bool LockBit => (Flags & OpCodeOperandKindDefFlags.LockBit) != 0;
public bool RegPlus1 => (Flags & OpCodeOperandKindDefFlags.RegPlus1) != 0;
public bool RegPlus3 => (Flags & OpCodeOperandKindDefFlags.RegPlus3) != 0;
public bool Memory => (Flags & OpCodeOperandKindDefFlags.Memory) != 0;
public bool MPX => (Flags & OpCodeOperandKindDefFlags.MPX) != 0;
public bool MIB => (Flags & OpCodeOperandKindDefFlags.MIB) != 0;
public bool SibRequired => (Flags & OpCodeOperandKindDefFlags.SibRequired) != 0;
public bool Vsib => (Flags & (OpCodeOperandKindDefFlags.Vsib32 | OpCodeOperandKindDefFlags.Vsib64)) != 0;
public bool Vsib32 => (Flags & OpCodeOperandKindDefFlags.Vsib32) != 0;
public bool Vsib64 => (Flags & OpCodeOperandKindDefFlags.Vsib64) != 0;
public bool Modrm => (Flags & OpCodeOperandKindDefFlags.Modrm) != 0;
public bool M2Z => (Flags & OpCodeOperandKindDefFlags.M2Z) != 0;
readonly int arg1, arg2;
readonly Register register;
public OpCodeOperandKindDef(EnumValue enumValue, OpCodeOperandKindDefFlags flags, OperandEncoding encoding, int arg1, int arg2, Register register) {
EnumValue = enumValue;
Flags = flags;
OperandEncoding = encoding;
this.arg1 = arg1;
this.arg2 = arg2;
this.register = register;
}
internal int Arg1 => arg1;
internal int Arg2 => arg2;
/// <summary>
/// Used if <see cref="OperandEncoding"/> is
/// <see cref="OperandEncoding.NearBranch"/>,
/// <see cref="OperandEncoding.Xbegin"/>,
/// <see cref="OperandEncoding.AbsNearBranch"/>,
/// <see cref="OperandEncoding.FarBranch"/>
/// <br/>
/// <br/>
/// Size in bits of the branch displacement. This is 8, 16 or 32 bits if it's a
/// near branch else it's 16 or 32 bits.
/// </summary>
public int BranchOffsetSize => arg1;
/// <summary>
/// Used if <see cref="OperandEncoding"/> == <see cref="OperandEncoding.NearBranch"/><br/>
/// <br/>
/// Operand size in bits (16, 32 or 64 bits)
/// </summary>
public int NearBranchOpSize => arg2;
/// <summary>
/// Used if <see cref="OperandEncoding"/> == <see cref="OperandEncoding.Immediate"/><br/>
/// <br/>
/// Size in bits of the immediate encoded in the instruction (2, 8, 16, 32, 64 bits)
/// </summary>
public int ImmediateSize => arg1;
/// <summary>
/// Used if <see cref="OperandEncoding"/> == <see cref="OperandEncoding.Immediate"/><br/>
/// <br/>
/// Size in bits of the immediate after being sign extended (2, 8, 16, 32, 64 bits) and this value is >= <see cref="ImmediateSize"/>
/// </summary>
public int ImmediateSignExtSize => arg2;
/// <summary>
/// Used if <see cref="OperandEncoding"/> == <see cref="OperandEncoding.ImpliedConst"/><br/>
/// <br/>
/// Implied value not encoded in the instruction
/// </summary>
public int ImpliedConst => arg1;
/// <summary>
/// Used if <see cref="OperandEncoding"/> is
/// <see cref="OperandEncoding.ImpliedRegister"/>,
/// <see cref="OperandEncoding.RegImm"/>,
/// <see cref="OperandEncoding.RegOpCode"/>,
/// <see cref="OperandEncoding.RegModrmReg"/>,
/// <see cref="OperandEncoding.RegModrmRm"/>,
/// <see cref="OperandEncoding.RegMemModrmRm"/>,
/// <see cref="OperandEncoding.RegVvvvv"/>,
/// <see cref="OperandEncoding.MemModrmRm"/> (if <see cref="Vsib"/> only)
/// <br/>
/// <br/>
/// If <see cref="OperandEncoding.ImpliedRegister"/>, it's the implied register (not encoded in the
/// instruction), else it's the base register that's encoded in the instruction (eg.
/// <see cref="Register.EAX"/>, <see cref="Register.YMM0"/>, <see cref="Register.K0"/>).
/// </summary>
public Register Register => register;
/// <summary>
/// <see langword="true"/> if <see cref="Register"/> is valid
/// </summary>
public bool HasRegister =>
OperandEncoding switch {
OperandEncoding.ImpliedRegister or OperandEncoding.RegImm or OperandEncoding.RegOpCode or OperandEncoding.RegModrmReg or
OperandEncoding.RegModrmRm or OperandEncoding.RegMemModrmRm or OperandEncoding.RegVvvvv => true,
OperandEncoding.MemModrmRm => Vsib,
_ => false,
};
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace Owf.Controls
{
public partial class DigitalDisplayControl : UserControl
{
private Color _digitColor = Color.GreenYellow;
[Browsable(true), DefaultValue("Color.GreenYellow")]
public Color DigitColor
{
get { return _digitColor; }
set { _digitColor = value; Invalidate(); }
}
private string _digitText = "88.88";
[Browsable(true), DefaultValue("88.88")]
public string DigitText
{
get { return _digitText; }
set
{
if (_digitText != value)
{
_digitText = value; Invalidate();
}
}
}
public DigitalDisplayControl()
{
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
InitializeComponent();
this.BackColor = Color.Transparent;
}
private void DigitalGauge_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
SevenSegmentHelper sevenSegmentHelper = new SevenSegmentHelper(e.Graphics);
SizeF digitSizeF = sevenSegmentHelper.GetStringSize(_digitText, Font);
float scaleFactor = Math.Min(ClientSize.Width / digitSizeF.Width, ClientSize.Height / digitSizeF.Height);
Font font = new Font(Font.FontFamily, scaleFactor * Font.SizeInPoints);
digitSizeF = sevenSegmentHelper.GetStringSize(_digitText, font);
using (SolidBrush brush = new SolidBrush(_digitColor))
{
using (SolidBrush lightBrush = new SolidBrush(Color.FromArgb(20, _digitColor)))
{
sevenSegmentHelper.DrawDigits(
_digitText, font, brush, lightBrush,
(ClientSize.Width - digitSizeF.Width) / 2,
(ClientSize.Height - digitSizeF.Height) / 2);
}
}
}
}
public class SevenSegmentHelper
{
Graphics _graphics;
// Indicates what segments are illuminated for all 10 digits
static byte[,] _segmentData = {{1, 1, 1, 0, 1, 1, 1},
{0, 0, 1, 0, 0, 1, 0},
{1, 0, 1, 1, 1, 0, 1},
{1, 0, 1, 1, 0, 1, 1},
{0, 1, 1, 1, 0, 1, 0},
{1, 1, 0, 1, 0, 1, 1},
{1, 1, 0, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 1, 0},
{1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 1, 1}};
// Points that define each of the seven segments
readonly Point[][] _segmentPoints = new Point[7][];
public SevenSegmentHelper(Graphics graphics)
{
this._graphics = graphics;
_segmentPoints[0] = new Point[] {new Point( 3, 2), new Point(39, 2), new Point(31, 10), new Point(11, 10)};
_segmentPoints[1] = new Point[] {new Point( 2, 3), new Point(10, 11), new Point(10, 31), new Point( 2, 35)};
_segmentPoints[2] = new Point[] {new Point(40, 3), new Point(40, 35), new Point(32, 31), new Point(32, 11)};
_segmentPoints[3] = new Point[] {new Point( 3, 36), new Point(11, 32), new Point(31, 32), new Point(39, 36), new Point(31, 40), new Point(11, 40)};
_segmentPoints[4] = new Point[] {new Point( 2, 37), new Point(10, 41), new Point(10, 61), new Point( 2, 69)};
_segmentPoints[5] = new Point[] {new Point(40, 37), new Point(40, 69), new Point(32, 61), new Point(32, 41)};
_segmentPoints[6] = new Point[] {new Point(11, 62), new Point(31, 62), new Point(39, 70), new Point( 3, 70)};
}
public SizeF GetStringSize(string text, Font font)
{
SizeF sizef = new SizeF(0, _graphics.DpiX * font.SizeInPoints / 72);
for (int i = 0; i < text.Length; i++)
{
if (Char.IsDigit(text[i]) || text[i] == '-')
sizef.Width += 42 * _graphics.DpiX * font.SizeInPoints / 72 / 72;
else if (text[i] == ':' || text[i] == '.' || text[i] == ',')
sizef.Width += 12 * _graphics.DpiX * font.SizeInPoints / 72 / 72;
}
return sizef;
}
public void DrawDigits(string text, Font font, Brush brush, Brush brushLight, float x, float y)
{
for (int cnt = 0; cnt < text.Length; cnt++)
{
// For digits 0-9
if (Char.IsDigit(text[cnt]))
x = DrawDigit(text[cnt] - '0', font, brush, brushLight, x, y);
// For colon :
else if (text[cnt] == ':')
x = DrawColon(font, brush, x, y);
// For dot . and comma
else if (text[cnt] == '.' || text[cnt] == ',')
x = DrawDot(font, brush, x, y);
// For dash -
else if (text[cnt] == '-')
x = DrawDash(font, brush, x, y);
}
}
private float DrawDigit(int num, Font font, Brush brush, Brush brushLight, float x, float y)
{
for (int cnt = 0; cnt < _segmentPoints.Length; cnt++)
{
if (_segmentData[num, cnt] == 1)
{
FillPolygon(_segmentPoints[cnt], font, brush, x, y);
}
else
{
FillPolygon(_segmentPoints[cnt], font, brushLight, x, y);
}
}
return x + 42 * _graphics.DpiX * font.SizeInPoints / 72 / 72;
}
private float DrawDot(Font font, Brush brush, float x, float y)
{
Point[][] dotPoints = new Point[1][];
dotPoints[0] = new Point[] {new Point( 2, 64), new Point( 6, 61),
new Point(10, 64), new Point( 6, 69)};
for (int cnt = 0; cnt < dotPoints.Length; cnt++)
{
FillPolygon(dotPoints[cnt], font, brush, x, y);
}
return x + 12 * _graphics.DpiX * font.SizeInPoints / 72 / 72;
}
private float DrawDash(Font font, Brush brush, float x, float y)
{
Point[][] dashPoints = new Point[1][];
dashPoints[0] = new Point[] { new Point(16, 39), new Point(14, 35), new Point(16, 31), new Point(32, 31), new Point(34, 35), new Point(32, 39) };
for (int cnt = 0; cnt < dashPoints.Length; cnt++)
{
FillPolygon(dashPoints[cnt], font, brush, x, y);
}
return x + 42 * _graphics.DpiX * font.SizeInPoints / 72 / 72;
}
private float DrawColon(Font font, Brush brush, float x, float y)
{
Point[][] colonPoints = new Point[2][];
colonPoints[0] = new Point[] {new Point( 2, 21), new Point( 6, 17), new Point(10, 21), new Point( 6, 25)};
colonPoints[1] = new Point[] {new Point( 2, 51), new Point( 6, 47), new Point(10, 51), new Point( 6, 55)};
for (int cnt = 0; cnt < colonPoints.Length; cnt++)
{
FillPolygon(colonPoints[cnt], font, brush, x, y);
}
return x + 12 * _graphics.DpiX * font.SizeInPoints / 72 / 72;
}
private void FillPolygon(Point[] polygonPoints, Font font, Brush brush, float x, float y)
{
PointF[] polygonPointsF = new PointF[polygonPoints.Length];
for (int cnt = 0; cnt < polygonPoints.Length; cnt++)
{
polygonPointsF[cnt].X = x + polygonPoints[cnt].X * _graphics.DpiX * font.SizeInPoints / 72 / 72;
polygonPointsF[cnt].Y = y + polygonPoints[cnt].Y * _graphics.DpiY * font.SizeInPoints / 72 / 72;
}
_graphics.FillPolygon(brush, polygonPointsF);
}
}
}
| |
// Copyright (c) 2016 robosoup
// www.robosoup.com
using Cudafy;
using Cudafy.Host;
using Cudafy.Translator;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Athena
{
internal class Word2Vec
{
// Start hyperparameters.
private const bool USE_CBOW = true;
private const float BaseLearningRate = 0.05f;
private const double SubSample = 1e-8;
private const int Iterations = 5;
private const int NegativeSamples = 5;
private const int SentenceBatches = 10;
private const int SentencePositions = 64;
private const int Window = 5;
// End hyperparameters.
private readonly Model _model;
private readonly Random _rnd = new Random();
private int[,] _tokens = new int[SentenceBatches, 1 + SentencePositions];
private float _learningRate = BaseLearningRate;
private float[,] _gpuContext;
private float[,] _gpuLocation;
private int[] _gpuRoulette;
private int _rouletteLength;
private int _sentence;
private GPGPU _gpu;
public Word2Vec(bool learnVocab)
{
_model = new Model(learnVocab);
_gpu = CudafyHost.GetDevice(CudafyModes.Target, Program.DeviceID);
_gpu.LoadModule(CudafyTranslator.Cudafy(_gpu.GetArchitecture()));
_gpu.FreeAll();
CopyToGPU();
for (var iteration = 0; iteration < Iterations; iteration++)
{
Train(iteration);
CopyFromGPU();
_model.Save();
}
_gpu.FreeAll();
}
private void CopyToGPU()
{
var arrayContext = new float[_model.Count, Model.Dims];
var arrayLocation = new float[_model.Count, Model.Dims];
int id = 0;
foreach (var item in _model)
{
item.Value.ID = id;
for (var i = 0; i < Model.Dims; i++)
{
arrayContext[id, i] = (float)(0.5 - _rnd.NextDouble());
arrayLocation[id, i] = (float)(0.5 - _rnd.NextDouble());
}
id++;
}
var tmp = new List<int>();
var div = Math.Pow(Model.TrainMin, 0.6);
foreach (var word in _model)
{
var count = (int)(Math.Pow(word.Value.Count, 0.6) / div);
for (var i = 0; i < count; i++) tmp.Add(word.Value.ID);
}
var arrayRoulette = tmp.ToArray();
_rouletteLength = arrayRoulette.Length;
_gpuContext = _gpu.Allocate<float>(arrayContext);
_gpuLocation = _gpu.Allocate<float>(arrayLocation);
_gpuRoulette = _gpu.Allocate<int>(arrayRoulette);
_gpu.CopyToDevice(arrayContext, _gpuContext);
_gpu.CopyToDevice(arrayLocation, _gpuLocation);
_gpu.CopyToDevice(arrayRoulette, _gpuRoulette);
}
private void CopyFromGPU()
{
var arrayContext = new float[_model.Count, Model.Dims];
var arrayLocation = new float[_model.Count, Model.Dims];
_gpu.CopyFromDevice(_gpuContext, arrayContext);
_gpu.CopyFromDevice(_gpuLocation, arrayLocation);
foreach (var item in _model)
{
var id = item.Value.ID;
var location = item.Value.Vector;
for (var i = 0; i < Model.Dims; i++)
location[i] = arrayLocation[id, i];
}
}
private void Train(int iteration)
{
Console.WriteLine("Training model [{0:H:mm:ss}]", DateTime.Now);
Console.WriteLine();
var start = DateTime.Now;
var checkpoint = DateTime.Now;
var wordCount = 0;
double length = new FileInfo(Program.Path_Corpus_1).Length;
using (var sr = new StreamReader(Program.Path_Corpus_1))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var sentence = new List<string>();
foreach (
var word in
line.Split(null as string[], StringSplitOptions.RemoveEmptyEntries)
.Where(word => _model.ContainsKey(word)))
{
wordCount++;
sentence.Add(word);
}
if (sentence.Count > 1) ProcessSentence(sentence, _learningRate);
if (checkpoint < DateTime.Now)
{
var progress = (float)(sr.BaseStream.Position / length);
var seconds = (DateTime.Now - start).TotalSeconds + 1;
var rate = wordCount / seconds / 1000.0;
_learningRate = BaseLearningRate - (iteration * BaseLearningRate / Iterations) - (progress * BaseLearningRate / Iterations);
Console.Write("Iteration {0} Progress: {1:0.000%} words/sec: {2:0.000}k learning rate: {3:0.000} \r", iteration, progress, rate, _learningRate);
checkpoint = DateTime.Now.AddSeconds(1);
}
}
}
Console.WriteLine("\r\n");
}
private void ProcessSentence(IReadOnlyList<string> sentence, float learningRate)
{
var position = 1;
foreach (var word in sentence)
{
var tmp = _model[word];
if (_rnd.NextDouble() > 1 - Math.Sqrt(SubSample * tmp.Count)) continue;
_tokens[_sentence, position] = tmp.ID;
position++;
if (position == SentencePositions) break;
}
_tokens[_sentence, 0] = position - 1;
_sentence++;
if (_sentence == SentenceBatches)
{
_sentence = 0;
_gpu.CopyToConstantMemory(_tokens, Tokens);
if (USE_CBOW)
_gpu.Launch(SentenceBatches * SentencePositions, Model.Dims).CBOW(_gpuContext, _gpuLocation, _gpuRoulette, _rouletteLength, _rnd.Next(99999), learningRate);
else
_gpu.Launch(SentenceBatches * SentencePositions, Model.Dims).SGNS(_gpuContext, _gpuLocation, _gpuRoulette, _rouletteLength, _rnd.Next(99999), learningRate);
_tokens = new int[SentenceBatches, 1 + SentencePositions];
}
}
[Cudafy]
public static int[,] Tokens = new int[SentenceBatches, 1 + SentencePositions];
[Cudafy]
// Predict a word given its context.
public static void CBOW(GThread thread, float[,] context, float[,] location, int[] roulette, int rouletteLength, int seed, float learningRate)
{
float[] activation = thread.AllocateShared<float>("activation", Model.Dims);
float[] error = thread.AllocateShared<float>("error", Model.Dims);
float[] hidden = thread.AllocateShared<float>("hidden", Model.Dims);
float[] g = thread.AllocateShared<float>("g", 1);
int[] crop = thread.AllocateShared<int>("crop", 1);
int[] negID = thread.AllocateShared<int>("negID", 1);
int sentence = thread.blockIdx.x / SentencePositions;
int position = thread.blockIdx.x - sentence * SentencePositions;
int dim = thread.threadIdx.x;
int len = Tokens[sentence, 0];
if (position <= len)
{
uint random = (uint)(seed + position);
if (dim == 0)
{
random = random * 1664525u + 1013904223u;
crop[0] = (int)(random % Window);
}
thread.SyncThreads();
int c = 0;
hidden[dim] = 0;
for (var w = crop[0]; w < Window * 2 + 1 - crop[0]; w++)
{
var p = position - Window + w;
if ((p < 0) || (p >= len)) continue;
if (w == Window) continue;
hidden[dim] += location[Tokens[sentence, p + 1], dim];
c++;
}
hidden[dim] /= c;
error[dim] = 0;
for (int n = 0; n <= NegativeSamples; n++)
{
if (dim == 0)
{
random = random * 1664525u + 1013904223u;
negID[0] = roulette[random % rouletteLength];
}
thread.SyncThreads();
int targetID = negID[0];
if (n == 0) targetID = Tokens[sentence, position + 1];
activation[dim] = hidden[dim] * context[targetID, dim];
thread.SyncThreads();
int j = Model.Dims / 2;
while (j != 0)
{
if (dim < j) activation[dim] += activation[dim + j];
thread.SyncThreads();
j /= 2;
}
if ((n != 0 || activation[0] <= 5f) && (n == 0 || activation[0] >= -5f))
{
if (dim == 0)
{
int label = 0;
if (n == 0) label = 1;
g[0] = (label - 1 / (1 + GMath.Exp(-activation[0]))) * learningRate;
}
thread.SyncThreads();
error[dim] += g[0] * context[targetID, dim];
context[targetID, dim] += g[0] * hidden[dim];
}
thread.SyncThreads();
}
for (var w = crop[0]; w < Window * 2 + 1 - crop[0]; w++)
{
var p = position - Window + w;
if ((p < 0) || (p >= len)) continue;
if (w == Window) continue;
location[Tokens[sentence, p + 1], dim] += error[dim];
}
}
}
[Cudafy]
// Predict the context given a word.
public static void SGNS(GThread thread, float[,] context, float[,] location, int[] roulette, int rouletteLength, int seed, float learningRate)
{
float[] activation = thread.AllocateShared<float>("activation", Model.Dims);
float[] error = thread.AllocateShared<float>("error", Model.Dims);
float[] g = thread.AllocateShared<float>("g", 1);
int[] crop = thread.AllocateShared<int>("crop", 1);
int[] negID = thread.AllocateShared<int>("negID", 1);
int sentence = thread.blockIdx.x / SentencePositions;
int position = thread.blockIdx.x - sentence * SentencePositions;
int dim = thread.threadIdx.x;
int len = Tokens[sentence, 0];
if (position <= len)
{
uint random = (uint)(seed + position);
if (dim == 0)
{
random = random * 1664525u + 1013904223u;
crop[0] = (int)(random % Window);
}
thread.SyncThreads();
for (var w = crop[0]; w < Window * 2 + 1 - crop[0]; w++)
{
if (w != Window)
{
var p = position - Window + w;
if ((p < 0) || (p >= len)) continue;
error[dim] = 0;
for (int n = 0; n < NegativeSamples + 1; n++)
{
if (dim == 0)
{
random = random * 1664525u + 1013904223u;
negID[0] = roulette[random % rouletteLength];
}
thread.SyncThreads();
int targetID = negID[0];
if (n == 0) targetID = Tokens[sentence, p + 1];
activation[dim] = location[Tokens[sentence, position + 1], dim] * context[targetID, dim];
thread.SyncThreads();
int j = Model.Dims / 2;
while (j != 0)
{
if (dim < j) activation[dim] += activation[dim + j];
thread.SyncThreads();
j /= 2;
}
if ((n != 0 || activation[0] <= 5f) && (n == 0 || activation[0] >= -5f))
{
if (dim == 0)
{
int label = 0;
if (n == 0) label = 1;
g[0] = (label - 1 / (1 + GMath.Exp(-activation[0]))) * learningRate;
}
thread.SyncThreads();
error[dim] += g[0] * context[targetID, dim];
context[targetID, dim] += g[0] * location[Tokens[sentence, position + 1], dim];
}
thread.SyncThreads();
}
location[Tokens[sentence, position + 1], dim] += error[dim];
}
}
}
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.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 = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// PaymentsConfigurationCOD
/// </summary>
[DataContract]
public partial class PaymentsConfigurationCOD : IEquatable<PaymentsConfigurationCOD>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PaymentsConfigurationCOD" /> class.
/// </summary>
/// <param name="acceptCod">Master flag indicating this merchant accepts COD.</param>
/// <param name="approvedCustomersOnly">If true, only approved customers may pay with COD.</param>
/// <param name="restrictions">restrictions.</param>
/// <param name="surchargeAccountingCode">Optional field, if surcharge is set, this is the accounting code the surcharge is tagged with when sent to Quickbooks.</param>
/// <param name="surchargeFee">Additional cost for using COD.</param>
/// <param name="surchargePercentage">Additional percentage cost for using COD.</param>
public PaymentsConfigurationCOD(bool? acceptCod = default(bool?), bool? approvedCustomersOnly = default(bool?), PaymentsConfigurationRestrictions restrictions = default(PaymentsConfigurationRestrictions), string surchargeAccountingCode = default(string), decimal? surchargeFee = default(decimal?), decimal? surchargePercentage = default(decimal?))
{
this.AcceptCod = acceptCod;
this.ApprovedCustomersOnly = approvedCustomersOnly;
this.Restrictions = restrictions;
this.SurchargeAccountingCode = surchargeAccountingCode;
this.SurchargeFee = surchargeFee;
this.SurchargePercentage = surchargePercentage;
}
/// <summary>
/// Master flag indicating this merchant accepts COD
/// </summary>
/// <value>Master flag indicating this merchant accepts COD</value>
[DataMember(Name="accept_cod", EmitDefaultValue=false)]
public bool? AcceptCod { get; set; }
/// <summary>
/// If true, only approved customers may pay with COD
/// </summary>
/// <value>If true, only approved customers may pay with COD</value>
[DataMember(Name="approved_customers_only", EmitDefaultValue=false)]
public bool? ApprovedCustomersOnly { get; set; }
/// <summary>
/// Gets or Sets Restrictions
/// </summary>
[DataMember(Name="restrictions", EmitDefaultValue=false)]
public PaymentsConfigurationRestrictions Restrictions { get; set; }
/// <summary>
/// Optional field, if surcharge is set, this is the accounting code the surcharge is tagged with when sent to Quickbooks
/// </summary>
/// <value>Optional field, if surcharge is set, this is the accounting code the surcharge is tagged with when sent to Quickbooks</value>
[DataMember(Name="surcharge_accounting_code", EmitDefaultValue=false)]
public string SurchargeAccountingCode { get; set; }
/// <summary>
/// Additional cost for using COD
/// </summary>
/// <value>Additional cost for using COD</value>
[DataMember(Name="surcharge_fee", EmitDefaultValue=false)]
public decimal? SurchargeFee { get; set; }
/// <summary>
/// Additional percentage cost for using COD
/// </summary>
/// <value>Additional percentage cost for using COD</value>
[DataMember(Name="surcharge_percentage", EmitDefaultValue=false)]
public decimal? SurchargePercentage { 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 PaymentsConfigurationCOD {\n");
sb.Append(" AcceptCod: ").Append(AcceptCod).Append("\n");
sb.Append(" ApprovedCustomersOnly: ").Append(ApprovedCustomersOnly).Append("\n");
sb.Append(" Restrictions: ").Append(Restrictions).Append("\n");
sb.Append(" SurchargeAccountingCode: ").Append(SurchargeAccountingCode).Append("\n");
sb.Append(" SurchargeFee: ").Append(SurchargeFee).Append("\n");
sb.Append(" SurchargePercentage: ").Append(SurchargePercentage).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PaymentsConfigurationCOD);
}
/// <summary>
/// Returns true if PaymentsConfigurationCOD instances are equal
/// </summary>
/// <param name="input">Instance of PaymentsConfigurationCOD to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PaymentsConfigurationCOD input)
{
if (input == null)
return false;
return
(
this.AcceptCod == input.AcceptCod ||
(this.AcceptCod != null &&
this.AcceptCod.Equals(input.AcceptCod))
) &&
(
this.ApprovedCustomersOnly == input.ApprovedCustomersOnly ||
(this.ApprovedCustomersOnly != null &&
this.ApprovedCustomersOnly.Equals(input.ApprovedCustomersOnly))
) &&
(
this.Restrictions == input.Restrictions ||
(this.Restrictions != null &&
this.Restrictions.Equals(input.Restrictions))
) &&
(
this.SurchargeAccountingCode == input.SurchargeAccountingCode ||
(this.SurchargeAccountingCode != null &&
this.SurchargeAccountingCode.Equals(input.SurchargeAccountingCode))
) &&
(
this.SurchargeFee == input.SurchargeFee ||
(this.SurchargeFee != null &&
this.SurchargeFee.Equals(input.SurchargeFee))
) &&
(
this.SurchargePercentage == input.SurchargePercentage ||
(this.SurchargePercentage != null &&
this.SurchargePercentage.Equals(input.SurchargePercentage))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AcceptCod != null)
hashCode = hashCode * 59 + this.AcceptCod.GetHashCode();
if (this.ApprovedCustomersOnly != null)
hashCode = hashCode * 59 + this.ApprovedCustomersOnly.GetHashCode();
if (this.Restrictions != null)
hashCode = hashCode * 59 + this.Restrictions.GetHashCode();
if (this.SurchargeAccountingCode != null)
hashCode = hashCode * 59 + this.SurchargeAccountingCode.GetHashCode();
if (this.SurchargeFee != null)
hashCode = hashCode * 59 + this.SurchargeFee.GetHashCode();
if (this.SurchargePercentage != null)
hashCode = hashCode * 59 + this.SurchargePercentage.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using GraphQL.Execution;
namespace GraphQL.SystemTextJson
{
/// <summary>
/// Converts an instance of <see cref="ExecutionResult"/> to JSON. Doesn't support read from JSON.
/// </summary>
public class ExecutionResultJsonConverter : JsonConverter<ExecutionResult>
{
private readonly IErrorInfoProvider _errorInfoProvider;
/// <summary>
/// Creates an instance of <see cref="ExecutionResultJsonConverter"/> with the specified <see cref="IErrorInfoProvider"/>.
/// </summary>
public ExecutionResultJsonConverter(IErrorInfoProvider errorInfoProvider)
{
_errorInfoProvider = errorInfoProvider ?? throw new ArgumentNullException(nameof(errorInfoProvider));
}
/// <inheritdoc/>
public override void Write(Utf8JsonWriter writer, ExecutionResult value, JsonSerializerOptions options)
{
writer.WriteStartObject();
// Important: Be careful with passing the same options down when recursively calling Serialize.
// See docs: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to
WriteErrors(writer, value.Errors, _errorInfoProvider, options);
WriteData(writer, value, options);
WriteExtensions(writer, value, options);
writer.WriteEndObject();
}
private static void WriteData(Utf8JsonWriter writer, ExecutionResult result, JsonSerializerOptions options)
{
if (result.Executed)
{
writer.WritePropertyName("data");
if (result.Data is ExecutionNode executionNode)
{
WriteExecutionNode(writer, executionNode, options);
}
else
{
WriteValue(writer, result.Data, options);
}
}
}
private static void WriteExecutionNode(Utf8JsonWriter writer, ExecutionNode node, JsonSerializerOptions options)
{
if (node is ValueExecutionNode valueExecutionNode)
{
WriteValue(writer, valueExecutionNode.ToValue(), options);
}
else if (node is ObjectExecutionNode objectExecutionNode)
{
if (objectExecutionNode.SubFields == null)
{
writer.WriteNullValue();
}
else
{
writer.WriteStartObject();
foreach (var childNode in objectExecutionNode.SubFields)
{
var propertyName = childNode.Name;
if (options.PropertyNamingPolicy != null)
propertyName = options.PropertyNamingPolicy.ConvertName(propertyName);
writer.WritePropertyName(propertyName);
WriteExecutionNode(writer, childNode, options);
}
writer.WriteEndObject();
}
}
else if (node is ArrayExecutionNode arrayExecutionNode)
{
var items = arrayExecutionNode.Items;
if (items == null)
{
writer.WriteNullValue();
}
else
{
writer.WriteStartArray();
foreach (var childNode in items)
{
WriteExecutionNode(writer, childNode, options);
}
writer.WriteEndArray();
}
}
else if (node == null || node is NullExecutionNode)
{
writer.WriteNullValue();
}
else
{
WriteValue(writer, node.ToValue(), options);
}
}
private static void WriteProperty(Utf8JsonWriter writer, string propertyName, object propertyValue, JsonSerializerOptions options)
{
if (options.PropertyNamingPolicy != null)
propertyName = options.PropertyNamingPolicy.ConvertName(propertyName);
writer.WritePropertyName(propertyName);
WriteValue(writer, propertyValue, options);
}
private static void WriteValue(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
switch (value)
{
case null:
{
writer.WriteNullValue();
break;
}
case string s:
{
writer.WriteStringValue(s);
break;
}
case bool b:
{
writer.WriteBooleanValue(b);
break;
}
case int i:
{
writer.WriteNumberValue(i);
break;
}
case long l:
{
writer.WriteNumberValue(l);
break;
}
case float f:
{
writer.WriteNumberValue(f);
break;
}
case double d:
{
writer.WriteNumberValue(d);
break;
}
case decimal dm:
{
writer.WriteNumberValue(dm);
break;
}
case uint ui:
{
writer.WriteNumberValue(ui);
break;
}
case ulong ul:
{
writer.WriteNumberValue(ul);
break;
}
case short sh:
{
writer.WriteNumberValue(sh);
break;
}
case ushort ush:
{
writer.WriteNumberValue(ush);
break;
}
case byte bt:
{
writer.WriteNumberValue(bt);
break;
}
case sbyte sbt:
{
writer.WriteNumberValue(sbt);
break;
}
case Dictionary<string, object> dictionary:
{
writer.WriteStartObject();
foreach (var kvp in dictionary)
WriteProperty(writer, kvp.Key, kvp.Value, options);
writer.WriteEndObject();
break;
}
case List<object> list:
{
writer.WriteStartArray();
foreach (object item in list)
WriteValue(writer, item, options);
writer.WriteEndArray();
break;
}
case object[] list:
{
writer.WriteStartArray();
foreach (object item in list)
WriteValue(writer, item, options);
writer.WriteEndArray();
break;
}
default:
{
// TODO: Guid, BigInteger, DateTime, <Anonymous Type> fall here
// Need to avoid this call by all means! The question remains open - why this API so expensive?
JsonSerializer.Serialize(writer, value, options);
break;
}
}
}
private static void WriteErrors(Utf8JsonWriter writer, ExecutionErrors errors, IErrorInfoProvider errorInfoProvider, JsonSerializerOptions options)
{
if (errors == null || errors.Count == 0)
{
return;
}
writer.WritePropertyName("errors");
writer.WriteStartArray();
foreach (var error in errors)
{
var info = errorInfoProvider.GetInfo(error);
writer.WriteStartObject();
writer.WritePropertyName("message");
JsonSerializer.Serialize(writer, info.Message, options);
if (error.Locations != null)
{
writer.WritePropertyName("locations");
writer.WriteStartArray();
foreach (var location in error.Locations)
{
writer.WriteStartObject();
writer.WritePropertyName("line");
JsonSerializer.Serialize(writer, location.Line, options);
writer.WritePropertyName("column");
JsonSerializer.Serialize(writer, location.Column, options);
writer.WriteEndObject();
}
writer.WriteEndArray();
}
if (error.Path != null && error.Path.Any())
{
writer.WritePropertyName("path");
JsonSerializer.Serialize(writer, error.Path, options);
}
if (info.Extensions?.Count > 0)
{
writer.WritePropertyName("extensions");
JsonSerializer.Serialize(writer, info.Extensions, options);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
}
private static void WriteExtensions(Utf8JsonWriter writer, ExecutionResult result, JsonSerializerOptions options)
{
if (result.Extensions?.Count > 0)
{
writer.WritePropertyName("extensions");
JsonSerializer.Serialize(writer, result.Extensions, options);
}
}
/// <inheritdoc/>
public override ExecutionResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();
/// <inheritdoc/>
public override bool CanConvert(Type typeToConvert) => typeof(ExecutionResult).IsAssignableFrom(typeToConvert);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Implementation of a dynamic data collection based on generic Collection<T>,
/// implementing INotifyCollectionChanged to notify listeners
/// when items get added, removed or the whole list is refreshed.
/// </summary>
[Serializable]
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private SimpleMonitor _monitor; // Lazily allocated only when a subclass calls BlockReentrancy() or during serialization. Do not rename (binary serialization)
[NonSerialized]
private int _blockReentrancyCount;
#endregion Private Fields
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
/// </summary>
public ObservableCollection() { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class that contains
/// elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the collection.
/// </remarks>
/// <exception cref="ArgumentNullException"> collection is a null reference </exception>
public ObservableCollection(IEnumerable<T> collection) : base(CreateCopy(collection, nameof(collection))) { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class
/// that contains elements copied from the specified list
/// </summary>
/// <param name="list">The list whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the list.
/// </remarks>
/// <exception cref="ArgumentNullException"> list is a null reference </exception>
public ObservableCollection(List<T> list) : base(CreateCopy(list, nameof(list))) { }
private static List<T> CreateCopy(IEnumerable<T> collection, string paramName)
{
if (collection == null)
throw new ArgumentNullException(paramName);
return new List<T>(collection);
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Move item at oldIndex to newIndex.
/// </summary>
public void Move(int oldIndex, int newIndex)
{
MoveItem(oldIndex, newIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
//------------------------------------------------------
#region INotifyPropertyChanged implementation
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
PropertyChanged += value;
}
remove
{
PropertyChanged -= value;
}
}
#endregion INotifyPropertyChanged implementation
//------------------------------------------------------
/// <summary>
/// Occurs when the collection changes, either by adding or removing an item.
/// </summary>
/// <remarks>
/// see <seealso cref="INotifyCollectionChanged"/>
/// </remarks>
[field: NonSerialized]
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Called by base class Collection<T> when the list is being cleared;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void ClearItems()
{
CheckReentrancy();
base.ClearItems();
OnCountPropertyChanged();
OnIndexerPropertyChanged();
OnCollectionReset();
}
/// <summary>
/// Called by base class Collection<T> when an item is removed from list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void RemoveItem(int index)
{
CheckReentrancy();
T removedItem = this[index];
base.RemoveItem(index);
OnCountPropertyChanged();
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is added to list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void InsertItem(int index, T item)
{
CheckReentrancy();
base.InsertItem(index, item);
OnCountPropertyChanged();
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is set in list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void SetItem(int index, T item)
{
CheckReentrancy();
T originalItem = this[index];
base.SetItem(index, item);
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
}
/// <summary>
/// Called by base class ObservableCollection<T> when an item is to be moved within the list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected virtual void MoveItem(int oldIndex, int newIndex)
{
CheckReentrancy();
T removedItem = this[oldIndex];
base.RemoveItem(oldIndex);
base.InsertItem(newIndex, removedItem);
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex);
}
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(this, e);
}
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
[field: NonSerialized]
protected virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raise CollectionChanged event to any listeners.
/// Properties/methods modifying this ObservableCollection will raise
/// a collection changed event through this virtual method.
/// </summary>
/// <remarks>
/// When overriding this method, either call its base implementation
/// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
/// </remarks>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = CollectionChanged;
if (handler != null)
{
// Not calling BlockReentrancy() here to avoid the SimpleMonitor allocation.
_blockReentrancyCount++;
try
{
handler(this, e);
}
finally
{
_blockReentrancyCount--;
}
}
}
/// <summary>
/// Disallow reentrant attempts to change this collection. E.g. a event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
/// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope:
/// <code>
/// using (BlockReentrancy())
/// {
/// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index));
/// }
/// </code>
/// </remarks>
protected IDisposable BlockReentrancy()
{
_blockReentrancyCount++;
return EnsureMonitorInitialized();
}
/// <summary> Check and assert for reentrant attempts to change this collection. </summary>
/// <exception cref="InvalidOperationException"> raised when changing the collection
/// while another collection change is still being notified to other listeners </exception>
protected void CheckReentrancy()
{
if (_blockReentrancyCount > 0)
{
// we can allow changes if there's only one listener - the problem
// only arises if reentrant changes make the original event args
// invalid for later listeners. This keeps existing code working
// (e.g. Selector.SelectedItems).
if (CollectionChanged?.GetInvocationList().Length > 1)
throw new InvalidOperationException(SR.ObservableCollectionReentrancyNotAllowed);
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Helper to raise a PropertyChanged event for the Count property
/// </summary>
private void OnCountPropertyChanged()
{
OnPropertyChanged(EventArgsCache.CountPropertyChanged);
}
/// <summary>
/// Helper to raise a PropertyChanged event for the Indexer property
/// </summary>
private void OnIndexerPropertyChanged()
{
OnPropertyChanged(EventArgsCache.IndexerPropertyChanged);
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
}
/// <summary>
/// Helper to raise CollectionChanged event with action == Reset to any listeners
/// </summary>
private void OnCollectionReset()
{
OnCollectionChanged(EventArgsCache.ResetCollectionChanged);
}
private SimpleMonitor EnsureMonitorInitialized()
{
return _monitor ?? (_monitor = new SimpleMonitor(this));
}
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
EnsureMonitorInitialized();
_monitor._busyCount = _blockReentrancyCount;
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
_blockReentrancyCount = _monitor._busyCount;
_monitor._collection = this;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// this class helps prevent reentrant calls
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
private sealed class SimpleMonitor : IDisposable
{
internal int _busyCount; // Only used during (de)serialization to maintain compatibility with desktop. Do not rename (binary serialization)
[NonSerialized]
internal ObservableCollection<T> _collection;
public SimpleMonitor(ObservableCollection<T> collection)
{
Debug.Assert(collection != null);
_collection = collection;
}
public void Dispose()
{
_collection._blockReentrancyCount--;
}
}
#endregion Private Types
}
internal static class EventArgsCache
{
internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count");
internal static readonly PropertyChangedEventArgs IndexerPropertyChanged = new PropertyChangedEventArgs("Item[]");
internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Diagnostics;
namespace Sxta.GenericProtocol.Encoding
{
#if TODO
public class BitArrayEncodingLE
{
public static readonly EndianTypes Endian = (BitConverter.IsLittleEndian ? EndianTypes.LittleEndian : EndianTypes.BigEndian);
/// <summary>
/// Encodes the specified parameterValue, returning the result as a byte array.
/// </summary>
/// <param name="parameterValue">the parameterValue to Encode
/// </param>
/// <returns>
/// a byte array containing the encoded parameterValue
/// An array of bytes with length 1.
/// </returns>
public static byte[] Encode (BitArray val) /// public static void Encode (Stream stream, Msg1 val)
{
byte[] buf = new byte[(int)Math.Ceiling (val.Count / 8.0f) + sizeof(short)];
Array.Copy (Int16EncodingLE.Encode ((short)val.Length), buf, sizeof(short));
val.CopyTo (buf, 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buf, 2, buf.Length);
return buf;
}
public static void Encode (Stream stream, BitArray val)
{
byte[] buf = new byte[(int)Math.Ceiling (val.Count / 8.0f) + sizeof(short)];
Array.Copy (Int16EncodingLE.Encode ((short)val.Length), buf, sizeof(short));
val.CopyTo (buf, 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buf, 2, buf.Length);
stream.Write (buf, 0, buf.Length);
}
/// <summary>
/// Decodes and returns the parameterValue stored in the specified bufferStream.
/// </summary>
/// <param name="bufferStream">the bufferStream containing the encoded parameterValue
/// </param>
/// <returns> the decoded parameterValue
/// </returns>
/// <exception cref="System.IO.IOException"> if the parameterValue could not be decoded
/// </exception>
public static BitArray Decode (byte[] buffer)
{
if (buffer == null || (buffer.Length <= sizeof(short)))
throw new Exception ();
byte [] buffer2 = new byte[buffer.Length -2];
byte[] buffer3=new byte[2];
Array.Copy(buffer,0,buffer3,0,2);
Int16 num = Int16EncodingLE.Decode(buffer3);
Array.Copy (buffer, 2, buffer2, 0, buffer.Length - 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer2, 2, buffer2.Length);
BitArray bitarr = new BitArray (buffer2);
bitarr.Length=num;
return bitarr;
}
public static void Decode (Stream stream, BitArray val)
{
Debug.Assert (stream != null, "Stream is null");
Int16 num = Int16EncodingLE.Decode (stream);
byte[] buffer = new byte[stream.Length-2];
buffer = stream.ReadBytes (2, ((uint)stream.Length - 2));
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer, 2, buffer.Length);
val = new BitArray (buffer);
val.Length = num;
}
// public static void Decode (Stream stream)
// {
//
// Debug.Assert (stream != null, "Stream is null");
// byte[] buffer = new byte[stream.Length - 2];
//
// buffer = stream.ReadBytes (2, ((uint)stream.Length - 2));
//
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer);
//
// }
public static BitArray Decode (Stream stream)
{
Debug.Assert (stream != null, "Stream is null");
Int16 num = Int16EncodingLE.Decode (stream);
byte[] buffer = new byte[stream.Length - 2];
buffer = stream.ReadBytes (2, ((uint)stream.Length) - 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer, 2, buffer.Length);
BitArray val = new BitArray (buffer);
val.Length = num;
return val;
}
}
public class BitArrayEncodingBE
{
public static readonly EndianTypes Endian = (BitConverter.IsLittleEndian ? EndianTypes.LittleEndian : EndianTypes.BigEndian);
/// <summary>
/// Encodes the specified parameterValue, returning the result as a byte array.
/// </summary>
/// <param name="parameterValue">the parameterValue to Encode
/// </param>
/// <returns>
/// a byte array containing the encoded parameterValue
/// An array of bytes with length 1.
/// </returns>
public static byte[] Encode (BitArray val) /// public static void Encode (Stream stream, Msg1 val)
{
byte[] buf = new byte[(int)Math.Ceiling (val.Count / 8.0f) + sizeof(short)];
Array.Copy (Int16EncodingBE.Encode ((short)val.Length), buf, sizeof(short));
val.CopyTo (buf, 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buf, 2, buf.Length);
return buf;
}
public static void Encode (Stream stream, BitArray val)
{
byte[] buf = new byte[(int)Math.Ceiling (val.Count / 8.0f) + sizeof(short)];
Array.Copy (Int16EncodingBE.Encode ((short)val.Length), buf, sizeof(short));
val.CopyTo (buf, 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buf, 2, buf.Length);
stream.Write (buf, 0, buf.Length);
}
/// <summary>
/// Decodes and returns the parameterValue stored in the specified bufferStream.
/// </summary>
/// <param name="bufferStream">the bufferStream containing the encoded parameterValue
/// </param>
/// <returns> the decoded parameterValue
/// </returns>
/// <exception cref="System.IO.IOException"> if the parameterValue could not be decoded
/// </exception>
public static BitArray Decode (byte[] buffer)
{
if (buffer == null || (buffer.Length <= sizeof(short)))
throw new Exception ();
byte [] buffer2 = new byte[buffer.Length -2];
byte[] buffer3=new byte[2];
Array.Copy(buffer,0,buffer3,0,2);
Int16 num = Int16EncodingBE.Decode(buffer3);
Array.Copy (buffer, 2, buffer2, 0, buffer.Length - 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer2, 2, buffer2.Length);
BitArray bitarr = new BitArray (buffer2);
bitarr.Length=num;
return bitarr;
}
public static void Decode (Stream stream, BitArray val)
{
Debug.Assert (stream != null, "Stream is null");
Int16 num = Int16EncodingBE.Decode (stream);
byte[] buffer = new byte[stream.Length-2];
buffer = stream.ReadBytes (2, ((uint)stream.Length - 2));
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer, 2, buffer.Length);
val = new BitArray (buffer);
val.Length = num;
}
// public static void Decode (Stream stream)
// {
//
// Debug.Assert (stream != null, "Stream is null");
// byte[] buffer = new byte[stream.Length - 2];
//
// buffer = stream.ReadBytes (2, ((uint)stream.Length - 2));
//
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer);
//
// }
public static BitArray Decode (Stream stream)
{
Debug.Assert (stream != null, "Stream is null");
Int16 num = Int16EncodingBE.Decode (stream);
byte[] buffer = new byte[stream.Length - 2];
buffer = stream.ReadBytes (2, ((uint)stream.Length) - 2);
// if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
// EncodingHelpers.ReverseBytes (buffer, 2, buffer.Length);
BitArray val = new BitArray (buffer);
val.Length = num;
return val;
}
}
#endif
}
| |
#region Header
/**
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
namespace LitJson
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
private float inst_float;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
public bool IsFloat
{
get { return type == JsonType.Float; }
}
public ICollection<string> Keys {
get { EnsureDictionary (); return inst_object.Keys; }
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
bool IJsonWrapper.IsFloat
{
get { return IsFloat; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
return inst_object[prop_name];
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData(float number)
{
type = JsonType.Float;
inst_float = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is float)
{
type = JsonType.Float;
inst_float = (float)obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
public static implicit operator JsonData(float data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32 (JsonData data)
{
if (data.type != JsonType.Int)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_int;
}
public static explicit operator Int64 (JsonData data)
{
if (data.type != JsonType.Long)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_long;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
public static explicit operator float(JsonData data)
{
if(data.type!=JsonType.Float)
throw new InvalidCastException(
"Instance of JsonData doesn't hold a float");
return data.inst_float;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
float IJsonWrapper.GetFloat()
{
if(type!=JsonType.Float)
throw new InvalidOperationException(
"JsonData instance doesn't hold a float");
return inst_float;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
void IJsonWrapper.SetFloat(float val)
{
type = JsonType.Float;
inst_float = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj == null) {
writer.Write (null);
return;
}
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsFloat)
{
writer.Write(obj.GetFloat());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
return false;
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
return this.inst_int.Equals (x.inst_int);
case JsonType.Long:
return this.inst_long.Equals (x.inst_long);
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
case JsonType.Float:
return this.inst_float.Equals(x.inst_float);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
case JsonType.Float:
inst_float = default(float);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
case JsonType.Float:
return inst_float.ToString();
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| |
using System;
using OpenADK.Library;
using OpenADK.Library.us.Infrastructure;
using OpenADK.Library.us.Common;
using OpenADK.Library.Impl;
using OpenADK.Library.Infra;
using OpenADK.Library.us.Student;
using OpenADK.Library.Global;
using OpenADK.Library.Tools.XPath;
using NUnit.Framework;
using Library.UnitTesting.Framework;
namespace Library.Nunit.US.Library
{
[TestFixture]
public class SifResponseSenderTests : InMemoryProtocolTest
{
/**
* Tests basic support for SifResponseSender and that the SIF_Responses
* are actually sent
* @throws Exception
*/
[Test]
public void testSifResponseSender()
{
MessageDispatcher testDispatcher = new MessageDispatcher( Zone );
Zone.SetDispatcher( testDispatcher );
Zone.Connect( ProvisioningFlags.None );
InMemoryProtocolHandler testProto = (InMemoryProtocolHandler) Zone.ProtocolHandler;
testProto.clear();
// Send a single SIF_Response with a small Authentication object
String SifRequestMsgId = Adk.MakeGuid();
String sourceId = "TEST_SOURCEID";
SifVersion testVersion = SifVersion.LATEST;
int maxBufferSize = int.MaxValue;
IElementDef[] testRestrictions = new IElementDef[] {InfrastructureDTD.AUTHENTICATION_REFID};
SifResponseSender srs = new SifResponseSender();
srs.Open( Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Close();
// Retrieve the SIF_Response message off the protocol handler and asssert the results
SIF_Response response = (SIF_Response) testProto.readMsg();
Assert.AreEqual( SifRequestMsgId, response.SIF_RequestMsgId );
Assert.AreEqual( 1, response.SIF_PacketNumber.Value );
Assert.AreEqual( "No", response.SIF_MorePackets );
SIF_Header header = response.SIF_Header;
Assert.AreEqual( sourceId, header.SIF_DestinationId );
SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];
Assert.IsNotNull( responseObject );
}
/**
* Tests basic support for SifResponseSender and that the SIF_Responses
* are actually sent
* @throws Exception
*/
[Test]
public void testSifResponseSenderMultiplePackets()
{
MessageDispatcher testDispatcher = new MessageDispatcher( Zone );
Zone.Properties.OneObjectPerResponse = true;
Zone.SetDispatcher( testDispatcher );
Zone.Connect( ProvisioningFlags.None );
InMemoryProtocolHandler testProto = (InMemoryProtocolHandler) Zone.ProtocolHandler;
testProto.clear();
// Send a single SIF_Response with a small Authentication object
String SifRequestMsgId = Adk.MakeGuid();
String sourceId = "TEST_SOURCEID";
SifVersion testVersion = SifVersion.LATEST;
int maxBufferSize = int.MaxValue;
IElementDef[] testRestrictions = new IElementDef[] {InfrastructureDTD.AUTHENTICATION_REFID};
SifResponseSender srs = new SifResponseSender();
srs.Open( Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Close();
for ( int x = 0; x < 5; x ++ )
{
// Retrieve the SIF_Response message off the protocol handler and asssert the results
SIF_Response response = (SIF_Response) testProto.readMsg();
Assert.AreEqual( SifRequestMsgId, response.SIF_RequestMsgId );
Assert.AreEqual( x + 1, response.SIF_PacketNumber.Value );
if ( x == 4 )
{
Assert.AreEqual( "No", response.SIF_MorePackets );
}
else
{
Assert.AreEqual( "Yes", response.SIF_MorePackets );
}
SIF_Header header = response.SIF_Header;
Assert.AreEqual( sourceId, header.SIF_DestinationId );
SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];
Assert.IsNotNull( responseObject );
}
}
/**
* Tests basic support for SifResponseSender when an error packet is set
* @throws Exception
*/
[Test]
public void testSifResponseSenderError()
{
MessageDispatcher testDispatcher = new MessageDispatcher( Zone );
Zone.SetDispatcher( testDispatcher );
Zone.Connect( ProvisioningFlags.None );
InMemoryProtocolHandler testProto = (InMemoryProtocolHandler) Zone.ProtocolHandler;
testProto.clear();
// Send a single SIF_Response with a small Authentication object
String SifRequestMsgId = Adk.MakeGuid();
String sourceId = "TEST_SOURCEID";
SifVersion testVersion = SifVersion.LATEST;
int maxBufferSize = int.MaxValue;
SIF_Error error =
new SIF_Error( SifErrorCategoryCode.Generic, SifErrorCodes.GENERIC_GENERIC_ERROR_1, "ERROR", "EXT_ERROR" );
IElementDef[] testRestrictions = new IElementDef[] {InfrastructureDTD.AUTHENTICATION_REFID};
SifResponseSender srs = new SifResponseSender();
srs.Open( Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions );
srs.Write( new Authentication( Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL ) );
srs.Write( error );
srs.Close();
// Retrieve the SIF_Response message off the protocol handler and asssert the results
SIF_Response response = (SIF_Response) testProto.readMsg();
Assert.AreEqual( SifRequestMsgId, response.SIF_RequestMsgId );
Assert.AreEqual( 1, response.SIF_PacketNumber.Value );
Assert.AreEqual( "Yes", response.SIF_MorePackets );
SIF_Header header = response.SIF_Header;
Assert.AreEqual( sourceId, header.SIF_DestinationId );
SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];
Assert.IsNotNull( responseObject );
// now test the error packet
response = (SIF_Response) testProto.readMsg();
Assert.AreEqual( SifRequestMsgId, response.SIF_RequestMsgId );
Assert.AreEqual( 2, response.SIF_PacketNumber.Value );
Assert.AreEqual( "No", response.SIF_MorePackets );
header = response.SIF_Header;
Assert.AreEqual( sourceId, header.SIF_DestinationId );
Assert.IsNull( response.SIF_ObjectData );
SIF_Error respError = response.SIF_Error;
Assert.IsNotNull( respError );
Assert.AreEqual( 12, respError.SIF_Category.Value );
Assert.AreEqual( 1, respError.SIF_Code.Value );
Assert.AreEqual( "ERROR", respError.SIF_Desc );
Assert.AreEqual( "EXT_ERROR", respError.SIF_ExtendedDesc );
}
/**
* Tests basic support for SifResponseSender and that the SIF_Responses
* are actually sent
* @throws Exception
*/
[Test]
public void testSetPacketNumberAndMorePackets()
{
MessageDispatcher testDispatcher = new MessageDispatcher(this.Zone);
this.Zone.SetDispatcher(testDispatcher);
this.Zone.Connect( ProvisioningFlags.None );
InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)this.Zone.ProtocolHandler;
testProto.clear();
// Send a single SIF_Response with a small Authentication object
String SifRequestMsgId = Adk.MakeGuid();
String sourceId = "TEST_SOURCEID";
SifVersion testVersion = SifVersion.LATEST;
int maxBufferSize = int.MaxValue;
int packetNumber = 999;
YesNo morePacketsValue = YesNo.YES;
IElementDef[] testRestrictions = new IElementDef[] { InfrastructureDTD.AUTHENTICATION_REFID };
SifResponseSender srs = new SifResponseSender();
srs.Open(this.Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions);
srs.SIF_PacketNumber = packetNumber;
srs.SIF_MorePackets = morePacketsValue;
// Assert the values of the properties set before writing
Assert.AreEqual(packetNumber, srs.SIF_PacketNumber);
Assert.AreEqual(morePacketsValue, srs.SIF_MorePackets);
srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
srs.Close();
// Assert the values of the properties set after writing
Assert.AreEqual(packetNumber, srs.SIF_PacketNumber);
Assert.AreEqual(morePacketsValue, srs.SIF_MorePackets);
// Retrieve the SIF_Response message off the protocol handler and asssert the results
SIF_Response response = (SIF_Response)testProto.readMsg();
Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
Assert.AreEqual(packetNumber, response.SIF_PacketNumber.Value);
Assert.AreEqual(morePacketsValue.ToString(), response.SIF_MorePackets);
SIF_Header header = response.SIF_Header;
Assert.AreEqual(sourceId, header.SIF_DestinationId);
SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];
Assert.IsNotNull(responseObject);
}
[Test]
public void testSifResponseSender010()
{
string queryStr =
@"<SIF_Query>
<SIF_QueryObject ObjectName='SectionInfo'>
<SIF_Element>@RefId</SIF_Element>
<SIF_Element>@SchoolCourseInfoRefId</SIF_Element>
<SIF_Element>@SchoolYear</SIF_Element>
<SIF_Element>LocalId</SIF_Element>
<SIF_Element>ScheduleInfoList/ScheduleInfo/@TermInfoRefId</SIF_Element>
<SIF_Element>Description</SIF_Element>
<SIF_Element>LanguageOfInstruction</SIF_Element>
<SIF_Element>LanguageOfInstruction/Code</SIF_Element>
</SIF_QueryObject>
</SIF_Query>";
string sectionInfoStr =
@"<SectionInfo RefId='D9C9889878144863B190C7D3428D7953' SchoolCourseInfoRefId='587F89D23EDD4761A59C04BA0D39E8D9' SchoolYear='2008'>
<LocalId>1</LocalId>
<Description>section 19</Description>
<ScheduleInfoList>
<ScheduleInfo TermInfoRefId='0D8165B1ADB34780BD1DFF9E38A7B935'>
<TeacherList>
<StaffPersonalRefId>F9D3916707634682B84C530BCF96B5CA</StaffPersonalRefId>
</TeacherList>
<SectionRoomList>
<RoomInfoRefId>EED167D761CD493EA94A875F56ABB0CB</RoomInfoRefId>
</SectionRoomList>
<MeetingTimeList>
<MeetingTime>
<TimetableDay>R</TimetableDay>
<TimetablePeriod>6</TimetablePeriod>
</MeetingTime>
<MeetingTime>
<TimetableDay>F</TimetableDay>
<TimetablePeriod>6</TimetablePeriod>
</MeetingTime>
<MeetingTime>
<TimetableDay>W</TimetableDay>
<TimetablePeriod>6</TimetablePeriod>
</MeetingTime>
<MeetingTime>
<TimetableDay>M</TimetableDay>
<TimetablePeriod>6</TimetablePeriod>
</MeetingTime>
<MeetingTime>
<TimetableDay>T</TimetableDay>
<TimetablePeriod>6</TimetablePeriod>
</MeetingTime>
</MeetingTimeList>
</ScheduleInfo>
</ScheduleInfoList>
<MediumOfInstruction><Code>0605</Code></MediumOfInstruction>
<LanguageOfInstruction><Code>eng</Code></LanguageOfInstruction>
<SummerSchool>No</SummerSchool>
</SectionInfo>";
SifParser parser = SifParser.NewInstance();
SIF_Query sifquery = (SIF_Query) parser.Parse( queryStr );
SectionInfo section = (SectionInfo) parser.Parse( sectionInfoStr );
Query query = new Query( sifquery );
String SifRequestMsgId = Adk.MakeGuid();
String sourceId = "TEST_SOURCEID";
SifVersion testVersion = SifVersion.LATEST;
int maxBufferSize = int.MaxValue;
MessageDispatcher testDispatcher = new MessageDispatcher(Zone);
Zone.SetDispatcher(testDispatcher);
Zone.Connect(ProvisioningFlags.None);
InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)Zone.ProtocolHandler;
testProto.clear();
SifResponseSender srs = new SifResponseSender();
srs.Open(Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, query );
srs.Write( section );
srs.Close();
// Retrieve the SIF_Response message off the protocol handler and asssert the results
SIF_Response response = (SIF_Response)testProto.readMsg();
Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
Assert.AreEqual(1, response.SIF_PacketNumber.Value);
Assert.AreEqual("No", response.SIF_MorePackets);
SIF_Header header = response.SIF_Header;
Assert.AreEqual(sourceId, header.SIF_DestinationId);
SifDataObject responseObject = (SifDataObject)response.SIF_ObjectData.GetChildList()[0];
Assert.IsNotNull(responseObject);
Console.Out.WriteLine( responseObject.ToXml() );
SifXPathContext context = SifXPathContext.NewSIFContext( responseObject );
foreach( ElementRef reference in query.FieldRestrictionRefs )
{
Element found = context.GetElementOrAttribute( reference.XPath );
Assert.IsNotNull( found, reference.XPath );
}
Element sectionInfoList =
responseObject.GetElementOrAttribute( "ScheduleInfoList/ScheduleInfo/SectionInfoList" );
Assert.IsNull( sectionInfoList );
}
}
}
| |
// 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.ObjectModel;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using DelegateHelpers = System.Linq.Expressions.Compiler.DelegateHelpers;
namespace System.Dynamic
{
/// <summary>
/// The dynamic call site binder that participates in the <see cref="DynamicMetaObject"/> binding protocol.
/// </summary>
/// <remarks>
/// The <see cref="CallSiteBinder"/> performs the binding of the dynamic operation using the runtime values
/// as input. On the other hand, the <see cref="DynamicMetaObjectBinder"/> participates in the <see cref="DynamicMetaObject"/>
/// binding protocol.
/// </remarks>
public abstract class DynamicMetaObjectBinder : CallSiteBinder
{
#region Public APIs
/// <summary>
/// Initializes a new instance of the <see cref="DynamicMetaObjectBinder"/> class.
/// </summary>
protected DynamicMetaObjectBinder()
{
}
/// <summary>
/// The result type of the operation.
/// </summary>
public virtual Type ReturnType
{
get { return typeof(object); }
}
/// <summary>
/// Performs the runtime binding of the dynamic operation on a set of arguments.
/// </summary>
/// <param name="args">An array of arguments to the dynamic operation.</param>
/// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param>
/// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param>
/// <returns>
/// An Expression that performs tests on the dynamic operation arguments, and
/// performs the dynamic operation if the tests are valid. If the tests fail on
/// subsequent occurrences of the dynamic operation, Bind will be called again
/// to produce a new <see cref="Expression"/> for the new argument types.
/// </returns>
public sealed override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel)
{
ContractUtils.RequiresNotNull(args, "args");
ContractUtils.RequiresNotNull(parameters, "parameters");
ContractUtils.RequiresNotNull(returnLabel, "returnLabel");
if (args.Length == 0)
{
throw Error.OutOfRange("args.Length", 1);
}
if (parameters.Count == 0)
{
throw Error.OutOfRange("parameters.Count", 1);
}
if (args.Length != parameters.Count)
{
throw new ArgumentOutOfRangeException("args");
}
// Ensure that the binder's ReturnType matches CallSite's return
// type. We do this so meta objects and language binders can
// compose trees together without needing to insert converts.
Type expectedResult;
if (IsStandardBinder)
{
expectedResult = ReturnType;
if (returnLabel.Type != typeof(void) &&
!TypeUtils.AreReferenceAssignable(returnLabel.Type, expectedResult))
{
throw Error.BinderNotCompatibleWithCallSite(expectedResult, this, returnLabel.Type);
}
}
else
{
// Even for non-standard binders, we have to at least make sure
// it works with the CallSite's type to build the return.
expectedResult = returnLabel.Type;
}
DynamicMetaObject target = DynamicMetaObject.Create(args[0], parameters[0]);
DynamicMetaObject[] metaArgs = CreateArgumentMetaObjects(args, parameters);
DynamicMetaObject binding = Bind(target, metaArgs);
if (binding == null)
{
throw Error.BindingCannotBeNull();
}
Expression body = binding.Expression;
BindingRestrictions restrictions = binding.Restrictions;
// Ensure the result matches the expected result type.
if (expectedResult != typeof(void) &&
!TypeUtils.AreReferenceAssignable(expectedResult, body.Type))
{
//
// Blame the last person that handled the result: assume it's
// the dynamic object (if any), otherwise blame the language.
//
if (target.Value is IDynamicMetaObjectProvider)
{
throw Error.DynamicObjectResultNotAssignable(body.Type, target.Value.GetType(), this, expectedResult);
}
else
{
throw Error.DynamicBinderResultNotAssignable(body.Type, this, expectedResult);
}
}
// if the target is IDO, standard binders ask it to bind the rule so we may have a target-specific binding.
// it makes sense to restrict on the target's type in such cases.
// ideally IDO metaobjects should do this, but they often miss that type of "this" is significant.
if (IsStandardBinder && args[0] as IDynamicMetaObjectProvider != null)
{
if (restrictions == BindingRestrictions.Empty)
{
throw Error.DynamicBindingNeedsRestrictions(target.Value.GetType(), this);
}
}
// Add the return
if (body.NodeType != ExpressionType.Goto)
{
body = Expression.Return(returnLabel, body);
}
// Finally, add restrictions
if (restrictions != BindingRestrictions.Empty)
{
body = Expression.IfThen(restrictions.ToExpression(), body);
}
return body;
}
private static DynamicMetaObject[] CreateArgumentMetaObjects(object[] args, ReadOnlyCollection<ParameterExpression> parameters)
{
DynamicMetaObject[] mos;
if (args.Length != 1)
{
mos = new DynamicMetaObject[args.Length - 1];
for (int i = 1; i < args.Length; i++)
{
mos[i - 1] = DynamicMetaObject.Create(args[i], parameters[i]);
}
}
else
{
mos = DynamicMetaObject.EmptyMetaObjects;
}
return mos;
}
/// <summary>
/// When overridden in the derived class, performs the binding of the dynamic operation.
/// </summary>
/// <param name="target">The target of the dynamic operation.</param>
/// <param name="args">An array of arguments of the dynamic operation.</param>
/// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public abstract DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args);
/// <summary>
/// Gets an expression that will cause the binding to be updated. It
/// indicates that the expression's binding is no longer valid.
/// This is typically used when the "version" of a dynamic object has
/// changed.
/// </summary>
/// <param name="type">The <see cref="Expression.Type">Type</see> property of the resulting expression; any type is allowed.</param>
/// <returns>The update expression.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public Expression GetUpdateExpression(Type type)
{
return Expression.Goto(CallSiteBinder.UpdateLabel, type);
}
/// <summary>
/// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed.
/// </summary>
/// <param name="target">The target of the dynamic operation.</param>
/// <param name="args">An array of arguments of the dynamic operation.</param>
/// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public DynamicMetaObject Defer(DynamicMetaObject target, params DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(target, "target");
if (args == null)
{
return MakeDeferred(target.Restrictions, target);
}
else
{
return MakeDeferred(
target.Restrictions.Merge(BindingRestrictions.Combine(args)),
args.AddFirst(target)
);
}
}
/// <summary>
/// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed.
/// </summary>
/// <param name="args">An array of arguments of the dynamic operation.</param>
/// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public DynamicMetaObject Defer(params DynamicMetaObject[] args)
{
return MakeDeferred(BindingRestrictions.Combine(args), args);
}
private DynamicMetaObject MakeDeferred(BindingRestrictions rs, params DynamicMetaObject[] args)
{
var exprs = DynamicMetaObject.GetExpressions(args);
Type delegateType = DelegateHelpers.MakeDeferredSiteDelegate(args, ReturnType);
// Because we know the arguments match the delegate type (we just created the argument types)
// we go directly to DynamicExpression.Make to avoid a bunch of unnecessary argument validation
return new DynamicMetaObject(
DynamicExpression.Make(ReturnType, delegateType, this, new TrueReadOnlyCollection<Expression>(exprs)),
rs
);
}
#endregion
// used to detect standard MetaObjectBinders.
internal virtual bool IsStandardBinder
{
get
{
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using DevExpress.XtraEditors.Controls;
namespace OnlineGraph
{
public enum PanType : int
{
PanLeft,
PanRight
}
public partial class OnlineGraphControl : UserControl
{
public delegate void GraphPainted(object sender, EventArgs e);
private GraphLineCollection _lines = new GraphLineCollection();
public event GraphPainted onGraphPainted;
private string _contextDescription = string.Empty;
private string _selectedSymbol = string.Empty;
private bool _panning = false;
public bool Panning
{
get { return _panning; }
set { _panning = value; }
}
private PanType _pantype = PanType.PanLeft;
public PanType Pantype
{
get { return _pantype; }
set { _pantype = value; }
}
private float _zoomfactor = 1;
public float Zoomfactor
{
get { return _zoomfactor; }
set
{
_zoomfactor = value;
Invalidate();
}
}
private DateTime _centerDateTime = DateTime.Now;
public DateTime CenterDateTime
{
get { return _centerDateTime; }
set
{
_centerDateTime = value;
Invalidate();
}
}
private DateTime _mindt = DateTime.Now;
public DateTime Mindt
{
get { return _mindt; }
set { _mindt = value; }
}
private DateTime _maxdt = DateTime.Now;
public DateTime Maxdt
{
get { return _maxdt; }
set { _maxdt = value; }
}
public string ContextDescription
{
get { return _contextDescription; }
set { _contextDescription = value; }
}
private bool m_allowconfig = true;
public bool Allowconfig
{
get { return m_allowconfig; }
set { m_allowconfig = value; }
}
public OnlineGraphControl()
{
InitializeComponent();
}
public void AddMeasurement(string Graphname, string SymbolName, DateTime Timestamp, float value, float minrange, float maxrange, Color linecolor)
{
bool _linefound = false;
//Console.WriteLine(Graphname + " " + SymbolName + " " + value.ToString());
foreach (GraphLine line in _lines)
{
if (line.Symbol == SymbolName)
{
_linefound = true;
// if (value < minrange) minrange = value - 5;
// if (value > maxrange) maxrange = value + 5;
line.AddPoint(value, Timestamp, minrange, maxrange, linecolor);
break;
}
}
if (!_linefound)
{
GraphLine _newline = new GraphLine();
_newline.Symbol = SymbolName;
_newline.ChannelName = Graphname;
_newline.Clear();
_lines.Add(_newline);
// if (value < minrange) minrange = value;
// if (value > maxrange) maxrange = value;
_newline.AddPoint(value, Timestamp, minrange, maxrange, linecolor);
// set visible or invisible according to registry setting
_newline.LineVisible = GetRegistryValue(Graphname);
}
}
private bool GetRegistryValue(string key)
{
RegistryKey TempKey = null;
TempKey = Registry.CurrentUser.CreateSubKey("Software");
bool retval = true;
using (RegistryKey Settings = TempKey.CreateSubKey("T5Suite\\Channels"))
{
if (Settings != null)
{
string[] vals = Settings.GetValueNames();
foreach (string a in vals)
{
try
{
if (a == key.ToUpper())
{
retval = Convert.ToBoolean(Settings.GetValue(a).ToString());
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}
}
return retval;
}
private void WriteLastestValuesToLog(int m_knock)
{
DateTime datet = DateTime.Now;
string logline = datet.ToString("dd/MM/yyyy HH:mm:ss") + "." + datet.Millisecond.ToString("D3") + "|";
foreach (GraphLine line in _lines)
{
logline += line.Symbol + "=" + line.Measurements[line.Measurements.Count - 1].Value.ToString("F2") + "|";
}
logline += "KnockInfo=" + m_knock.ToString() + "|";
using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "-"+ _contextDescription + ".t5l", true))
{
sw.WriteLine(logline);
}
}
public void ForceRepaint(int m_knock)
{
this.Invalidate();
// all new values, write them to a logfile (5tl)
WriteLastestValuesToLog(m_knock);
}
private void OnlineGraphControl_Paint(object sender, PaintEventArgs e)
{
// paint the graphs in the control
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
this.DrawBackground(this.ClientRectangle, e.Graphics);
//this.DrawYScale(this.ClientRectangle, e.Graphics);
//this.DrawYLines(this.ClientRectangle, e.Graphics);
//this.DrawXScale(this.ClientRectangle, e.Graphics);
this.DrawGrid(this.ClientRectangle, e.Graphics);
this.DrawLines(this.ClientRectangle, e.Graphics);
this.DrawLabels(this.ClientRectangle, e.Graphics);
// e.Clipractangle
if (onGraphPainted != null)
{
onGraphPainted(this, EventArgs.Empty);
}
}
private void DrawGrid(Rectangle r, Graphics graphics)
{
int numberofsections = 20;
int numberofscales = 10;
Color c = Color.FromArgb(175, Color.DimGray);
Pen p = new Pen(c);
float sectionwidth = (float)(r.Width - 75) / numberofsections;
float scaleheight = (float)(r.Height) / numberofscales;
for (int xcount = 1; xcount < numberofsections; xcount++)
{
graphics.DrawLine(p, xcount * sectionwidth, 0, xcount * sectionwidth , r.Height);
}
for (int ycount = 1; ycount < numberofscales; ycount++)
{
graphics.DrawLine(p, 0, ycount * scaleheight, r.Width - 75, ycount * scaleheight);
}
p.Dispose();
}
private DateTime GetMinDateTime()
{
DateTime retval = DateTime.Now.AddDays(1);
foreach (GraphLine _line in _lines)
{
foreach (GraphMeasurement gm in _line.Measurements)
{
if (gm.Timestamp < retval) retval = gm.Timestamp;
}
}
return retval;
}
private DateTime GetMaxDateTime()
{
DateTime retval = DateTime.MinValue;
foreach (GraphLine _line in _lines)
{
foreach (GraphMeasurement gm in _line.Measurements)
{
if (gm.Timestamp > retval) retval = gm.Timestamp;
}
}
if (retval == DateTime.MinValue) retval = DateTime.Now;
return retval;
}
private void DrawXScale(Rectangle r, Graphics graphics)
{
_mindt = GetMinDateTime();
_maxdt = GetMaxDateTime();
TimeSpan ts = new TimeSpan(_maxdt.Ticks - _mindt.Ticks);
if (_zoomfactor == 1)
{
_centerDateTime = new DateTime(_mindt.Ticks + ((_maxdt.Ticks - _mindt.Ticks) / 2));
}
else
{
// dan moet er iets gebeuren
_mindt = _centerDateTime.AddTicks(-(long)((ts.Ticks / 2) / _zoomfactor /** 10*/));
_maxdt = _centerDateTime.AddTicks((long)((ts.Ticks / 2) / _zoomfactor /** 10*/));
}
ts = new TimeSpan(_maxdt.Ticks - _mindt.Ticks);
Font f = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular);
Pen pen = new Pen(Color.FromArgb(100, Color.Wheat));
// total number of labels depends on with of the drawing surface
SizeF stringsize = graphics.MeasureString("00/00 00:00:00", f);
int numberoflabels = (r.Width - 100)/ ((int)stringsize.Width + 10);
//Console.WriteLine("dates: " + mindt.ToString("dd/MM HH:mm:ss") + " - " + maxdt.ToString("dd/MM HH:mm:ss") + " #labels: " + numberoflabels.ToString());
for (int xtel = 0; xtel < numberoflabels; xtel++)
{
DateTime xvalue = _mindt.AddTicks(ts.Ticks / numberoflabels * xtel);
PointF p = new PointF(100 + (xtel * ((float)stringsize.Width + 10)) , r.Top + r.Height - 80);
graphics.DrawString(xvalue.ToString("dd/MM HH:mm:ss"), f, Brushes.White, p);
graphics.DrawLine(pen, (int)p.X , r.Top + 10, (int)p.X , r.Top + r.Height - 98);
}
pen.Dispose();
}
private void DrawYScale(Rectangle r, Graphics graphics)
{
float _maxscale = 0;
float _minscale = 0;
bool drawYscale = false;
Color lineColor = Color.White;
if (_lines.Count == 1)
{
_selectedSymbol = _lines[0].Symbol;
}
if (_selectedSymbol != string.Empty)
{
foreach (GraphLine line in _lines)
{
if (line.Symbol == _selectedSymbol)
{
_maxscale = line.Maxrange;
_minscale = line.Minrange;
lineColor = line.LineColor;
drawYscale = true;
//Console.WriteLine("sym: " + line.Symbol + " max = " + _maxscale.ToString() + " min = " + _minscale.ToString());
break;
}
}
}
if (drawYscale)
{
// number to draw is determined by the height of the control and the selected font
SolidBrush sbback = new SolidBrush(this.BackColor);
graphics.FillRectangle(sbback, 0, 0, 100, r.Height);
Pen pen = new Pen(Color.FromArgb(100, Color.Wheat));
SolidBrush sb = new SolidBrush(lineColor);
SizeF stringsize = graphics.MeasureString("000", this.Font);
int numberoflabels = (r.Height - 100) / ((int)stringsize.Height + 20);
//int numberoflabels = 30;
float divisionvalue = (_maxscale - _minscale) / (float)(numberoflabels);
float divisionpixels = (r.Height - 100) / (float)(numberoflabels );
for (int ytel = numberoflabels -1; ytel > 0 ; ytel--)
{
float yvalue = _maxscale - (ytel * divisionvalue);
//PointF p = new PointF(50 - (stringsize.Width / 2), ytel * ((float)stringsize.Height + 20) - (stringsize.Height / 2));
PointF p = new PointF(50 - (stringsize.Width / 2), ytel * divisionpixels);
graphics.DrawString(yvalue.ToString("F2"), this.Font, sb, p);
// graphics.DrawLine(pen, 95, p.Y + stringsize.Height / 2, r.Width - 100, p.Y + stringsize.Height / 2);
}
sbback.Dispose();
sb.Dispose();
pen.Dispose();
}
}
private void DrawYLines(Rectangle r, Graphics graphics)
{
Pen pen = new Pen(Color.FromArgb(100, Color.Wheat));
SizeF stringsize = graphics.MeasureString("000", this.Font);
int numberoflabels = /*30;*/ (r.Height - 100) / ((int)stringsize.Height + 20);
float divisionpixels = (r.Height - 100) / (float)(numberoflabels );
for (int ytel = numberoflabels - 1; ytel > 0; ytel--)
//for (int ytel = 0; ytel < numberoflabels; ytel++)
{
PointF p = new PointF(5, (ytel * divisionpixels)/* ytel * ((float)stringsize.Height + 20)*/ /*- stringsize.Height/2*/);
graphics.DrawLine(pen, 100, p.Y, r.Width - 100, p.Y );
}
pen.Dispose();
}
private void DrawLabels(Rectangle r, Graphics graphics)
{
SolidBrush brsh = new SolidBrush(Color.Red);
int cnt = 0;
foreach (GraphLine line in _lines)
{
if (line.LineVisible)
{
brsh.Color = line.LineColor;
PointF pntF = new PointF((float)(r.Width - 70), (float)((cnt + 1) * 20));
graphics.DrawString(line.ChannelName, this.Font, brsh, pntF);
cnt++;
}
}
// determine scales in Y axis
brsh.Dispose();
}
public void AddMeasurementToCollection(GraphLineCollection coll, string Graphname, string SymbolName, DateTime Timestamp, float value, float minrange, float maxrange, Color linecolor)
{
bool _linefound = false;
foreach (GraphLine line in coll)
{
if (line.Symbol == SymbolName)
{
_linefound = true;
// if (value < minrange) minrange = value - 5;
// if (value > maxrange) maxrange = value + 5;
line.AddPoint(value, Timestamp, minrange, maxrange, linecolor);
break;
}
}
if (!_linefound)
{
GraphLine _newline = new GraphLine();
_newline.Symbol = SymbolName;
_newline.ChannelName = Graphname;
_newline.Clear();
coll.Add(_newline);
_newline.AddPoint(value, Timestamp, minrange, maxrange, linecolor);
_newline.LineVisible = GetRegistryValue(Graphname);
}
}
private GraphLineCollection GetLinesInSelection()
{
GraphLineCollection coll = new GraphLineCollection();
//Console.WriteLine("date selection: " + _mindt.ToString("dd/MM HH:mm:ss") + " - " + _maxdt.ToString("dd/MM HH:mm:ss"));
bool _measurementfound = false;
while (!_measurementfound)
{
foreach (GraphLine _line in _lines)
{
foreach (GraphMeasurement gm in _line.Measurements)
{
if (gm.Timestamp >= _mindt && gm.Timestamp <= _maxdt)
{
_measurementfound = true;
AddMeasurementToCollection(coll, _line.ChannelName, _line.Symbol, gm.Timestamp, gm.Value, _line.Minrange, _line.Maxrange, _line.LineColor);
}
}
}
if (!_measurementfound)
{
if(!(PanToLeft())) _measurementfound = true;
}
}
return coll;
}
private void DrawLines(Rectangle r, Graphics graphics)
{
Pen p = new Pen(Color.Red);
//SolidBrush sb = new SolidBrush(Color.Red);
foreach (GraphLine line in _lines)
{
if (line.LineVisible)
{
//Console.WriteLine("Visible line: " + line.ChannelName);
if (line.Maxrange == 0) line.Maxrange = 1;
//Console.WriteLine(line.Symbol + " contains: " + line.Numberofmeasurements.ToString());
int cnt = 0;
foreach (GraphMeasurement measurement in line.Measurements)
{
//Console.WriteLine(" measurement " + measurement.Timestamp.ToString("HH:mm:ss") + " " + measurement.Value.ToString("F2"));
if (cnt > 0)
{
float sectionwidth = (float)(r.Width - 75) / (float)line.Maxpoints;
float x1 = (float)(cnt - 1) * sectionwidth ;
float x2 = (float)cnt * sectionwidth ;
float y1 = (r.Height ) - (line.Measurements[cnt - 1].Value - line.Minrange) / (line.Maxrange - line.Minrange) * (r.Height );
float y2 = (r.Height ) - (line.Measurements[cnt].Value - line.Minrange) / (line.Maxrange - line.Minrange) * (r.Height );
// Console.WriteLine("Line with value from : " + line.Measurements[cnt -1].Value.ToString() + " and to: " + line.Measurements[cnt].Value.ToString() + " x1: " + x1.ToString() + " y1: " + y1.ToString() + " x2: " + x2.ToString() + " y2: " + y2.ToString());
p.Color = line.LineColor;
//sb.Color = line.LineColor;
graphics.DrawLine(p, x1, y1, x2, y2);
//graphics.FillEllipse(sb, x2-2, y2-2, 4, 4);
//graphics.FillEllipse(sb, x1 - 2, y1 - 2, 4, 4);
}
cnt++;
}
}
}
p.Dispose();
// sb.Dispose();
}
private void DrawBackground(Rectangle r, Graphics graphics)
{
SolidBrush sbback = new SolidBrush(this.BackColor);
graphics.FillRectangle(sbback, 0 , 0, r.Width, r.Height);
sbback.Dispose();
}
private void OnlineGraphControl_Click(object sender, EventArgs e)
{
}
private void DumpLineVisiblity()
{
foreach (GraphLine line in _lines)
{
Console.WriteLine("Channel: " + line.ChannelName + " symbol: " + line.Symbol + " visible: " + line.LineVisible.ToString());
}
}
private void DoConfig()
{
frmLineselection linesel = new frmLineselection();
linesel.TopMost = true;
//linesel.checkedListBoxControl1.DataSource = _lines;
linesel.SetDataSource(_lines);
//DumpLineVisiblity();
if (linesel.ShowDialog() == DialogResult.OK)
{
// save values to file/registry
foreach (CheckedListBoxItem item in linesel.checkedListBoxControl1.Items)
{
foreach (GraphLine line in _lines)
{
if (line.ChannelName == (string)item.Description)
{
if (item.CheckState == CheckState.Unchecked || item.CheckState == CheckState.Indeterminate)
{
line.LineVisible = false;
}
else
{
line.LineVisible = true;
}
break;
}
}
}
SaveConfig();
Invalidate();
}
//DumpLineVisiblity();
}
private void SaveConfig()
{
foreach (GraphLine line in _lines)
{
SaveRegistrySetting(line.ChannelName, line.LineVisible);
}
}
private void SaveRegistrySetting(string key, bool value)
{
RegistryKey TempKey = null;
TempKey = Registry.CurrentUser.CreateSubKey("Software");
using (RegistryKey saveSettings = TempKey.CreateSubKey("T5Suite\\Channels"))
{
saveSettings.SetValue(key.ToUpper(), value);
}
}
private void OnlineGraphControl_MouseClick(object sender, MouseEventArgs e)
{
Point p = PointToClient(e.Location);
// Console.WriteLine(e.Location.X.ToString() + " " + p.X.ToString());
if (e.Button == MouseButtons.Left)
{
if (e.Location.X > this.ClientRectangle.Width - 75)
{
if (m_allowconfig)
{
DoConfig();
}
}
// anders misschien inzoomen
else if (e.Location.Y > this.ClientRectangle.Height - 100)
{
// Console.WriteLine("Zooming in");
// determine centerdatetime by the point the user clicked
_centerDateTime = GetCenterDateTimeByMouseClick(e.Location.X, e.Location.Y);
TryToZoomIn();
}
else
{
// pan left or right depending on position on graph
if (e.Location.X > this.ClientRectangle.Width / 2)
{
// pan right
// Console.WriteLine("Panning right");
PanToRight();
}
else
{
// pan left
// Console.WriteLine("Panning left");
PanToLeft();
}
}
}
else if (e.Button == MouseButtons.Right)
{
// uitzoomen
// Console.WriteLine("Zooming out");
_centerDateTime = GetCenterDateTimeByMouseClick(e.Location.X, e.Location.Y);
TryToZoomOut();
}
}
private DateTime GetCenterDateTimeByMouseClick(int x, int y)
{
// relative y position in selected daterange
DateTime returnvalue = _centerDateTime;
int graphwidth = this.ClientRectangle.Width - 175;
int positioningraph = x - 100;
float percentage = (float)positioningraph / graphwidth;
TimeSpan ts = new TimeSpan(_maxdt.Ticks - _mindt.Ticks);
returnvalue = _mindt.AddTicks((long)(percentage * ts.Ticks));
return returnvalue;
}
private bool PanToLeft()
{
bool _panned = false;
/*if (_zoomfactor == 1)
{
// kan niet pannen nie
}
else
{
_centerDateTime = GetPreviousCenterDateTime(out _panned);
Invalidate();
}*/
return _panned;
}
private DateTime GetNextCenterDateTime(out bool _panned)
{
_panned = true;
// add a percentage depending on zoomfactor
DateTime maxdt = GetMaxDateTime();
DateTime mindt = GetMinDateTime();
TimeSpan ts = new TimeSpan(maxdt.Ticks - mindt.Ticks);
_centerDateTime = _centerDateTime.AddTicks((long)(ts.Ticks / (_zoomfactor * 10)));
if (_centerDateTime > maxdt)
{
_centerDateTime = maxdt.AddTicks(-(long)((ts.Ticks / 50)));
_panned = false;
}
return _centerDateTime;
}
private bool PanToRight()
{
bool _panned = false;
/*if (_zoomfactor == 1)
{
// kan niet pannen nie
}
else
{
_centerDateTime = GetNextCenterDateTime(out _panned);
Invalidate();
}*/
return _panned;
}
private DateTime GetPreviousCenterDateTime(out bool _panned)
{
// substract a percentage depending on zoomfactor
_panned = true;
DateTime maxdt = GetMaxDateTime();
DateTime mindt = GetMinDateTime();
TimeSpan ts = new TimeSpan(maxdt.Ticks - mindt.Ticks);
_centerDateTime = _centerDateTime.AddTicks(-(long)(ts.Ticks / (_zoomfactor * 10)));
if (_centerDateTime < mindt)
{
_centerDateTime = mindt.AddTicks((long)ts.Ticks / 50);
_panned = false;
}
return _centerDateTime;
}
private void TryToZoomOut()
{
/* if (_zoomfactor == 1)
{
}
else if (_zoomfactor <= 1)
{
_zoomfactor = 1;
Invalidate();
}
else
{
// zoomfactor > 1
_zoomfactor-=2;
Invalidate();
}*/
}
private void TryToZoomIn()
{
/*if (_zoomfactor == 40)
{
}
else if (_zoomfactor > 40)
{
_zoomfactor = 40;
Invalidate();
}
else
{
_zoomfactor+=2;
Invalidate();
}*/
}
private double ConvertToDouble(string v)
{
double d = 0;
if (v == "") return d;
string vs = "";
vs = v.Replace(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator, System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
Double.TryParse(vs, out d);
return d;
}
private Color GetGraphColor(string symbolname)
{
Color retval = Color.White;
symbolname = symbolname.ToUpper();
if (symbolname == "BIL_HAST") retval = Color.LightGreen;
else if (symbolname == "P_MANIFOLD") retval = Color.Red;
else if (symbolname == "P_MANIFOLD10") retval = Color.Red;
else if (symbolname == "LUFTTEMP") retval = Color.LightBlue;
else if (symbolname == "KYL_TEMP") retval = Color.LightGray;
else if (symbolname == "AD_SOND") retval = Color.Yellow;
else if (symbolname == "AD_EGR") retval = Color.GreenYellow;
else if (symbolname == "RPM") retval = Color.Gold;
else if (symbolname == "INSPTID_MS10") retval = Color.Firebrick;
else if (symbolname == "GEAR") retval = Color.Purple;
else if (symbolname == "APC_DECRESE") retval = Color.LightPink;
else if (symbolname == "IGN_ANGLE") retval = Color.LightSeaGreen;
else if (symbolname == "P_FAK") retval = Color.LightYellow;
else if (symbolname == "I_FAK") retval = Color.LightSteelBlue;
else if (symbolname == "D_FAK") retval = Color.AntiqueWhite;
else if (symbolname == "REGL_TRYCK") retval = Color.RosyBrown;
else if (symbolname == "MAX_TRYCK") retval = Color.Pink;
else if (symbolname == "PWM_UT10") retval = Color.PaleGreen;
else if (symbolname == "REG_KON_APC") retval = Color.PapayaWhip;
else if (symbolname == "MEDELTROT") retval = Color.SpringGreen;
else if (symbolname == "TORT_MIN") retval = Color.Silver;
else if (symbolname == "KNOCK_MAP_OFFSET") retval = Color.DarkTurquoise;
else if (symbolname == "KNOCK_OFFSETT1234") retval = Color.Aqua;
else if (symbolname == "KNOCK_AVERAGE") retval = Color.Orange;
else if (symbolname == "KNOCK_AVERAGE_LIMIT") retval = Color.OliveDrab;
else if (symbolname == "KNOCK_LEVEL") retval = Color.OrangeRed;
else if (symbolname == "KNOCK_MAP_LIM") retval = Color.Navy;
else if (symbolname == "KNOCK_LIM") retval = Color.Moccasin;
else if (symbolname == "KNOCK_REF_LEVEL") retval = Color.SeaShell;
else if (symbolname == "LKNOCK_OREF_LEVEL") retval = Color.MistyRose;
else if (symbolname == "SPIK_COUNT") retval = Color.Brown;
else if (symbolname == "KNOCK_DIAG_LEVEL") retval = Color.Chartreuse;// (groter maken)
else if (symbolname == "KNOCK_ANG_DEC!") retval = Color.DarkGoldenrod;
return retval;
}
private string GetGraphName(string symbolname)
{
string retval = symbolname;
symbolname = symbolname.ToUpper();
if (symbolname == "BIL_HAST") retval = "Speed";
else if (symbolname == "P_MANIFOLD") retval = "Boost";
else if (symbolname == "P_MANIFOLD10") retval = "Boost";
else if (symbolname == "LUFTTEMP") retval = "IAT";
else if (symbolname == "KYL_TEMP") retval = "Coolant";
else if (symbolname == "AD_SOND") retval = "Lambda A/D";
else if (symbolname == "RPM") retval = "Rpm";
else if (symbolname == "INSPTID_MS10") retval = "Inj.dur";
else if (symbolname == "GEAR") retval = "Gear";
else if (symbolname == "APC_DECRESE") retval = "APCD";
else if (symbolname == "IGN_ANGLE") retval = "Ign.angle";
else if (symbolname == "P_FAK") retval = "P factor";
else if (symbolname == "I_FAK") retval = "I factor";
else if (symbolname == "D_FAK") retval = "D factor";
else if (symbolname == "REGL_TRYCK") retval = "Target boost";
else if (symbolname == "MAX_TRYCK") retval = "Max boost";
else if (symbolname == "PWM_UT10") retval = "APC PWM";
else if (symbolname == "REG_KON_APC") retval = "Reg. value";
else if (symbolname == "MEDELTROT") retval = "TPS";
else if (symbolname == "TROT_MIN") retval = "TPS offset";
else if (symbolname == "KNOCK_MAP_OFFSET") retval = "Map offset";
else if (symbolname == "KNOCK_OFFSET1234") retval = "Offset1234";
else if (symbolname == "KNOCK_AVERAGE") retval = "Average";
else if (symbolname == "KNOCK_AVERAGE_LIMIT") retval = "Average limit";
else if (symbolname == "KNOCK_LEVEL") retval = "Level";
else if (symbolname == "KNOCK_MAP_LIM") retval = "Ign.map limit";
else if (symbolname == "KNOCK_LIM") retval = "Map limit";
else if (symbolname == "KNOCK_REF_LEVEL") retval = "Ref. level";
else if (symbolname == "LKNOCK_OREF_LEVEL") retval = "ORef level";
else if (symbolname == "SPIK_COUNT") retval = "Spik";
else if (symbolname == "KNOCK_DIAG_LEVEL") retval = "Diag level";// (groter maken)
else if (symbolname == "KNOCK_ANG_DEC!") retval = "Ign. decrease";
return retval;
}
public void ImportT5Logfile(string filename)
{
frmProgress progress = new frmProgress();
progress.Show();
Application.DoEvents();
if(File.Exists(filename))
{
_lines.Clear();
_zoomfactor = 1;
FileInfo fi = new FileInfo(filename);
long bytesread = 0;
using (StreamReader sr = new StreamReader(filename))
{
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
bytesread += line.Length + 2;
progress.SetProgressPercentage((int)(bytesread * 100 / fi.Length));
char[] sep = new char[1];
sep.SetValue('|', 0);
char[] sepequals = new char[1];
sepequals.SetValue('=', 0);
if (line.Length > 0)
{
//10/03/2009 07:33:06.187|P_Manifold10=-0.64|Lufttemp=8.00|Rpm=1660.00|Bil_hast=15.20|Ign_angle=28.50|AD_EGR=127.00|AFR=17.86|InjectorDC=2.49|Power=0.00|Torque=0.00|
// fetch all values from the line including the timestamp
string[] values = line.Split(sep);
if (values.Length > 1)
{
try
{
DateTime dt = Convert.ToDateTime(values.GetValue(0));
for (int tel = 1; tel < values.Length; tel++)
{
string valuepart = (string)values.GetValue(tel);
string[] valueparts = valuepart.Split(sepequals);
if (valueparts.Length == 2)
{
string symbol = (string)valueparts.GetValue(0);
string strvalue = (string)valueparts.GetValue(1);
double dval = ConvertToDouble(strvalue);
this.AddMeasurement(GetGraphName(symbol), symbol, dt, (float)dval, 0, 1, GetGraphColor(symbol));
}
}
}
catch (Exception E)
{
Console.WriteLine("Failed to process line: " + line + " : " + E.Message);
}
}
}
}
foreach (GraphLine _line in _lines)
{
float _min = 0;
float _max = -10000;
foreach (GraphMeasurement gm in _line.Measurements)
{
if (gm.Value > _max) _max = gm.Value;
if (gm.Value < _min) _min = gm.Value;
}
DetermineRange(_line, _min, _max);
}
}
}
progress.Close();
}
private void DetermineRange(GraphLine _line, float _min, float _max)
{
_line.Maxrange = _max * 1.05F;
_line.Minrange = _min * 1.05F;
switch (_line.Symbol.ToUpper())
{
case "RPM":
_line.Minrange = 0;
_line.Maxrange = 7000;
break;
case "BIL_HAST":
_line.Minrange = 0;
_line.Maxrange = 300;
break;
case "P_MANIFOLD":
case "P_MANIFOLD10":
case "REGL_TRYCK":
case "MAX_TRYCK":
_line.Minrange = -1;
_line.Maxrange = 2;
break;
case "LUFTTEMP":
_line.Minrange = -30;
_line.Maxrange = 120;
break;
case "KYL_TEMP":
_line.Minrange = -30;
_line.Maxrange = 120;
break;
case "INSPTID_MS10":
_line.Minrange = 0;
_line.Maxrange = 50;
break;
case "GEAR":
_line.Minrange = -1;
_line.Maxrange = 5;
break;
case "APC_DECRESE":
case "APC_DECREASE":
_line.Minrange = 0;
_line.Maxrange = 200;
break;
case "IGN_ANGLE":
_line.Minrange = -10;
_line.Maxrange = 50;
break;
case "PWM_UT10":
case "REG_KON_APC":
_line.Minrange = 0;
_line.Maxrange = 100;
break;
case "MODELTROT":
case "TROT_MIN":
_line.Minrange = 0;
_line.Maxrange = 255;
break;
case "AFR":
case "wAFR":
case "AD_EGR":
case "AD_SOND":
_line.Minrange = 7;
_line.Maxrange = 23;
break;
_line.Minrange = 0;
_line.Maxrange = 255;
break;
}
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
// paint the graphs in the control
//this.DrawBackground(e.ClipRectangle, e.Graphics);
//this.DrawGrid(e.ClipRectangle, e.Graphics);
//this.DrawLines(e.ClipRectangle, e.Graphics);
//Console.WriteLine("Done painting panel2");
//this.DrawLabels(e.Graphics);
/*foreach(GraphLine line in _lines)
{
Console.WriteLine(line.Symbol + " contains: " + line.Numberofmeasurements.ToString());
foreach (GraphMeasurement measurement in line.Measurements)
{
Console.WriteLine(" measurement " + measurement.Timestamp.ToString("HH:mm:ss") + " " + measurement.Value.ToString("F2"));
}
}*/
}
private string DetermineGraphNameByLinesPosition(Rectangle r, float x, float y,out DateTime measurementdt, out float value, out bool _valid)
{
float _max_dev = 3;
_valid = false;
measurementdt = DateTime.Now;
value = 0;
GraphLineCollection linesinselection = GetLinesInSelection();
foreach (GraphLine line in linesinselection)
{
if (line.LineVisible)
{
int cnt = 0;
foreach (GraphMeasurement measurement in line.Measurements)
{
if (cnt > 0)
{
//Console.WriteLine(" measurement " + measurement.Timestamp.ToString("HH:mm:ss") + " " + measurement.Value.ToString("F2"));
float sectionwidth = (float)(r.Width - 175) / (float)line.Maxpoints;
float x1 = (float)(cnt - 1) * sectionwidth + 100;
float x2 = (float)cnt * sectionwidth + 100;
float y1 = (r.Height - 100) - (line.Measurements[cnt - 1].Value - line.Minrange) / (line.Maxrange - line.Minrange) * (r.Height - 100);
float y2 = (r.Height - 100) - (line.Measurements[cnt].Value - line.Minrange) / (line.Maxrange - line.Minrange) * (r.Height - 100);
if (Math.Abs(x1 - x) <= _max_dev && Math.Abs(y1 - y) <= _max_dev)
{
value = line.Measurements[cnt - 1].Value;
measurementdt = line.Measurements[cnt - 1].Timestamp;
//Console.WriteLine("Match: " + value.ToString() + " dt: " + measurementdt.ToString("dd/MM HH:mm:ss") + " x1: " + x1.ToString() + " y1: " + y1.ToString() + " x2: " + x2.ToString() + " y2: " + y2.ToString());
_valid = true;
return line.Symbol;
}
else if (Math.Abs(x2 - x) <= _max_dev && Math.Abs(y2 - y) <= _max_dev)
{
value = measurement.Value;
measurementdt = measurement.Timestamp;
_valid = true;
//Console.WriteLine("Match: " + value.ToString() + " dt: " + measurementdt.ToString("dd/MM HH:mm:ss") + " x1: " + x1.ToString() + " y1: " + y1.ToString() + " x2: " + x2.ToString() + " y2: " + y2.ToString());
return line.Symbol;
}
}
cnt++;
}
}
}
return string.Empty;
}
private void OnlineGraphControl_MouseMove(object sender, MouseEventArgs e)
{
// check whether we're close to one of the lines in the graph
// or over one of the labels in the legenda
DateTime measurement = DateTime.Now;
float value = 0;
bool _valid = false;
//Point p = PointToClient(e.Location);
_selectedSymbol = DetermineGraphNameByLinesPosition(this.Bounds, (float)e.X, (float)e.Y, out measurement, out value, out _valid);
// only redraw the yaxis
this.DrawYScale(this.ClientRectangle, this.CreateGraphics());
if (_selectedSymbol != string.Empty && _valid)
{
//toolTip1.Show(_selectedSymbol + "=" + value.ToString("F2") + " at " + measurement.ToString("dd/MM/yyyy HH:mm:ss"), this);
// update the labels that reflect the current values for all lines
label1.Text = _selectedSymbol + "=" + value.ToString("F2") + " at " + measurement.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
label1.Text = "";
}
// Invalidate();
}
private void OnlineGraphControl_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void OnlineGraphControl_MouseDown(object sender, MouseEventArgs e)
{
_panning = true;
Point p = PointToClient(e.Location);
if (e.Button == MouseButtons.Left)
{
if (e.Location.X > this.ClientRectangle.Width - 75)
{
}
// anders misschien inzoomen
else if (e.Location.Y > this.ClientRectangle.Height - 100)
{
}
else
{
// pan left or right depending on position on graph
if (e.Location.X > this.ClientRectangle.Width / 2)
{
// pan right
_pantype = PanType.PanRight;
PanToRight();
}
else
{
// pan left
_pantype = PanType.PanLeft;
PanToLeft();
}
}
}
}
private void OnlineGraphControl_MouseUp(object sender, MouseEventArgs e)
{
_panning = false;
}
private void OnlineGraphControl_MouseLeave(object sender, EventArgs e)
{
_panning = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_panning)
{
if (_pantype == PanType.PanLeft)
{
if (!PanToLeft())
{
_panning = false;
}
}
else
{
if (!PanToRight())
{
_panning = false;
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
namespace MetsParser
{
public class IssueList
{
//
// Issue Errors
//
internal enum IssueError { None = 0x00, Gap = 0x01, IssueSequence = 0x02 };
//
// ArrayList To Hold Issues
//
ArrayList ArrayListIssues;
//
// Class To Contain List Of Issues
//
public IssueList()
{
ArrayListIssues = new ArrayList();
}
//
// Add New Issue To List
//
internal void AddIssue(StreamWriter StreamWriterLog, String StrMetsFile, String StrMetsIssue, String StrMetsVolume, String StrMetsDate, String StrModsTitle)
{
ArrayListIssues.Add(new Issue(StreamWriterLog, StrMetsFile, StrMetsIssue, StrMetsVolume, StrMetsDate, StrModsTitle));
return;
}
//
// Sort Issues Into Date Order
//
internal void Sort()
{
int iIssueCount = ArrayListIssues.Count;
//
// Allocate Arrays
//
long[] lArrayListDates = new long[iIssueCount];
int[] iArrayListIndex = new int[iIssueCount];
//
// Load Arrays
//
for (int iListInx = 0; iListInx < iIssueCount; iListInx += 1)
{
Issue IssueThis = (Issue)ArrayListIssues[iListInx];
lArrayListDates[iListInx] = IssueThis.Ticks();
iArrayListIndex[iListInx] = iListInx;
}
//
// Sort
//
Array.Sort(lArrayListDates, iArrayListIndex);
//
// Create New ArrayList & Load
//
ArrayList ArrayListIssuesNew = new ArrayList();
for (int iListInx = 0; iListInx < iIssueCount; iListInx += 1)
{
ArrayListIssuesNew.Add(ArrayListIssues[iArrayListIndex[iListInx]]);
}
//
// Copy New ArrayList To Old
//
ArrayListIssues = ArrayListIssuesNew;
//
return;
}
//
// Display Title
//
internal void DisplayTitle(StreamWriter StreamWriterLog)
{
Issue IssueThis = (Issue)ArrayListIssues[0];
if (IssueThis != null)
{
WriteLine(StreamWriterLog, "");
Console.Out.WriteLine();
WriteLine(StreamWriterLog, IssueThis.GetTitle());
Console.Out.WriteLine(IssueThis.GetTitle());
}
return;
}
//
// Report Assume Sorted
//
internal void Report(StreamWriter StreamWriterLog)
{
int iIssue = -1;
int iIssueOld = -1;
Issue IssueThis = null;
Issue IssueOld = null;
double[] dDaysOfWeek = new double[7];
for (int iListInx = 0; iListInx < ArrayListIssues.Count; iListInx += 1)
{
//
// Get Issue
//
IssueOld = IssueThis;
IssueThis = (Issue)ArrayListIssues[iListInx];
dDaysOfWeek[(int )IssueThis.GetIssueDate().DayOfWeek] += 1.0;
//
// Check Issue Sequence If Year Difference Is Equal Or Less Than 1
//
if ((IssueThis != null) && (IssueOld != null) &&
((Math.Abs(IssueThis.GetIssueDate().Year - IssueOld.GetIssueDate().Year) <= 1)))
{
iIssueOld = iIssue;
iIssue = IssueThis.GetIssue();
if ((iIssueOld != -1) && ((iIssueOld + 1) != iIssue))
{
IssueOld.SetErrorFlag(IssueError.IssueSequence);
}
}
//
}
//
// Output Issues Data
//
Issue IssueGood = null;
bool fTimeGapError = false;
for (int iListInx = 0; iListInx < ArrayListIssues.Count; iListInx += 1)
{
//
// Get Issue
//
IssueOld = IssueThis;
IssueThis = (Issue)ArrayListIssues[iListInx];
DateTime DateTimeThis = IssueThis.GetIssueDate();
//
// Write Output
//
Write(StreamWriterLog, IssueThis.GetNLP());
if (fTimeGapError == true)
WriteLine(StreamWriterLog, " " + IssueThis.GetStrDate() + " Publication Pattern Error - Issue Not Expected On This Date");
else
{
WriteLine(StreamWriterLog, " " + IssueThis.GetStrDate() + " ok");
IssueGood = IssueThis;
}
fTimeGapError = false;
IssueError IssueErrorThis = IssueThis.GetErrorFlag();
if (IssueErrorThis == (IssueError.Gap | IssueError.IssueSequence))
{
//
// Number Of Issues Missing
//
Issue IssueNext = (Issue)ArrayListIssues[iListInx + 1];
DateTime DateTimeNext = IssueNext.GetIssueDate();
int iIssuesToInsert = IssueNext.GetIssue() - IssueThis.GetIssue() - 1;
//
// Average Number Of Days Between Publications
//
double dAverageDays = IssueThis.GetAverageDays();
if (dAverageDays < 6.0)
{
//
// Day Of The Week For Valid Publication
//
int iDayOfWeek = (int )DateTimeThis.DayOfWeek;
//
// Threshold Number Of Publications To Make This Day Of The Week A Legitimate Publication Day
//
double dDayOfWeekThreshold = dDaysOfWeek[iDayOfWeek] * 0.6;
DateTime DateTimeGood = IssueGood.GetIssueDate();
int iDayCount = 0;
for (int iInsertInx = 0; iInsertInx < iIssuesToInsert; iInsertInx += 1)
{
iDayOfWeek = (iDayOfWeek + 1) % 7;
iDayCount += 1;
if (dDaysOfWeek[iDayOfWeek] > dDayOfWeekThreshold)
{
DateTime DateTimeNew = DateTimeGood.AddDays((double)iDayCount);
if (DateTimeNew < DateTimeNext)
{
//
// Write Additional Record
//
Write(StreamWriterLog, IssueThis.GetNLP());
WriteLine(StreamWriterLog, " " + DateTimeNew.ToString("yyyy-MM-dd") + " Inserted Entry Date and Issue Number Gap Found");
//
}
}
}
}
else
{
int iWeekGap = (int)((dAverageDays + 4) / 7);
DateTime DateTimeGood = IssueGood.GetIssueDate();
DateTime DateTimeNew = DateTimeGood.AddDays((double)(iWeekGap * 7));
while (DateTimeNew < DateTimeNext)
{
//
// Write Additional Record
//
Write(StreamWriterLog, IssueThis.GetNLP());
WriteLine(StreamWriterLog, " " + DateTimeNew.ToString("yyyy-MM-dd") + " Inserted Entry Date and Issue Number Gap Found");
DateTimeNew = DateTimeNew.AddDays((double)(iWeekGap * 7));
//
}
//
// Get Next Date - Set Error Flag If Not Next Issue Date
//
TimeSpan TimeSpanDays = DateTimeNext - DateTimeNew;
if (TimeSpanDays.Days != 0)
{
fTimeGapError = true;
}
}
}
//
}
//
return;
}
//
// Write Line
//
void WriteLine(StreamWriter StreamWriterLog, String StrLine)
{
if (StreamWriterLog != null)
StreamWriterLog.WriteLine(StrLine);
else
Console.Out.WriteLine(StrLine);
return;
}
//
// Write
//
void Write(StreamWriter StreamWriterLog, String StrLine)
{
if (StreamWriterLog != null)
StreamWriterLog.Write(StrLine);
else
Console.Out.Write(StrLine);
return;
}
//
// Do Publication Pattern Analysis
//
internal void PublicationPattern(StreamWriter StreamWriterLog)
{
//
// Get Day of Week Information For Each Year In Turn
//
int[] iDayOfWeekCount = new int[7];
int iYear = -1;
int iYearBegInx = 0;
int iYearEndInx = 0;
for (int iListInx = 0; iListInx < ArrayListIssues.Count; iListInx += 1)
{
//
// Get Issue & Day Of Week
//
Issue IssueThis = (Issue)ArrayListIssues[iListInx];
DateTime DateTimeIssue = IssueThis.GetIssueDate();
//
// Initalise Year
//
if (iYear == -1)
iYear = DateTimeIssue.Year;
//
// Determine If Year Has Changed
//
if (iYear != DateTimeIssue.Year)
{
iYearEndInx = iListInx - 1;
//
// Compute Average Number Of Days Between Issues For This Year
//
double dAverageDaysBetweeenIssues = 365 / (double)(iYearEndInx - iYearBegInx + 1);
//
// Go Through List Again Looking For Gap Between Issues
//
int iDayOfYear = -1;
Issue IssueYearOld = null;
Issue IssueYear = null;
for (int iYearInx = iYearBegInx; iYearInx <= iYearEndInx; iYearInx += 1)
{
IssueYearOld = IssueYear;
IssueYear = (Issue)ArrayListIssues[iYearInx];
DateTime DateTimeYear = IssueYear.GetIssueDate();
if (iDayOfYear == -1)
iDayOfYear = DateTimeYear.DayOfYear;
else
{
int iDayDifference = Math.Abs(DateTimeYear.DayOfYear - iDayOfYear);
if ((iDayDifference > (dAverageDaysBetweeenIssues * 1.3)) ||
(iDayDifference < (dAverageDaysBetweeenIssues * 0.8)))
{
IssueYearOld.SetErrorFlag(IssueError.Gap);
IssueYearOld.SetAverageDays(dAverageDaysBetweeenIssues);
//Console.Out.WriteLine("Error Big Gap In Publication Dates, Average = " + dAverageDaysBetweeenIssues);
//Console.Out.WriteLine(IssueYearOld.GetStrDate() + " File: " + IssueYearOld.GetFileName());
//Console.Out.WriteLine(IssueYear.GetStrDate() + " File: " + IssueYear.GetFileName());
//StreamWriterLog.WriteLine("Error Big Gap In Publication Dates, Average = " + dAverageDaysBetweeenIssues);
//StreamWriterLog.WriteLine(IssueYearOld.GetStrDate() + " File: " + IssueYearOld.GetFileName());
//StreamWriterLog.WriteLine(IssueYear.GetStrDate() + " File: " + IssueYear.GetFileName());
}
iDayOfYear = DateTimeYear.DayOfYear;
}
}
//
iYearBegInx = iListInx;
iYear = DateTimeIssue.Year;
}
}
return;
}
//
// Number Of Issues
//
internal int Count
{
get { return (ArrayListIssues.Count); }
}
//
// Issue Class
//
internal class Issue
{
//
// Passed Values
//
String StrMetsFile;
String StrMetsIssue;
String StrMetsVolume;
String StrMetsDate;
String StrModsTitle;
//
// Computed Values
//
int iIssue;
int iVolume;
DateTime DateTimeIssue;
DateTime DateTimeFileName;
double dAverageDays;
//
// Error Flag
//
IssueError IssueErrorThis;
//
// Initalisation
//
internal Issue(StreamWriter StreamWriterLog, String StrMetsFile, String StrMetsIssue, String StrMetsVolume, String StrMetsDate, String StrModsTitle)
{
this.StrMetsFile = StrMetsFile;
this.StrMetsIssue = StrMetsIssue;
this.StrMetsVolume = StrMetsVolume;
this.StrMetsDate = StrMetsDate;
this.StrModsTitle = StrModsTitle;
//
// Error Flag
//
IssueErrorThis = IssueError.None;
//
// Convert To Numbers If Possible
//
iIssue = GetNumber(StrMetsIssue);
iVolume = GetNumber(StrMetsVolume);
DateTimeIssue = GetDate(StrMetsDate);
//
// Parse FileName For Date
//
DateTimeFileName = GetFileNameDate(StrMetsFile);
//
// Compare Year, Month & Day
//
if ((DateTimeIssue.Year != DateTimeFileName.Year) ||
(DateTimeIssue.Month != DateTimeFileName.Month) ||
(DateTimeIssue.Day != DateTimeFileName.Day))
{
Console.Out.WriteLine("Error: Date Mismatch Between Mods Filename: " + StrMetsFile + " and Mods File Content: " + DateTimeIssue.ToString());
StreamWriterLog.WriteLine("Error: Date Mismatch Between Mods Filename: " + StrMetsFile + " and Mods File Content: " + DateTimeIssue.ToString());
}
//
}
//
// Get Number
//
int GetNumber(String StrValue)
{
int iValue = -1;
if (StrValue != null)
{
try
{
iValue = int.Parse(StrValue);
}
catch { }
}
return (iValue);
}
//
// Get Date yyyy-mm-dd
//
DateTime GetDate(String StrDate)
{
DateTime DateTimeThis = new DateTime(1, 1, 1);
//
// 0123456789
// Date Is In Format YYYY-MM-DD
//
int iYear = -1;
int iMonth = -1;
int iDay = -1;
if (StrDate.Length >= 10)
{
iYear = GetNumber(StrDate.Substring(0, 4));
iMonth = GetNumber(StrDate.Substring(5, 2));
iDay = GetNumber(StrDate.Substring(8, 2));
}
//
// Ensure Values Are Reasonable
//
if ((iYear > 0) && (iMonth > 0) && (iMonth <= 12) && (iDay > 0) && (iDay <= 31))
{
DateTimeThis = new DateTime(iYear, iMonth, iDay);
}
//
return (DateTimeThis);
}
//
// Get Date From File Name
//
DateTime GetFileNameDate(String StrMetsFile)
{
DateTime DateTimeThis = new DateTime(1, 1, 1);
//
// 9876543211987654321
// nnnnnnn_yyyymmdd_mets.xml (nnnnnnn - NLP; yyyy - Year; mm - Month; dd - Day)
// 0000187_18200106_mets.xml
//
int iYear = -1;
int iMonth = -1;
int iDay = -1;
if (StrMetsFile.Length >= 25)
{
int iLength = StrMetsFile.Length;
iYear = GetNumber(StrMetsFile.Substring(iLength - 17, 4));
iMonth = GetNumber(StrMetsFile.Substring(iLength - 13, 2));
iDay = GetNumber(StrMetsFile.Substring(iLength - 11, 2));
}
//
// Ensure Values Are Reasonable
//
if ((iYear > 0) && (iMonth > 0) && (iMonth <= 12) && (iDay > 0) && (iDay <= 31))
{
DateTimeThis = new DateTime(iYear, iMonth, iDay);
}
//
return (DateTimeThis);
}
//
// Ticks For Issue Date
//
internal long Ticks()
{
return (DateTimeIssue.Ticks);
}
//
// Get StrDate
//
internal String GetStrDate()
{
String StrDate = DateTimeIssue.ToString("yyyy-MM-dd");
return (StrDate);
}
//
// Get Date
//
internal DateTime GetIssueDate()
{
return (DateTimeIssue);
}
//
// Get Issue
//
internal int GetIssue()
{
return (iIssue);
}
//
// Get FileName
//
internal String GetFileName()
{
return (StrMetsFile);
}
//
// Get Title
//
internal String GetTitle()
{
return (StrModsTitle);
}
//
// Set Error Flag
//
internal void SetErrorFlag(IssueError IssueErrorThis)
{
this.IssueErrorThis |= IssueErrorThis;
return;
}
//
// Get Error Flag
//
internal IssueError GetErrorFlag()
{
return (IssueErrorThis);
}
//
// Get NLP
//
internal String GetNLP()
{
int iMetsXml = StrMetsFile.IndexOf("_mets.xml");
String StrNLP = "";
if (iMetsXml >= 16)
StrNLP = StrMetsFile.Substring(iMetsXml - 16, 7);
return (StrNLP);
}
//
// Set Average Days
//
internal void SetAverageDays(double dAverageDays)
{
this.dAverageDays = dAverageDays;
return;
}
//
// Get Average Days
//
internal double GetAverageDays()
{
return (dAverageDays);
}
}
}
}
| |
using System;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Provides helper overloads to a <see cref = "Configuration" />.
/// </summary>
public static class ConfigurationExtensions
{
/// <summary>
/// Delete a configuration variable (key and value).
/// </summary>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "key">The key to delete.</param>
/// <param name = "level">The configuration file which should be considered as the target of this operation</param>
[Obsolete("This method will be removed in the next release. Please use Unset() instead.")]
public static void Delete(this Configuration config, string key,
ConfigurationLevel level = ConfigurationLevel.Local)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
config.Unset(key, level);
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare", false);
/// </code>
/// </para>
/// </summary>
/// <typeparam name = "T">The configuration value type</typeparam>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "key">The key</param>
/// <param name = "defaultValue">The default value</param>
/// <returns>The configuration value, or <c>defaultValue</c> if not set</returns>
[Obsolete("This method will be removed in the next release. Please use a different overload instead.")]
public static T Get<T>(this Configuration config, string key, T defaultValue)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
var val = config.Get<T>(key);
return val == null ? defaultValue : val.Value;
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core", "bare", false);
/// </code>
/// </para>
/// </summary>
/// <typeparam name = "T">The configuration value type</typeparam>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "firstKeyPart">The first key part</param>
/// <param name = "secondKeyPart">The second key part</param>
/// <param name = "defaultValue">The default value</param>
/// <returns>The configuration value, or <c>defaultValue</c> if not set</returns>
[Obsolete("This method will be removed in the next release. Please use a different overload instead.")]
public static T Get<T>(this Configuration config, string firstKeyPart, string secondKeyPart, T defaultValue)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
return config.Get(new[] { firstKeyPart, secondKeyPart }, defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [difftool "kdiff3"]
/// path = c:/Program Files/KDiff3/kdiff3.exe
/// </code>
///
/// You would call:
///
/// <code>
/// string where = repo.Config.Get<string>("difftool", "kdiff3", "path", null);
/// </code>
/// </para>
/// </summary>
/// <typeparam name = "T">The configuration value type</typeparam>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "firstKeyPart">The first key part</param>
/// <param name = "secondKeyPart">The second key part</param>
/// <param name = "thirdKeyPart">The third key part</param>
/// <param name = "defaultValue">The default value</param>
/// <returns>The configuration value, or <c>defaultValue</c> if not set</returns>
[Obsolete("This method will be removed in the next release. Please use a different overload instead.")]
public static T Get<T>(this Configuration config, string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "secondKeyPart");
return config.Get(new[] { firstKeyPart, secondKeyPart, thirdKeyPart }, defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>(new []{ "core", "bare" }, false);
/// </code>
/// </para>
/// </summary>
/// <typeparam name = "T">The configuration value type</typeparam>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "keyParts">The key parts</param>
/// <param name = "defaultValue">The default value</param>
/// <returns>The configuration value, or <c>defaultValue</c> if not set</returns>
[Obsolete("This method will be removed in the next release. Please use a different overload instead.")]
public static T Get<T>(this Configuration config, string[] keyParts, T defaultValue)
{
Ensure.ArgumentNotNull(keyParts, "keyParts");
return config.Get(string.Join(".", keyParts), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>(new []{ "core", "bare" }).Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name = "T">The configuration value type</typeparam>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "keyParts">The key parts</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public static ConfigurationEntry<T> Get<T>(this Configuration config, string[] keyParts)
{
Ensure.ArgumentNotNull(keyParts, "keyParts");
return config.Get<T>(string.Join(".", keyParts));
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [difftool "kdiff3"]
/// path = c:/Program Files/KDiff3/kdiff3.exe
/// </code>
///
/// You would call:
///
/// <code>
/// string where = repo.Config.Get<string>("difftool", "kdiff3", "path").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name = "T">The configuration value type</typeparam>
/// <param name = "config">The configuration being worked with.</param>
/// <param name = "firstKeyPart">The first key part</param>
/// <param name = "secondKeyPart">The second key part</param>
/// <param name = "thirdKeyPart">The third key part</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public static ConfigurationEntry<T> Get<T>(this Configuration config, string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "secondKeyPart");
return config.Get<T>(new[] { firstKeyPart, secondKeyPart, thirdKeyPart });
}
}
}
| |
// 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.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal class WinHttpWebSocket : WebSocket
{
#region Constants
// TODO (#7893): This code needs to be shared with WinHttpClientHandler
private const string HeaderNameCookie = "Cookie";
private const string HeaderNameWebSocketProtocol = "Sec-WebSocket-Protocol";
#endregion
// TODO (Issue 2503): move System.Net.* strings to resources as appropriate.
// NOTE: All WinHTTP operations must be called while holding the _operation.Lock.
// It is critical that no handle gets closed while a WinHTTP function is running.
private WebSocketCloseStatus? _closeStatus = null;
private string _closeStatusDescription = null;
private string _subProtocol = null;
private bool _disposed = false;
private WinHttpWebSocketState _operation = new WinHttpWebSocketState();
public WinHttpWebSocket()
{
}
#region Properties
public override WebSocketCloseStatus? CloseStatus
{
get
{
return _closeStatus;
}
}
public override string CloseStatusDescription
{
get
{
return _closeStatusDescription;
}
}
public override WebSocketState State
{
get
{
return _operation.State;
}
}
public override string SubProtocol
{
get
{
return _subProtocol;
}
}
#endregion
static readonly WebSocketState[] s_validConnectStates = { WebSocketState.None };
static readonly WebSocketState[] s_validConnectingStates = { WebSocketState.Connecting };
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validConnectingStates);
// Must grab lock until RequestHandle is populated, otherwise we risk resource leaks on Abort.
//
// TODO (Issue 2506): Alternatively, release the lock between WinHTTP operations and check, under lock, that the
// state is still valid to continue operation.
_operation.SessionHandle = InitializeWinHttp(options);
_operation.ConnectionHandle = Interop.WinHttp.WinHttpConnectWithCallback(
_operation.SessionHandle,
uri.IdnHost,
(ushort)uri.Port,
0);
ThrowOnInvalidHandle(_operation.ConnectionHandle);
bool secureConnection = uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss;
_operation.RequestHandle = Interop.WinHttp.WinHttpOpenRequestWithCallback(
_operation.ConnectionHandle,
"GET",
uri.PathAndQuery,
null,
Interop.WinHttp.WINHTTP_NO_REFERER,
null,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(_operation.RequestHandle);
_operation.IncrementHandlesOpenWithCallback();
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET,
IntPtr.Zero,
0))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SECURE_FAILURE;
if (Interop.WinHttp.WinHttpSetStatusCallback(
_operation.RequestHandle,
WinHttpWebSocketCallback.s_StaticCallbackDelegate,
notificationFlags,
IntPtr.Zero) == (IntPtr)Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.RequestHandle.AttachCallback();
// We need to pin the operation object at this point in time since the WinHTTP callback
// has been fully wired to the request handle and the operation object has been set as
// the context value of the callback. Any notifications from activity on the handle will
// result in the callback being called with the context value.
_operation.Pin();
AddRequestHeaders(uri, options);
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
}
await InternalSendWsUpgradeRequestAsync().ConfigureAwait(false);
await InternalReceiveWsUpgradeResponse().ConfigureAwait(false);
lock (_operation.Lock)
{
VerifyUpgradeResponse();
ThrowOnInvalidConnectState();
_operation.WebSocketHandle =
Interop.WinHttp.WinHttpWebSocketCompleteUpgrade(_operation.RequestHandle, IntPtr.Zero);
ThrowOnInvalidHandle(_operation.WebSocketHandle);
_operation.IncrementHandlesOpenWithCallback();
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.WebSocketHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.WebSocketHandle.AttachCallback();
_operation.UpdateState(WebSocketState.Open);
if (_operation.RequestHandle != null)
{
_operation.RequestHandle.Dispose();
// RequestHandle will be set to null in the callback.
}
_operation.TcsUpgrade = null;
ctr.Dispose();
}
}
}
// Requires lock taken.
private Interop.WinHttp.SafeWinHttpHandle InitializeWinHttp(ClientWebSocketOptions options)
{
Interop.WinHttp.SafeWinHttpHandle sessionHandle;
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
null,
null,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return sessionHandle;
}
private Task<bool> InternalSendWsUpgradeRequestAsync()
{
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
if (!Interop.WinHttp.WinHttpSendRequest(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_NO_ADDITIONAL_HEADERS,
0,
IntPtr.Zero,
0,
0,
_operation.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private Task<bool> InternalReceiveWsUpgradeResponse()
{
// TODO (Issue 2507): Potential optimization: move this in WinHttpWebSocketCallback.
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
if (!Interop.WinHttp.WinHttpReceiveResponse(_operation.RequestHandle, IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private void ThrowOnInvalidConnectState()
{
// A special behavior for WebSocket upgrade: throws ConnectFailure instead of other Abort messages.
if (_operation.State != WebSocketState.Connecting)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
private static readonly WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived };
public override Task SendAsync(
ArraySegment<byte> buffer,
WebSocketMessageType messageType,
bool endOfMessage,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validSendStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
var bufferType = WebSocketMessageTypeAdapter.GetWinHttpMessageType(messageType, endOfMessage);
_operation.PinSendBuffer(buffer);
bool sendOperationAlreadyPending = false;
if (_operation.PendingWriteOperation == false)
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validSendStates);
if (_operation.PendingWriteOperation == false)
{
_operation.PendingWriteOperation = true;
_operation.TcsSend = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
uint ret = Interop.WinHttp.WinHttpWebSocketSend(
_operation.WebSocketHandle,
bufferType,
buffer.Count > 0 ? Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset) : IntPtr.Zero,
(uint)buffer.Count);
if (Interop.WinHttp.ERROR_SUCCESS != ret)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
else
{
sendOperationAlreadyPending = true;
}
}
}
else
{
sendOperationAlreadyPending = true;
}
if (sendOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync"));
_operation.TcsSend.TrySetException(exception);
Abort();
}
return _operation.TcsSend.Task;
}
}
private static readonly WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent };
private static readonly WebSocketState[] s_validAfterReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent, WebSocketState.CloseReceived };
public override async Task<WebSocketReceiveResult> ReceiveAsync(
ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validReceiveStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.PinReceiveBuffer(buffer);
await InternalReceiveAsync(buffer).ConfigureAwait(false);
// Check for abort.
_operation.InterlockedCheckValidStates(s_validAfterReceiveStates);
WebSocketMessageType bufferType;
bool endOfMessage;
bufferType = WebSocketMessageTypeAdapter.GetWebSocketMessageType(_operation.BufferType, out endOfMessage);
int bytesTransferred = 0;
checked
{
bytesTransferred = (int)_operation.BytesTransferred;
}
WebSocketReceiveResult ret;
if (bufferType == WebSocketMessageType.Close)
{
UpdateServerCloseStatus();
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage, _closeStatus, _closeStatusDescription);
}
else
{
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage);
}
return ret;
}
}
private Task<bool> InternalReceiveAsync(ArraySegment<byte> buffer)
{
bool receiveOperationAlreadyPending = false;
if (_operation.PendingReadOperation == false)
{
lock (_operation.Lock)
{
if (_operation.PendingReadOperation == false)
{
_operation.CheckValidState(s_validReceiveStates);
// Prevent continuations from running on the same thread as the callback to prevent re-entrance deadlocks
_operation.TcsReceive = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_operation.PendingReadOperation = true;
uint bytesRead = 0;
Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE winHttpBufferType = 0;
uint status = Interop.WinHttp.WinHttpWebSocketReceive(
_operation.WebSocketHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset),
(uint)buffer.Count,
out bytesRead, // Unused in async mode: ignore.
out winHttpBufferType); // Unused in async mode: ignore.
if (Interop.WinHttp.ERROR_SUCCESS != status)
{
throw WinHttpException.CreateExceptionUsingError((int)status);
}
}
else
{
receiveOperationAlreadyPending = true;
}
}
}
else
{
receiveOperationAlreadyPending = true;
}
if (receiveOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "ReceiveAsync"));
_operation.TcsReceive.TrySetException(exception);
Abort();
}
return _operation.TcsReceive.Task;
}
private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override async Task CloseAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.TcsClose = new TaskCompletionSource<bool>();
await InternalCloseAsync(closeStatus, statusDescription).ConfigureAwait(false);
UpdateServerCloseStatus();
}
}
private Task<bool> InternalCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription)
{
uint ret;
_operation.TcsClose = new TaskCompletionSource<bool>();
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseStates);
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsClose.Task;
}
private void UpdateServerCloseStatus()
{
uint ret;
ushort serverStatus;
var closeDescription = new byte[WebSocketValidate.MaxControlFramePayloadLength];
uint closeDescriptionConsumed;
lock (_operation.Lock)
{
ret = Interop.WinHttp.WinHttpWebSocketQueryCloseStatus(
_operation.WebSocketHandle,
out serverStatus,
closeDescription,
(uint)closeDescription.Length,
out closeDescriptionConsumed);
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
_closeStatus = (WebSocketCloseStatus)serverStatus;
_closeStatusDescription = Encoding.UTF8.GetString(closeDescription, 0, (int)closeDescriptionConsumed);
}
}
private static readonly WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived };
private static readonly WebSocketState[] s_validCloseOutputStatesAfterUpdate = { WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override Task CloseOutputAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseOutputStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseOutputStatesAfterUpdate);
uint ret;
_operation.TcsCloseOutput = new TaskCompletionSource<bool>();
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsCloseOutput.Task;
}
}
private void VerifyUpgradeResponse()
{
// Check the status code
var statusCode = GetHttpStatusCode();
if (statusCode != HttpStatusCode.SwitchingProtocols)
{
Abort();
return;
}
_subProtocol = GetResponseHeader(HeaderNameWebSocketProtocol);
}
private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (options.Cookies != null)
{
AppendCookieHeaderLine(uri, options.Cookies, requestHeadersBuffer);
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(options.RequestHeaders.ToString());
using (List<string>.Enumerator e = options.RequestedSubProtocols.GetEnumerator())
{
if (e.MoveNext())
{
requestHeadersBuffer.Append(HeaderNameWebSocketProtocol + ": ");
requestHeadersBuffer.Append(e.Current);
while (e.MoveNext())
{
requestHeadersBuffer.Append(", ");
requestHeadersBuffer.Append(e.Current);
}
requestHeadersBuffer.AppendLine();
}
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
_operation.RequestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void AppendCookieHeaderLine(Uri uri, CookieContainer cookies, StringBuilder requestHeadersBuffer)
{
Debug.Assert(cookies != null);
Debug.Assert(requestHeadersBuffer != null);
string cookieValues = cookies.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
requestHeadersBuffer.Append(HeaderNameCookie + ": ");
requestHeadersBuffer.AppendLine(cookieValues);
}
}
private HttpStatusCode GetHttpStatusCode()
{
uint infoLevel = Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER;
uint result = 0;
uint resultSize = sizeof(uint);
if (!Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
ref result,
ref resultSize,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return (HttpStatusCode)result;
}
private unsafe string GetResponseHeader(string headerName, char[] buffer = null)
{
const int StackLimit = 128;
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = &buffer[0])
{
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(headerName, buffer);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
private unsafe bool QueryHeaders(string headerName, char* buffer, ref int bufferLength)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
uint index = 0;
// Convert the char buffer length to the length in bytes.
uint bufferLengthInBytes = (uint)bufferLength * sizeof(char);
// The WinHttpQueryHeaders buffer length is in bytes,
// but the API actually returns Unicode characters.
bool result = Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
public override void Dispose()
{
if (!_disposed)
{
lock (_operation.Lock)
{
// Disposing will involve calling WinHttpClose on handles. It is critical that no other WinHttp
// function is running at the same time.
if (!_disposed)
{
_operation.Dispose();
_disposed = true;
}
}
}
// No need to suppress finalization since the finalizer is not overridden.
}
public override void Abort()
{
lock (_operation.Lock)
{
if ((State != WebSocketState.None) && (State != WebSocketState.Connecting))
{
_operation.UpdateState(WebSocketState.Aborted);
}
else
{
// ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted.
_operation.UpdateState(WebSocketState.Closed);
}
Dispose();
}
CancelAllOperations();
}
private void CancelAllOperations()
{
if (_operation.TcsClose != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsClose.TrySetException(exception);
}
if (_operation.TcsCloseOutput != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsCloseOutput.TrySetException(exception);
}
if (_operation.TcsReceive != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsReceive.TrySetException(exception);
}
if (_operation.TcsSend != null)
{
var exception = new OperationCanceledException();
_operation.TcsSend.TrySetException(exception);
}
if (_operation.TcsUpgrade != null)
{
var exception = new WebSocketException(SR.net_webstatus_ConnectFailure);
_operation.TcsUpgrade.TrySetException(exception);
}
}
private void ThrowOnInvalidHandle(Interop.WinHttp.SafeWinHttpHandle value)
{
if (value.IsInvalid)
{
Abort();
throw new WebSocketException(
SR.net_webstatus_ConnectFailure,
WinHttpException.CreateExceptionUsingLastError());
}
}
private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
Abort();
cancellationToken.ThrowIfCancellationRequested();
}
CancellationTokenRegistration cancellationRegistration =
cancellationToken.Register(s => ((WinHttpWebSocket)s).Abort(), this);
return cancellationRegistration;
}
}
}
| |
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Batch.Pipeline
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using Exceptions;
using Magnum.Threading;
using MassTransit.Pipeline;
using MassTransit.Pipeline.Configuration.Subscribers;
using MassTransit.Pipeline.Sinks;
public class BatchSubscriber :
PipelineSubscriberBase
{
private static readonly Type _batchType = typeof (Batch<,>);
private static readonly Type _interfaceType = typeof (Consumes<>.All);
private readonly ReaderWriterLockedDictionary<Type, Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction>> _components;
private readonly ReaderWriterLockedDictionary<Type, Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction>> _instances;
public BatchSubscriber()
{
_instances = new ReaderWriterLockedDictionary<Type, Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction>>();
_components = new ReaderWriterLockedDictionary<Type, Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction>>();
}
protected virtual UnsubscribeAction Connect<TMessage, TBatchId>(ISubscriberContext context, Consumes<Batch<TMessage, TBatchId>>.All consumer)
where TMessage : class, BatchedBy<TBatchId>
{
var configurator = BatchMessageRouterConfigurator.For(context.Pipeline);
var router = configurator.FindOrCreate<TMessage, TBatchId>();
var result = router.Connect(new InstanceMessageSink<Batch<TMessage, TBatchId>>(message => consumer.Consume));
UnsubscribeAction remove = context.SubscribedTo<TMessage>();
return () => result() && (router.SinkCount == 0) && remove();
}
protected virtual UnsubscribeAction Connect<TComponent, TMessage, TBatchId>(ISubscriberContext context)
where TMessage : class, BatchedBy<TBatchId>
where TComponent : class, Consumes<Batch<TMessage, TBatchId>>.All
{
var configurator = BatchMessageRouterConfigurator.For(context.Pipeline);
var router = configurator.FindOrCreate<TMessage, TBatchId>();
var result = router.Connect(new ComponentMessageSink<TComponent, Batch<TMessage, TBatchId>>(context));
UnsubscribeAction remove = context.SubscribedTo<TMessage>();
return () => result() && (router.SinkCount == 0) && remove();
}
public override IEnumerable<UnsubscribeAction> Subscribe<TComponent>(ISubscriberContext context)
{
Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction> invoker = GetInvoker<TComponent>();
if (invoker == null)
yield break;
foreach (Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction> action in invoker.GetInvocationList())
{
yield return action(this, context);
}
}
public override IEnumerable<UnsubscribeAction> Subscribe<TComponent>(ISubscriberContext context, TComponent instance)
{
Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction> invoker = GetInvokerForInstance<TComponent>();
if (invoker == null)
yield break;
foreach (Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction> action in invoker.GetInvocationList())
{
yield return action(this, context, instance);
}
}
private Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction> GetInvokerForInstance<TComponent>()
{
Type componentType = typeof (TComponent);
return _instances.Retrieve(componentType, () =>
{
Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction> invoker = null;
// since we don't have it, we're going to build it
foreach (Type interfaceType in componentType.GetInterfaces())
{
Type messageType;
Type keyType;
if (!GetMessageType(interfaceType, out messageType, out keyType))
continue;
var typeArguments = new[] {messageType, keyType};
MethodInfo genericMethod = FindMethod(GetType(), "Connect", typeArguments, new[] {typeof (ISubscriberContext), typeof (TComponent)});
if (genericMethod == null)
throw new PipelineException(string.Format("Unable to subscribe for type: {0} ({1})",
typeof (TComponent).FullName, messageType.FullName));
var interceptorParameter = Expression.Parameter(typeof (BatchSubscriber), "interceptor");
var contextParameter = Expression.Parameter(typeof (ISubscriberContext), "context");
var instanceParameter = Expression.Parameter(typeof (object), "instance");
var instanceCast = Expression.Convert(instanceParameter, typeof (TComponent));
var call = Expression.Call(interceptorParameter, genericMethod, contextParameter, instanceCast);
var parameters = new[] {interceptorParameter, contextParameter, instanceParameter};
var connector = Expression.Lambda<Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction>>(call, parameters).Compile();
Func<BatchSubscriber, ISubscriberContext, object, UnsubscribeAction> method = (interceptor, context, obj) =>
{
if (context.HasMessageTypeBeenDefined(messageType))
return () => false;
context.MessageTypeWasDefined(messageType);
context.MessageTypeWasDefined(_batchType.MakeGenericType(messageType, keyType));
return connector(interceptor, context, obj);
};
if (invoker == null)
invoker = method;
else
invoker += method;
}
return invoker;
});
}
private Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction> GetInvoker<TComponent>()
{
Type componentType = typeof (TComponent);
return _components.Retrieve(componentType, () =>
{
Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction> invoker = null;
// since we don't have it, we're going to build it
foreach (Type interfaceType in componentType.GetInterfaces())
{
Type messageType;
Type keyType;
if (!GetMessageType(interfaceType, out messageType, out keyType))
continue;
var typeArguments = new[] {typeof (TComponent), messageType, keyType};
MethodInfo genericMethod = FindMethod(GetType(), "Connect", typeArguments, new[] {typeof (ISubscriberContext)});
if (genericMethod == null)
throw new PipelineException(string.Format("Unable to subscribe for type: {0} ({1})",
typeof (TComponent).FullName, messageType.FullName));
var interceptorParameter = Expression.Parameter(typeof (BatchSubscriber), "interceptor");
var contextParameter = Expression.Parameter(typeof (ISubscriberContext), "context");
var call = Expression.Call(interceptorParameter, genericMethod, contextParameter);
var parameters = new[] {interceptorParameter, contextParameter};
var connector = Expression.Lambda<Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction>>(call, parameters).Compile();
Func<BatchSubscriber, ISubscriberContext, UnsubscribeAction> method = (interceptor, context) =>
{
if (context.HasMessageTypeBeenDefined(messageType))
return () => false;
context.MessageTypeWasDefined(messageType);
context.MessageTypeWasDefined(_batchType.MakeGenericType(messageType, keyType));
return connector(interceptor, context);
};
if (invoker == null)
invoker = method;
else
invoker += method;
}
return invoker;
});
}
private static bool GetMessageType(Type interfaceType, out Type messageType, out Type keyType)
{
messageType = null;
keyType = null;
if (!interfaceType.IsGenericType) return false;
Type genericType = interfaceType.GetGenericTypeDefinition();
if (genericType != _interfaceType) return false;
Type[] types = interfaceType.GetGenericArguments();
messageType = types[0];
if (!messageType.IsGenericType || messageType.GetGenericTypeDefinition() != _batchType) return false;
Type[] genericArguments = messageType.GetGenericArguments();
messageType = genericArguments[0];
keyType = genericArguments[1];
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ---------------------------------------------------------------------------
// Generic functions to compute the hashcode value of types
// ---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Internal.NativeFormat
{
static public class TypeHashingAlgorithms
{
public struct HashCodeBuilder
{
private int _hash1;
private int _hash2;
private int _numCharactersHashed;
public HashCodeBuilder(string seed)
{
_hash1 = 0x6DA3B944;
_hash2 = 0;
_numCharactersHashed = 0;
Append(seed);
}
public void Append(string src)
{
if (src.Length == 0)
return;
int startIndex = 0;
if ((_numCharactersHashed & 1) == 1)
{
_hash2 = (_hash2 + _rotl(_hash2, 5)) ^ src[0];
startIndex = 1;
}
for (int i = startIndex; i < src.Length; i += 2)
{
_hash1 = (_hash1 + _rotl(_hash1, 5)) ^ src[i];
if ((i + 1) < src.Length)
_hash2 = (_hash2 + _rotl(_hash2, 5)) ^ src[i + 1];
}
_numCharactersHashed += src.Length;
}
public int ToHashCode()
{
int hash1 = _hash1 + _rotl(_hash1, 8);
int hash2 = _hash2 + _rotl(_hash2, 8);
return hash1 ^ hash2;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int _rotl(int value, int shift)
{
return (int)(((uint)value << shift) | ((uint)value >> (32 - shift)));
}
//
// Returns the hashcode value of the 'src' string
//
public static int ComputeNameHashCode(string src)
{
int hash1 = 0x6DA3B944;
int hash2 = 0;
for (int i = 0; i < src.Length; i += 2)
{
hash1 = (hash1 + _rotl(hash1, 5)) ^ src[i];
if ((i + 1) < src.Length)
hash2 = (hash2 + _rotl(hash2, 5)) ^ src[i + 1];
}
hash1 += _rotl(hash1, 8);
hash2 += _rotl(hash2, 8);
return hash1 ^ hash2;
}
public static unsafe int ComputeASCIINameHashCode(byte* data, int length, out bool isAscii)
{
int hash1 = 0x6DA3B944;
int hash2 = 0;
int asciiMask = 0;
for (int i = 0; i < length; i += 2)
{
int b1 = data[i];
asciiMask |= b1;
hash1 = (hash1 + _rotl(hash1, 5)) ^ b1;
if ((i + 1) < length)
{
int b2 = data[i];
asciiMask |= b2;
hash2 = (hash2 + _rotl(hash2, 5)) ^ b2;
}
}
hash1 += _rotl(hash1, 8);
hash2 += _rotl(hash2, 8);
isAscii = (asciiMask & 0x80) == 0;
return hash1 ^ hash2;
}
public static int ComputeArrayTypeHashCode(int elementTypeHashCode, int rank)
{
// Arrays are treated as generic types in some parts of our system. The array hashcodes are
// carefully crafted to be the same as the hashcodes of their implementation generic types.
int hashCode;
if (rank == 1)
{
hashCode = unchecked((int)0xd5313557u);
Debug.Assert(hashCode == ComputeNameHashCode("System.Array`1"));
}
else
{
hashCode = ComputeNameHashCode("System.MDArrayRank" + rank.ToStringInvariant() + "`1");
}
hashCode = (hashCode + _rotl(hashCode, 13)) ^ elementTypeHashCode;
return (hashCode + _rotl(hashCode, 15));
}
public static int ComputeArrayTypeHashCode<T>(T elementType, int rank)
{
return ComputeArrayTypeHashCode(elementType.GetHashCode(), rank);
}
public static int ComputePointerTypeHashCode(int pointeeTypeHashCode)
{
return (pointeeTypeHashCode + _rotl(pointeeTypeHashCode, 5)) ^ 0x12D0;
}
public static int ComputePointerTypeHashCode<T>(T pointeeType)
{
return ComputePointerTypeHashCode(pointeeType.GetHashCode());
}
public static int ComputeByrefTypeHashCode(int parameterTypeHashCode)
{
return (parameterTypeHashCode + _rotl(parameterTypeHashCode, 7)) ^ 0x4C85;
}
public static int ComputeByrefTypeHashCode<T>(T parameterType)
{
return ComputeByrefTypeHashCode(parameterType.GetHashCode());
}
public static int ComputeNestedTypeHashCode(int enclosingTypeHashCode, int nestedTypeNameHash)
{
return (enclosingTypeHashCode + _rotl(enclosingTypeHashCode, 11)) ^ nestedTypeNameHash;
}
public static int ComputeGenericInstanceHashCode<ARG>(int genericDefinitionHashCode, ARG[] genericTypeArguments)
{
int hashcode = genericDefinitionHashCode;
for (int i = 0; i < genericTypeArguments.Length; i++)
{
int argumentHashCode = genericTypeArguments[i].GetHashCode();
hashcode = (hashcode + _rotl(hashcode, 13)) ^ argumentHashCode;
}
return (hashcode + _rotl(hashcode, 15));
}
/// <summary>
/// Produce a hashcode for a specific method
/// </summary>
/// <param name="typeHashCode">HashCode of the type that owns the method</param>
/// <param name="nameOrNameAndGenericArgumentsHashCode">HashCode of either the name of the method (for non-generic methods) or the GenericInstanceHashCode of the name+generic arguments of the method.</param>
/// <returns></returns>
public static int ComputeMethodHashCode(int typeHashCode, int nameOrNameAndGenericArgumentsHashCode)
{
// TODO! This hash combining function isn't good, but it matches logic used in the past
// consider changing to a better combining function once all uses use this function
return typeHashCode ^ nameOrNameAndGenericArgumentsHashCode;
}
/// <summary>
/// Produce a hashcode for a generic signature variable
/// </summary>
/// <param name="index">zero based index</param>
/// <param name="method">true if the signature variable describes a method</param>
public static int ComputeSignatureVariableHashCode(int index, bool method)
{
if (method)
{
return index * 0x7822381 + 0x54872645;
}
else
{
return index * 0x5498341 + 0x832424;
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2017 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if MSTEST
#pragma warning disable 162
#endif // MSTEST
using System;
using System.IO;
using System.Threading.Tasks;
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
namespace MsgPack
{
// This file was generated from UnpackerTest.Skip.tt T4Template.
// Do not modify this file. Edit UnpackerTest.Skip.tt instead.
// ReSharper disable once InconsistentNaming
partial class UnpackerTest
{
[Test]
public void TestSkip_Empty_Null()
{
if ( this.CanReadFromEmptySource )
{
using ( var buffer = new MemoryStream( new byte[ 0 ] ) )
using ( var target = this.CreateUnpacker( buffer ) )
{
Assert.That( target.Skip(), Is.Null );
}
}
else
{
using ( var buffer = new MemoryStream( new byte[ 0 ] ) )
{
Assert.Throws<ArgumentException>(
() => this.CreateUnpacker( buffer )
);
}
}
}
[Test]
public void TestSkip_FixNum_1()
{
using ( var stream = new MemoryStream( new byte[] { 1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_Scalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xD2, 0x1, 0x2, 0x3, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_ContinuousScalar_ReportedSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0xD2, 0x1, 0x2, 0x3, 0x4, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( 5L ) );
Assert.That( target.Skip(), Is.EqualTo( 1L ) );
}
}
[Test]
public void TestSkip_RawEmpty_0()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_FixRaw_1()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, ( byte )'A' } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_Raw_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDB, 0x0, 0x0, 0x0, 0x1, ( byte )'A' } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_ContinuousRaw_ReportedSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0xA2, ( byte )'A', ( byte )'B', 0xA2, ( byte )'C', ( byte )'D' } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( 3L ) );
Assert.That( target.Skip(), Is.EqualTo( 3L ) );
}
}
[Test]
public void TestSkip_FixArrayEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x90 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_FixArrayFixNum_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x1, 0x2 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_ArrayEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDD, 0x0, 0x0, 0x0, 0x0 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_ArrayScalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDD, 0x0, 0x0, 0x0, 0x2, 0xD2, 0x1, 0x2, 0x3, 0x4, 0xD2, 0x1, 0x2, 0x3, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_CotinuousArray_ReportsSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x1, 0x2, 0x91, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( 3L ) );
Assert.That( target.Skip(), Is.EqualTo( 2L ) );
}
}
[Test]
public void TestSkip_NestedArray_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x91, 0x1, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_NestedArrayContainsEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x90, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_FixMapEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x80 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_FixMapFixNum_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x1, 0x2, 0x2 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_MapEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDF, 0x0, 0x0, 0x0, 0x0 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_MapScalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDE, 0x0, 0x2, 0xD0, 0x1, 0xD0, 0x1, 0xD0, 0x2, 0xD0, 0x2 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_CotinuousMap_ReportsSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x1, 0x2, 0x2, 0x81, 0x3, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( 5L ) );
Assert.That( target.Skip(), Is.EqualTo( 3L ) );
}
}
[Test]
public void TestSkip_NestedMap_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x81, 0x2, 0x2, 0x3, 0x81, 0x4, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_SubtreeReader_NestedMapContainsEmpty_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x80, 0x2, 0x81, 0x3, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Skip(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public void TestSkip_SubtreeReader_NestedArray_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x91, 0x1, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Read() );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public void TestSkip_SubtreeReader_NestedArrayContainsEmpty_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x90, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Read() );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 0 ) );
}
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public void TestSkip_BetweenSubtreeReader_NestedArray_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x93, 0x91, 0x1, 0x2, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Read() );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
Assert.That( target.Skip(), Is.EqualTo( 1 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public void TestSkip_SubtreeReader_NestedMap_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x81, 0x2, 0x2, 0x3, 0x81, 0x4, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Read() );
Assert.That( target.IsMapHeader );
Assert.That( target.Read() );
Assert.That( target.LastReadData.Equals( 0x1 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
Assert.That( target.Read() );
Assert.That( target.LastReadData.Equals( 0x3 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public void TestSkip_NestedMapContainsEmpty_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x80, 0x2, 0x81, 0x3, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Read() );
Assert.That( target.IsMapHeader );
Assert.That( target.Read() );
Assert.That( target.LastReadData.Equals( 0x1 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 0 ) );
}
Assert.That( target.Read() );
Assert.That( target.LastReadData.Equals( 0x2 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public void TestSkip_BetweenSubtreeReader_NestedMap_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x83, 0x1, 0x81, 0x2, 0x2, 0x3, 0x3, 0x4, 0x81, 0x4, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( target.Read() );
Assert.That( target.Skip(), Is.EqualTo( 1 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
Assert.That( target.Skip(), Is.EqualTo( 1 ) );
Assert.That( target.Skip(), Is.EqualTo( 1 ) );
Assert.That( target.Skip(), Is.EqualTo( 1 ) );
Assert.That( target.Read() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
Assert.That( subTreeReader.Skip(), Is.EqualTo( 1 ) );
}
}
}
#if FEATURE_TAP
[Test]
public void TestSkipAsync_Empty_Null()
{
if ( this.CanReadFromEmptySource )
{
using ( var buffer = new MemoryStream( new byte[ 0 ] ) )
using ( var target = this.CreateUnpacker( buffer ) )
{
Assert.That( target.SkipAsync().Result, Is.Null );
}
}
else
{
using ( var buffer = new MemoryStream( new byte[ 0 ] ) )
{
Assert.Throws<ArgumentException>(
() => this.CreateUnpacker( buffer )
);
}
}
}
[Test]
public async Task TestSkipAsync_FixNum_1()
{
using ( var stream = new MemoryStream( new byte[] { 1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_Scalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xD2, 0x1, 0x2, 0x3, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_ContinuousScalar_ReportedSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0xD2, 0x1, 0x2, 0x3, 0x4, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( 5L ) );
Assert.That( await target.SkipAsync(), Is.EqualTo( 1L ) );
}
}
[Test]
public async Task TestSkipAsync_RawEmpty_0()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_FixRaw_1()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, ( byte )'A' } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_Raw_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDB, 0x0, 0x0, 0x0, 0x1, ( byte )'A' } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_ContinuousRaw_ReportedSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0xA2, ( byte )'A', ( byte )'B', 0xA2, ( byte )'C', ( byte )'D' } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( 3L ) );
Assert.That( await target.SkipAsync(), Is.EqualTo( 3L ) );
}
}
[Test]
public async Task TestSkipAsync_FixArrayEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x90 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_FixArrayFixNum_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x1, 0x2 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_ArrayEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDD, 0x0, 0x0, 0x0, 0x0 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_ArrayScalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDD, 0x0, 0x0, 0x0, 0x2, 0xD2, 0x1, 0x2, 0x3, 0x4, 0xD2, 0x1, 0x2, 0x3, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_CotinuousArray_ReportsSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x1, 0x2, 0x91, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( 3L ) );
Assert.That( await target.SkipAsync(), Is.EqualTo( 2L ) );
}
}
[Test]
public async Task TestSkipAsync_NestedArray_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x91, 0x1, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_NestedArrayContainsEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x90, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_FixMapEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x80 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_FixMapFixNum_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x1, 0x2, 0x2 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_MapEmpty_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDF, 0x0, 0x0, 0x0, 0x0 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_MapScalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xDE, 0x0, 0x2, 0xD0, 0x1, 0xD0, 0x1, 0xD0, 0x2, 0xD0, 0x2 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_CotinuousMap_ReportsSeparately()
{
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x1, 0x2, 0x2, 0x81, 0x3, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( 5L ) );
Assert.That( await target.SkipAsync(), Is.EqualTo( 3L ) );
}
}
[Test]
public async Task TestSkipAsync_NestedMap_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x81, 0x2, 0x2, 0x3, 0x81, 0x4, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_SubtreeReader_NestedMapContainsEmpty_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x80, 0x2, 0x81, 0x3, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.SkipAsync(), Is.EqualTo( stream.Length ) );
}
}
[Test]
public async Task TestSkipAsync_SubtreeReader_NestedArray_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x91, 0x1, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.ReadAsync() );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public async Task TestSkipAsync_SubtreeReader_NestedArrayContainsEmpty_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x92, 0x90, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.ReadAsync() );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 0 ) );
}
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public async Task TestSkipAsync_BetweenSubtreeReader_NestedArray_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x93, 0x91, 0x1, 0x2, 0x91, 0x1 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.ReadAsync() );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
Assert.That( await target.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public async Task TestSkipAsync_SubtreeReader_NestedMap_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x81, 0x2, 0x2, 0x3, 0x81, 0x4, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.ReadAsync() );
Assert.That( target.IsMapHeader );
Assert.That( await target.ReadAsync() );
Assert.That( target.LastReadData.Equals( 0x1 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
Assert.That( await target.ReadAsync() );
Assert.That( target.LastReadData.Equals( 0x3 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public async Task TestSkipAsync_NestedMapContainsEmpty_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x82, 0x1, 0x80, 0x2, 0x81, 0x3, 0x3 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.ReadAsync() );
Assert.That( target.IsMapHeader );
Assert.That( await target.ReadAsync() );
Assert.That( target.LastReadData.Equals( 0x1 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 0 ) );
}
Assert.That( await target.ReadAsync() );
Assert.That( target.LastReadData.Equals( 0x2 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
}
}
[Test]
public async Task TestSkipAsync_BetweenSubtreeReader_NestedMap_AsIs()
{
if ( !this.ShouldCheckSubtreeUnpacker )
{
#if MSTEST
// MSTEST cannot handle inconclusive in async test correctly.
await Task.Delay( 0 );
return;
#endif // MSTEST
Assert.Ignore( "Cannot test subtree unpacker in " + this.GetType().Name );
}
using ( var stream = new MemoryStream( new byte[] { 0x83, 0x1, 0x81, 0x2, 0x2, 0x3, 0x3, 0x4, 0x81, 0x4, 0x4 } ) )
using ( var target = this.CreateUnpacker( stream ) )
{
Assert.That( await target.ReadAsync() );
Assert.That( await target.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
Assert.That( await target.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await target.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await target.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await target.ReadAsync() );
using ( var subTreeReader = target.ReadSubtree() )
{
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
Assert.That( await subTreeReader.SkipAsync(), Is.EqualTo( 1 ) );
}
}
}
#endif // FEATURE_TAP
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.WorkflowExecutions.v1
{
/// <summary>The WorkflowExecutions Service.</summary>
public class WorkflowExecutionsService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public WorkflowExecutionsService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public WorkflowExecutionsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "workflowexecutions";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://workflowexecutions.googleapis.com/";
#else
"https://workflowexecutions.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://workflowexecutions.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Workflow Executions API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Workflow Executions API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for WorkflowExecutions requests.</summary>
public abstract class WorkflowExecutionsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new WorkflowExecutionsBaseServiceRequest instance.</summary>
protected WorkflowExecutionsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes WorkflowExecutions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Workflows = new WorkflowsResource(service);
}
/// <summary>Gets the Workflows resource.</summary>
public virtual WorkflowsResource Workflows { get; }
/// <summary>The "workflows" collection of methods.</summary>
public class WorkflowsResource
{
private const string Resource = "workflows";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public WorkflowsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Executions = new ExecutionsResource(service);
}
/// <summary>Gets the Executions resource.</summary>
public virtual ExecutionsResource Executions { get; }
/// <summary>The "executions" collection of methods.</summary>
public class ExecutionsResource
{
private const string Resource = "executions";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ExecutionsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Cancels an execution of the given name.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. Name of the execution to be cancelled. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}
/// </param>
public virtual CancelRequest Cancel(Google.Apis.WorkflowExecutions.v1.Data.CancelExecutionRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>Cancels an execution of the given name.</summary>
public class CancelRequest : WorkflowExecutionsBaseServiceRequest<Google.Apis.WorkflowExecutions.v1.Data.Execution>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.WorkflowExecutions.v1.Data.CancelExecutionRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Name of the execution to be cancelled. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.WorkflowExecutions.v1.Data.CancelExecutionRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:cancel";
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/workflows/[^/]+/executions/[^/]+$",
});
}
}
/// <summary>Creates a new execution using the latest revision of the given workflow.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Name of the workflow for which an execution should be created. Format:
/// projects/{project}/locations/{location}/workflows/{workflow} The latest revision of the workflow
/// will be used.
/// </param>
public virtual CreateRequest Create(Google.Apis.WorkflowExecutions.v1.Data.Execution body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a new execution using the latest revision of the given workflow.</summary>
public class CreateRequest : WorkflowExecutionsBaseServiceRequest<Google.Apis.WorkflowExecutions.v1.Data.Execution>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.WorkflowExecutions.v1.Data.Execution body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Name of the workflow for which an execution should be created. Format:
/// projects/{project}/locations/{location}/workflows/{workflow} The latest revision of the
/// workflow will be used.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.WorkflowExecutions.v1.Data.Execution Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/executions";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/workflows/[^/]+$",
});
}
}
/// <summary>Returns an execution of the given name.</summary>
/// <param name="name">
/// Required. Name of the execution to be retrieved. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns an execution of the given name.</summary>
public class GetRequest : WorkflowExecutionsBaseServiceRequest<Google.Apis.WorkflowExecutions.v1.Data.Execution>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. Name of the execution to be retrieved. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. A view defining which fields should be filled in the returned execution. The API
/// will default to the FULL view.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ViewEnum> View { get; set; }
/// <summary>
/// Optional. A view defining which fields should be filled in the returned execution. The API
/// will default to the FULL view.
/// </summary>
public enum ViewEnum
{
/// <summary>The default / unset value.</summary>
[Google.Apis.Util.StringValueAttribute("EXECUTION_VIEW_UNSPECIFIED")]
EXECUTIONVIEWUNSPECIFIED = 0,
/// <summary>
/// Includes only basic metadata about the execution. Following fields are returned: name,
/// start_time, end_time, state and workflow_revision_id.
/// </summary>
[Google.Apis.Util.StringValueAttribute("BASIC")]
BASIC = 1,
/// <summary>Includes all data.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL = 2,
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/workflows/[^/]+/executions/[^/]+$",
});
RequestParameters.Add("view", new Google.Apis.Discovery.Parameter
{
Name = "view",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Returns a list of executions which belong to the workflow with the given name. The method
/// returns executions of all workflow revisions. Returned executions are ordered by their start
/// time (newest first).
/// </summary>
/// <param name="parent">
/// Required. Name of the workflow for which the executions should be listed. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>
/// Returns a list of executions which belong to the workflow with the given name. The method
/// returns executions of all workflow revisions. Returned executions are ordered by their start
/// time (newest first).
/// </summary>
public class ListRequest : WorkflowExecutionsBaseServiceRequest<Google.Apis.WorkflowExecutions.v1.Data.ListExecutionsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. Name of the workflow for which the executions should be listed. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Maximum number of executions to return per call. Max supported value depends on the selected
/// Execution view: it's 10000 for BASIC and 100 for FULL. The default value used if the field
/// is not specified is 100, regardless of the selected view. Values greater than the max value
/// will be coerced down to it.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A page token, received from a previous `ListExecutions` call. Provide this to retrieve the
/// subsequent page. When paginating, all other parameters provided to `ListExecutions` must
/// match the call that provided the page token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>
/// Optional. A view defining which fields should be filled in the returned executions. The API
/// will default to the BASIC view.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ViewEnum> View { get; set; }
/// <summary>
/// Optional. A view defining which fields should be filled in the returned executions. The API
/// will default to the BASIC view.
/// </summary>
public enum ViewEnum
{
/// <summary>The default / unset value.</summary>
[Google.Apis.Util.StringValueAttribute("EXECUTION_VIEW_UNSPECIFIED")]
EXECUTIONVIEWUNSPECIFIED = 0,
/// <summary>
/// Includes only basic metadata about the execution. Following fields are returned: name,
/// start_time, end_time, state and workflow_revision_id.
/// </summary>
[Google.Apis.Util.StringValueAttribute("BASIC")]
BASIC = 1,
/// <summary>Includes all data.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL = 2,
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/executions";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/workflows/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("view", new Google.Apis.Discovery.Parameter
{
Name = "view",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
}
}
namespace Google.Apis.WorkflowExecutions.v1.Data
{
/// <summary>Request for the CancelExecution method.</summary>
public class CancelExecutionRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Error describes why the execution was abnormally terminated.</summary>
public class Error : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Human-readable stack trace string.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("context")]
public virtual string Context { get; set; }
/// <summary>Error message and data returned represented as a JSON string.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual string Payload { get; set; }
/// <summary>Stack trace with detailed information of where error was generated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stackTrace")]
public virtual StackTrace StackTrace { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A running instance of a [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows).
/// </summary>
public class Execution : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Input parameters of the execution represented as a JSON string. The size limit is 32KB. *Note*: If you are
/// using the REST API directly to run your workflow, you must escape any JSON string value of `argument`.
/// Example: `'{"argument":"{\"firstName\":\"FIRST\",\"lastName\":\"LAST\"}"}'`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("argument")]
public virtual string Argument { get; set; }
/// <summary>The call logging level associated to this execution.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("callLogLevel")]
public virtual string CallLogLevel { get; set; }
/// <summary>Output only. Marks the end of execution, successful or not.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// Output only. The error which caused the execution to finish prematurely. The value is only present if the
/// execution's state is `FAILED` or `CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Error Error { get; set; }
/// <summary>
/// Output only. The resource name of the execution. Format:
/// projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Output only. Output of the execution represented as a JSON string. The value can only be present if the
/// execution's state is `SUCCEEDED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("result")]
public virtual string Result { get; set; }
/// <summary>Output only. Marks the beginning of execution.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>Output only. Current state of the execution.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Output only. Revision of the workflow this execution is using.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("workflowRevisionId")]
public virtual string WorkflowRevisionId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for the ListExecutions method.</summary>
public class ListExecutionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The executions which match the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("executions")]
public virtual System.Collections.Generic.IList<Execution> Executions { get; set; }
/// <summary>
/// A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no
/// subsequent pages.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Position contains source position information about the stack trace element such as line number, column number
/// and length of the code block in bytes.
/// </summary>
public class Position : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The source code column position (of the line) the current instruction was generated from.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("column")]
public virtual System.Nullable<long> Column { get; set; }
/// <summary>The number of bytes of source code making up this stack trace element.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("length")]
public virtual System.Nullable<long> Length { get; set; }
/// <summary>The source code line number the current instruction was generated from.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("line")]
public virtual System.Nullable<long> Line { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A collection of stack elements (frames) where an error occurred.</summary>
public class StackTrace : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>An array of stack elements.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("elements")]
public virtual System.Collections.Generic.IList<StackTraceElement> Elements { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A single stack element (frame) where an error occurred.</summary>
public class StackTraceElement : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The source position information of the stack trace element.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("position")]
public virtual Position Position { get; set; }
/// <summary>The routine where the error occurred.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("routine")]
public virtual string Routine { get; set; }
/// <summary>The step the error occurred at.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("step")]
public virtual string Step { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class File_Move_Tests : FileSystemWatcherTest
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Expected WatcherChangeTypes are different based on OS
public void Windows_File_Move_To_Same_Directory()
{
FileMove_SameDirectory(WatcherChangeTypes.Renamed);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected WatcherChangeTypes are different based on OS
public void Unix_File_Move_To_Same_Directory()
{
FileMove_SameDirectory(WatcherChangeTypes.Created | WatcherChangeTypes.Deleted);
}
[Fact]
public void File_Move_From_Watched_To_Unwatched()
{
FileMove_FromWatchedToUnwatched(WatcherChangeTypes.Deleted);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Expected WatcherChangeTypes are different based on OS
public void Windows_File_Move_To_Different_Watched_Directory()
{
FileMove_DifferentWatchedDirectory(WatcherChangeTypes.Changed);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected WatcherChangeTypes are different based on OS
public void OSX_File_Move_To_Different_Watched_Directory()
{
FileMove_DifferentWatchedDirectory(WatcherChangeTypes.Changed);
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)] // Expected WatcherChangeTypes are different based on OS
public void Linux_File_Move_To_Different_Watched_Directory()
{
FileMove_DifferentWatchedDirectory(0);
}
[Fact]
public void File_Move_From_Unwatched_To_Watched()
{
FileMove_FromUnwatchedToWatched(WatcherChangeTypes.Created);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
[PlatformSpecific(TestPlatforms.Windows)] // Expected WatcherChangeTypes are different based on OS
public void Windows_File_Move_In_Nested_Directory(bool includeSubdirectories)
{
FileMove_NestedDirectory(includeSubdirectories ? WatcherChangeTypes.Renamed : 0, includeSubdirectories);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected WatcherChangeTypes are different based on OS
public void Unix_File_Move_In_Nested_Directory(bool includeSubdirectories)
{
FileMove_NestedDirectory(includeSubdirectories ? WatcherChangeTypes.Created | WatcherChangeTypes.Deleted : 0, includeSubdirectories);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Expected WatcherChangeTypes are different based on OS
public void Windows_File_Move_With_Set_NotifyFilter()
{
FileMove_WithNotifyFilter(WatcherChangeTypes.Renamed);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected WatcherChangeTypes are different based on OS
public void Unix_File_Move_With_Set_NotifyFilter()
{
FileMove_WithNotifyFilter(WatcherChangeTypes.Deleted);
}
#region Test Helpers
private void FileMove_SameDirectory(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
using (var watcher = new FileSystemWatcher(dir.Path, "*"))
{
string sourcePath = testFile.Path;
string targetPath = testFile.Path + "_" + eventType.ToString();
// Move the testFile to a different name in the same directory
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
if ((eventType & WatcherChangeTypes.Deleted) > 0)
ExpectEvent(watcher, eventType, action, cleanup, new string[] { sourcePath, targetPath });
else
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
private void FileMove_DifferentWatchedDirectory(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var dir_adjacent = new TempDirectory(Path.Combine(testDirectory.Path, "dir_adj")))
using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, "*"))
{
string sourcePath = testFile.Path;
string targetPath = Path.Combine(dir_adjacent.Path, Path.GetFileName(testFile.Path) + "_" + eventType.ToString());
// Move the testFile to a different directory under the Watcher
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
ExpectEvent(watcher, eventType, action, cleanup, new string[] { dir.Path, dir_adjacent.Path });
}
}
private void FileMove_FromWatchedToUnwatched(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir_watched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_watched")))
using (var dir_unwatched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_unwatched")))
using (var testFile = new TempFile(Path.Combine(dir_watched.Path, "file")))
using (var watcher = new FileSystemWatcher(dir_watched.Path, "*"))
{
string sourcePath = testFile.Path; // watched
string targetPath = Path.Combine(dir_unwatched.Path, "file");
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
ExpectEvent(watcher, eventType, action, cleanup, sourcePath);
}
}
private void FileMove_FromUnwatchedToWatched(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir_watched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_watched")))
using (var dir_unwatched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_unwatched")))
using (var testFile = new TempFile(Path.Combine(dir_unwatched.Path, "file")))
using (var watcher = new FileSystemWatcher(dir_watched.Path, "*"))
{
string sourcePath = testFile.Path; // unwatched
string targetPath = Path.Combine(dir_watched.Path, "file");
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
private void FileMove_NestedDirectory(WatcherChangeTypes eventType, bool includeSubdirectories)
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var firstDir = new TempDirectory(Path.Combine(dir.Path, "dir1")))
using (var nestedDir = new TempDirectory(Path.Combine(firstDir.Path, "nested")))
using (var nestedFile = new TempFile(Path.Combine(nestedDir.Path, "nestedFile" + eventType.ToString())))
using (var watcher = new FileSystemWatcher(dir.Path, "*"))
{
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.IncludeSubdirectories = includeSubdirectories;
string sourcePath = nestedFile.Path;
string targetPath = nestedFile.Path + "_2";
// Move the testFile to a different name within the same nested directory
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
if ((eventType & WatcherChangeTypes.Deleted) > 0)
ExpectEvent(watcher, eventType, action, cleanup, new string[] { targetPath, sourcePath });
else
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
private void FileMove_WithNotifyFilter(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = NotifyFilters.FileName;
string sourcePath = file.Path;
string targetPath = Path.Combine(testDirectory.Path, "target");
// Move the testFile to a different name under the same directory with active notifyfilters
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
if ((eventType & WatcherChangeTypes.Deleted) > 0)
ExpectEvent(watcher, eventType, action, cleanup, sourcePath);
else
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
#endregion
}
}
| |
// Nombre: Document.cs
// Fecha: 2011-01-20
// Autor: baltasarq@gmail.com
using System;
using System.IO;
using System.Text;
namespace Visor.Core {
/// <summary>
/// This is a buffer frame view over the file contents.
/// </summary>
public class Document {
public enum ValueType { Txt, Hex, Dec };
public const int Columns = 16;
public const int MaxRows = 16;
public const string Delimiters = ",;\t.:-/";
private long position = 0;
/// <summary>
/// The position inside the File
/// </summary>
public long Position {
get { return this.position; }
set {
if ( value > -1
&& value < this.FileLength )
{
long oldPos = this.position;
this.position = value;
this.CheckToInvalidateData( oldPos );
}
}
}
/// <summary>
/// Determines whether the data block must be read from disk
/// </summary>
public bool IsInvalidated
{
get; set;
}
/// <summary>
/// The current frame buffer number
/// </summary>
public long FrameBufferNumber {
get { return ( this.Position / this.BufferSize ); }
set {
if ( value > -1 ) {
this.Position = value * this.BufferSize;
}
}
}
/// <summary>
/// Next read will happen on the next framebuffer
/// </summary>
public void Advance()
{
this.Position += this.BufferSize;
}
/// <summary>
/// Next read will happen in the previous framebuffer
/// </summary>
public void Recede()
{
this.Position -= this.BufferSize;
}
private long totalFrameBuffersNumber = -1;
/// <summary>
/// Number of total frame buffers
/// </summary>
public long TotalFrameBuffersNumber {
get {
if ( this.totalFrameBuffersNumber < 0 ) {
this.totalFrameBuffersNumber = ( this.FileLength / this.BufferSize );
if ( ( this.FileLength % this.BufferSize ) != 0 ) {
++( this.totalFrameBuffersNumber );
}
}
return this.totalFrameBuffersNumber;
}
}
/// <summary>
/// Invalidates data, provided the oldPos is different than current position
/// </summary>
/// <param name="oldPos">
/// A <see cref="System.Int32"/> The old position the document was in, as integer.
/// </param>
public bool CheckToInvalidateData(long oldPos)
{
this.IsInvalidated = false;
if ( Position != oldPos ) {
this.tabulatedData = null;
this.IsInvalidated = true;
}
return this.IsInvalidated;
}
private byte[] data = null;
private string[][] tabulatedData = null;
/// <summary>
/// Returns the raw data for this frame in the document
/// </summary>
public byte[] RawData {
get { return this.data; }
}
/// <summary>
/// The data inside the file (this buffer frame)
/// The data is tabulated in tabulatedData.
/// Each movement invalidates tabulatedData.
/// </summary>
public string[][] Data {
get {
if ( this.tabulatedData == null ) {
if ( this.IsInvalidated ) {
this.ReadCurrentFrameBuffer();
}
this.tabulatedData = new string[ this.data.Length / Columns ][];
for(int i = 0; i < this.tabulatedData.Length; ++i) {
this.tabulatedData[ i ] = new string[ Columns ];
}
for(int i = 0; i < this.data.Length; ++i) {
this.tabulatedData[ i / Columns ][ i% Columns ] = this.data[ i ].ToString( "X2" );
}
}
return this.tabulatedData;
}
}
private FileStream file;
/// <summary>
/// The FileStream of the file to read
/// </summary>
public FileStream File {
get { return this.file; }
}
private string path;
/// <summary>
/// The path of the file
/// </summary>
public string Path {
get { return this.path; }
}
private int bufferSize = 256;
/// <summary>
/// The size of the frame buffer to use
/// </summary>
public int BufferSize {
get { return this.bufferSize; }
set {
if ( value >= 512 ) {
this.bufferSize = value;
var oldData = this.RawData;
this.data = new byte[ this.BufferSize ];
oldData.CopyTo( this.data, 0 );
}
}
}
/// <summary>
/// Returns the length of the file
/// </summary>
public long FileLength {
get { if ( file != null )
return this.file.Length;
else return 0;
}
}
/// <summary>
/// Create a document, attached to a given file
/// </summary>
/// <param name="path">
/// A <see cref="string"/> to the file to open
/// </param>
public Document(string path)
{
this.path = path;
this.file = new FileStream( path.ToString(), FileMode.Open, FileAccess.Read );
this.position = 0;
this.data = new byte[ this.BufferSize ];
this.IsInvalidated = true;
this.ReadCurrentFrameBuffer();
}
~Document()
{
file.Close();
}
/// <summary>
/// Reads the frame buffer marked by the current position
/// </summary>
public void ReadCurrentFrameBuffer()
{
// Calculate position given buffer size
for(int framePos = 0; framePos < this.FileLength; framePos += this.BufferSize) {
if ( framePos >= this.Position ) {
this.Position = framePos;
break;
}
}
// Determine number of bytes to read
int count = this.BufferSize;
if ( ( this.Position + this.BufferSize ) > this.FileLength ) {
count = (int) ( this.FileLength - ( (long) this.Position ) );
}
// Prepare the data buffer
if ( count < this.BufferSize ) {
for(int i = Math.Max( 0, count -1 ); i < this.BufferSize; ++i) {
this.data[ i ] = 0;
}
}
// Read that buffer frame
file.Position = this.Position;
file.Read( this.data, 0, count );
}
/// <summary>
/// Returns the position of the value to find, -1 if not found
/// </summary>
/// <param name="txt">
/// A <see cref="System.String"/> holding the value to look for
/// </param>
/// <param name="vt">
/// A <see cref="ValueType"/> the type of the value to find
/// </param>
/// <returns>
/// A <see cref="System.Int64"/> with the position of the of the value found, -1 if not found.
/// </returns>
public long Find(string txt, ValueType vt)
{
if ( vt == ValueType.Txt ) {
return this.FindText( txt );
}
else {
return this.FindByteSequence( DecodeTxtToByteArray( txt, vt ) );
}
}
/// <summary>
/// Looks for the text passed as parameter.
/// </summary>
/// <param name="txt">
/// A <see cref="System.String"/> holding the text to find.
/// </param>
/// <returns>
/// A <see cref="System.Int64"/> with the position of the of the value found, -1 if not found.
/// </returns>
public long FindText(string txt)
{
return this.FindByteSequence( Encoding.UTF8.GetBytes( txt ) );
}
/// <summary>
/// Looks for the byte sequence passed as parameter.
/// </summary>
/// <param name="txt">
/// A <see cref="System.Byte[]"/> holding the byte sequence to find.
/// </param>
/// <returns>
/// A <see cref="System.Int64"/> with the position of the of the value found, -1 if not found.
/// </returns>
public long FindByteSequence(byte[] bs)
{
long i = -1;
byte[] chunk;
if ( bs != null ) {
int chunkLength = bs.Length;
// Look for the next instance of the byte block
for(i = this.Position; i < this.FileLength; ++i) {
byte b = (byte) this.File.ReadByte();
if ( bs[ 0 ] == b ) {
chunk = new byte[ bs.Length ];
this.File.Seek( -1, SeekOrigin.Current );
this.File.Read( chunk, 0, chunkLength );
if ( isArrayEqualTo( bs, chunk ) ) {
break;
}
}
}
}
// Adapt i in case it was not found
if ( i >= this.FileLength ) {
i = -1;
}
return i;
}
public static bool isArrayEqualTo(byte[] array1, byte[] array2)
{
int i = 0;
if ( array1.Length == array2.Length ) {
for(; i < array2.Length; ++i) {
if ( array1[ i ] != array2[ i ] ) {
break;
}
}
}
return ( i >= array1.Length );
}
/// <summary>
/// Returns the values coded in the text, as a vector.
/// </summary>
/// <param name="txt">
/// A <see cref="System.String"/> with the string to look for.
/// </param>
/// <param name="vt">
/// A <see cref="ValueType"/> holding the type of decimal values to decode.
/// </param>
/// <returns>
/// A <see cref="System.Byte[]"/> sequence that holds the representation of the values to look for.
/// </returns>
public byte[] DecodeTxtToByteArray(string txt, ValueType vt)
{
byte[] toret = null;
StringBuilder txtCopy = new StringBuilder();
int fromBase = 10;
// Decide base
if ( vt == Document.ValueType.Hex ) {
fromBase = 16;
}
// Changes all ',' and ';' to spaces
for(int i = 0; i < txt.Length; ++i) {
if ( Delimiters.IndexOf( txt[ i ] ) > -1 ) {
txtCopy.Append( ' ' );
} else {
txtCopy.Append( txt[ i ] );
}
}
// Divide string in its values
string[] values = txtCopy.ToString().Split( new char[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries );
// Decode each value
toret = new byte[ values.Length ];
for(int i = 0; i < values.Length; ++i) {
toret[ i ] = Convert.ToByte( values[ i ], fromBase );
}
return toret;
}
/// <summary>
/// Returns whether a char is not printable
/// </summary>
/// <param name="x">
/// A <see cref="System.Char"/> containing the character
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/> holding true if the character is printable; false otherwise
/// </returns>
public static bool IsPrintable(char x)
{
return (
char.IsLetterOrDigit( x )
|| char.IsPunctuation( x )
|| char.IsSeparator( x )
|| char.IsSymbol( x )
|| char.IsWhiteSpace( x )
);
}
/// <summary>
/// Returns whether a char is strictly printable in one and only one position.
/// </summary>
/// <param name="x">
/// A <see cref="System.Char"/> holding the character.
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/> holdin true if is printable, false otherwise.
/// </returns>
public static bool IsStrictlyPrintable(char x)
{
if ( x == '\n'
|| x == '\r'
|| x == '\t' )
{
return false;
}
else return IsPrintable( x );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System
{
public static class Console
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader s_in;
private static TextWriter s_out, s_error;
private static Encoding s_inputEncoding;
private static Encoding s_outputEncoding;
private static bool s_isOutTextWriterRedirected = false;
private static bool s_isErrorTextWriterRedirected = false;
private static ConsoleCancelEventHandler _cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar _registrar;
internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class =>
LazyInitializer.EnsureInitialized(ref field, ref InternalSyncObject, initializer);
public static TextReader In => EnsureInitialized(ref s_in, () => ConsolePal.GetOrCreateReader());
public static Encoding InputEncoding
{
get
{
return EnsureInitialized(ref s_inputEncoding, () => ConsolePal.InputEncoding);
}
set
{
CheckNonNull(value, nameof(value));
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleInputEncoding(value);
Volatile.Write(ref s_inputEncoding, (Encoding)value.Clone());
// We need to reinitialize Console.In in the next call to s_in
// This will discard the current StreamReader, potentially
// losing buffered data.
Volatile.Write(ref s_in, null);
}
}
}
public static Encoding OutputEncoding
{
get
{
return EnsureInitialized(ref s_outputEncoding, () => ConsolePal.OutputEncoding);
}
set
{
CheckNonNull(value, nameof(value));
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleOutputEncoding(value);
// Before changing the code page we need to flush the data
// if Out hasn't been redirected. Also, have the next call to
// s_out reinitialize the console code page.
if (Volatile.Read(ref s_out) != null && !s_isOutTextWriterRedirected)
{
s_out.Flush();
Volatile.Write(ref s_out, null);
}
if (Volatile.Read(ref s_error) != null && !s_isErrorTextWriterRedirected)
{
s_error.Flush();
Volatile.Write(ref s_error, null);
}
Volatile.Write(ref s_outputEncoding, (Encoding)value.Clone());
}
}
}
public static bool KeyAvailable
{
get
{
if (IsInputRedirected)
{
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
}
return ConsolePal.KeyAvailable;
}
}
public static ConsoleKeyInfo ReadKey()
{
return ConsolePal.ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
return ConsolePal.ReadKey(intercept);
}
public static TextWriter Out => EnsureInitialized(ref s_out, () => CreateOutputWriter(OpenStandardOutput()));
public static TextWriter Error => EnsureInitialized(ref s_error, () => CreateOutputWriter(OpenStandardError()));
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: new ConsoleEncoding(OutputEncoding), // This ensures no prefix is written to the stream.
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true) { AutoFlush = true });
}
private static StrongBox<bool> _isStdInRedirected;
private static StrongBox<bool> _isStdOutRedirected;
private static StrongBox<bool> _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static int CursorSize
{
get { return ConsolePal.CursorSize; }
set { ConsolePal.CursorSize = value; }
}
public static bool NumberLock { get { return ConsolePal.NumberLock; } }
public static bool CapsLock { get { return ConsolePal.CapsLock; } }
internal const ConsoleColor UnknownColor = (ConsoleColor)(-1);
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int BufferWidth
{
get { return ConsolePal.BufferWidth; }
set { ConsolePal.BufferWidth = value; }
}
public static int BufferHeight
{
get { return ConsolePal.BufferHeight; }
set { ConsolePal.BufferHeight = value; }
}
public static void SetBufferSize(int width, int height)
{
ConsolePal.SetBufferSize(width, height);
}
public static int WindowLeft
{
get { return ConsolePal.WindowLeft; }
set { ConsolePal.WindowLeft = value; }
}
public static int WindowTop
{
get { return ConsolePal.WindowTop; }
set { ConsolePal.WindowTop = value; }
}
public static int WindowWidth
{
get
{
return ConsolePal.WindowWidth;
}
set
{
ConsolePal.WindowWidth = value;
}
}
public static int WindowHeight
{
get
{
return ConsolePal.WindowHeight;
}
set
{
ConsolePal.WindowHeight = value;
}
}
public static void SetWindowPosition(int left, int top)
{
ConsolePal.SetWindowPosition(left, top);
}
public static void SetWindowSize(int width, int height)
{
ConsolePal.SetWindowSize(width, height);
}
public static int LargestWindowWidth
{
get { return ConsolePal.LargestWindowWidth; }
}
public static int LargestWindowHeight
{
get { return ConsolePal.LargestWindowHeight; }
}
public static bool CursorVisible
{
get { return ConsolePal.CursorVisible; }
set { ConsolePal.CursorVisible = value; }
}
public static int CursorLeft
{
get { return ConsolePal.CursorLeft; }
set { SetCursorPosition(value, CursorTop); }
}
public static int CursorTop
{
get { return ConsolePal.CursorTop; }
set { SetCursorPosition(CursorLeft, value); }
}
private const int MaxConsoleTitleLength = 24500; // same value as in .NET Framework
public static string Title
{
get { return ConsolePal.Title; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length > MaxConsoleTitleLength)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_ConsoleTitleTooLong);
}
ConsolePal.Title = value;
}
}
public static void Beep()
{
ConsolePal.Beep();
}
public static void Beep(int frequency, int duration)
{
ConsolePal.Beep(frequency, duration);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, ' ', ConsoleColor.Black, BackgroundColor);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, sourceChar, sourceForeColor, sourceBackColor);
}
public static void Clear()
{
ConsolePal.Clear();
}
public static void SetCursorPosition(int left, int top)
{
// Basic argument validation. The PAL implementation may provide further validation.
if (left < 0 || left >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
ConsolePal.SetCursorPosition(left, top);
}
public static event ConsoleCancelEventHandler CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (_registrar == null)
{
_registrar = new ConsolePal.ControlCHandlerRegistrar();
_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
_cancelCallbacks -= value;
if (_registrar != null && _cancelCallbacks == null)
{
_registrar.Unregister();
_registrar = null;
}
}
}
}
public static bool TreatControlCAsInput
{
get { return ConsolePal.TreatControlCAsInput; }
set { ConsolePal.TreatControlCAsInput = value; }
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardInput(int bufferSize)
{
// bufferSize is ignored, other than in argument validation, even in the .NET Framework
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardOutput(int bufferSize)
{
// bufferSize is ignored, other than in argument validation, even in the .NET Framework
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static Stream OpenStandardError(int bufferSize)
{
// bufferSize is ignored, other than in argument validation, even in the .NET Framework
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, nameof(newIn));
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject)
{
Volatile.Write(ref s_in, newIn);
}
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, nameof(newOut));
newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut);
Volatile.Write(ref s_isOutTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_out, newOut);
}
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, nameof(newError));
newError = SyncTextWriter.GetSynchronizedTextWriter(newError);
Volatile.Write(ref s_isErrorTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_error, newError);
}
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static String ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(Object value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String value)
{
Out.Write(value);
}
private sealed class ControlCDelegateData
{
private readonly ConsoleSpecialKey _controlKey;
private readonly ConsoleCancelEventHandler _cancelCallbacks;
internal bool Cancel;
internal bool DelegateStarted;
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks)
{
_controlKey = controlKey;
_cancelCallbacks = cancelCallbacks;
}
// This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so
// the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task
// to start).
internal void HandleBreakEvent()
{
DelegateStarted = true;
var args = new ConsoleCancelEventArgs(_controlKey);
_cancelCallbacks(null, args);
Cancel = args.Cancel;
}
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
// The thread that this gets called back on has a very small stack on some systems. There is
// not enough space to handle a managed exception being caught and thrown. So, run a task
// on the threadpool for the actual event callback.
// To avoid the race condition between remove handler and raising the event
ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks;
if (cancelCallbacks == null)
{
return false;
}
var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks);
Task callBackTask = Task.Factory.StartNew(
d => ((ControlCDelegateData)d).HandleBreakEvent(),
delegateData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Block until the delegate is done. We need to be robust in the face of the task not executing
// but we also want to get control back immediately after it is done and we don't want to give the
// handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a
// timeout and a second time without if we are sure that the handler actually started.
TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds
callBackTask.Wait(controlCWaitTime);
if (!delegateData.DelegateStarted)
{
Debug.Assert(false, "The task to execute the handler did not start within 30 seconds.");
return false;
}
callBackTask.Wait();
return delegateData.Cancel;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: addressbook.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 GoogleUtils.Tests.Serialization {
/// <summary>Holder for reflection information generated from addressbook.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class AddressbookReflection {
#region Descriptor
/// <summary>File descriptor for addressbook.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static AddressbookReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwi1QEKBlBlcnNvbhIMCgRu",
"YW1lGAEgASgJEgoKAmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25l",
"cxgEIAMoCzIcLnR1dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchpHCgtQaG9u",
"ZU51bWJlchIOCgZudW1iZXIYASABKAkSKAoEdHlwZRgCIAEoDjIaLnR1dG9y",
"aWFsLlBlcnNvbi5QaG9uZVR5cGUiKwoJUGhvbmVUeXBlEgoKBk1PQklMRRAA",
"EggKBEhPTUUQARIICgRXT1JLEAIiSAoLQWRkcmVzc0Jvb2sSIAoGcGVvcGxl",
"GAEgAygLMhAudHV0b3JpYWwuUGVyc29uEhcKD2FkZHJlc3NCb29rTmFtZRgC",
"IAEoCUIaqgIXVW5pdFRlc3RzLlNlcmlhbGl6YXRpb25iBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::GoogleUtils.Tests.Serialization.Person), global::GoogleUtils.Tests.Serialization.Person.Parser, new[]{ "Name", "Id", "Email", "Phones" }, null, new[]{ typeof(global::GoogleUtils.Tests.Serialization.Person.Types.PhoneType) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber), global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber.Parser, new[]{ "Number", "Type" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::GoogleUtils.Tests.Serialization.AddressBook), global::GoogleUtils.Tests.Serialization.AddressBook.Parser, new[]{ "People", "AddressBookName" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// [START messages]
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Person : pb::IMessage<Person> {
private static readonly pb::MessageParser<Person> _parser = new pb::MessageParser<Person>(() => new Person());
public static pb::MessageParser<Person> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::GoogleUtils.Tests.Serialization.AddressbookReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Person() {
OnConstruction();
}
partial void OnConstruction();
public Person(Person other) : this() {
name_ = other.name_;
id_ = other.id_;
email_ = other.email_;
phones_ = other.phones_.Clone();
}
public Person Clone() {
return new Person(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 2;
private int id_;
/// <summary>
/// Unique ID number for this person.
/// </summary>
public int Id {
get { return id_; }
set {
id_ = value;
}
}
/// <summary>Field number for the "email" field.</summary>
public const int EmailFieldNumber = 3;
private string email_ = "";
public string Email {
get { return email_; }
set {
email_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "phones" field.</summary>
public const int PhonesFieldNumber = 4;
private static readonly pb::FieldCodec<global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber> _repeated_phones_codec
= pb::FieldCodec.ForMessage(34, global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber.Parser);
private readonly pbc::RepeatedField<global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber> phones_ = new pbc::RepeatedField<global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber>();
public pbc::RepeatedField<global::GoogleUtils.Tests.Serialization.Person.Types.PhoneNumber> Phones {
get { return phones_; }
}
public override bool Equals(object other) {
return Equals(other as Person);
}
public bool Equals(Person other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Id != other.Id) return false;
if (Email != other.Email) return false;
if(!phones_.Equals(other.phones_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Id != 0) hash ^= Id.GetHashCode();
if (Email.Length != 0) hash ^= Email.GetHashCode();
hash ^= phones_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Id != 0) {
output.WriteRawTag(16);
output.WriteInt32(Id);
}
if (Email.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Email);
}
phones_.WriteTo(output, _repeated_phones_codec);
}
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Id != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id);
}
if (Email.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Email);
}
size += phones_.CalculateSize(_repeated_phones_codec);
return size;
}
public void MergeFrom(Person other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Id != 0) {
Id = other.Id;
}
if (other.Email.Length != 0) {
Email = other.Email;
}
phones_.Add(other.phones_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
Id = input.ReadInt32();
break;
}
case 26: {
Email = input.ReadString();
break;
}
case 34: {
phones_.AddEntriesFrom(input, _repeated_phones_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Person message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum PhoneType {
[pbr::OriginalName("MOBILE")] Mobile = 0,
[pbr::OriginalName("HOME")] Home = 1,
[pbr::OriginalName("WORK")] Work = 2,
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber> {
private static readonly pb::MessageParser<PhoneNumber> _parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber());
public static pb::MessageParser<PhoneNumber> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::GoogleUtils.Tests.Serialization.Person.Descriptor.NestedTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PhoneNumber() {
OnConstruction();
}
partial void OnConstruction();
public PhoneNumber(PhoneNumber other) : this() {
number_ = other.number_;
type_ = other.type_;
}
public PhoneNumber Clone() {
return new PhoneNumber(this);
}
/// <summary>Field number for the "number" field.</summary>
public const int NumberFieldNumber = 1;
private string number_ = "";
public string Number {
get { return number_; }
set {
number_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 2;
private global::GoogleUtils.Tests.Serialization.Person.Types.PhoneType type_ = 0;
public global::GoogleUtils.Tests.Serialization.Person.Types.PhoneType Type {
get { return type_; }
set {
type_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as PhoneNumber);
}
public bool Equals(PhoneNumber other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Number != other.Number) return false;
if (Type != other.Type) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Number.Length != 0) hash ^= Number.GetHashCode();
if (Type != 0) hash ^= Type.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Number.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Number);
}
if (Type != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Type);
}
}
public int CalculateSize() {
int size = 0;
if (Number.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Number);
}
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
return size;
}
public void MergeFrom(PhoneNumber other) {
if (other == null) {
return;
}
if (other.Number.Length != 0) {
Number = other.Number;
}
if (other.Type != 0) {
Type = other.Type;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Number = input.ReadString();
break;
}
case 16: {
type_ = (global::GoogleUtils.Tests.Serialization.Person.Types.PhoneType) input.ReadEnum();
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// Our address book file is just one of these.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class AddressBook : pb::IMessage<AddressBook> {
private static readonly pb::MessageParser<AddressBook> _parser = new pb::MessageParser<AddressBook>(() => new AddressBook());
public static pb::MessageParser<AddressBook> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::GoogleUtils.Tests.Serialization.AddressbookReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public AddressBook() {
OnConstruction();
}
partial void OnConstruction();
public AddressBook(AddressBook other) : this() {
people_ = other.people_.Clone();
addressBookName_ = other.addressBookName_;
}
public AddressBook Clone() {
return new AddressBook(this);
}
/// <summary>Field number for the "people" field.</summary>
public const int PeopleFieldNumber = 1;
private static readonly pb::FieldCodec<global::GoogleUtils.Tests.Serialization.Person> _repeated_people_codec
= pb::FieldCodec.ForMessage(10, global::GoogleUtils.Tests.Serialization.Person.Parser);
private readonly pbc::RepeatedField<global::GoogleUtils.Tests.Serialization.Person> people_ = new pbc::RepeatedField<global::GoogleUtils.Tests.Serialization.Person>();
public pbc::RepeatedField<global::GoogleUtils.Tests.Serialization.Person> People {
get { return people_; }
}
/// <summary>Field number for the "addressBookName" field.</summary>
public const int AddressBookNameFieldNumber = 2;
private string addressBookName_ = "";
/// <summary>
/// the name of this address book
/// </summary>
public string AddressBookName {
get { return addressBookName_; }
set {
addressBookName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as AddressBook);
}
public bool Equals(AddressBook other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!people_.Equals(other.people_)) return false;
if (AddressBookName != other.AddressBookName) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= people_.GetHashCode();
if (AddressBookName.Length != 0) hash ^= AddressBookName.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
people_.WriteTo(output, _repeated_people_codec);
if (AddressBookName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(AddressBookName);
}
}
public int CalculateSize() {
int size = 0;
size += people_.CalculateSize(_repeated_people_codec);
if (AddressBookName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AddressBookName);
}
return size;
}
public void MergeFrom(AddressBook other) {
if (other == null) {
return;
}
people_.Add(other.people_);
if (other.AddressBookName.Length != 0) {
AddressBookName = other.AddressBookName;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
people_.AddEntriesFrom(input, _repeated_people_codec);
break;
}
case 18: {
AddressBookName = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal.Windows
{
internal sealed partial class DecryptorPalWindows : DecryptorPal
{
public sealed override ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception)
{
Debug.Assert(recipientInfo != null);
Debug.Assert(cert != null);
Debug.Assert(originatorCerts != null);
Debug.Assert(extraStore != null);
CryptKeySpec keySpec;
exception = TryGetKeySpecForCertificate(cert, out keySpec);
if (exception != null)
return null;
// Desktop compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
using (SafeProvOrNCryptKeyHandle hKey = TryGetCertificatePrivateKey(cert, false, out exception))
{
if (hKey == null)
return null;
RecipientInfoType type = recipientInfo.Type;
switch (type)
{
case RecipientInfoType.KeyTransport:
exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
break;
case RecipientInfoType.KeyAgreement:
exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
break;
default:
// Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
// returning to the caller.
Debug.Fail($"Unexpected RecipientInfoType: {type}");
throw new NotSupportedException();
}
if (exception != null)
return null;
// If we got here, we successfully decrypted. Return the decrypted content.
return _hCryptMsg.GetContentInfo();
}
}
private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
{
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
int cbSize = 0;
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
byte[] pData = new byte[cbSize];
unsafe
{
fixed (byte* pvData = pData)
{
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, pData, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
CRYPT_KEY_PROV_INFO* pCryptKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pvData;
keySpec = pCryptKeyProvInfo->dwKeySpec;
return null;
}
}
}
}
private static SafeProvOrNCryptKeyHandle TryGetCertificatePrivateKey(X509Certificate2 cert, bool silent, out Exception exception)
{
CryptAcquireCertificatePrivateKeyFlags flags =
CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_COMPARE_KEY_FLAG
// Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG because wrapping an NCrypt wrapper over CAPI keys unconditionally
// causes some legacy features (such as RC4 support) to break.
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG;
if (silent)
{
flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_SILENT_FLAG;
}
bool mustFree;
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
IntPtr hKey;
CryptKeySpec keySpec;
if (!Interop.Crypt32.CryptAcquireCertificatePrivateKey(hCertContext, flags, IntPtr.Zero, out hKey, out keySpec, out mustFree))
{
exception = Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
// We need to know whether we got back a CRYPTPROV or NCrypt handle. Unfortunately, NCryptIsKeyHandle() is a prohibited api on UWP.
// Fortunately, CryptAcquireCertificatePrivateKey() is documented to tell us which one we got through the keySpec value.
bool isNCrypt;
switch (keySpec)
{
case CryptKeySpec.AT_KEYEXCHANGE:
case CryptKeySpec.AT_SIGNATURE:
isNCrypt = false;
break;
case CryptKeySpec.CERT_NCRYPT_KEY_SPEC:
isNCrypt = true;
break;
default:
// As of this writing, we've exhausted all the known values of keySpec. We have no idea what kind of key handle we got so
// play it safe and fail fast.
throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_UnknownKeySpec, keySpec));
}
SafeProvOrNCryptKeyHandleUwp hProvOrNCryptKey = new SafeProvOrNCryptKeyHandleUwp(hKey, ownsHandle: mustFree, isNcrypt: isNCrypt);
exception = null;
return hProvOrNCryptKey;
}
}
private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
{
KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);
CMSG_CTRL_DECRYPT_PARA decryptPara;
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_DECRYPT_PARA>();
decryptPara.hKey = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.dwRecipientIndex = pal.Index;
bool success = Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_DECRYPT, ref decryptPara);
if (!success)
return Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
{
unsafe
{
KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
return pal.WithCmsgCmsRecipientInfo<Exception>(
delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
{
CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
decryptPara.hProv = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
decryptPara.dwRecipientIndex = pal.Index;
decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
switch (originatorChoice)
{
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
{
X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
candidateCerts.AddRange(originatorCerts);
candidateCerts.AddRange(extraStore);
SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
using (X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId))
{
if (originatorCert == null)
return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
{
CERT_CONTEXT* pOriginatorCertContext = hCertContext.DangerousGetCertContext();
decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;
// Do not factor this call out of the switch statement as leaving this "using" block will free up
// native memory that decryptPara points to.
return TryExecuteDecryptAgree(ref decryptPara);
}
}
}
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
{
decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
return TryExecuteDecryptAgree(ref decryptPara);
}
default:
return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
}
});
}
}
private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
{
if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetHRForLastWin32Error());
return errorCode.ToCryptographicException();
}
return null;
}
}
}
| |
namespace System
{
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1>
{
[Bridge.Template("{ Item1: {item1} }")]
public extern Tuple(T1 item1);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2} }")]
public extern Tuple(T1 item1, T2 item2);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2, T3>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3} }")]
public extern Tuple(T1 item1, T2 item2, T3 item3);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
public extern T3 Item3
{
[Bridge.Template("Item3")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2, T3, T4>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4} }")]
public extern Tuple(T1 item1, T2 item2, T3 item3, T4 item4);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
public extern T3 Item3
{
[Bridge.Template("Item3")]
get;
}
public extern T4 Item4
{
[Bridge.Template("Item4")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2, T3, T4, T5>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5} }")]
public extern Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
public extern T3 Item3
{
[Bridge.Template("Item3")]
get;
}
public extern T4 Item4
{
[Bridge.Template("Item4")]
get;
}
public extern T5 Item5
{
[Bridge.Template("Item5")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2, T3, T4, T5, T6>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5}, Item6: {item6} }")]
public extern Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
public extern T3 Item3
{
[Bridge.Template("Item3")]
get;
}
public extern T4 Item4
{
[Bridge.Template("Item4")]
get;
}
public extern T5 Item5
{
[Bridge.Template("Item5")]
get;
}
public extern T6 Item6
{
[Bridge.Template("Item6")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2, T3, T4, T5, T6, T7>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5}, Item6: {item6}, Item7: {item7} }")]
public extern Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
public extern T3 Item3
{
[Bridge.Template("Item3")]
get;
}
public extern T4 Item4
{
[Bridge.Template("Item4")]
get;
}
public extern T5 Item5
{
[Bridge.Template("Item5")]
get;
}
public extern T6 Item6
{
[Bridge.Template("Item6")]
get;
}
public extern T7 Item7
{
[Bridge.Template("Item7")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public sealed class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
{
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5}, Item6: {item6}, Item7: {item7}, rest: {rest} }")]
public extern Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest);
public extern T1 Item1
{
[Bridge.Template("Item1")]
get;
}
public extern T2 Item2
{
[Bridge.Template("Item2")]
get;
}
public extern T3 Item3
{
[Bridge.Template("Item3")]
get;
}
public extern T4 Item4
{
[Bridge.Template("Item4")]
get;
}
public extern T5 Item5
{
[Bridge.Template("Item5")]
get;
}
public extern T6 Item6
{
[Bridge.Template("Item6")]
get;
}
public extern T7 Item7
{
[Bridge.Template("Item7")]
get;
}
public extern TRest Rest
{
[Bridge.Template("rest")]
get;
}
[Bridge.Template("Bridge.objectEquals({this}, {o}, true)")]
public override extern bool Equals(object o);
[Bridge.Template("Bridge.getHashCode({this}, false, true)")]
public override extern int GetHashCode();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.IgnoreCast]
public static class Tuple
{
[Bridge.Template("{ Item1: {item1} }")]
public static extern Tuple<T1> Create<T1>(T1 item1);
[Bridge.Template("{ Item1: {item1}, Item2: {item2} }")]
public static extern Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2);
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3} }")]
public static extern Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3);
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4} }")]
public static extern Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4);
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5} }")]
public static extern Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5);
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5}, Item6: {item6} }")]
public static extern Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6);
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5}, Item6: {item6}, Item7: {item7} }")]
public static extern Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7);
[Bridge.Template("{ Item1: {item1}, Item2: {item2}, Item3: {item3}, Item4: {item4}, Item5: {item5}, Item6: {item6}, Item7: {item7}, rest: {rest} }")]
public static extern Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> Create<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
public partial class ASCIIEncoding : System.Text.Encoding
{
public ASCIIEncoding() { }
public override bool IsSingleByte { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetByteCount(char* chars, int count) { throw null; }
public override int GetByteCount(char[] chars, int index, int count) { throw null; }
public override int GetByteCount(string chars) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { throw null; }
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
public override int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetCharCount(byte* bytes, int count) { throw null; }
public override int GetCharCount(byte[] bytes, int index, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { throw null; }
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { throw null; }
public override System.Text.Decoder GetDecoder() { throw null; }
public override System.Text.Encoder GetEncoder() { throw null; }
public override int GetMaxByteCount(int charCount) { throw null; }
public override int GetMaxCharCount(int byteCount) { throw null; }
public override string GetString(byte[] bytes, int byteIndex, int byteCount) { throw null; }
}
public abstract partial class Decoder
{
protected Decoder() { }
public System.Text.DecoderFallback Fallback { get { throw null; } set { } }
public System.Text.DecoderFallbackBuffer FallbackBuffer { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public unsafe virtual void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { throw null; }
public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { throw null; }
public virtual void Convert(System.ReadOnlySpan<byte> bytes, System.Span<char> chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetCharCount(byte* bytes, int count, bool flush) { throw null; }
public abstract int GetCharCount(byte[] bytes, int index, int count);
public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { throw null; }
public virtual int GetCharCount(System.ReadOnlySpan<byte> bytes, bool flush) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { throw null; }
public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { throw null; }
public virtual int GetChars(System.ReadOnlySpan<byte> bytes, System.Span<char> chars, bool flush) { throw null; }
public virtual void Reset() { }
}
public sealed partial class DecoderExceptionFallback : System.Text.DecoderFallback
{
public DecoderExceptionFallback() { }
public override int MaxCharCount { get { throw null; } }
public override System.Text.DecoderFallbackBuffer CreateFallbackBuffer() { throw null; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
}
public sealed partial class DecoderExceptionFallbackBuffer : System.Text.DecoderFallbackBuffer
{
public DecoderExceptionFallbackBuffer() { }
public override int Remaining { get { throw null; } }
public override bool Fallback(byte[] bytesUnknown, int index) { throw null; }
public override char GetNextChar() { throw null; }
public override bool MovePrevious() { throw null; }
}
public abstract partial class DecoderFallback
{
protected DecoderFallback() { }
public static System.Text.DecoderFallback ExceptionFallback { get { throw null; } }
public abstract int MaxCharCount { get; }
public static System.Text.DecoderFallback ReplacementFallback { get { throw null; } }
public abstract System.Text.DecoderFallbackBuffer CreateFallbackBuffer();
}
public abstract partial class DecoderFallbackBuffer
{
protected DecoderFallbackBuffer() { }
public abstract int Remaining { get; }
public abstract bool Fallback(byte[] bytesUnknown, int index);
public abstract char GetNextChar();
public abstract bool MovePrevious();
public virtual void Reset() { }
}
public sealed partial class DecoderFallbackException : System.ArgumentException
{
public DecoderFallbackException() { }
public DecoderFallbackException(string message) { }
public DecoderFallbackException(string message, byte[] bytesUnknown, int index) { }
public DecoderFallbackException(string message, System.Exception innerException) { }
public byte[] BytesUnknown { get { throw null; } }
public int Index { get { throw null; } }
}
public sealed partial class DecoderReplacementFallback : System.Text.DecoderFallback
{
public DecoderReplacementFallback() { }
public DecoderReplacementFallback(string replacement) { }
public string DefaultString { get { throw null; } }
public override int MaxCharCount { get { throw null; } }
public override System.Text.DecoderFallbackBuffer CreateFallbackBuffer() { throw null; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
}
public sealed partial class DecoderReplacementFallbackBuffer : System.Text.DecoderFallbackBuffer
{
public DecoderReplacementFallbackBuffer(System.Text.DecoderReplacementFallback fallback) { }
public override int Remaining { get { throw null; } }
public override bool Fallback(byte[] bytesUnknown, int index) { throw null; }
public override char GetNextChar() { throw null; }
public override bool MovePrevious() { throw null; }
public override void Reset() { }
}
public abstract partial class Encoder
{
protected Encoder() { }
public System.Text.EncoderFallback Fallback { get { throw null; } set { } }
public System.Text.EncoderFallbackBuffer FallbackBuffer { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public unsafe virtual void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { throw null; }
public virtual void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { throw null; }
public virtual void Convert(System.ReadOnlySpan<char> chars, System.Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetByteCount(char* chars, int count, bool flush) { throw null; }
public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
public virtual int GetByteCount(System.ReadOnlySpan<char> chars, bool flush) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { throw null; }
public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush);
public virtual int GetBytes(System.ReadOnlySpan<char> chars, System.Span<byte> bytes, bool flush) { throw null; }
public virtual void Reset() { }
}
public sealed partial class EncoderExceptionFallback : System.Text.EncoderFallback
{
public EncoderExceptionFallback() { }
public override int MaxCharCount { get { throw null; } }
public override System.Text.EncoderFallbackBuffer CreateFallbackBuffer() { throw null; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
}
public sealed partial class EncoderExceptionFallbackBuffer : System.Text.EncoderFallbackBuffer
{
public EncoderExceptionFallbackBuffer() { }
public override int Remaining { get { throw null; } }
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { throw null; }
public override bool Fallback(char charUnknown, int index) { throw null; }
public override char GetNextChar() { throw null; }
public override bool MovePrevious() { throw null; }
}
public abstract partial class EncoderFallback
{
protected EncoderFallback() { }
public static System.Text.EncoderFallback ExceptionFallback { get { throw null; } }
public abstract int MaxCharCount { get; }
public static System.Text.EncoderFallback ReplacementFallback { get { throw null; } }
public abstract System.Text.EncoderFallbackBuffer CreateFallbackBuffer();
}
public abstract partial class EncoderFallbackBuffer
{
protected EncoderFallbackBuffer() { }
public abstract int Remaining { get; }
public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index);
public abstract bool Fallback(char charUnknown, int index);
public abstract char GetNextChar();
public abstract bool MovePrevious();
public virtual void Reset() { }
}
public sealed partial class EncoderFallbackException : System.ArgumentException
{
public EncoderFallbackException() { }
public EncoderFallbackException(string message) { }
public EncoderFallbackException(string message, System.Exception innerException) { }
public char CharUnknown { get { throw null; } }
public char CharUnknownHigh { get { throw null; } }
public char CharUnknownLow { get { throw null; } }
public int Index { get { throw null; } }
public bool IsUnknownSurrogate() { throw null; }
}
public sealed partial class EncoderReplacementFallback : System.Text.EncoderFallback
{
public EncoderReplacementFallback() { }
public EncoderReplacementFallback(string replacement) { }
public string DefaultString { get { throw null; } }
public override int MaxCharCount { get { throw null; } }
public override System.Text.EncoderFallbackBuffer CreateFallbackBuffer() { throw null; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
}
public sealed partial class EncoderReplacementFallbackBuffer : System.Text.EncoderFallbackBuffer
{
public EncoderReplacementFallbackBuffer(System.Text.EncoderReplacementFallback fallback) { }
public override int Remaining { get { throw null; } }
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { throw null; }
public override bool Fallback(char charUnknown, int index) { throw null; }
public override char GetNextChar() { throw null; }
public override bool MovePrevious() { throw null; }
public override void Reset() { }
}
public abstract partial class Encoding : System.ICloneable
{
protected Encoding() { }
protected Encoding(int codePage) { }
protected Encoding(int codePage, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback) { }
public static System.Text.Encoding ASCII { get { throw null; } }
public static System.Text.Encoding BigEndianUnicode { get { throw null; } }
public virtual string BodyName { get { throw null; } }
public virtual int CodePage { get { throw null; } }
public System.Text.DecoderFallback DecoderFallback { get { throw null; } set { } }
public static System.Text.Encoding Default { get { throw null; } }
public System.Text.EncoderFallback EncoderFallback { get { throw null; } set { } }
public virtual string EncodingName { get { throw null; } }
public virtual string HeaderName { get { throw null; } }
public virtual bool IsBrowserDisplay { get { throw null; } }
public virtual bool IsBrowserSave { get { throw null; } }
public virtual bool IsMailNewsDisplay { get { throw null; } }
public virtual bool IsMailNewsSave { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public virtual bool IsSingleByte { get { throw null; } }
public virtual System.ReadOnlySpan<byte> Preamble { get { throw null; } }
public static System.Text.Encoding Unicode { get { throw null; } }
public static System.Text.Encoding UTF32 { get { throw null; } }
public static System.Text.Encoding UTF7 { get { throw null; } }
public static System.Text.Encoding UTF8 { get { throw null; } }
public virtual string WebName { get { throw null; } }
public virtual int WindowsCodePage { get { throw null; } }
public virtual object Clone() { throw null; }
public static byte[] Convert(System.Text.Encoding srcEncoding, System.Text.Encoding dstEncoding, byte[] bytes) { throw null; }
public static byte[] Convert(System.Text.Encoding srcEncoding, System.Text.Encoding dstEncoding, byte[] bytes, int index, int count) { throw null; }
public override bool Equals(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetByteCount(char* chars, int count) { throw null; }
public virtual int GetByteCount(char[] chars) { throw null; }
public abstract int GetByteCount(char[] chars, int index, int count);
public virtual int GetByteCount(System.ReadOnlySpan<char> chars) { throw null; }
public virtual int GetByteCount(string s) { throw null; }
public int GetByteCount(string s, int index, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { throw null; }
public virtual byte[] GetBytes(char[] chars) { throw null; }
public virtual byte[] GetBytes(char[] chars, int index, int count) { throw null; }
public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex);
public virtual int GetBytes(System.ReadOnlySpan<char> chars, System.Span<byte> bytes) { throw null; }
public virtual byte[] GetBytes(string s) { throw null; }
public byte[] GetBytes(string s, int index, int count) { throw null; }
public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetCharCount(byte* bytes, int count) { throw null; }
public virtual int GetCharCount(byte[] bytes) { throw null; }
public abstract int GetCharCount(byte[] bytes, int index, int count);
public virtual int GetCharCount(System.ReadOnlySpan<byte> bytes) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { throw null; }
public virtual char[] GetChars(byte[] bytes) { throw null; }
public virtual char[] GetChars(byte[] bytes, int index, int count) { throw null; }
public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
public virtual int GetChars(System.ReadOnlySpan<byte> bytes, System.Span<char> chars) { throw null; }
public virtual System.Text.Decoder GetDecoder() { throw null; }
public virtual System.Text.Encoder GetEncoder() { throw null; }
public static System.Text.Encoding GetEncoding(int codepage) { throw null; }
public static System.Text.Encoding GetEncoding(int codepage, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback) { throw null; }
public static System.Text.Encoding GetEncoding(string name) { throw null; }
public static System.Text.Encoding GetEncoding(string name, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback) { throw null; }
public static System.Text.EncodingInfo[] GetEncodings() { throw null; }
public override int GetHashCode() { throw null; }
public abstract int GetMaxByteCount(int charCount);
public abstract int GetMaxCharCount(int byteCount);
public virtual byte[] GetPreamble() { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe string GetString(byte* bytes, int byteCount) { throw null; }
public virtual string GetString(byte[] bytes) { throw null; }
public virtual string GetString(byte[] bytes, int index, int count) { throw null; }
public string GetString(System.ReadOnlySpan<byte> bytes) { throw null; }
public bool IsAlwaysNormalized() { throw null; }
public virtual bool IsAlwaysNormalized(System.Text.NormalizationForm form) { throw null; }
public static void RegisterProvider(System.Text.EncodingProvider provider) { }
}
public sealed partial class EncodingInfo
{
internal EncodingInfo() { }
public int CodePage { get { throw null; } }
public string DisplayName { get { throw null; } }
public string Name { get { throw null; } }
public override bool Equals(object value) { throw null; }
public System.Text.Encoding GetEncoding() { throw null; }
public override int GetHashCode() { throw null; }
}
public abstract partial class EncodingProvider
{
public EncodingProvider() { }
public abstract System.Text.Encoding GetEncoding(int codepage);
public virtual System.Text.Encoding GetEncoding(int codepage, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback) { throw null; }
public abstract System.Text.Encoding GetEncoding(string name);
public virtual System.Text.Encoding GetEncoding(string name, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback) { throw null; }
}
public enum NormalizationForm
{
FormC = 1,
FormD = 2,
FormKC = 5,
FormKD = 6,
}
public sealed partial class StringBuilder : System.Runtime.Serialization.ISerializable
{
public StringBuilder() { }
public StringBuilder(int capacity) { }
public StringBuilder(int capacity, int maxCapacity) { }
public StringBuilder(string value) { }
public StringBuilder(string value, int capacity) { }
public StringBuilder(string value, int startIndex, int length, int capacity) { }
public int Capacity { get { throw null; } set { } }
[System.Runtime.CompilerServices.IndexerName("Chars")]
public char this[int index] { get { throw null; } set { } }
public int Length { get { throw null; } set { } }
public int MaxCapacity { get { throw null; } }
public System.Text.StringBuilder Append(bool value) { throw null; }
public System.Text.StringBuilder Append(byte value) { throw null; }
public System.Text.StringBuilder Append(char value) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe System.Text.StringBuilder Append(char* value, int valueCount) { throw null; }
public System.Text.StringBuilder Append(char value, int repeatCount) { throw null; }
public System.Text.StringBuilder Append(char[] value) { throw null; }
public System.Text.StringBuilder Append(char[] value, int startIndex, int charCount) { throw null; }
public System.Text.StringBuilder Append(decimal value) { throw null; }
public System.Text.StringBuilder Append(double value) { throw null; }
public System.Text.StringBuilder Append(short value) { throw null; }
public System.Text.StringBuilder Append(int value) { throw null; }
public System.Text.StringBuilder Append(long value) { throw null; }
public System.Text.StringBuilder Append(object value) { throw null; }
public System.Text.StringBuilder Append(System.ReadOnlySpan<char> value) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Append(sbyte value) { throw null; }
public System.Text.StringBuilder Append(float value) { throw null; }
public System.Text.StringBuilder Append(string value) { throw null; }
public System.Text.StringBuilder Append(string value, int startIndex, int count) { throw null; }
public System.Text.StringBuilder Append(System.Text.StringBuilder value) { throw null; }
public System.Text.StringBuilder Append(System.Text.StringBuilder value, int startIndex, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Append(ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Append(uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Append(ulong value) { throw null; }
public System.Text.StringBuilder AppendFormat(System.IFormatProvider provider, string format, object arg0) { throw null; }
public System.Text.StringBuilder AppendFormat(System.IFormatProvider provider, string format, object arg0, object arg1) { throw null; }
public System.Text.StringBuilder AppendFormat(System.IFormatProvider provider, string format, object arg0, object arg1, object arg2) { throw null; }
public System.Text.StringBuilder AppendFormat(System.IFormatProvider provider, string format, params object[] args) { throw null; }
public System.Text.StringBuilder AppendFormat(string format, object arg0) { throw null; }
public System.Text.StringBuilder AppendFormat(string format, object arg0, object arg1) { throw null; }
public System.Text.StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2) { throw null; }
public System.Text.StringBuilder AppendFormat(string format, params object[] args) { throw null; }
public System.Text.StringBuilder AppendJoin(char separator, params object[] values) { throw null; }
public System.Text.StringBuilder AppendJoin(char separator, params string[] values) { throw null; }
public System.Text.StringBuilder AppendJoin(string separator, params object[] values) { throw null; }
public System.Text.StringBuilder AppendJoin(string separator, params string[] values) { throw null; }
public System.Text.StringBuilder AppendJoin<T>(char separator, System.Collections.Generic.IEnumerable<T> values) { throw null; }
public System.Text.StringBuilder AppendJoin<T>(string separator, System.Collections.Generic.IEnumerable<T> values) { throw null; }
public System.Text.StringBuilder AppendLine() { throw null; }
public System.Text.StringBuilder AppendLine(string value) { throw null; }
public System.Text.StringBuilder Clear() { throw null; }
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { }
public void CopyTo(int sourceIndex, System.Span<char> destination, int count) { }
public int EnsureCapacity(int capacity) { throw null; }
public bool Equals(System.ReadOnlySpan<char> span) { throw null; }
public bool Equals(System.Text.StringBuilder sb) { throw null; }
public System.Text.StringBuilder Insert(int index, bool value) { throw null; }
public System.Text.StringBuilder Insert(int index, byte value) { throw null; }
public System.Text.StringBuilder Insert(int index, char value) { throw null; }
public System.Text.StringBuilder Insert(int index, char[] value) { throw null; }
public System.Text.StringBuilder Insert(int index, char[] value, int startIndex, int charCount) { throw null; }
public System.Text.StringBuilder Insert(int index, decimal value) { throw null; }
public System.Text.StringBuilder Insert(int index, double value) { throw null; }
public System.Text.StringBuilder Insert(int index, short value) { throw null; }
public System.Text.StringBuilder Insert(int index, int value) { throw null; }
public System.Text.StringBuilder Insert(int index, long value) { throw null; }
public System.Text.StringBuilder Insert(int index, object value) { throw null; }
public System.Text.StringBuilder Insert(int index, System.ReadOnlySpan<char> value) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Insert(int index, sbyte value) { throw null; }
public System.Text.StringBuilder Insert(int index, float value) { throw null; }
public System.Text.StringBuilder Insert(int index, string value) { throw null; }
public System.Text.StringBuilder Insert(int index, string value, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Insert(int index, ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Insert(int index, uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public System.Text.StringBuilder Insert(int index, ulong value) { throw null; }
public System.Text.StringBuilder Remove(int startIndex, int length) { throw null; }
public System.Text.StringBuilder Replace(char oldChar, char newChar) { throw null; }
public System.Text.StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) { throw null; }
public System.Text.StringBuilder Replace(string oldValue, string newValue) { throw null; }
public System.Text.StringBuilder Replace(string oldValue, string newValue, int startIndex, int count) { throw null; }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
public string ToString(int startIndex, int length) { throw null; }
}
public partial class UnicodeEncoding : System.Text.Encoding
{
public const int CharSize = 2;
public UnicodeEncoding() { }
public UnicodeEncoding(bool bigEndian, bool byteOrderMark) { }
public UnicodeEncoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes) { }
public override bool Equals(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetByteCount(char* chars, int count) { throw null; }
public override int GetByteCount(char[] chars, int index, int count) { throw null; }
public override int GetByteCount(string s) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { throw null; }
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetCharCount(byte* bytes, int count) { throw null; }
public override int GetCharCount(byte[] bytes, int index, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { throw null; }
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { throw null; }
public override System.Text.Decoder GetDecoder() { throw null; }
public override System.Text.Encoder GetEncoder() { throw null; }
public override int GetHashCode() { throw null; }
public override int GetMaxByteCount(int charCount) { throw null; }
public override int GetMaxCharCount(int byteCount) { throw null; }
public override byte[] GetPreamble() { throw null; }
public override string GetString(byte[] bytes, int index, int count) { throw null; }
}
public sealed partial class UTF32Encoding : System.Text.Encoding
{
public UTF32Encoding() { }
public UTF32Encoding(bool bigEndian, bool byteOrderMark) { }
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) { }
public override bool Equals(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetByteCount(char* chars, int count) { throw null; }
public override int GetByteCount(char[] chars, int index, int count) { throw null; }
public override int GetByteCount(string s) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { throw null; }
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetCharCount(byte* bytes, int count) { throw null; }
public override int GetCharCount(byte[] bytes, int index, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { throw null; }
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { throw null; }
public override System.Text.Decoder GetDecoder() { throw null; }
public override System.Text.Encoder GetEncoder() { throw null; }
public override int GetHashCode() { throw null; }
public override int GetMaxByteCount(int charCount) { throw null; }
public override int GetMaxCharCount(int byteCount) { throw null; }
public override byte[] GetPreamble() { throw null; }
public override string GetString(byte[] bytes, int index, int count) { throw null; }
}
public partial class UTF7Encoding : System.Text.Encoding
{
public UTF7Encoding() { }
public UTF7Encoding(bool allowOptionals) { }
public override bool Equals(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetByteCount(char* chars, int count) { throw null; }
public override int GetByteCount(char[] chars, int index, int count) { throw null; }
public override int GetByteCount(string s) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { throw null; }
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetCharCount(byte* bytes, int count) { throw null; }
public override int GetCharCount(byte[] bytes, int index, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { throw null; }
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { throw null; }
public override System.Text.Decoder GetDecoder() { throw null; }
public override System.Text.Encoder GetEncoder() { throw null; }
public override int GetHashCode() { throw null; }
public override int GetMaxByteCount(int charCount) { throw null; }
public override int GetMaxCharCount(int byteCount) { throw null; }
public override string GetString(byte[] bytes, int index, int count) { throw null; }
}
public partial class UTF8Encoding : System.Text.Encoding
{
public UTF8Encoding() { }
public UTF8Encoding(bool encoderShouldEmitUTF8Identifier) { }
public UTF8Encoding(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes) { }
public override bool Equals(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetByteCount(char* chars, int count) { throw null; }
public override int GetByteCount(char[] chars, int index, int count) { throw null; }
public override int GetByteCount(string chars) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { throw null; }
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetCharCount(byte* bytes, int count) { throw null; }
public override int GetCharCount(byte[] bytes, int index, int count) { throw null; }
[System.CLSCompliantAttribute(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { throw null; }
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { throw null; }
public override System.Text.Decoder GetDecoder() { throw null; }
public override System.Text.Encoder GetEncoder() { throw null; }
public override int GetHashCode() { throw null; }
public override int GetMaxByteCount(int charCount) { throw null; }
public override int GetMaxCharCount(int byteCount) { throw null; }
public override byte[] GetPreamble() { throw null; }
public override string GetString(byte[] bytes, int index, int count) { throw null; }
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Globalization;
using System.Reflection;
using System.Security.Principal;
#if !MONO && !NETSTANDARD
namespace NLog.UnitTests.Targets
{
using System.Diagnostics;
using NLog.Config;
using NLog.Targets;
using System;
using System.Linq;
using Xunit;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using NLog.Layouts;
using Xunit.Extensions;
public class EventLogTargetTests : NLogTestBase
{
[Fact]
public void MaxMessageLengthShouldBe16384_WhenNotSpecifyAnyOption()
{
const int expectedMaxMessageLength = 16384;
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog ThrowExceptions='true'>
<targets>
<target type='EventLog' name='eventLog1' layout='${message}' />
</targets>
<rules>
<logger name='*' writeTo='eventLog1'>
</logger>
</rules>
</nlog>");
var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1");
Assert.Equal(expectedMaxMessageLength, eventLog1.MaxMessageLength);
}
[Fact]
public void MaxMessageLengthShouldBeAsSpecifiedOption()
{
const int expectedMaxMessageLength = 1000;
LoggingConfiguration c = CreateConfigurationFromString($@"
<nlog ThrowExceptions='true'>
<targets>
<target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{
expectedMaxMessageLength
}' />
</targets>
<rules>
<logger name='*' writeTo='eventLog1'>
</logger>
</rules>
</nlog>");
var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1");
Assert.Equal(expectedMaxMessageLength, eventLog1.MaxMessageLength);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void ConfigurationShouldThrowException_WhenMaxMessageLengthIsNegativeOrZero(int maxMessageLength)
{
string configrationText = $@"
<nlog ThrowExceptions='true'>
<targets>
<target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{
maxMessageLength
}' />
</targets>
<rules>
<logger name='*' writeTo='eventLog1'>
</logger>
</rules>
</nlog>";
NLogConfigurationException ex = Assert.Throws<NLogConfigurationException>(() => CreateConfigurationFromString(configrationText));
Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.InnerException.InnerException.Message);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void ShouldThrowException_WhenMaxMessageLengthSetNegativeOrZero(int maxMessageLength)
{
ArgumentException ex = Assert.Throws<ArgumentException>(() =>
{
var target = new EventLogTarget();
target.MaxMessageLength = maxMessageLength;
});
Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.Message);
}
private void AssertMessageAndLogLevelForTruncatedMessages(LogLevel loglevel, EventLogEntryType expectedEventLogEntryType, string expectedMessage, Layout entryTypeLayout)
{
var eventRecords = WriteWithMock(loglevel, expectedEventLogEntryType, expectedMessage, entryTypeLayout, EventLogTargetOverflowAction.Truncate).ToList();
Assert.Single(eventRecords);
AssertWrittenMessage(eventRecords, expectedMessage);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsTrace()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Trace, EventLogEntryType.Information, "TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsTrace", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsDebug()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Debug, EventLogEntryType.Information, "TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsDebug", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsInfo()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Info, EventLogEntryType.Information, "TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsInfo", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtWarningLevel_WhenNLogLevelIsWarn()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.Warning, "TruncatedMessagesShouldBeWrittenAtWarningLevel_WhenNLogLevelIsWarn", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsError()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Error, EventLogEntryType.Error, "TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsError", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsFatal()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Fatal, EventLogEntryType.Error, "TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsFatal", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.SuccessAudit, "TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit", new SimpleLayout("SuccessAudit"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit_Uppercase()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.SuccessAudit, "TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit_Uppercase", new SimpleLayout("SUCCESSAUDIT"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtFailureAuditLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Debug, EventLogEntryType.FailureAudit, "TruncatedMessagesShouldBeWrittenAtFailureAuditLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit", new SimpleLayout("FailureAudit"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Debug, EventLogEntryType.Error, "TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError", new SimpleLayout("error"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.Warning, "TruncatedMessagesShouldBeWrittenAtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied", new SimpleLayout("fallback to auto determined"));
}
private void AssertMessageCountAndLogLevelForSplittedMessages(LogLevel loglevel, EventLogEntryType expectedEventLogEntryType, Layout entryTypeLayout)
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 2;
string messagePart1 = string.Join("", Enumerable.Repeat("l", maxMessageLength));
string messagePart2 = "this part must be splitted";
string testMessage = messagePart1 + messagePart2;
var entries = WriteWithMock(loglevel, expectedEventLogEntryType, testMessage, entryTypeLayout, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsTrace()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Trace, EventLogEntryType.Information, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsDebug()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.Information, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsInfo()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Info, EventLogEntryType.Information, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtWarningLevel_WhenNLogLevelIsWarn()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Warn, EventLogEntryType.Warning, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsError()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Error, EventLogEntryType.Error, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsFatal()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Fatal, EventLogEntryType.Error, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.SuccessAudit, new SimpleLayout("SuccessAudit"));
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtFailureLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.FailureAudit, new SimpleLayout("FailureAudit"));
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.Error, new SimpleLayout("error"));
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Info, EventLogEntryType.Information, new SimpleLayout("wrong entry type level"));
}
[Fact]
public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowTruncate_TruncatesTheMessage()
{
const int maxMessageLength = 16384;
string expectedMessage = string.Join("", Enumerable.Repeat("t", maxMessageLength));
string expectedToTruncateMessage = " this part will be truncated";
string testMessage = expectedMessage + expectedToTruncateMessage;
var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Truncate, maxMessageLength).ToList();
Assert.Single(entries);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowTruncate_TheMessageIsNotTruncated()
{
const int maxMessageLength = 16384;
string expectedMessage = string.Join("", Enumerable.Repeat("t", maxMessageLength));
var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Truncate, maxMessageLength).ToList();
Assert.Single(entries);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplitted()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 5;
string messagePart1 = string.Join("", Enumerable.Repeat("a", maxMessageLength));
string messagePart2 = string.Join("", Enumerable.Repeat("b", maxMessageLength));
string messagePart3 = string.Join("", Enumerable.Repeat("c", maxMessageLength));
string messagePart4 = string.Join("", Enumerable.Repeat("d", maxMessageLength));
string messagePart5 = "this part must be splitted too";
string testMessage = messagePart1 + messagePart2 + messagePart3 + messagePart4 + messagePart5;
var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, messagePart1);
AssertWrittenMessage(entries, messagePart2);
AssertWrittenMessage(entries, messagePart3);
AssertWrittenMessage(entries, messagePart4);
AssertWrittenMessage(entries, messagePart5);
}
[Fact]
public void WriteEventLogEntryEqual2MaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplittedInTwoChunk()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 2;
string messagePart1 = string.Join("", Enumerable.Repeat("a", maxMessageLength));
string messagePart2 = string.Join("", Enumerable.Repeat("b", maxMessageLength));
string testMessage = messagePart1 + messagePart2;
var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, messagePart1);
AssertWrittenMessage(entries, messagePart2);
}
[Fact]
public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowSplitEntries_TheMessageIsNotSplit()
{
const int maxMessageLength = 16384;
string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength));
var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Single(entries);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowDiscard_TheMessageIsWritten()
{
const int maxMessageLength = 16384;
string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength));
var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Discard, maxMessageLength).ToList();
Assert.Single(entries);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowDiscard_TheMessageIsNotWritten()
{
const int maxMessageLength = 16384;
string messagePart1 = string.Join("", Enumerable.Repeat("a", maxMessageLength));
string messagePart2 = "b";
string testMessage = messagePart1 + messagePart2;
bool wasWritten = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Discard, maxMessageLength).Any();
Assert.False(wasWritten);
}
[Fact]
public void WriteEventLogEntryWithDynamicSource()
{
const int maxMessageLength = 10;
string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength));
var target = CreateEventLogTarget<EventLogTarget>(null, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Split, maxMessageLength);
target.Layout = new SimpleLayout("${message}");
target.Source = new SimpleLayout("${event-properties:item=DynamicSource}");
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
var logger = LogManager.GetLogger("WriteEventLogEntry");
var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N");
var logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName);
logger.Log(logEvent);
var eventLog = new EventLog(target.Log);
var entries = GetEventRecords(eventLog.Log).ToList();
entries = entries.Where(a => a.ProviderName == sourceName).ToList();
Assert.Single(entries);
AssertWrittenMessage(entries, expectedMessage);
sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N");
expectedMessage = string.Join("", Enumerable.Repeat("b", maxMessageLength));
logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName);
logger.Log(logEvent);
entries = GetEventRecords(eventLog.Log).ToList();
entries = entries.Where(a => a.ProviderName == sourceName).ToList();
Assert.Single(entries);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void LogEntryWithStaticEventIdAndCategoryInTargetLayout()
{
var rnd = new Random();
int eventId = rnd.Next(1, short.MaxValue);
int category = rnd.Next(1, short.MaxValue);
var target = CreateEventLogTarget<EventLogTarget>(null, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000);
target.EventId = new SimpleLayout(eventId.ToString());
target.Category = new SimpleLayout(category.ToString());
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
var logger = LogManager.GetLogger("WriteEventLogEntry");
logger.Log(LogLevel.Error, "Simple Test Message");
var eventLog = new EventLog(target.Log);
var entries = GetEventRecords(eventLog.Log).ToList();
var expectedProviderName = target.GetFixedSource();
var filtered = entries.Where(entry =>
entry.ProviderName == expectedProviderName &&
HasEntryType(entry, EventLogEntryType.Error)
);
Assert.Single(filtered);
var record = filtered.First();
Assert.Equal(eventId, record.Id);
Assert.Equal(category, record.Task);
}
[Fact]
public void LogEntryWithDynamicEventIdAndCategory()
{
var rnd = new Random();
int eventId = rnd.Next(1, short.MaxValue);
int category = rnd.Next(1, short.MaxValue);
var target = CreateEventLogTarget<EventLogTarget>(null, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000);
target.EventId = new SimpleLayout("${event-properties:EventId}");
target.Category = new SimpleLayout("${event-properties:Category}");
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
var logger = LogManager.GetLogger("WriteEventLogEntry");
LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, "TestLoggerName", "Simple Message");
theEvent.Properties["EventId"] = eventId;
theEvent.Properties["Category"] = category;
logger.Log(theEvent);
var eventLog = new EventLog(target.Log);
var entries = GetEventRecords(eventLog.Log).ToList();
var expectedProviderName = target.GetFixedSource();
var filtered = entries.Where(entry =>
entry.ProviderName == expectedProviderName &&
HasEntryType(entry, EventLogEntryType.Error)
);
Assert.Single(filtered);
var record = filtered.First();
Assert.Equal(eventId, record.Id);
Assert.Equal(category, record.Task);
}
private static IEnumerable<EventRecord> WriteWithMock(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType,
string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = 16384)
{
var target = CreateEventLogTarget<EventLogTargetMock>(entryType, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), overflowAction, maxMessageLength);
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
var logger = LogManager.GetLogger("WriteEventLogEntry");
logger.Log(logLevel, logMessage);
var entries = target.CapturedEvents;
var expectedSource = target.GetFixedSource();
var filteredEntries = entries.Where(entry =>
entry.ProviderName == expectedSource &&
HasEntryType(entry, expectedEventLogEntryType)
);
if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength)
{
Assert.False(filteredEntries.Any(),
$"No message is expected. But {filteredEntries.Count()} message(s) found entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'.");
}
else
{
Assert.True(filteredEntries.Any(),
$"Failed to find entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'");
}
return filteredEntries;
}
private class EventRecordMock : EventRecord
{
/// <summary>Initializes a new instance of the <see cref="T:System.Diagnostics.Eventing.Reader.EventRecord" /> class.</summary>
public EventRecordMock(int id, string logName, string providerName, EventLogEntryType type, string message, short category)
{
Id = id;
LogName = logName;
ProviderName = providerName;
if (type == EventLogEntryType.FailureAudit)
{
Keywords = (long)StandardEventKeywords.AuditFailure;
}
else if (type == EventLogEntryType.SuccessAudit)
{
Keywords = (long)StandardEventKeywords.AuditSuccess;
}
else
{
Keywords = (long)StandardEventKeywords.EventLogClassic;
if (type == EventLogEntryType.Error)
Level = (byte)StandardEventLevel.Error;
else if (type == EventLogEntryType.Warning)
Level = (byte)StandardEventLevel.Warning;
else if (type == EventLogEntryType.Information)
Level = (byte)StandardEventLevel.Informational;
}
var eventProperty = CreateEventProperty(message);
Properties = new List<EventProperty> { eventProperty };
}
/// <summary>
/// EventProperty ctor is internal
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private static EventProperty CreateEventProperty(string message)
{
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
CultureInfo culture = null; // use InvariantCulture or other if you prefer
object instantiatedType =
Activator.CreateInstance(typeof(EventProperty), flags, null, new object[] { message }, culture);
return (EventProperty)instantiatedType;
}
#region Overrides of EventRecord
/// <summary>Gets the event message in the current locale.</summary>
/// <returns>Returns a string that contains the event message in the current locale.</returns>
public override string FormatDescription()
{
throw new NotImplementedException();
}
/// <summary>Gets the event message, replacing variables in the message with the specified values.</summary>
/// <returns>Returns a string that contains the event message in the current locale.</returns>
/// <param name="values">The values used to replace variables in the event message. Variables are represented by %n, where n is a number.</param>
public override string FormatDescription(IEnumerable<object> values)
{
throw new NotImplementedException();
}
/// <summary>Gets the XML representation of the event. All of the event properties are represented in the event XML. The XML conforms to the event schema.</summary>
/// <returns>Returns a string that contains the XML representation of the event.</returns>
public override string ToXml()
{
throw new NotImplementedException();
}
/// <summary>Gets the identifier for this event. All events with this identifier value represent the same type of event.</summary>
/// <returns>Returns an integer value. This value can be null.</returns>
public override int Id { get; }
/// <summary>Gets the version number for the event.</summary>
/// <returns>Returns a byte value. This value can be null.</returns>
public override byte? Version { get; }
/// <summary>Gets the level of the event. The level signifies the severity of the event. For the name of the level, get the value of the <see cref="P:System.Diagnostics.Eventing.Reader.EventRecord.LevelDisplayName" /> property.</summary>
/// <returns>Returns a byte value. This value can be null.</returns>
public override byte? Level { get; }
/// <summary>Gets a task identifier for a portion of an application or a component that publishes an event. A task is a 16-bit value with 16 top values reserved. This type allows any value between 0x0000 and 0xffef to be used. To obtain the task name, get the value of the <see cref="P:System.Diagnostics.Eventing.Reader.EventRecord.TaskDisplayName" /> property.</summary>
/// <returns>Returns an integer value. This value can be null.</returns>
public override int? Task { get; }
/// <summary>Gets the opcode of the event. The opcode defines a numeric value that identifies the activity or a point within an activity that the application was performing when it raised the event. For the name of the opcode, get the value of the <see cref="P:System.Diagnostics.Eventing.Reader.EventRecord.OpcodeDisplayName" /> property.</summary>
/// <returns>Returns a short value. This value can be null.</returns>
public override short? Opcode { get; }
/// <summary>Gets the keyword mask of the event. Get the value of the <see cref="P:System.Diagnostics.Eventing.Reader.EventRecord.KeywordsDisplayNames" /> property to get the name of the keywords used in this mask.</summary>
/// <returns>Returns a long value. This value can be null.</returns>
public override long? Keywords { get; }
/// <summary>Gets the event record identifier of the event in the log.</summary>
/// <returns>Returns a long value. This value can be null.</returns>
public override long? RecordId { get; }
/// <summary>Gets the name of the event provider that published this event.</summary>
/// <returns>Returns a string that contains the name of the event provider that published this event.</returns>
public override string ProviderName { get; }
/// <summary>Gets the globally unique identifier (GUID) of the event provider that published this event.</summary>
/// <returns>Returns a GUID value. This value can be null.</returns>
public override Guid? ProviderId { get; }
/// <summary>Gets the name of the event log where this event is logged.</summary>
/// <returns>Returns a string that contains a name of the event log that contains this event.</returns>
public override string LogName { get; }
/// <summary>Gets the process identifier for the event provider that logged this event.</summary>
/// <returns>Returns an integer value. This value can be null.</returns>
public override int? ProcessId { get; }
/// <summary>Gets the thread identifier for the thread that the event provider is running in.</summary>
/// <returns>Returns an integer value. This value can be null.</returns>
public override int? ThreadId { get; }
/// <summary>Gets the name of the computer on which this event was logged.</summary>
/// <returns>Returns a string that contains the name of the computer on which this event was logged.</returns>
public override string MachineName { get; }
/// <summary>Gets the security descriptor of the user whose context is used to publish the event.</summary>
/// <returns>Returns a <see cref="T:System.Security.Principal.SecurityIdentifier" /> value.</returns>
public override SecurityIdentifier UserId { get; }
/// <summary>Gets the time, in <see cref="T:System.DateTime" /> format, that the event was created.</summary>
/// <returns>Returns a <see cref="T:System.DateTime" /> value. The value can be null.</returns>
public override DateTime? TimeCreated { get; }
/// <summary>Gets the globally unique identifier (GUID) for the activity in process for which the event is involved. This allows consumers to group related activities.</summary>
/// <returns>Returns a GUID value.</returns>
public override Guid? ActivityId { get; }
/// <summary>Gets a globally unique identifier (GUID) for a related activity in a process for which an event is involved.</summary>
/// <returns>Returns a GUID value. This value can be null.</returns>
public override Guid? RelatedActivityId { get; }
/// <summary>Gets qualifier numbers that are used for event identification.</summary>
/// <returns>Returns an integer value. This value can be null.</returns>
public override int? Qualifiers { get; }
/// <summary>Gets the display name of the level for this event.</summary>
/// <returns>Returns a string that contains the display name of the level for this event.</returns>
public override string LevelDisplayName { get; }
/// <summary>Gets the display name of the opcode for this event.</summary>
/// <returns>Returns a string that contains the display name of the opcode for this event.</returns>
public override string OpcodeDisplayName { get; }
/// <summary>Gets the display name of the task for the event.</summary>
/// <returns>Returns a string that contains the display name of the task for the event.</returns>
public override string TaskDisplayName { get; }
/// <summary>Gets the display names of the keywords used in the keyword mask for this event. </summary>
/// <returns>Returns an enumerable collection of strings that contain the display names of the keywords used in the keyword mask for this event.</returns>
public override IEnumerable<string> KeywordsDisplayNames { get; }
/// <summary>Gets a placeholder (bookmark) that corresponds to this event. This can be used as a placeholder in a stream of events.</summary>
/// <returns>Returns a <see cref="T:System.Diagnostics.Eventing.Reader.EventBookmark" /> object.</returns>
public override EventBookmark Bookmark { get; }
/// <summary>Gets the user-supplied properties of the event.</summary>
/// <returns>Returns a list of <see cref="T:System.Diagnostics.Eventing.Reader.EventProperty" /> objects.</returns>
public override IList<EventProperty> Properties { get; }
#endregion
}
private class EventLogTargetMock : EventLogTarget
{
public List<EventRecordMock> CapturedEvents { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTargetMock()
{
CapturedEvents = new List<EventRecordMock>();
}
#region Overrides of EventLogTarget
internal override void WriteEntry(LogEventInfo logEventInfo, string message, EventLogEntryType entryType, int eventId, short category)
{
var source = RenderSource(logEventInfo);
CapturedEvents.Add(new EventRecordMock(eventId, this.Log, source, entryType, message, category));
}
#endregion
}
private void AssertWrittenMessage(IEnumerable<EventRecord> eventLogs, string expectedMessage)
{
var messages = eventLogs.Where(entry => entry.Properties.Any(prop => Convert.ToString(prop.Value) == expectedMessage));
Assert.True(messages.Any(), $"Event records has not the expected message: '{expectedMessage}'");
}
private static TEventLogTarget CreateEventLogTarget<TEventLogTarget>(Layout entryType, string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength)
where TEventLogTarget : EventLogTarget, new()
{
var target = new TEventLogTarget();
//The Log to write to is intentionally lower case!!
target.Log = "application";
// set the source explicitly to prevent random AppDomain name being used as the source name
target.Source = sourceName;
//Be able to check message length and content, the Layout is intentionally only ${message}.
target.Layout = new SimpleLayout("${message}");
if (entryType != null)
{
//set only when not default
target.EntryType = entryType;
}
target.OnOverflow = overflowAction;
target.MaxMessageLength = maxMessageLength;
return target;
}
private LogEventInfo CreateLogEventWithDynamicSource(string message, LogLevel level, string propertyKey, string proertyValue)
{
var logEvent = new LogEventInfo();
logEvent.Message = message;
logEvent.Level = level;
logEvent.Properties[propertyKey] = proertyValue;
return logEvent;
}
private static IEnumerable<EventRecord> GetEventRecords(string logName)
{
var query = new EventLogQuery(logName, PathType.LogName) { ReverseDirection = true };
using (var reader = new EventLogReader(query))
for (var eventInstance = reader.ReadEvent(); eventInstance != null; eventInstance = reader.ReadEvent())
yield return eventInstance;
}
private static bool HasEntryType(EventRecord eventRecord, EventLogEntryType entryType)
{
var keywords = (StandardEventKeywords)(eventRecord.Keywords ?? 0);
var level = (StandardEventLevel)(eventRecord.Level ?? 0);
bool isClassicEvent = keywords.HasFlag(StandardEventKeywords.EventLogClassic);
switch (entryType)
{
case EventLogEntryType.Error:
return isClassicEvent && level == StandardEventLevel.Error;
case EventLogEntryType.Warning:
return isClassicEvent && level == StandardEventLevel.Warning;
case EventLogEntryType.Information:
return isClassicEvent && level == StandardEventLevel.Informational;
case EventLogEntryType.SuccessAudit:
return keywords.HasFlag(StandardEventKeywords.AuditSuccess);
case EventLogEntryType.FailureAudit:
return keywords.HasFlag(StandardEventKeywords.AuditFailure);
}
return false;
}
}
}
#endif
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace fyiReporting.RDL
{
///<summary>
/// TableRow represents a Row in a table. This can be part of a header, footer, or detail definition.
///</summary>
[Serializable]
internal class TableRow : ReportLink
{
TableCells _TableCells; // Contents of the row. One cell per column
RSize _Height; // Height of the row
Visibility _Visibility; // Indicates if the row should be hidden
bool _CanGrow; // indicates that row height can increase in size
List<Textbox> _GrowList; // list of TextBox's that need to be checked for growth
internal TableRow(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_TableCells=null;
_Height=null;
_Visibility=null;
_CanGrow = false;
_GrowList = null;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "TableCells":
_TableCells = new TableCells(r, this, xNodeLoop);
break;
case "Height":
_Height = new RSize(r, xNodeLoop);
break;
case "Visibility":
_Visibility = new Visibility(r, this, xNodeLoop);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown TableRow element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_TableCells == null)
OwnerReport.rl.LogError(8, "TableRow requires the TableCells element.");
if (_Height == null)
OwnerReport.rl.LogError(8, "TableRow requires the Height element.");
}
override internal void FinalPass()
{
_TableCells.FinalPass();
if (_Visibility != null)
_Visibility.FinalPass();
foreach (TableCell tc in _TableCells.Items)
{
ReportItem ri = tc.ReportItems.Items[0] as ReportItem;
if (!(ri is Textbox))
continue;
Textbox tb = ri as Textbox;
if (tb.CanGrow)
{
if (this._GrowList == null)
_GrowList = new List<Textbox>();
_GrowList.Add(tb);
_CanGrow = true;
}
}
if (_CanGrow) // shrink down the resulting list
_GrowList.TrimExcess();
return;
}
internal void Run(IPresent ip, Row row)
{
if (this.Visibility != null && Visibility.IsHidden(ip.Report(), row))
return;
ip.TableRowStart(this, row);
_TableCells.Run(ip, row);
ip.TableRowEnd(this, row);
return ;
}
internal void RunPage(Pages pgs, Row row)
{
if (this.Visibility != null && Visibility.IsHidden(pgs.Report, row))
return;
_TableCells.RunPage(pgs, row);
WorkClass wc = GetWC(pgs.Report);
pgs.CurrentPage.YOffset += wc.CalcHeight;
return ;
}
internal TableCells TableCells
{
get { return _TableCells; }
set { _TableCells = value; }
}
internal RSize Height
{
get { return _Height; }
set { _Height = value; }
}
internal float HeightOfRow(Pages pgs, Row r)
{
return HeightOfRow(pgs.Report, pgs.G, r);
}
internal float HeightOfRow(Report rpt, System.Drawing.Graphics g, Row r)
{
WorkClass wc = GetWC(rpt);
if (this.Visibility != null && Visibility.IsHidden(rpt, r))
{
wc.CalcHeight = 0;
return 0;
}
float defnHeight = _Height.Points;
if (!_CanGrow)
{
wc.CalcHeight = defnHeight;
return defnHeight;
}
TableColumns tcs= this.Table.TableColumns;
float height=0;
foreach (Textbox tb in this._GrowList)
{
int ci = tb.TC.ColIndex;
if (tcs[ci].IsHidden(rpt, r)) // if column is hidden don't use in calculation
continue;
height = Math.Max(height, tb.RunTextCalcHeight(rpt, g, r));
}
wc.CalcHeight = Math.Max(height, defnHeight);
return wc.CalcHeight;
}
internal float HeightCalc(Report rpt)
{
WorkClass wc = GetWC(rpt);
return wc.CalcHeight;
}
private Table Table
{
get
{
ReportLink p= this.Parent;
while (p != null)
{
if (p is Table)
return p as Table;
p = p.Parent;
}
throw new Exception("Internal error: TableRow not related to a Table");
}
}
internal Visibility Visibility
{
get { return _Visibility; }
set { _Visibility = value; }
}
internal bool CanGrow
{
get { return _CanGrow; }
}
internal List<Textbox> GrowList
{
get { return _GrowList; }
}
private WorkClass GetWC(Report rpt)
{
WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass;
if (wc == null)
{
wc = new WorkClass(this);
rpt.Cache.Add(this, "wc", wc);
}
return wc;
}
private void RemoveWC(Report rpt)
{
rpt.Cache.Remove(this, "wc");
}
class WorkClass
{
internal float CalcHeight; // dynamic when CanGrow true
internal WorkClass(TableRow tr)
{
CalcHeight = tr.Height.Points;
}
}
}
}
| |
using LibCSV.Dialects;
using LibCSV.Exceptions;
using NUnit.Framework;
using System.IO;
using static NUnit.Framework.Assert;
namespace LibCSV.Tests
{
[TestFixture]
public class AdapterTests
{
[Test]
public void ReadAll_ExistingFileName_ReturnsRecords()
{
var filename = Path.Combine(TestContext.CurrentContext.TestDirectory, "test.csv");
var transformer = new NullTransformerForAdapterTesting
(
new [] { "Header#1", "Header#2", "Header#3" },
new []
{
new [] {"1", "2", "3"},
new [] {"4", "5", "6"}
}
);
using (var dialect = new Dialect
{
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = true
})
{
using (var adapter = new CSVAdapter(dialect, filename, "utf-8"))
{
adapter.ReadAll(transformer);
}
}
}
[Test]
public void ReadAll_ExistingStream_ReturnsRecords()
{
const string input = "Header#1;Header#2;Header#3\r\n1;2;3\r\n4;5;6";
var transformer = new NullTransformerForAdapterTesting
(
new [] { "Header#1", "Header#2", "Header#3" },
new []
{
new[] {"1", "2", "3"},
new[] {"4", "5", "6"}
}
);
using (var dialect = new Dialect
{
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = true
})
{
using (var adapter = new CSVAdapter(dialect, new StringReader(input)))
{
adapter.ReadAll(transformer);
}
}
}
[Test]
public void ReadAll_WithoutHeaders_ReturnRecords()
{
const string input = "1;2;3\r\n4;5;6";
var transformer = new NullTransformerForAdapterTesting
(
expectedAliases: null,
expectedResults: new[]
{
new[] {"1", "2", "3"},
new[] {"4", "5", "6"}
}
);
using (var dialect = new Dialect
{
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = false
})
{
using (var adapter = new CSVAdapter(dialect, new StringReader(input)))
{
adapter.ReadAll(transformer);
}
}
}
[Test]
public void WriteAll_WithoutHeaders_WroteRecords()
{
var data = new[]
{
new[] {"1", "2", "3"},
new[] {"4", "5", "6"}
};
var transformer = new NullTransformerForAdapterTesting(null, data);
using (var dialect = new Dialect
{
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = false
})
{
using (var adapter = new CSVAdapter(dialect, new StringWriter()))
{
adapter.WriteAll(data, transformer);
}
}
}
[Test]
public void WriteAll_WithHeader_WroteRecords()
{
var headers = new [] { "Header#1", "Header#2", "Header#3" };
var data = new []
{
new [] {"1", "2", "3"},
new [] {"4", "5", "6"}
};
var transformer = new NullTransformerForAdapterTesting(headers, data);
using (var dialect = new Dialect
{
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = true
})
{
using (var adapter = new CSVAdapter(dialect, new StringWriter(), headers))
{
adapter.WriteAll(data, transformer);
}
}
}
[Test]
public void Adapter_HeaderIsNull_ThrowsException()
{
Throws<HeaderIsNullException>(() =>
{
var transformer = new NullTransformerForAdapterTesting(new string[] { }, new string[] { });
using (var dialect = new Dialect {
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = true
})
{
using (var adapter = new CSVAdapter(dialect, new StringWriter(), null))
{
}
}
});
}
[Test]
public void WriteAll_DataTransformerIsNull_ThrowsException()
{
Throws<DataTransformerIsNullException>(() =>
{
var headers = new [] { "Header#1", "Header#2", "Header#3" };
var data = new []
{
new [] {"1", "2", "3"},
new [] {"4", "5", "6"}
};
using (var dialect = new Dialect
{
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = false
})
{
using (var adapter = new CSVAdapter(dialect, new StringWriter(), headers))
{
adapter.WriteAll(data, null);
}
}
});
}
[Test]
public void WriteAll_NotEqualCellCountInRows_ThrowsException()
{
Throws<NotEqualCellCountInRowsException>(() =>
{
var headers = new [] { "Header#1", "Header#2", "Header#3" };
var data = new []
{
new [] {"1", "2", "3"},
new [] {"4", "5"}
};
var transformer = new NullTransformerForAdapterTesting(headers, data);
using (var dialect = new Dialect {
DoubleQuote = true,
Delimiter = ';',
Quote = '"',
Escape = '\\',
SkipInitialSpace = true,
LineTerminator = "\n\r",
Quoting = QuoteStyle.QuoteNone,
Strict = true,
HasHeader = false
})
{
using (var adapter = new CSVAdapter(dialect, new StringWriter(), null))
{
adapter.WriteAll(data, transformer);
}
}
});
}
}
}
| |
using System;
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Support;
/*
* 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 Lucene.Net.Util;
using NUnit.Framework;
using System.Runtime.CompilerServices;
using Codec = Lucene.Net.Codecs.Codec;
// NOTE: this test will fail w/ PreFlexRW codec! (Because
// this test uses full binary term space, but PreFlex cannot
// handle this since it requires the terms are UTF8 bytes).
//
// Also, SimpleText codec will consume very large amounts of
// disk (but, should run successfully). Best to run w/
// -Dtests.codec=Standard, and w/ plenty of RAM, eg:
//
// ant test -Dtest.slow=true -Dtests.heapsize=8g
//
// java -server -Xmx8g -d64 -cp .:lib/junit-4.10.jar:./build/classes/test:./build/classes/test-framework:./build/classes/java -Dlucene.version=4.0-dev -Dtests.directory=MMapDirectory -DtempDir=build -ea org.junit.runner.JUnitCore Lucene.Net.Index.Test2BTerms
//
[Ignore]
[TestFixture]
public class Test2BTerms : LuceneTestCase
{
private const int TOKEN_LEN = 5;
private static readonly BytesRef Bytes = new BytesRef(TOKEN_LEN);
private sealed class MyTokenStream : TokenStream
{
internal readonly int TokensPerDoc;
internal int TokenCount;
public readonly IList<BytesRef> SavedTerms = new List<BytesRef>();
internal int NextSave;
internal long TermCounter;
internal readonly Random Random;
public MyTokenStream(Random random, int tokensPerDoc)
: base(new MyAttributeFactory(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY))
{
this.TokensPerDoc = tokensPerDoc;
AddAttribute<ITermToBytesRefAttribute>();
Bytes.Length = TOKEN_LEN;
this.Random = random;
NextSave = TestUtil.NextInt(random, 500000, 1000000);
}
public override bool IncrementToken()
{
ClearAttributes();
if (TokenCount >= TokensPerDoc)
{
return false;
}
int shift = 32;
for (int i = 0; i < 5; i++)
{
Bytes.Bytes[i] = unchecked((byte)((TermCounter >> shift) & 0xFF));
shift -= 8;
}
TermCounter++;
TokenCount++;
if (--NextSave == 0)
{
SavedTerms.Add(BytesRef.DeepCopyOf(Bytes));
Console.WriteLine("TEST: save term=" + Bytes);
NextSave = TestUtil.NextInt(Random, 500000, 1000000);
}
return true;
}
public override void Reset()
{
TokenCount = 0;
}
private sealed class MyTermAttributeImpl : Attribute, ITermToBytesRefAttribute
{
public void FillBytesRef()
{
// no-op: the bytes was already filled by our owner's incrementToken
}
public BytesRef BytesRef
{
get
{
return Bytes;
}
}
public override void Clear()
{
}
public override bool Equals(object other)
{
return other == this;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
public override void CopyTo(Attribute target)
{
}
public override object Clone()
{
throw new System.NotSupportedException();
}
}
private sealed class MyAttributeFactory : AttributeFactory
{
internal readonly AttributeFactory @delegate;
public MyAttributeFactory(AttributeFactory @delegate)
{
this.@delegate = @delegate;
}
public override Attribute CreateAttributeInstance<T>()
{
var attClass = typeof(T);
if (attClass == typeof(ITermToBytesRefAttribute))
{
return new MyTermAttributeImpl();
}
if (attClass.IsSubclassOf(typeof(CharTermAttribute)))
{
throw new System.ArgumentException("no");
}
return @delegate.CreateAttributeInstance<T>();
}
}
}
//ORIGINAL LINE: @Ignore("Very slow. Enable manually by removing @Ignore.") public void test2BTerms() throws java.io.IOException
[Ignore]
[Test]
public virtual void Test2BTerms_Mem([ValueSource(typeof(ConcurrentMergeSchedulers), "Values")]IConcurrentMergeScheduler scheduler)
{
if ("Lucene3x".Equals(Codec.Default.Name))
{
throw new Exception("this test cannot run with PreFlex codec");
}
Console.WriteLine("Starting Test2B");
long TERM_COUNT = ((long)int.MaxValue) + 100000000;
int TERMS_PER_DOC = TestUtil.NextInt(Random(), 100000, 1000000);
IList<BytesRef> savedTerms = null;
BaseDirectoryWrapper dir = NewFSDirectory(CreateTempDir("2BTerms"));
//MockDirectoryWrapper dir = NewFSDirectory(new File("/p/lucene/indices/2bindex"));
if (dir is MockDirectoryWrapper)
{
((MockDirectoryWrapper)dir).Throttling = MockDirectoryWrapper.Throttling_e.NEVER;
}
dir.CheckIndexOnClose = false; // don't double-checkindex
if (true)
{
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH)
.SetRAMBufferSizeMB(256.0)
.SetMergeScheduler(scheduler)
.SetMergePolicy(NewLogMergePolicy(false, 10))
.SetOpenMode(IndexWriterConfig.OpenMode_e.CREATE));
MergePolicy mp = w.Config.MergePolicy;
if (mp is LogByteSizeMergePolicy)
{
// 1 petabyte:
((LogByteSizeMergePolicy)mp).MaxMergeMB = 1024 * 1024 * 1024;
}
Documents.Document doc = new Documents.Document();
MyTokenStream ts = new MyTokenStream(Random(), TERMS_PER_DOC);
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.IndexOptions = FieldInfo.IndexOptions.DOCS_ONLY;
customType.OmitNorms = true;
Field field = new Field("field", ts, customType);
doc.Add(field);
//w.setInfoStream(System.out);
int numDocs = (int)(TERM_COUNT / TERMS_PER_DOC);
Console.WriteLine("TERMS_PER_DOC=" + TERMS_PER_DOC);
Console.WriteLine("numDocs=" + numDocs);
for (int i = 0; i < numDocs; i++)
{
long t0 = Environment.TickCount;
w.AddDocument(doc);
Console.WriteLine(i + " of " + numDocs + " " + (Environment.TickCount - t0) + " msec");
}
savedTerms = ts.SavedTerms;
Console.WriteLine("TEST: full merge");
w.ForceMerge(1);
Console.WriteLine("TEST: close writer");
w.Dispose();
}
Console.WriteLine("TEST: open reader");
IndexReader r = DirectoryReader.Open(dir);
if (savedTerms == null)
{
savedTerms = FindTerms(r);
}
int numSavedTerms = savedTerms.Count;
IList<BytesRef> bigOrdTerms = new List<BytesRef>(savedTerms.SubList(numSavedTerms - 10, numSavedTerms));
Console.WriteLine("TEST: test big ord terms...");
TestSavedTerms(r, bigOrdTerms);
Console.WriteLine("TEST: test all saved terms...");
TestSavedTerms(r, savedTerms);
r.Dispose();
Console.WriteLine("TEST: now CheckIndex...");
CheckIndex.Status status = TestUtil.CheckIndex(dir);
long tc = status.SegmentInfos[0].TermIndexStatus.TermCount;
Assert.IsTrue(tc > int.MaxValue, "count " + tc + " is not > " + int.MaxValue);
dir.Dispose();
Console.WriteLine("TEST: done!");
}
private IList<BytesRef> FindTerms(IndexReader r)
{
Console.WriteLine("TEST: findTerms");
TermsEnum termsEnum = MultiFields.GetTerms(r, "field").Iterator(null);
IList<BytesRef> savedTerms = new List<BytesRef>();
int nextSave = TestUtil.NextInt(Random(), 500000, 1000000);
BytesRef term;
while ((term = termsEnum.Next()) != null)
{
if (--nextSave == 0)
{
savedTerms.Add(BytesRef.DeepCopyOf(term));
Console.WriteLine("TEST: add " + term);
nextSave = TestUtil.NextInt(Random(), 500000, 1000000);
}
}
return savedTerms;
}
private void TestSavedTerms(IndexReader r, IList<BytesRef> terms)
{
Console.WriteLine("TEST: run " + terms.Count + " terms on reader=" + r);
IndexSearcher s = NewSearcher(r);
terms = CollectionsHelper.Shuffle(terms);
TermsEnum termsEnum = MultiFields.GetTerms(r, "field").Iterator(null);
bool failed = false;
for (int iter = 0; iter < 10 * terms.Count; iter++)
{
BytesRef term = terms[Random().Next(terms.Count)];
Console.WriteLine("TEST: search " + term);
long t0 = Environment.TickCount;
int count = s.Search(new TermQuery(new Term("field", term)), 1).TotalHits;
if (count <= 0)
{
Console.WriteLine(" FAILED: count=" + count);
failed = true;
}
long t1 = Environment.TickCount;
Console.WriteLine(" took " + (t1 - t0) + " millis");
TermsEnum.SeekStatus result = termsEnum.SeekCeil(term);
if (result != TermsEnum.SeekStatus.FOUND)
{
if (result == TermsEnum.SeekStatus.END)
{
Console.WriteLine(" FAILED: got END");
}
else
{
Console.WriteLine(" FAILED: wrong term: got " + termsEnum.Term());
}
failed = true;
}
}
Assert.IsFalse(failed);
}
}
}
| |
// 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.IO;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using Internal.Reflection.Core;
using Internal.Runtime.TypeLoader;
using Internal.Metadata.NativeFormat;
namespace Internal.Reflection.Execution
{
//=============================================================================================================================
// The assembly resolution policy for Project N's emulation of "classic reflection."
//
// The policy is very simple: the only assemblies that can be "loaded" are those that are statically linked into the running
// native process. There is no support for probing for assemblies in directories, user-supplied files, GACs, NICs or any
// other repository.
//=============================================================================================================================
public sealed partial class AssemblyBinderImplementation : AssemblyBinder
{
private AssemblyBinderImplementation()
{
_scopeGroups = new KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[0];
ModuleList.AddModuleRegistrationCallback(RegisterModule);
}
public static AssemblyBinderImplementation Instance { get; } = new AssemblyBinderImplementation();
partial void BindEcmaByteArray(byte[] rawAssembly, byte[] rawSymbolStore, ref AssemblyBindResult bindResult, ref Exception exception, ref bool? result);
partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, ref AssemblyBindResult result, ref Exception exception, ref bool resultBoolean);
partial void InsertEcmaLoadedAssemblies(List<AssemblyBindResult> loadedAssemblies);
public sealed override bool Bind(byte[] rawAssembly, byte[] rawSymbolStore, out AssemblyBindResult bindResult, out Exception exception)
{
bool? result = null;
exception = null;
bindResult = default(AssemblyBindResult);
BindEcmaByteArray(rawAssembly, rawSymbolStore, ref bindResult, ref exception, ref result);
// If the Ecma assembly binder isn't linked in, simply throw PlatformNotSupportedException
if (!result.HasValue)
throw new PlatformNotSupportedException();
else
return result.Value;
}
public sealed override bool Bind(RuntimeAssemblyName refName, out AssemblyBindResult result, out Exception exception)
{
bool foundMatch = false;
result = default(AssemblyBindResult);
exception = null;
refName = refName.CanonicalizePublicKeyToken();
// At least one real-world app calls Type.GetType() for "char" using the assembly name "mscorlib". To accomodate this,
// we will adopt the desktop CLR rule that anything named "mscorlib" automatically binds to the core assembly.
bool useMscorlibNameCompareFunc = false;
RuntimeAssemblyName compareRefName = refName;
if (refName.Name == "mscorlib")
{
useMscorlibNameCompareFunc = true;
compareRefName = AssemblyNameParser.Parse(AssemblyBinder.DefaultAssemblyNameForGetType);
}
foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> group in ScopeGroups)
{
bool nameMatches;
if (useMscorlibNameCompareFunc)
{
nameMatches = MscorlibAssemblyNameMatches(compareRefName, group.Key);
}
else
{
nameMatches = AssemblyNameMatches(refName, group.Key);
}
if (nameMatches)
{
if (foundMatch)
{
exception = new AmbiguousMatchException();
return false;
}
foundMatch = true;
ScopeDefinitionGroup scopeDefinitionGroup = group.Value;
result.Reader = scopeDefinitionGroup.CanonicalScope.Reader;
result.ScopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle;
result.OverflowScopes = scopeDefinitionGroup.OverflowScopes;
}
}
BindEcmaAssemblyName(refName, ref result, ref exception, ref foundMatch);
if (exception != null)
return false;
if (!foundMatch)
{
exception = new IOException(SR.Format(SR.FileNotFound_AssemblyNotFound, refName.FullName));
return false;
}
return true;
}
public sealed override IList<AssemblyBindResult> GetLoadedAssemblies()
{
List<AssemblyBindResult> loadedAssemblies = new List<AssemblyBindResult>(ScopeGroups.Length);
foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> group in ScopeGroups)
{
ScopeDefinitionGroup scopeDefinitionGroup = group.Value;
AssemblyBindResult result = default(AssemblyBindResult);
result.Reader = scopeDefinitionGroup.CanonicalScope.Reader;
result.ScopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle;
result.OverflowScopes = scopeDefinitionGroup.OverflowScopes;
loadedAssemblies.Add(result);
}
InsertEcmaLoadedAssemblies(loadedAssemblies);
return loadedAssemblies;
}
//
// Name match routine for mscorlib references
//
private bool MscorlibAssemblyNameMatches(RuntimeAssemblyName coreAssemblyName, RuntimeAssemblyName defName)
{
//
// The defName came from trusted metadata so it should be fully specified.
//
Debug.Assert(defName.Version != null);
Debug.Assert(defName.CultureName != null);
Debug.Assert((coreAssemblyName.Flags & AssemblyNameFlags.PublicKey) == 0);
Debug.Assert((defName.Flags & AssemblyNameFlags.PublicKey) == 0);
if (defName.Name != coreAssemblyName.Name)
return false;
byte[] defPkt = defName.PublicKeyOrToken;
if (defPkt == null)
return false;
if (!ArePktsEqual(defPkt, coreAssemblyName.PublicKeyOrToken))
return false;
return true;
}
//
// Encapsulates the assembly ref->def matching policy.
//
private bool AssemblyNameMatches(RuntimeAssemblyName refName, RuntimeAssemblyName defName)
{
//
// The defName came from trusted metadata so it should be fully specified.
//
Debug.Assert(defName.Version != null);
Debug.Assert(defName.CultureName != null);
Debug.Assert((defName.Flags & AssemblyNameFlags.PublicKey) == 0);
Debug.Assert((refName.Flags & AssemblyNameFlags.PublicKey) == 0);
if (!(refName.Name.Equals(defName.Name, StringComparison.OrdinalIgnoreCase)))
return false;
if (refName.Version != null)
{
int compareResult = refName.Version.CompareTo(defName.Version);
if (compareResult > 0)
return false;
}
if (refName.CultureName != null)
{
if (!(refName.CultureName.Equals(defName.CultureName)))
return false;
}
AssemblyNameFlags materialRefNameFlags = refName.Flags.ExtractAssemblyNameFlags();
AssemblyNameFlags materialDefNameFlags = defName.Flags.ExtractAssemblyNameFlags();
if (materialRefNameFlags != materialDefNameFlags)
{
return false;
}
byte[] refPublicKeyToken = refName.PublicKeyOrToken;
if (refPublicKeyToken != null)
{
byte[] defPublicKeyToken = defName.PublicKeyOrToken;
if (defPublicKeyToken == null)
return false;
if (!ArePktsEqual(refPublicKeyToken, defPublicKeyToken))
return false;
}
return true;
}
/// <summary>
/// This callback gets called whenever a module gets registered. It adds the metadata reader
/// for the new module to the available scopes. The lock in ExecutionEnvironmentImplementation ensures
/// that this function may never be called concurrently so that we can assume that two threads
/// never update the reader and scope list at the same time.
/// </summary>
/// <param name="moduleInfo">Module to register</param>
private void RegisterModule(ModuleInfo moduleInfo)
{
NativeFormatModuleInfo nativeFormatModuleInfo = moduleInfo as NativeFormatModuleInfo;
if (nativeFormatModuleInfo == null)
{
return;
}
LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup> scopeGroups = new LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup>();
foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> oldGroup in _scopeGroups)
{
scopeGroups.Add(oldGroup.Key, oldGroup.Value);
}
AddScopesFromReaderToGroups(scopeGroups, nativeFormatModuleInfo.MetadataReader);
// Update reader and scope list
KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] scopeGroupsArray = new KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[scopeGroups.Count];
int i = 0;
foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> data in scopeGroups)
{
scopeGroupsArray[i] = data;
i++;
}
_scopeGroups = scopeGroupsArray;
}
private KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] ScopeGroups
{
get
{
return _scopeGroups;
}
}
private void AddScopesFromReaderToGroups(LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup> groups, MetadataReader reader)
{
foreach (ScopeDefinitionHandle scopeDefinitionHandle in reader.ScopeDefinitions)
{
RuntimeAssemblyName defName = scopeDefinitionHandle.ToRuntimeAssemblyName(reader).CanonicalizePublicKeyToken();
ScopeDefinitionGroup scopeDefinitionGroup;
if (groups.TryGetValue(defName, out scopeDefinitionGroup))
{
scopeDefinitionGroup.AddOverflowScope(new QScopeDefinition(reader, scopeDefinitionHandle));
}
else
{
scopeDefinitionGroup = new ScopeDefinitionGroup(new QScopeDefinition(reader, scopeDefinitionHandle));
groups.Add(defName, scopeDefinitionGroup);
}
}
}
private static bool ArePktsEqual(byte[] pkt1, byte[] pkt2)
{
if (pkt1.Length != pkt2.Length)
return false;
for (int i = 0; i < pkt1.Length; i++)
{
if (pkt1[i] != pkt2[i])
return false;
}
return true;
}
private volatile KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] _scopeGroups;
private class ScopeDefinitionGroup
{
public ScopeDefinitionGroup(QScopeDefinition canonicalScope)
{
_canonicalScope = canonicalScope;
}
public QScopeDefinition CanonicalScope { get { return _canonicalScope; } }
public IEnumerable<QScopeDefinition> OverflowScopes
{
get
{
return _overflowScopes.ToArray();
}
}
public void AddOverflowScope(QScopeDefinition overflowScope)
{
_overflowScopes.Add(overflowScope);
}
private readonly QScopeDefinition _canonicalScope;
private ArrayBuilder<QScopeDefinition> _overflowScopes;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_Layanan_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefLayanan";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["LayananManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddLayanan");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
GetListJenisLayanan();
GetListPoliklinik();
GetListKelompokLayanan();
UpdateDataView(true);
}
}
public void GetListKelompokLayanan()
{
string KelompokLayananId = "";
SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan();
DataTable dt = myObj.GetList();
cmbKelompokLayanan.Items.Clear();
int i = 0;
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = "";
cmbKelompokLayanan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = dr["Kode"].ToString() + ". " + dr["Nama"].ToString();
cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelompokLayananId)
cmbKelompokLayanan.SelectedIndex = i;
i++;
}
}
public void GetListJenisLayanan()
{
string JenisLayananId = "";
SIMRS.DataAccess.RS_JenisLayanan myObj = new SIMRS.DataAccess.RS_JenisLayanan();
DataTable dt = myObj.GetList();
cmbJenisLayanan.Items.Clear();
int i = 0;
cmbJenisLayanan.Items.Add("");
cmbJenisLayanan.Items[i].Text = "";
cmbJenisLayanan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbJenisLayanan.Items.Add("");
cmbJenisLayanan.Items[i].Text = dr["Kode"].ToString() + ". " + dr["Nama"].ToString();
cmbJenisLayanan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisLayananId)
cmbJenisLayanan.SelectedIndex = i;
i++;
}
}
public void GetListPoliklinik()
{
string PoliklinikId = "";
SIMRS.DataAccess.RS_Poliklinik myObj = new SIMRS.DataAccess.RS_Poliklinik();
DataTable dt = myObj.GetList();
cmbPoliklinik.Items.Clear();
int i = 0;
cmbPoliklinik.Items.Add("");
cmbPoliklinik.Items[i].Text = "";
cmbPoliklinik.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPoliklinik.Items.Add("");
cmbPoliklinik.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString() + " (" + dr["KelompokPoliklinikNama"].ToString() + ")";
cmbPoliklinik.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PoliklinikId)
cmbPoliklinik.SelectedIndex = i;
i++;
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan();
DataTable myData = myObj.SelectAll();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
string filter = "";
if (cmbJenisLayanan.SelectedIndex >0 )
filter = " JenisLayananId = " + cmbJenisLayanan.SelectedItem.Value;
if (cmbPoliklinik.SelectedIndex > 0)
{
filter += filter != "" ? " AND ":"";
filter += " PoliklinikId = " + cmbPoliklinik.SelectedItem.Value;
}
if (cmbKelompokLayanan.SelectedIndex > 0)
{
filter += filter != "" ? " AND " : "";
filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value;
}
dv.RowFilter = filter;
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["LayananManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
}
| |
using System;
using System.Collections;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
/**
* Test case for NaccacheStern cipher. For details on this cipher, please see
*
* http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
*
* Performs the following tests:
* <ul>
* <li> Toy example from the NaccacheSternPaper </li>
* <li> 768 bit test with text "Now is the time for all good men." (ripped from RSA test) and
* the same test with the first byte replaced by 0xFF </li>
* <li> 1024 bit test analog to 768 bit test </li>
* </ul>
*/
[TestFixture, Explicit]
public class NaccacheSternTest
: SimpleTest
{
static bool debug = false;
static readonly NaccacheSternEngine cryptEng = new NaccacheSternEngine();
static readonly NaccacheSternEngine decryptEng = new NaccacheSternEngine();
static NaccacheSternTest()
{
cryptEng.Debug = debug;
decryptEng.Debug = debug;
}
// Values from NaccacheStern paper
static readonly BigInteger a = BigInteger.ValueOf(101);
static readonly BigInteger u1 = BigInteger.ValueOf(3);
static readonly BigInteger u2 = BigInteger.ValueOf(5);
static readonly BigInteger u3 = BigInteger.ValueOf(7);
static readonly BigInteger b = BigInteger.ValueOf(191);
static readonly BigInteger v1 = BigInteger.ValueOf(11);
static readonly BigInteger v2 = BigInteger.ValueOf(13);
static readonly BigInteger v3 = BigInteger.ValueOf(17);
static readonly BigInteger sigma
= u1.Multiply(u2).Multiply(u3).Multiply(v1).Multiply(v2).Multiply(v3);
static readonly BigInteger p
= BigInteger.Two.Multiply(a).Multiply(u1).Multiply(u2).Multiply(u3).Add(BigInteger.One);
static readonly BigInteger q
= BigInteger.Two.Multiply(b).Multiply(v1).Multiply(v2).Multiply(v3).Add(BigInteger.One);
static readonly BigInteger n = p.Multiply(q);
static readonly BigInteger phi_n
= p.Subtract(BigInteger.One).Multiply(q.Subtract(BigInteger.One));
static readonly BigInteger g = BigInteger.ValueOf(131);
static readonly IList smallPrimes = new ArrayList();
// static final BigInteger paperTest = BigInteger.ValueOf(202);
static readonly string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
static readonly BigInteger paperTest = BigInteger.ValueOf(202);
//
// to check that we handling byte extension by big number correctly.
//
static readonly string edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
public override string Name
{
get { return "NaccacheStern"; }
}
public override void PerformTest()
{
// Test with given key from NaccacheSternPaper (totally insecure)
// First the Parameters from the NaccacheStern Paper
// (see http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf )
smallPrimes.Add(u1);
smallPrimes.Add(u2);
smallPrimes.Add(u3);
smallPrimes.Add(v1);
smallPrimes.Add(v2);
smallPrimes.Add(v3);
NaccacheSternKeyParameters pubParameters = new NaccacheSternKeyParameters(false, g, n, sigma.BitLength);
NaccacheSternPrivateKeyParameters privParameters = new NaccacheSternPrivateKeyParameters(g, n, sigma
.BitLength, smallPrimes, phi_n);
AsymmetricCipherKeyPair pair = new AsymmetricCipherKeyPair(pubParameters, privParameters);
// Initialize Engines with KeyPair
if (debug)
{
Console.WriteLine("initializing encryption engine");
}
cryptEng.Init(true, pair.Public);
if (debug)
{
Console.WriteLine("initializing decryption engine");
}
decryptEng.Init(false, pair.Private);
byte[] data = paperTest.ToByteArray();
if (!new BigInteger(data).Equals(new BigInteger(enDeCrypt(data))))
{
Fail("failed NaccacheStern paper test");
}
//
// key generation test
//
//
// 768 Bit test
//
if (debug)
{
Console.WriteLine();
Console.WriteLine("768 Bit TEST");
}
// specify key generation parameters
NaccacheSternKeyGenerationParameters genParam
= new NaccacheSternKeyGenerationParameters(new SecureRandom(), 768, 8, 30, debug);
// Initialize Key generator and generate key pair
NaccacheSternKeyPairGenerator pGen = new NaccacheSternKeyPairGenerator();
pGen.Init(genParam);
pair = pGen.GenerateKeyPair();
if (((NaccacheSternKeyParameters)pair.Public).Modulus.BitLength < 768)
{
Console.WriteLine("FAILED: key size is <786 bit, exactly "
+ ((NaccacheSternKeyParameters)pair.Public).Modulus.BitLength + " bit");
Fail("failed key generation (768) length test");
}
// Initialize Engines with KeyPair
if (debug)
{
Console.WriteLine("initializing " + genParam.Strength + " bit encryption engine");
}
cryptEng.Init(true, pair.Public);
if (debug)
{
Console.WriteLine("initializing " + genParam.Strength + " bit decryption engine");
}
decryptEng.Init(false, pair.Private);
// Basic data input
data = Hex.Decode(input);
if (!new BigInteger(1, data).Equals(new BigInteger(1, enDeCrypt(data))))
{
Fail("failed encryption decryption (" + genParam.Strength + ") basic test");
}
// Data starting with FF byte (would be interpreted as negative
// BigInteger)
data = Hex.Decode(edgeInput);
if (!new BigInteger(1, data).Equals(new BigInteger(1, enDeCrypt(data))))
{
Fail("failed encryption decryption (" + genParam.Strength + ") edgeInput test");
}
//
// 1024 Bit Test
//
/*
if (debug)
{
Console.WriteLine();
Console.WriteLine("1024 Bit TEST");
}
// specify key generation parameters
genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 1024, 8, 40, debug);
pGen.Init(genParam);
pair = pGen.generateKeyPair();
if (((NaccacheSternKeyParameters)pair.Public).getModulus().bitLength() < 1024)
{
if (debug)
{
Console.WriteLine("FAILED: key size is <1024 bit, exactly "
+ ((NaccacheSternKeyParameters)pair.Public).getModulus().bitLength() + " bit");
}
Fail("failed key generation (1024) length test");
}
// Initialize Engines with KeyPair
if (debug)
{
Console.WriteLine("initializing " + genParam.getStrength() + " bit encryption engine");
}
cryptEng.Init(true, pair.Public);
if (debug)
{
Console.WriteLine("initializing " + genParam.getStrength() + " bit decryption engine");
}
decryptEng.Init(false, pair.Private);
if (debug)
{
Console.WriteLine("Data is " + new BigInteger(1, data));
}
// Basic data input
data = Hex.Decode(input);
if (!new BigInteger(1, data).Equals(new BigInteger(1, enDeCrypt(data))))
{
Fail("failed encryption decryption (" + genParam.getStrength() + ") basic test");
}
// Data starting with FF byte (would be interpreted as negative
// BigInteger)
data = Hex.Decode(edgeInput);
if (!new BigInteger(1, data).Equals(new BigInteger(1, enDeCrypt(data))))
{
Fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test");
}
*/
// END OF TEST CASE
try
{
new NaccacheSternEngine().ProcessBlock(new byte[]{ 1 }, 0, 1);
Fail("failed initialisation check");
}
catch (InvalidOperationException)
{
// expected
}
if (debug)
{
Console.WriteLine("All tests successful");
}
}
private byte[] enDeCrypt(
byte[] input)
{
// create work array
byte[] data = new byte[input.Length];
Array.Copy(input, 0, data, 0, data.Length);
// Perform encryption like in the paper from Naccache-Stern
if (debug)
{
Console.WriteLine("encrypting data. Data representation\n"
// + "As string:.... " + new string(data) + "\n"
+ "As BigInteger: " + new BigInteger(1, data));
Console.WriteLine("data length is " + data.Length);
}
try
{
data = cryptEng.ProcessData(data);
}
catch (InvalidCipherTextException e)
{
if (debug)
{
Console.WriteLine("failed - exception " + e + "\n" + e.Message);
}
Fail("failed - exception " + e + "\n" + e.Message);
}
if (debug)
{
Console.WriteLine("enrypted data representation\n"
// + "As string:.... " + new string(data) + "\n"
+ "As BigInteger: " + new BigInteger(1, data));
Console.WriteLine("data length is " + data.Length);
}
try
{
data = decryptEng.ProcessData(data);
}
catch (InvalidCipherTextException e)
{
if (debug)
{
Console.WriteLine("failed - exception " + e + "\n" + e.Message);
}
Fail("failed - exception " + e + "\n" + e.Message);
}
if (debug)
{
Console.WriteLine("decrypted data representation\n"
// + "As string:.... " + new string(data) + "\n"
+ "As BigInteger: " + new BigInteger(1, data));
Console.WriteLine("data length is " + data.Length);
}
return data;
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
public static void Main(
string[] args)
{
ITest test = new NaccacheSternTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
}
}
| |
// Esperantus - The Web translator
// Copyright (C) 2003 Emmanuele De Andreis
//
// 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Emmanuele De Andreis (manu-dea@hotmail dot it)
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Rainbow.Framework.Web.UI.WebControls
{
/// <summary>
/// Summary description for LanguageSwitcher.
/// </summary>
[ToolboxData("<{0}:LanguageSwitcher runat='server'></{0}:LanguageSwitcher>")]
[Designer("Esperantus.Design.WebControls.LanguageSwitcherDesigner")]
[DefaultProperty("LanguageListString")]
//[PermissionSet(SecurityAction.LinkDemand, XML="<PermissionSet class=\"System.Security.PermissionSet\"\r\n version=\"1\">\r\n <IPermission class=\"System.Web.AspNetHostingPermission, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\r\n version=\"1\"\r\n Level=\"Minimal\"/>\r\n</PermissionSet>\r\n"), PermissionSet(SecurityAction.InheritanceDemand, XML="<PermissionSet class=\"System.Security.PermissionSet\"\r\n version=\"1\">\r\n <IPermission class=\"System.Web.AspNetHostingPermission, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\r\n version=\"1\"\r\n Level=\"Minimal\"/>\r\n</PermissionSet>\r\n")]
public class LanguageSwitcher : WebControl, IPostBackEventHandler
{
#region Constructors
/// <summary>
///
/// </summary>
public LanguageSwitcher()
{
//Trace.WriteLine("LanguageSwitcher() constructor *****************************************");
if (Context != null && Context.Request != null)
ChangeLanguageUrl = Context.Request.Path;
}
#endregion
#region Control creation
private const string SWITCHER_COOKIE_NAME = "languageSwitcher"; //TODO: do not hardcode cookie name
private const string SWITCHER_COOKIE_PREFIX = "Esperantus_Language_";
/// <summary>
///
/// </summary>
/// <param name="output"></param>
protected override void RenderContents(HtmlTextWriter output)
{
//Trace.WriteLine("RenderingContents");
EnsureChildControls();
foreach (Control ctrl in Controls)
ctrl.RenderControl(output);
}
private DropDownList langDropDown;
/// <summary>
/// Override CreateChildControls to create the control tree.
/// </summary>
protected override void CreateChildControls()
{
//Trace.WriteLine("Creating controls: Type: " + Type.ToString() + " / ChangeLanguageAction: " + ChangeLanguageAction.ToString() + " / Labels: " + Labels.ToString() + " / Flags: " + Flags.ToString() + " / LanguageListString: " + LanguageListString);
ProcessCultures(LanguageListString, SWITCHER_COOKIE_NAME, this);
Controls.Clear();
Table myTable = new Table();
myTable.CellPadding = 3;
myTable.CellSpacing = 0;
TableRowCollection myRows = myTable.Rows;
switch (Type)
{
//Drop down list
case LanguageSwitcherType.DropDownList:
TableRow myTableRowDD = new TableRow();
if (Flags != LanguageSwitcherDisplay.DisplayNone)
{
Image myImage = new Image();
myImage.ImageUrl = GetFlagImg(GetCurrentLanguage());
TableCell myTableCellFlag = new TableCell();
myTableCellFlag.Controls.Add(myImage);
myTableRowDD.Controls.Add(myTableCellFlag);
}
TableCell myTableCellDropDown = new TableCell();
langDropDown = new DropDownList();
langDropDown.CssClass = "rb_LangSw_dd"; //TODO make changeable
LanguageCultureItem myCurrentLanguage = GetCurrentLanguage();
// bind the dropdownlist
langDropDown.Items.Clear();
foreach (LanguageCultureItem i in LanguageList)
{
langDropDown.Items.Add(new ListItem(GetName(i), i.UICulture.Name));
if (i.UICulture.ToString() == myCurrentLanguage.UICulture.ToString()) //Select current language
langDropDown.Items[langDropDown.Items.Count - 1].Selected = true;
}
langDropDown.Attributes.Add("OnChange",
GetLangAction().Replace("''", "this[this.selectedIndex].value"));
myTableCellDropDown.Controls.Add(langDropDown);
myTableRowDD.Controls.Add(myTableCellDropDown);
myRows.Add(myTableRowDD);
break;
// Links
case LanguageSwitcherType.VerticalLinksList:
foreach (LanguageCultureItem l in LanguageList)
{
TableRow myTableRowLinks = new TableRow();
if (Flags != LanguageSwitcherDisplay.DisplayNone)
myTableRowLinks.Controls.Add(GetFlagCell(l));
if (Labels != LanguageSwitcherDisplay.DisplayNone)
myTableRowLinks.Controls.Add(GetLabelCell(l));
myRows.Add(myTableRowLinks);
}
break;
// Horizontal links
case LanguageSwitcherType.HorizontalLinksList:
TableRow myTableRowLinksHorizontal = new TableRow();
foreach (LanguageCultureItem l in LanguageList)
{
if (Flags != LanguageSwitcherDisplay.DisplayNone)
myTableRowLinksHorizontal.Controls.Add(GetFlagCell(l));
if (Labels != LanguageSwitcherDisplay.DisplayNone)
myTableRowLinksHorizontal.Controls.Add(GetLabelCell(l));
}
myRows.Add(myTableRowLinksHorizontal);
break;
}
Controls.Add(myTable);
}
#endregion
#region Events and delegates
/// <summary>
/// The ChangeLanguage event is defined using the event keyword.
/// The type of ChangeLanguage is EventHandler.
/// </summary>
public event LanguageSwitcherEventHandler ChangeLanguage;
/// <summary>
/// Examines/combines all the variables involved and sets
/// CurrentUICulture and CurrentCulture.
/// Can be overridden.
/// </summary>
/// <param name="e"></param>
protected virtual void OnChangeLanguage(LanguageSwitcherEventArgs e)
{
// Updates current cultures
SetCurrentLanguage(e.CultureItem, SWITCHER_COOKIE_NAME, this);
if (ChangeLanguage != null)
ChangeLanguage(this, e); //Invokes the delegates
}
/// <summary>
/// Implement the RaisePostBackEvent method
/// from the IPostBackEventHandler interface.
/// </summary>
/// <param name="eventArgument"></param>
public void RaisePostBackEvent(string eventArgument)
{
//Trace.WriteLine("RaisingPostBackEvent: eventArgument = '" + eventArgument + "'");
if (ChangeLanguageAction == LanguageSwitcherAction.LinkRedirect)
{
Context.Response.Redirect(GetLangUrl(eventArgument));
}
else
{
LanguageCultureItem myItem = LanguageList.GetBestMatching(new CultureInfo(eventArgument));
OnChangeLanguage(new LanguageSwitcherEventArgs(myItem));
}
}
#endregion
#region Private Implementation
private TableCell GetFlagCell(LanguageCultureItem l)
{
TableCell myTableCellFlag = new TableCell();
if (l.UICulture.ToString() == GetCurrentLanguage().UICulture.ToString())
myTableCellFlag.CssClass = "rb_LangSw_sel"; // TODO: not hardcode
else
myTableCellFlag.CssClass = "rb_LangSw_tbl"; // TODO: not hardcode
HyperLink myImage = new HyperLink();
myImage.NavigateUrl = GetLangUrl(l.UICulture.Name);
myImage.ImageUrl = GetFlagImg(l);
myImage.Text = GetName(l);
myTableCellFlag.Controls.Add(myImage);
return myTableCellFlag;
}
private TableCell GetLabelCell(LanguageCultureItem l)
{
TableCell myTableCellLabel = new TableCell();
if (l.UICulture.ToString() == GetCurrentLanguage().UICulture.ToString())
myTableCellLabel.CssClass = "rb_LangSw_sel"; // TODO: not hardcode
else
myTableCellLabel.CssClass = "rb_LangSw_tbl"; // TODO: not hardcode
HyperLink myLabel = new HyperLink();
myLabel.NavigateUrl = GetLangUrl(l.UICulture.Name);
myLabel.Text = GetName(l);
myTableCellLabel.Controls.Add(myLabel);
return myTableCellLabel;
}
private string GetFlagImg(LanguageCultureItem languageItem)
{
CultureInfo myCulture;
switch (Flags)
{
default:
case LanguageSwitcherDisplay.DisplayNone:
return string.Empty;
case LanguageSwitcherDisplay.DisplayUICultureList:
myCulture = languageItem.UICulture;
break;
case LanguageSwitcherDisplay.DisplayCultureList:
myCulture = languageItem.Culture;
break;
}
//Flag must be specific
if (myCulture.IsNeutralCulture)
myCulture = CultureInfo.CreateSpecificCulture(myCulture.Name);
string flagImgUrl;
if (myCulture.Name.Length > 0)
flagImgUrl = ImagePath + "flags_" + myCulture.Name + ".gif";
else
flagImgUrl = ImagePath + "flags_unknown.gif";
return flagImgUrl;
}
/// <summary>
/// Used by flags and label
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
private string GetLangUrl(string language)
{
if (ChangeLanguageAction == LanguageSwitcherAction.LinkRedirect)
return ChangeLanguageUrl + "?lang=" + language; //TODO replace lang if present
else
return "javascript:" + Page.GetPostBackEventReference(this, language);
}
/// <summary>
/// Used by dropdownlist
/// </summary>
/// <returns></returns>
private string GetLangAction()
{
return Page.GetPostBackEventReference(this);
}
private string GetName(LanguageCultureItem languageItem)
{
CultureInfo myCulture;
switch (Labels)
{
default:
case LanguageSwitcherDisplay.DisplayNone:
return string.Empty;
case LanguageSwitcherDisplay.DisplayUICultureList:
myCulture = languageItem.UICulture;
break;
case LanguageSwitcherDisplay.DisplayCultureList:
myCulture = languageItem.Culture;
break;
}
switch (ShowNameAs)
{
default:
case LanguageSwitcherName.NativeName:
return languageItem.Culture.TextInfo.ToTitleCase(myCulture.NativeName);
case LanguageSwitcherName.DisplayName:
return languageItem.Culture.TextInfo.ToTitleCase(myCulture.DisplayName);
case LanguageSwitcherName.EnglishName:
return languageItem.Culture.TextInfo.ToTitleCase(myCulture.EnglishName);
}
}
#endregion
#region Static Implementation
/// <summary>
///
/// </summary>
/// <param name="langItem"></param>
public static void SetCurrentLanguage(LanguageCultureItem langItem)
{
SetCurrentLanguage(langItem);
}
/// <summary>
///
/// </summary>
/// <param name="langItem"></param>
/// <param name="cookieAlias">Cookie name used for persist Language</param>
public static void SetCurrentLanguage(LanguageCultureItem langItem, string cookieAlias)
{
SetCurrentLanguage(langItem, cookieAlias, null);
}
/// <summary>
///
/// </summary>
/// <param name="langItem"></param>
/// <param name="cookieAlias">Cookie name used for persist Language</param>
/// <param name="switcher"></param>
internal static void SetCurrentLanguage(LanguageCultureItem langItem, string cookieAlias,
LanguageSwitcher switcher)
{
Thread.CurrentThread.CurrentUICulture = langItem.UICulture;
Thread.CurrentThread.CurrentCulture = langItem.Culture;
//Persists choice
InternalSetViewState(langItem, switcher);
InternalSetCookie(langItem, cookieAlias);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static LanguageCultureItem GetCurrentLanguage()
{
return new LanguageCultureItem(Thread.CurrentThread.CurrentUICulture, Thread.CurrentThread.CurrentCulture);
}
/// <summary>
/// Get current Language from Querystring
/// </summary>
/// <param name="myLanguagesCultureList"></param>
/// <returns></returns>
private static LanguageCultureItem InternalGetQuerystring(LanguageCultureCollection myLanguagesCultureList)
{
if (HttpContext.Current != null && HttpContext.Current.Request.Params["Lang"] != null &&
HttpContext.Current.Request.Params["Lang"].Length > 0)
{
try
{
return
myLanguagesCultureList.GetBestMatching(
new CultureInfo(HttpContext.Current.Request.Params["Lang"]));
}
catch (ArgumentException) //Maybe an invalid CultureInfo
{
return null;
}
}
return null;
}
/// <summary>
/// Get current Language from User language list
/// </summary>
/// <param name="myLanguagesCultureList"></param>
/// <returns></returns>
private static LanguageCultureItem InternalGetUserLanguages(LanguageCultureCollection myLanguagesCultureList)
{
//Get userLangs
CultureInfo[] userLangs;
if (HttpContext.Current != null && HttpContext.Current.Request.UserLanguages != null &&
HttpContext.Current.Request.UserLanguages.Length > 0)
{
ArrayList arrUserLangs = new ArrayList(HttpContext.Current.Request.UserLanguages);
if (arrUserLangs.Count > 0)
{
for (Int32 i = 0; i <= arrUserLangs.Count - 1; i++)
{
string currentLanguage;
if (arrUserLangs[i].ToString().IndexOf(';') >= 0)
currentLanguage =
arrUserLangs[i].ToString().Substring(0, arrUserLangs[i].ToString().IndexOf(';'));
else
currentLanguage = arrUserLangs[i].ToString();
try
{
// We try the full one... if this fails we catch it
arrUserLangs[i] = new CultureInfo(currentLanguage);
}
catch (ArgumentException)
{
try
{
// Some browsers can send an invalid language
// we try to get first two letters.. this is usually valid
arrUserLangs[i] = new CultureInfo(currentLanguage.Substring(2));
}
catch (ArgumentException)
{
}
return null;
}
}
}
userLangs = (CultureInfo[]) arrUserLangs.ToArray(typeof (CultureInfo));
// Try to match browser "accept languages" list
return myLanguagesCultureList.GetBestMatching(userLangs);
}
return null;
}
/// <summary>
/// Get current Language from Cookie
/// </summary>
/// <param name="myLanguagesCultureList"></param>
/// <param name="cookieAlias"></param>
/// <returns></returns>
private static LanguageCultureItem InternalGetCookie(LanguageCultureCollection myLanguagesCultureList,
string cookieAlias)
{
if (HttpContext.Current != null && cookieAlias != null &&
HttpContext.Current.Request.Cookies[SWITCHER_COOKIE_PREFIX + cookieAlias] != null &&
HttpContext.Current.Request.Cookies[SWITCHER_COOKIE_PREFIX + cookieAlias].Value.Length > 0)
{
try
{
return
myLanguagesCultureList.GetBestMatching(
new CultureInfo(
HttpContext.Current.Request.Cookies[SWITCHER_COOKIE_PREFIX + cookieAlias].Value));
}
catch (ArgumentException)
{
//Maybe an invalid CultureInfo
}
}
return null;
}
/// <summary>
/// Set current Cookie from Language
/// </summary>
/// <param name="myLanguageCultureItem"></param>
/// <param name="cookieAlias"></param>
/// <returns></returns>
private static void InternalSetCookie(LanguageCultureItem myLanguageCultureItem, string cookieAlias)
{
// Set language cookie
if (HttpContext.Current != null && cookieAlias != null)
{
//Trace.WriteLine("Persisting in cookie: '" + SWITCHER_COOKIE_PREFIX + cookieAlias + "'");
HttpCookie langCookie = HttpContext.Current.Response.Cookies[SWITCHER_COOKIE_PREFIX + cookieAlias];
langCookie.Value = myLanguageCultureItem.UICulture.Name;
langCookie.Path = "/";
// Keep the cookie?
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
langCookie.Expires = DateTime.Now.AddYears(50);
}
}
/// <summary>
/// Get current Language from ViewState
/// </summary>
/// <param name="myLanguagesCultureList"></param>
/// <returns></returns>
private static LanguageCultureItem InternalGetViewState(LanguageCultureCollection myLanguagesCultureList,
LanguageSwitcher switcher)
{
if (switcher != null && switcher.ViewState["RB_Language_CurrentUICulture"] != null &&
switcher.ViewState["RB_Language_CurrentCulture"] != null)
return
new LanguageCultureItem((CultureInfo) switcher.ViewState["RB_Language_CurrentUICulture"],
(CultureInfo) switcher.ViewState["RB_Language_CurrentCulture"]);
else
return null;
}
/// <summary>
/// Get current Language from ViewState
/// </summary>
/// <param name="myLanguageCultureItem"></param>
/// <returns></returns>
private static void InternalSetViewState(LanguageCultureItem myLanguageCultureItem, LanguageSwitcher switcher)
{
if (switcher != null)
{
//Trace.WriteLine("Persisting in viewstate");
switcher.ViewState["RB_Language_CurrentUICulture"] = myLanguageCultureItem.UICulture;
switcher.ViewState["RB_Language_CurrentCulture"] = myLanguageCultureItem.Culture;
}
}
/// <summary>
/// Get default
/// </summary>
/// <param name="myLanguagesCultureList"></param>
/// <returns></returns>
private static LanguageCultureItem InternalGetDefault(LanguageCultureCollection myLanguagesCultureList)
{
return myLanguagesCultureList[0];
}
/// <summary>
/// Examines/combines all the variables involved and sets
/// CurrentUICulture and CurrentCulture
/// </summary>
/// <param name="langList">Languages list. Something like it=it-IT;en=en-US</param>
public static void ProcessCultures(string langList)
{
ProcessCultures(langList, null);
}
/// <summary>
/// Examines/combines all the variables involved and sets
/// CurrentUICulture and CurrentCulture
/// </summary>
/// <param name="langList">Languages list. Something like it=it-IT;en=en-US</param>
/// <param name="cookieAlias">Alias used to make this cookie unique. Use null is you do not want cookies.</param>
public static void ProcessCultures(string langList, string cookieAlias)
{
ProcessCultures(langList, cookieAlias, null);
}
/// <summary>
/// Examines/combines all the variables involved and sets
/// CurrentUICulture and CurrentCulture
/// </summary>
/// <param name="langList">Languages list. Something like it=it-IT;en=en-US</param>
/// <param name="cookieAlias">Alias used to make this cookie unique. Use null is you do not want cookies.</param>
/// <param name="switcher">A referenct to a Switcher control for accessing viewstate</param>
internal static void ProcessCultures(string langList, string cookieAlias, LanguageSwitcher switcher)
{
LanguageCultureCollection myLanguagesCultureList = (LanguageCultureCollection) langList;
//Verify that at least on language is provided
if (myLanguagesCultureList.Count <= 0)
throw new ArgumentException("Please provide at least one language in the list.", "langList");
// Language Item
LanguageCultureItem langItem;
// Querystring
langItem = InternalGetQuerystring(myLanguagesCultureList);
//Trace.WriteLine("Evaluated InternalGetQuerystring: '" + (langItem == null ? "null" : langItem) + "'");
if (langItem != null) goto setLanguage;
// Viewstate
langItem = InternalGetViewState(myLanguagesCultureList, switcher);
//Trace.WriteLine("Evaluated InternalGetViewState: '" + (langItem == null ? "null" : langItem) + "'");
if (langItem != null) goto setLanguage;
// Cookie
langItem = InternalGetCookie(myLanguagesCultureList, cookieAlias);
//Trace.WriteLine("Evaluated InternalGetCookie: '" + (langItem == null ? "null" : langItem) + "'");
if (langItem != null) goto setLanguage;
// UserLanguageList
langItem = InternalGetUserLanguages(myLanguagesCultureList);
//Trace.WriteLine("Evaluated InternalGetUserLanguages: '" + (langItem == null ? "null" : langItem) + "'");
if (langItem != null) goto setLanguage;
// Default
langItem = InternalGetDefault(myLanguagesCultureList);
//Trace.WriteLine("Evaluated InternalGetDefault: '" + (langItem == null ? "null" : langItem) + "'");
setLanguage:
// Updates current cultures
SetCurrentLanguage(langItem, cookieAlias);
}
#endregion
#region Properties
/// <summary>
/// Normally the Language part is shown as Native name (the name in the proper language).
/// Set ShowNative to false for showing names in english.
/// </summary>
[DefaultValue(LanguageSwitcherName.NativeName)]
public LanguageSwitcherName ShowNameAs
{
get
{
if (ViewState["ShowNameAs"] != null)
return (LanguageSwitcherName) ViewState["ShowNameAs"];
return LanguageSwitcherName.NativeName;
}
set
{
ViewState["ShowNameAs"] = value;
ChildControlsCreated = false;
//EnsureChildControls();
}
}
/// <summary>
/// Normally the Language part is shown (UI).
/// Choose DisplayCultureList to show the Culture part.
/// Choose DisplayNone for hide labels.
/// </summary>
[DefaultValue(LanguageSwitcherDisplay.DisplayUICultureList)]
public LanguageSwitcherDisplay Labels
{
get
{
if (ViewState["Labels"] != null)
return (LanguageSwitcherDisplay) ViewState["Labels"];
return LanguageSwitcherDisplay.DisplayUICultureList;
}
set
{
ViewState["Labels"] = value;
ChildControlsCreated = false;
//EnsureChildControls();
}
}
/// <summary>
/// Normally the Language part is shown (UI).
/// Choose DisplayCultureList to show the Culture part.
/// Choose DisplayNone for hide Flags.
/// </summary>
[DefaultValue(LanguageSwitcherDisplay.DisplayCultureList)]
public LanguageSwitcherDisplay Flags
{
get
{
if (ViewState["Flags"] != null)
return ((LanguageSwitcherDisplay) ViewState["Flags"]);
return LanguageSwitcherDisplay.DisplayCultureList;
}
set
{
ViewState["Flags"] = value;
ChildControlsCreated = false;
//EnsureChildControls();
}
}
/// <summary>
/// LanguageSwitcher Type
/// </summary>
[DefaultValue(LanguageSwitcherType.DropDownList)]
public LanguageSwitcherType Type
{
get
{
if (ViewState["Type"] != null)
return (LanguageSwitcherType) ViewState["Type"];
return LanguageSwitcherType.DropDownList;
}
set
{
ViewState["Type"] = value;
ChildControlsCreated = false;
//EnsureChildControls();
}
}
/// <summary>
/// Image path
/// </summary>
[DefaultValue("images/flags/")]
public string ImagePath
{
get
{
string imagePath = ((string) ViewState["ImagePath"]);
if (imagePath != null)
return imagePath;
return "images/flags/"; //TODO: point to aspnet
}
set { ViewState["ImagePath"] = value; }
}
/// <summary>
/// Url where redirecting language changes.
/// An empty walue reload current page.
/// </summary>
[DefaultValue("")]
public string ChangeLanguageUrl
{
get
{
string changeLanguageUrl = ((string) ViewState["ChangeLanguageUrl"]);
if (changeLanguageUrl != null)
return changeLanguageUrl;
return string.Empty;
}
set { ViewState["ChangeLanguageUrl"] = value; }
}
/// <summary>
/// Choose how language switcher change language.
/// </summary>
/// <remarks>
/// In LanguageSwitcherAction.LinkRedirect mode
/// NO EVENT is raised because no posback occurs.
/// </remarks>
[DefaultValue(LanguageSwitcherAction.PostBack)]
public LanguageSwitcherAction ChangeLanguageAction
{
get
{
if (ViewState["ChangeLanguageAction"] != null)
return (LanguageSwitcherAction) ViewState["ChangeLanguageAction"];
return LanguageSwitcherAction.PostBack;
}
set { ViewState["ChangeLanguageAction"] = value; }
}
// private LanguageCultureCollection LanguageList;
// /// <summary>
// /// LanguageCultureCollection
// /// </summary>
// [DefaultValue("en=en-US;it=it-IT")]
// [PersistenceMode(PersistenceMode.Attribute)]
// [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
// [TypeConverter(typeof(TypeConverterLanguageCultureCollection))]
// [Description("The language list.")]
// [MergableProperty(false)]
private LanguageCultureCollection LanguageList
{
get { return (LanguageCultureCollection) LanguageListString; }
// set
// {
// Trace.WriteLine("LanguageList");
// LanguageListString = (string) value;
// }
}
//
// public void SetLanguagesCultureList(string languageList)
// {
// m_languageList = (LanguageCultureCollection) languageList;
// ChildControlsCreated = false;
// EnsureChildControls();
// }
// private string strLanguageList = "en=en-US;it=it-IT";
/// <summary>
///
/// </summary>
[DefaultValue("en=en-US;it=it-IT")]
[PersistenceMode(PersistenceMode.Attribute)]
public string LanguageListString
{
get
{
if (ViewState["LanguageList"] != null)
return (string) ViewState["LanguageList"];
return "en=en-US;it=it-IT";
//return strLanguageList;
}
set
{
//strLanguageList = value;
ViewState["LanguageList"] = (string) value;
ChildControlsCreated = false;
//EnsureChildControls();
}
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFirewallPoliciesClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFirewallPolicyRequest request = new GetFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicy expectedResponse = new FirewallPolicy
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreationTimestamp = "creation_timestamp235e59a1",
SelfLinkWithId = "self_link_with_id6d1e3896",
Parent = "parent7858e4d0",
Rules =
{
new FirewallPolicyRule(),
},
Fingerprint = "fingerprint009e6052",
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
ShortName = "short_namec7ba9846",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicy response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFirewallPolicyRequest request = new GetFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicy expectedResponse = new FirewallPolicy
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreationTimestamp = "creation_timestamp235e59a1",
SelfLinkWithId = "self_link_with_id6d1e3896",
Parent = "parent7858e4d0",
Rules =
{
new FirewallPolicyRule(),
},
Fingerprint = "fingerprint009e6052",
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
ShortName = "short_namec7ba9846",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicy responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPolicy responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFirewallPolicyRequest request = new GetFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicy expectedResponse = new FirewallPolicy
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreationTimestamp = "creation_timestamp235e59a1",
SelfLinkWithId = "self_link_with_id6d1e3896",
Parent = "parent7858e4d0",
Rules =
{
new FirewallPolicyRule(),
},
Fingerprint = "fingerprint009e6052",
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
ShortName = "short_namec7ba9846",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicy response = client.Get(request.FirewallPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFirewallPolicyRequest request = new GetFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicy expectedResponse = new FirewallPolicy
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreationTimestamp = "creation_timestamp235e59a1",
SelfLinkWithId = "self_link_with_id6d1e3896",
Parent = "parent7858e4d0",
Rules =
{
new FirewallPolicyRule(),
},
Fingerprint = "fingerprint009e6052",
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
ShortName = "short_namec7ba9846",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicy responseCallSettings = await client.GetAsync(request.FirewallPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPolicy responseCancellationToken = await client.GetAsync(request.FirewallPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAssociationRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAssociationFirewallPolicyRequest request = new GetAssociationFirewallPolicyRequest
{
Name = "name1c9368b0",
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyAssociation expectedResponse = new FirewallPolicyAssociation
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
AttachmentTarget = "attachment_targetf83a4ab8",
FirewallPolicyId = "firewall_policy_id306dc2cb",
ShortName = "short_namec7ba9846",
};
mockGrpcClient.Setup(x => x.GetAssociation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyAssociation response = client.GetAssociation(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAssociationRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAssociationFirewallPolicyRequest request = new GetAssociationFirewallPolicyRequest
{
Name = "name1c9368b0",
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyAssociation expectedResponse = new FirewallPolicyAssociation
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
AttachmentTarget = "attachment_targetf83a4ab8",
FirewallPolicyId = "firewall_policy_id306dc2cb",
ShortName = "short_namec7ba9846",
};
mockGrpcClient.Setup(x => x.GetAssociationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPolicyAssociation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyAssociation responseCallSettings = await client.GetAssociationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPolicyAssociation responseCancellationToken = await client.GetAssociationAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAssociation()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAssociationFirewallPolicyRequest request = new GetAssociationFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyAssociation expectedResponse = new FirewallPolicyAssociation
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
AttachmentTarget = "attachment_targetf83a4ab8",
FirewallPolicyId = "firewall_policy_id306dc2cb",
ShortName = "short_namec7ba9846",
};
mockGrpcClient.Setup(x => x.GetAssociation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyAssociation response = client.GetAssociation(request.FirewallPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAssociationAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAssociationFirewallPolicyRequest request = new GetAssociationFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyAssociation expectedResponse = new FirewallPolicyAssociation
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
AttachmentTarget = "attachment_targetf83a4ab8",
FirewallPolicyId = "firewall_policy_id306dc2cb",
ShortName = "short_namec7ba9846",
};
mockGrpcClient.Setup(x => x.GetAssociationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPolicyAssociation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyAssociation responseCallSettings = await client.GetAssociationAsync(request.FirewallPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPolicyAssociation responseCancellationToken = await client.GetAssociationAsync(request.FirewallPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyFirewallPolicyRequest request = new GetIamPolicyFirewallPolicyRequest
{
Resource = "resource164eab96",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyFirewallPolicyRequest request = new GetIamPolicyFirewallPolicyRequest
{
Resource = "resource164eab96",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyFirewallPolicyRequest request = new GetIamPolicyFirewallPolicyRequest
{
Resource = "resource164eab96",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyFirewallPolicyRequest request = new GetIamPolicyFirewallPolicyRequest
{
Resource = "resource164eab96",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRuleRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRuleFirewallPolicyRequest request = new GetRuleFirewallPolicyRequest
{
Priority = 1546225849,
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyRule expectedResponse = new FirewallPolicyRule
{
Kind = "kindf7aa39d9",
Match = new FirewallPolicyRuleMatcher(),
Direction = "direction7bc372ef",
Action = "action09558c41",
Disabled = false,
EnableLogging = false,
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
Priority = 1546225849,
TargetServiceAccounts =
{
"target_service_accounts61bf1663",
},
TargetResources =
{
"target_resources1e810c06",
},
};
mockGrpcClient.Setup(x => x.GetRule(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyRule response = client.GetRule(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRuleRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRuleFirewallPolicyRequest request = new GetRuleFirewallPolicyRequest
{
Priority = 1546225849,
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyRule expectedResponse = new FirewallPolicyRule
{
Kind = "kindf7aa39d9",
Match = new FirewallPolicyRuleMatcher(),
Direction = "direction7bc372ef",
Action = "action09558c41",
Disabled = false,
EnableLogging = false,
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
Priority = 1546225849,
TargetServiceAccounts =
{
"target_service_accounts61bf1663",
},
TargetResources =
{
"target_resources1e810c06",
},
};
mockGrpcClient.Setup(x => x.GetRuleAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPolicyRule>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyRule responseCallSettings = await client.GetRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPolicyRule responseCancellationToken = await client.GetRuleAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRule()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRuleFirewallPolicyRequest request = new GetRuleFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyRule expectedResponse = new FirewallPolicyRule
{
Kind = "kindf7aa39d9",
Match = new FirewallPolicyRuleMatcher(),
Direction = "direction7bc372ef",
Action = "action09558c41",
Disabled = false,
EnableLogging = false,
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
Priority = 1546225849,
TargetServiceAccounts =
{
"target_service_accounts61bf1663",
},
TargetResources =
{
"target_resources1e810c06",
},
};
mockGrpcClient.Setup(x => x.GetRule(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyRule response = client.GetRule(request.FirewallPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRuleAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRuleFirewallPolicyRequest request = new GetRuleFirewallPolicyRequest
{
FirewallPolicy = "firewall_policy1f9c9144",
};
FirewallPolicyRule expectedResponse = new FirewallPolicyRule
{
Kind = "kindf7aa39d9",
Match = new FirewallPolicyRuleMatcher(),
Direction = "direction7bc372ef",
Action = "action09558c41",
Disabled = false,
EnableLogging = false,
RuleTupleCount = -1393850828,
Description = "description2cf9da67",
Priority = 1546225849,
TargetServiceAccounts =
{
"target_service_accounts61bf1663",
},
TargetResources =
{
"target_resources1e810c06",
},
};
mockGrpcClient.Setup(x => x.GetRuleAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPolicyRule>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPolicyRule responseCallSettings = await client.GetRuleAsync(request.FirewallPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPolicyRule responseCancellationToken = await client.GetRuleAsync(request.FirewallPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListAssociationsRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListAssociationsFirewallPolicyRequest request = new ListAssociationsFirewallPolicyRequest
{
TargetResource = "target_resource7041731f",
};
FirewallPoliciesListAssociationsResponse expectedResponse = new FirewallPoliciesListAssociationsResponse
{
Kind = "kindf7aa39d9",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.ListAssociations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPoliciesListAssociationsResponse response = client.ListAssociations(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListAssociationsRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListAssociationsFirewallPolicyRequest request = new ListAssociationsFirewallPolicyRequest
{
TargetResource = "target_resource7041731f",
};
FirewallPoliciesListAssociationsResponse expectedResponse = new FirewallPoliciesListAssociationsResponse
{
Kind = "kindf7aa39d9",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.ListAssociationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPoliciesListAssociationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPoliciesListAssociationsResponse responseCallSettings = await client.ListAssociationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPoliciesListAssociationsResponse responseCancellationToken = await client.ListAssociationsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListAssociations()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListAssociationsFirewallPolicyRequest request = new ListAssociationsFirewallPolicyRequest { };
FirewallPoliciesListAssociationsResponse expectedResponse = new FirewallPoliciesListAssociationsResponse
{
Kind = "kindf7aa39d9",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.ListAssociations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPoliciesListAssociationsResponse response = client.ListAssociations();
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListAssociationsAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListAssociationsFirewallPolicyRequest request = new ListAssociationsFirewallPolicyRequest { };
FirewallPoliciesListAssociationsResponse expectedResponse = new FirewallPoliciesListAssociationsResponse
{
Kind = "kindf7aa39d9",
Associations =
{
new FirewallPolicyAssociation(),
},
};
mockGrpcClient.Setup(x => x.ListAssociationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FirewallPoliciesListAssociationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
FirewallPoliciesListAssociationsResponse responseCallSettings = await client.ListAssociationsAsync(gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FirewallPoliciesListAssociationsResponse responseCancellationToken = await client.ListAssociationsAsync(st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyFirewallPolicyRequest request = new SetIamPolicyFirewallPolicyRequest
{
GlobalOrganizationSetPolicyRequestResource = new GlobalOrganizationSetPolicyRequest(),
Resource = "resource164eab96",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyFirewallPolicyRequest request = new SetIamPolicyFirewallPolicyRequest
{
GlobalOrganizationSetPolicyRequestResource = new GlobalOrganizationSetPolicyRequest(),
Resource = "resource164eab96",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyFirewallPolicyRequest request = new SetIamPolicyFirewallPolicyRequest
{
GlobalOrganizationSetPolicyRequestResource = new GlobalOrganizationSetPolicyRequest(),
Resource = "resource164eab96",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request.Resource, request.GlobalOrganizationSetPolicyRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyFirewallPolicyRequest request = new SetIamPolicyFirewallPolicyRequest
{
GlobalOrganizationSetPolicyRequestResource = new GlobalOrganizationSetPolicyRequest(),
Resource = "resource164eab96",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.GlobalOrganizationSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.GlobalOrganizationSetPolicyRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsFirewallPolicyRequest request = new TestIamPermissionsFirewallPolicyRequest
{
Resource = "resource164eab96",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsFirewallPolicyRequest request = new TestIamPermissionsFirewallPolicyRequest
{
Resource = "resource164eab96",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsFirewallPolicyRequest request = new TestIamPermissionsFirewallPolicyRequest
{
Resource = "resource164eab96",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<FirewallPolicies.FirewallPoliciesClient> mockGrpcClient = new moq::Mock<FirewallPolicies.FirewallPoliciesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOrganizationOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsFirewallPolicyRequest request = new TestIamPermissionsFirewallPolicyRequest
{
Resource = "resource164eab96",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirewallPoliciesClient client = new FirewallPoliciesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.Tests;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Cassandra.IntegrationTests.Policies.Util;
using Cassandra.IntegrationTests.TestBase;
namespace Cassandra.IntegrationTests.Core
{
[TestFixture, Category(TestCategory.Long), Ignore("tests that are not marked with 'short' need to be refactored/deleted")]
public class StressTests : TestGlobals
{
/// <summary>
/// Insert and select records in parallel them using Session.Execute sync methods.
/// </summary>
[Test]
public void Parallel_Insert_And_Select_Sync()
{
var testCluster = TestClusterManager.GetNonShareableTestCluster(3, 1, true, false);
using (var cluster = ClusterBuilder()
.WithRetryPolicy(AlwaysRetryRetryPolicy.Instance)
.AddContactPoint(testCluster.InitialContactPoint)
.Build())
{
var session = cluster.Connect();
var uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10);
session.Execute(@"CREATE KEYSPACE " + uniqueKsName +
" WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};");
session.ChangeKeyspace(uniqueKsName);
var tableName = "table_" + Guid.NewGuid().ToString("N").ToLower();
session.Execute(string.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName));
var insertQuery = string.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName);
var insertQueryPrepared = session.Prepare(insertQuery);
var selectQuery = string.Format("SELECT * FROM {0} LIMIT 10000", tableName);
const int rowsPerId = 1000;
object insertQueryStatement = new SimpleStatement(insertQuery);
if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 0), Comparison.LessThan))
{
//Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2
insertQueryStatement = session.Prepare(insertQuery);
}
var actionInsert = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId);
var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId);
var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10);
//Execute insert sync to have some records
actionInsert();
//Execute select sync to assert that everything is going OK
actionSelect();
var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
//Add 10 actions to execute
actions.AddRange(new[] {actionInsert, actionSelect, actionInsertPrepared});
actions.AddRange(new[] {actionSelect, actionInsert, actionInsertPrepared, actionInsert});
actions.AddRange(new[] {actionInsertPrepared, actionInsertPrepared, actionSelect});
}
//Execute in parallel the 100 actions
TestHelper.ParallelInvoke(actions.ToArray());
}
}
/// <summary>
/// In parallel it inserts some records and selects them using Session.Execute sync methods.
/// </summary>
[Test]
[TestCassandraVersion(2, 0)]
public void Parallel_Insert_And_Select_Sync_With_Nodes_Failing()
{
var testCluster = TestClusterManager.GetNonShareableTestCluster(3, 1, true, false);
using (var cluster = ClusterBuilder()
.WithRetryPolicy(AlwaysRetryRetryPolicy.Instance)
.AddContactPoint(testCluster.InitialContactPoint)
.Build())
{
var session = cluster.Connect();
var uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10);
session.Execute(@"CREATE KEYSPACE " + uniqueKsName +
" WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};");
session.ChangeKeyspace(uniqueKsName);
var tableName = "table_" + Guid.NewGuid().ToString("N").ToLower();
session.Execute(string.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName));
var insertQuery = string.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName);
var insertQueryPrepared = session.Prepare(insertQuery);
var selectQuery = string.Format("SELECT * FROM {0} LIMIT 10000", tableName);
const int rowsPerId = 100;
object insertQueryStatement = new SimpleStatement(insertQuery);
if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 0), Comparison.LessThan))
{
//Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2
insertQueryStatement = session.Prepare(insertQuery);
}
var actionInsert = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId);
var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId);
var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10);
//Execute insert sync to have some records
actionInsert();
//Execute select sync to assert that everything is going OK
actionSelect();
var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
//Add 10 actions to execute
actions.AddRange(new[] { actionInsert, actionSelect, actionInsertPrepared });
actions.AddRange(new[] { actionSelect, actionInsert, actionInsertPrepared, actionInsert });
actions.AddRange(new[] { actionInsertPrepared, actionInsertPrepared, actionSelect });
}
actions.Insert(8, () =>
{
Thread.Sleep(300);
testCluster.StopForce(2);
});
TestHelper.ParallelInvoke(actions.ToArray());
}
}
/// <summary>
/// Creates thousands of Session instances and checks memory consumption before and after Dispose and dereferencing
/// </summary>
[Test]
public void Memory_Consumption_After_Cluster_Dispose()
{
var testCluster = TestClusterManager.GetTestCluster(2, DefaultMaxClusterCreateRetries, true, false);
//Only warning as tracing through console slows it down.
var start = GC.GetTotalMemory(false);
long diff = 0;
Trace.TraceInformation("--Initial memory: {0}", start / 1024);
Action multipleConnect = () =>
{
var cluster = ClusterBuilder().AddContactPoint(testCluster.InitialContactPoint).Build();
for (var i = 0; i < 200; i++)
{
var session = cluster.Connect();
TestHelper.ParallelInvoke(() => session.Execute("select * from system.local"), 20);
}
Trace.TraceInformation("--Before disposing: {0}", GC.GetTotalMemory(false) / 1024);
cluster.Dispose();
Trace.TraceInformation("--After disposing: {0}", GC.GetTotalMemory(false) / 1024);
};
multipleConnect();
var handle = new AutoResetEvent(false);
//Collect all generations
GC.Collect();
//Wait 5 seconds for all the connections resources to be freed
Timer timer = null;
timer = new Timer(s =>
{
GC.Collect();
handle.Set();
diff = GC.GetTotalMemory(false) - start;
Trace.TraceInformation("--End, diff memory: {0}", diff / 1024);
var t = timer;
if (t != null)
{
t.Dispose();
}
}, null, 5000, Timeout.Infinite);
handle.WaitOne();
//the end memory usage can not be greater than double the start memory
//If there is a memory leak, it should be an order of magnitude greater...
Assert.Less(diff, start / 2);
}
public Action GetInsertAction(ISession session, object bindableStatement, ConsistencyLevel consistency, int rowsPerId)
{
Action action = () =>
{
Trace.TraceInformation("Starting inserting from thread {0}", Thread.CurrentThread.ManagedThreadId);
var id = Guid.NewGuid();
for (var i = 0; i < rowsPerId; i++)
{
var paramsArray = new object[] { id, DateTime.Now, DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) };
IStatement statement;
if (bindableStatement is SimpleStatement)
{
statement = new SimpleStatement(((SimpleStatement)bindableStatement).QueryString, paramsArray).SetConsistencyLevel(consistency);
}
else if (bindableStatement is PreparedStatement)
{
statement = ((PreparedStatement)bindableStatement).Bind(paramsArray).SetConsistencyLevel(consistency);
}
else
{
throw new Exception("Can not bind a statement of type " + bindableStatement.GetType().FullName);
}
session.Execute(statement);
}
Trace.TraceInformation("Finished inserting from thread {0}", Thread.CurrentThread.ManagedThreadId);
};
return action;
}
public Action GetSelectAction(ISession session, string query, ConsistencyLevel consistency, int executeLength)
{
Action action = () =>
{
for (var i = 0; i < executeLength; i++)
{
session.Execute(new SimpleStatement(query).SetPageSize(500).SetConsistencyLevel(consistency));
//Count will iterate through the result set and it will likely to page results
//Assert.True(rs.Count() > 0);
}
};
return action;
}
}
}
| |
using System;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// An abstract <see cref="Query"/> that matches documents
/// containing a subset of terms provided by a
/// <see cref="Index.FilteredTermsEnum"/> enumeration.
///
/// <para/>This query cannot be used directly; you must subclass
/// it and define <see cref="GetTermsEnum(Terms,AttributeSource)"/> to provide a
/// <see cref="Index.FilteredTermsEnum"/> that iterates through the terms to be
/// matched.
///
/// <para/><b>NOTE</b>: if <see cref="MultiTermRewriteMethod"/> is either
/// <see cref="CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE"/> or
/// <see cref="SCORING_BOOLEAN_QUERY_REWRITE"/>, you may encounter a
/// <see cref="BooleanQuery.TooManyClausesException"/> exception during
/// searching, which happens when the number of terms to be
/// searched exceeds
/// <see cref="BooleanQuery.MaxClauseCount"/>. Setting
/// <see cref="MultiTermRewriteMethod"/> to <see cref="CONSTANT_SCORE_FILTER_REWRITE"/>
/// prevents this.
///
/// <para/>The recommended rewrite method is
/// <see cref="CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>: it doesn't spend CPU
/// computing unhelpful scores, and it tries to pick the most
/// performant rewrite method given the query. If you
/// need scoring (like <seea cref="FuzzyQuery"/>, use
/// <see cref="TopTermsScoringBooleanQueryRewrite"/> which uses
/// a priority queue to only collect competitive terms
/// and not hit this limitation.
///
/// <para/>Note that QueryParsers.Classic.QueryParser produces
/// <see cref="MultiTermQuery"/>s using
/// <see cref="CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/> by default.
/// </summary>
public abstract class MultiTermQuery : Query
{
protected internal readonly string m_field;
protected RewriteMethod m_rewriteMethod = CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
/// <summary>
/// Abstract class that defines how the query is rewritten. </summary>
public abstract class RewriteMethod
{
public abstract Query Rewrite(IndexReader reader, MultiTermQuery query);
/// <summary>
/// Returns the <see cref="MultiTermQuery"/>s <see cref="TermsEnum"/> </summary>
/// <seealso cref="MultiTermQuery.GetTermsEnum(Terms, AttributeSource)"/>
protected virtual TermsEnum GetTermsEnum(MultiTermQuery query, Terms terms, AttributeSource atts)
{
return query.GetTermsEnum(terms, atts); // allow RewriteMethod subclasses to pull a TermsEnum from the MTQ
}
}
/// <summary>
/// A rewrite method that first creates a private <see cref="Filter"/>,
/// by visiting each term in sequence and marking all docs
/// for that term. Matching documents are assigned a
/// constant score equal to the query's boost.
///
/// <para/> This method is faster than the <see cref="BooleanQuery"/>
/// rewrite methods when the number of matched terms or
/// matched documents is non-trivial. Also, it will never
/// hit an errant <see cref="BooleanQuery.TooManyClausesException"/>
/// exception.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public static readonly RewriteMethod CONSTANT_SCORE_FILTER_REWRITE = new RewriteMethodAnonymousInnerClassHelper();
private class RewriteMethodAnonymousInnerClassHelper : RewriteMethod
{
public RewriteMethodAnonymousInnerClassHelper()
{
}
public override Query Rewrite(IndexReader reader, MultiTermQuery query)
{
Query result = new ConstantScoreQuery(new MultiTermQueryWrapperFilter<MultiTermQuery>(query));
result.Boost = query.Boost;
return result;
}
}
/// <summary>
/// A rewrite method that first translates each term into
/// <see cref="Occur.SHOULD"/> clause in a
/// <see cref="BooleanQuery"/>, and keeps the scores as computed by the
/// query. Note that typically such scores are
/// meaningless to the user, and require non-trivial CPU
/// to compute, so it's almost always better to use
/// <see cref="CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/> instead.
///
/// <para/><b>NOTE</b>: this rewrite method will hit
/// <see cref="BooleanQuery.TooManyClausesException"/> if the number of terms
/// exceeds <see cref="BooleanQuery.MaxClauseCount"/>.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public static readonly RewriteMethod SCORING_BOOLEAN_QUERY_REWRITE = ScoringRewrite<MultiTermQuery>.SCORING_BOOLEAN_QUERY_REWRITE;
/// <summary>
/// Like <see cref="SCORING_BOOLEAN_QUERY_REWRITE"/> except
/// scores are not computed. Instead, each matching
/// document receives a constant score equal to the
/// query's boost.
///
/// <para/><b>NOTE</b>: this rewrite method will hit
/// <see cref="BooleanQuery.TooManyClausesException"/> if the number of terms
/// exceeds <see cref="BooleanQuery.MaxClauseCount"/>.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public static readonly RewriteMethod CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE = ScoringRewrite<MultiTermQuery>.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
/// <summary>
/// A rewrite method that first translates each term into
/// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the
/// scores as computed by the query.
///
/// <para/>
/// This rewrite method only uses the top scoring terms so it will not overflow
/// the boolean max clause count. It is the default rewrite method for
/// <see cref="FuzzyQuery"/>.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public sealed class TopTermsScoringBooleanQueryRewrite : TopTermsRewrite<BooleanQuery>
{
/// <summary>
/// Create a <see cref="TopTermsScoringBooleanQueryRewrite"/> for
/// at most <paramref name="size"/> terms.
/// <para/>
/// NOTE: if <see cref="BooleanQuery.MaxClauseCount"/> is smaller than
/// <paramref name="size"/>, then it will be used instead.
/// </summary>
public TopTermsScoringBooleanQueryRewrite(int size)
: base(size)
{
}
protected override int MaxSize => BooleanQuery.MaxClauseCount;
protected override BooleanQuery GetTopLevelQuery()
{
return new BooleanQuery(true);
}
protected override void AddClause(BooleanQuery topLevel, Term term, int docCount, float boost, TermContext states)
{
TermQuery tq = new TermQuery(term, states);
tq.Boost = boost;
topLevel.Add(tq, Occur.SHOULD);
}
}
/// <summary>
/// A rewrite method that first translates each term into
/// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, but the scores
/// are only computed as the boost.
/// <para/>
/// This rewrite method only uses the top scoring terms so it will not overflow
/// the boolean max clause count.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public sealed class TopTermsBoostOnlyBooleanQueryRewrite : TopTermsRewrite<BooleanQuery>
{
/// <summary>
/// Create a <see cref="TopTermsBoostOnlyBooleanQueryRewrite"/> for
/// at most <paramref name="size"/> terms.
/// <para/>
/// NOTE: if <see cref="BooleanQuery.MaxClauseCount"/> is smaller than
/// <paramref name="size"/>, then it will be used instead.
/// </summary>
public TopTermsBoostOnlyBooleanQueryRewrite(int size)
: base(size)
{
}
protected override int MaxSize => BooleanQuery.MaxClauseCount;
protected override BooleanQuery GetTopLevelQuery()
{
return new BooleanQuery(true);
}
protected override void AddClause(BooleanQuery topLevel, Term term, int docFreq, float boost, TermContext states)
{
Query q = new ConstantScoreQuery(new TermQuery(term, states));
q.Boost = boost;
topLevel.Add(q, Occur.SHOULD);
}
}
// LUCENENET specific - just use the non-nested class directly. This is
// confusing in .NET.
// /// <summary>
// /// A rewrite method that tries to pick the best
// /// constant-score rewrite method based on term and
// /// document counts from the query. If both the number of
// /// terms and documents is small enough, then
// /// <see cref="CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE"/> is used.
// /// Otherwise, <see cref="CONSTANT_SCORE_FILTER_REWRITE"/> is
// /// used.
// /// </summary>
// public class ConstantScoreAutoRewrite : Lucene.Net.Search.ConstantScoreAutoRewrite
// {
// }
/// <summary>
/// Read-only default instance of
/// <see cref="ConstantScoreAutoRewrite"/>, with
/// <see cref="Search.ConstantScoreAutoRewrite.TermCountCutoff"/> set to
/// <see cref="Search.ConstantScoreAutoRewrite.DEFAULT_TERM_COUNT_CUTOFF"/>
/// and
/// <see cref="Search.ConstantScoreAutoRewrite.DocCountPercent"/> set to
/// <see cref="Search.ConstantScoreAutoRewrite.DEFAULT_DOC_COUNT_PERCENT"/>.
/// Note that you cannot alter the configuration of this
/// instance; you'll need to create a private instance
/// instead.
/// </summary>
public static readonly RewriteMethod CONSTANT_SCORE_AUTO_REWRITE_DEFAULT = new ConstantScoreAutoRewriteAnonymousInnerClassHelper();
private class ConstantScoreAutoRewriteAnonymousInnerClassHelper : ConstantScoreAutoRewrite
{
public ConstantScoreAutoRewriteAnonymousInnerClassHelper()
{
}
public override int TermCountCutoff
{
get => base.TermCountCutoff; // LUCENENET specific - adding getter for API consistency check
set => throw new NotSupportedException("Please create a private instance");
}
public override double DocCountPercent
{
get => base.DocCountPercent; // LUCENENET specific - adding getter for API consistency check
set => throw new NotSupportedException("Please create a private instance");
}
}
/// <summary>
/// Constructs a query matching terms that cannot be represented with a single
/// <see cref="Term"/>.
/// </summary>
public MultiTermQuery(string field)
{
this.m_field = field ?? throw new ArgumentNullException(nameof(field), "field must not be null");
}
/// <summary>
/// Returns the field name for this query </summary>
public string Field => m_field;
/// <summary>
/// Construct the enumeration to be used, expanding the
/// pattern term. this method should only be called if
/// the field exists (ie, implementations can assume the
/// field does exist). this method should not return null
/// (should instead return <see cref="TermsEnum.EMPTY"/> if no
/// terms match). The <see cref="TermsEnum"/> must already be
/// positioned to the first matching term.
/// The given <see cref="AttributeSource"/> is passed by the <see cref="RewriteMethod"/> to
/// provide attributes, the rewrite method uses to inform about e.g. maximum competitive boosts.
/// this is currently only used by <see cref="TopTermsRewrite{Q}"/>.
/// </summary>
protected abstract TermsEnum GetTermsEnum(Terms terms, AttributeSource atts);
/// <summary>
/// Convenience method, if no attributes are needed:
/// this simply passes empty attributes and is equal to:
/// <code>GetTermsEnum(terms, new AttributeSource())</code>
/// </summary>
public TermsEnum GetTermsEnum(Terms terms)
{
return GetTermsEnum(terms, new AttributeSource());
}
/// <summary>
/// To rewrite to a simpler form, instead return a simpler
/// enum from <see cref="GetTermsEnum(Terms, AttributeSource)"/>. For example,
/// to rewrite to a single term, return a <see cref="Index.SingleTermsEnum"/>.
/// </summary>
public override sealed Query Rewrite(IndexReader reader)
{
return m_rewriteMethod.Rewrite(reader, this);
}
// LUCENENET NOTE: Renamed from RewriteMethod to prevent a naming
// conflict with the RewriteMethod class. MultiTermRewriteMethod is consistent
// with the name used in QueryParserBase.
/// <summary>
/// Gets or Sets the rewrite method to be used when executing the
/// query. You can use one of the four core methods, or
/// implement your own subclass of <see cref="RewriteMethod"/>.
/// </summary>
public virtual RewriteMethod MultiTermRewriteMethod
{
get => m_rewriteMethod;
set => m_rewriteMethod = value;
}
public override int GetHashCode()
{
const int prime = 31;
int result = 1;
result = prime * result + J2N.BitConversion.SingleToInt32Bits(Boost);
result = prime * result + m_rewriteMethod.GetHashCode();
if (m_field != null)
{
result = prime * result + m_field.GetHashCode();
}
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
MultiTermQuery other = (MultiTermQuery)obj;
if (J2N.BitConversion.SingleToInt32Bits(Boost) != J2N.BitConversion.SingleToInt32Bits(other.Boost))
{
return false;
}
if (!m_rewriteMethod.Equals(other.m_rewriteMethod))
{
return false;
}
return (other.m_field == null ? m_field == null : other.m_field.Equals(m_field, StringComparison.Ordinal));
}
}
}
| |
/*
* 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
* 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;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BulkEnvelopeStatus
/// </summary>
[DataContract]
public partial class BulkEnvelopeStatus : IEquatable<BulkEnvelopeStatus>, IValidatableObject
{
public BulkEnvelopeStatus()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BulkEnvelopeStatus" /> class.
/// </summary>
/// <param name="BatchId">Specifies an identifier which can be used to retrieve a more detailed status of individual bulk recipient batches..</param>
/// <param name="BatchSize">The number of items returned in this response..</param>
/// <param name="BulkEnvelopes">Reserved: TBD.</param>
/// <param name="BulkEnvelopesBatchUri">Reserved: TBD.</param>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="Failed">The number of entries with a status of failed. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="Queued">The number of entries with a status of queued. .</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="Sent">The number of entries with a status of sent..</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="SubmittedDate">.</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public BulkEnvelopeStatus(string BatchId = default(string), string BatchSize = default(string), List<BulkEnvelope> BulkEnvelopes = default(List<BulkEnvelope>), string BulkEnvelopesBatchUri = default(string), string EndPosition = default(string), string Failed = default(string), string NextUri = default(string), string PreviousUri = default(string), string Queued = default(string), string ResultSetSize = default(string), string Sent = default(string), string StartPosition = default(string), string SubmittedDate = default(string), string TotalSetSize = default(string))
{
this.BatchId = BatchId;
this.BatchSize = BatchSize;
this.BulkEnvelopes = BulkEnvelopes;
this.BulkEnvelopesBatchUri = BulkEnvelopesBatchUri;
this.EndPosition = EndPosition;
this.Failed = Failed;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.Queued = Queued;
this.ResultSetSize = ResultSetSize;
this.Sent = Sent;
this.StartPosition = StartPosition;
this.SubmittedDate = SubmittedDate;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// Specifies an identifier which can be used to retrieve a more detailed status of individual bulk recipient batches.
/// </summary>
/// <value>Specifies an identifier which can be used to retrieve a more detailed status of individual bulk recipient batches.</value>
[DataMember(Name="batchId", EmitDefaultValue=false)]
public string BatchId { get; set; }
/// <summary>
/// The number of items returned in this response.
/// </summary>
/// <value>The number of items returned in this response.</value>
[DataMember(Name="batchSize", EmitDefaultValue=false)]
public string BatchSize { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="bulkEnvelopes", EmitDefaultValue=false)]
public List<BulkEnvelope> BulkEnvelopes { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="bulkEnvelopesBatchUri", EmitDefaultValue=false)]
public string BulkEnvelopesBatchUri { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The number of entries with a status of failed.
/// </summary>
/// <value>The number of entries with a status of failed. </value>
[DataMember(Name="failed", EmitDefaultValue=false)]
public string Failed { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of entries with a status of queued.
/// </summary>
/// <value>The number of entries with a status of queued. </value>
[DataMember(Name="queued", EmitDefaultValue=false)]
public string Queued { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// The number of entries with a status of sent.
/// </summary>
/// <value>The number of entries with a status of sent.</value>
[DataMember(Name="sent", EmitDefaultValue=false)]
public string Sent { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="submittedDate", EmitDefaultValue=false)]
public string SubmittedDate { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { 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 BulkEnvelopeStatus {\n");
sb.Append(" BatchId: ").Append(BatchId).Append("\n");
sb.Append(" BatchSize: ").Append(BatchSize).Append("\n");
sb.Append(" BulkEnvelopes: ").Append(BulkEnvelopes).Append("\n");
sb.Append(" BulkEnvelopesBatchUri: ").Append(BulkEnvelopesBatchUri).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" Failed: ").Append(Failed).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" Queued: ").Append(Queued).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" Sent: ").Append(Sent).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" SubmittedDate: ").Append(SubmittedDate).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).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 BulkEnvelopeStatus);
}
/// <summary>
/// Returns true if BulkEnvelopeStatus instances are equal
/// </summary>
/// <param name="other">Instance of BulkEnvelopeStatus to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkEnvelopeStatus other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BatchId == other.BatchId ||
this.BatchId != null &&
this.BatchId.Equals(other.BatchId)
) &&
(
this.BatchSize == other.BatchSize ||
this.BatchSize != null &&
this.BatchSize.Equals(other.BatchSize)
) &&
(
this.BulkEnvelopes == other.BulkEnvelopes ||
this.BulkEnvelopes != null &&
this.BulkEnvelopes.SequenceEqual(other.BulkEnvelopes)
) &&
(
this.BulkEnvelopesBatchUri == other.BulkEnvelopesBatchUri ||
this.BulkEnvelopesBatchUri != null &&
this.BulkEnvelopesBatchUri.Equals(other.BulkEnvelopesBatchUri)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.Failed == other.Failed ||
this.Failed != null &&
this.Failed.Equals(other.Failed)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.Queued == other.Queued ||
this.Queued != null &&
this.Queued.Equals(other.Queued)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.Sent == other.Sent ||
this.Sent != null &&
this.Sent.Equals(other.Sent)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.SubmittedDate == other.SubmittedDate ||
this.SubmittedDate != null &&
this.SubmittedDate.Equals(other.SubmittedDate)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <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.BatchId != null)
hash = hash * 59 + this.BatchId.GetHashCode();
if (this.BatchSize != null)
hash = hash * 59 + this.BatchSize.GetHashCode();
if (this.BulkEnvelopes != null)
hash = hash * 59 + this.BulkEnvelopes.GetHashCode();
if (this.BulkEnvelopesBatchUri != null)
hash = hash * 59 + this.BulkEnvelopesBatchUri.GetHashCode();
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.Failed != null)
hash = hash * 59 + this.Failed.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.Queued != null)
hash = hash * 59 + this.Queued.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.Sent != null)
hash = hash * 59 + this.Sent.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.SubmittedDate != null)
hash = hash * 59 + this.SubmittedDate.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// <copyright file="IPlayGamesClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using UnityEngine;
using UnityEngine.SocialPlatforms;
/// <summary>
/// Defines an abstract interface for a Play Games Client.
/// </summary>
/// <remarks>Concrete implementations
/// might be, for example, the client for Android or for iOS. One fundamental concept
/// that implementors of this class must adhere to is stable authentication state.
/// This means that once Authenticate() returns true through its callback, the user is
/// considered to be forever after authenticated while the app is running. The implementation
/// must make sure that this is the case -- for example, it must try to silently
/// re-authenticate the user if authentication is lost or wait for the authentication
/// process to get fixed if it is temporarily in a bad state (such as when the
/// Activity in Android has just been brought to the foreground and the connection to
/// the Games services hasn't yet been established). To the user of this
/// interface, once the user is authenticated, they're forever authenticated.
/// Unless, of course, there is an unusual permanent failure such as the underlying
/// service dying, in which it's acceptable that API method calls will fail.
///
/// <para>All methods can be called from the game thread. The user of this interface
/// DOES NOT NEED to call them from the UI thread of the game. Transferring to the UI
/// thread when necessary is a responsibility of the implementors of this interface.</para>
///
/// <para>CALLBACKS: all callbacks must be invoked in Unity's main thread.
/// Implementors of this interface must guarantee that (suggestion: use
/// <see cref="GooglePlayGames.OurUtils.RunOnGameThread(System.Action action)"/>).</para>
/// </remarks>
public interface IPlayGamesClient
{
/// <summary>
/// Starts the authentication process.
/// </summary>
/// <remarks>If silent == true, no UIs will be shown
/// (if UIs are needed, it will fail rather than show them). If silent == false,
/// this may show UIs, consent dialogs, etc.
/// At the end of the process, callback will be invoked to notify of the result.
/// Once the callback returns true, the user is considered to be authenticated
/// forever after.
/// </remarks>
/// <param name="callback">Callback.</param>
/// <param name="silent">If set to <c>true</c> silent.</param>
void Authenticate(System.Action<bool> callback, bool silent);
/// <summary>
/// Returns whether or not user is authenticated.
/// </summary>
/// <returns><c>true</c> if the user is authenticated; otherwise, <c>false</c>.</returns>
bool IsAuthenticated();
/// <summary>
/// Signs the user out.
/// </summary>
void SignOut();
/// <summary>Retrieves an OAuth 2.0 bearer token for the client.</summary>
/// <returns>A string representing the bearer token.</returns>
string GetToken();
/// <summary>
/// Returns the authenticated user's ID. Note that this value may change if a user signs
/// on and signs in with a different account.
/// </summary>
/// <returns>The user's ID, <code>null</code> if the user is not logged in.</returns>
string GetUserId();
/// <summary>
/// Load friends of the authenticated user.
/// </summary>
/// <param name="callback">Callback invoked when complete. bool argument
/// indicates success.</param>
void LoadFriends(Action<bool> callback);
/// <summary>
/// Returns a human readable name for the user, if they are logged in.
/// </summary>
/// <returns>The user's human-readable name. <code>null</code> if they are not logged
/// in</returns>
string GetUserDisplayName();
/// <summary>
/// Returns an id token, which can be verified server side, if they are logged in.
/// </summary>
/// <param name="idTokenCallback"> A callback to be invoked after token is retrieved. Will be passed null value
/// on failure. </param>
void GetIdToken(Action<string> idTokenCallback);
/// <summary>
/// Gets an access token.
/// </summary>
/// <returns>An it token. <code>null</code> if they are not logged
/// in</returns>
string GetAccessToken();
/// <summary>
/// Asynchronously retrieves the server auth code for this client.
/// </summary>
/// <remarks>
/// Note: This function is currently only implemented for Android.
/// </remarks>
/// <param name="serverClientId">The Client ID.</param>
/// <param name="callback">Callback for response.</param>
void GetServerAuthCode(string serverClientId, Action<CommonStatusCodes, string> callback);
/// <summary>
/// Gets the user email.
/// </summary>
/// <returns>The user email or null if not authenticated or the permission is
/// not available.</returns>
string GetUserEmail();
/// <summary>
/// Returns the user's avatar url, if they are logged in and have an avatar.
/// </summary>
/// <returns>The URL to load the avatar image. <code>null</code> if they are not logged
/// in</returns>
string GetUserImageUrl();
/// <summary>Gets the player stats.</summary>
/// <param name="callback">Callback for response.</param>
void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback);
/// <summary>
/// Loads the users specified. This is mainly used by the leaderboard
/// APIs to get the information of a high scorer.
/// </summary>
/// <param name="userIds">User identifiers.</param>
/// <param name="callback">Callback.</param>
void LoadUsers(string[] userIds, Action<IUserProfile[]> callback);
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>The achievement corresponding to the identifer. <code>null</code> if no such
/// achievement is found or if authentication has not occurred.</returns>
/// <param name="achievementId">The identifier of the achievement.</param>
Achievement GetAchievement(string achievementId);
/// <summary>
/// Loads the achievements for the current signed in user and invokes
/// the callback.
/// </summary>
void LoadAchievements(Action<Achievement[]> callback);
/// <summary>
/// Unlocks the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the callback
/// will be invoked on the game thread with <code>true</code>. If the operation fails, the
/// callback will be invoked with <code>false</code>. This operation will immediately fail if
/// the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>). If the achievement is already unlocked, this call will
/// succeed immediately.
/// </remarks>
/// <param name="achievementId">The ID of the achievement to unlock.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void UnlockAchievement(string achievementId, Action<bool> successOrFailureCalllback);
/// <summary>
/// Reveals the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the callback
/// will be invoked on the game thread with <code>true</code>. If the operation fails, the
/// callback will be invoked with <code>false</code>. This operation will immediately fail if
/// the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>). If the achievement is already in a revealed state, this call will
/// succeed immediately.
/// </remarks>
/// <param name="achievementId">The ID of the achievement to reveal.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void RevealAchievement(string achievementId, Action<bool> successOrFailureCalllback);
/// <summary>
/// Increments the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the
/// callback will be invoked on the game thread with <code>true</code>. If the operation fails,
/// the callback will be invoked with <code>false</code>. This operation will immediately fail
/// if the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>).
/// </remarks>
/// <param name="achievementId">The ID of the achievement to increment.</param>
/// <param name="steps">The number of steps to increment by.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void IncrementAchievement(string achievementId, int steps,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// </summary>
/// <remarks>
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </remarks>
/// <param name="achId">Ach identifier.</param>
/// <param name="steps">Steps.</param>
/// <param name="callback">Callback.</param>
void SetStepsAtLeast(string achId, int steps, Action<bool> callback);
/// <summary>
/// Shows the appropriate platform-specific achievements UI.
/// <param name="callback">The callback to invoke when complete. If null,
/// no callback is called. </param>
/// </summary>
void ShowAchievementsUI(Action<UIStatus> callback);
/// <summary>
/// Shows the leaderboard UI for a specific leaderboard.
/// </summary>
/// <remarks>If the passed ID is <code>null</code>, all leaderboards are displayed.
/// </remarks>
/// <param name="leaderboardId">The leaderboard to display. <code>null</code> to display
/// all.</param>
/// <param name="span">Timespan to display for the leaderboard</param>
/// <param name="callback">If non-null, the callback to invoke when the
/// leaderboard is dismissed.
/// </param>
void ShowLeaderboardUI(string leaderboardId,
LeaderboardTimeSpan span,
Action<UIStatus> callback);
/// <summary>
/// Loads the score data for the given leaderboard.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start indicating the top scores or player centric</param>
/// <param name="rowCount">max number of scores to return. non-positive indicates
// no rows should be returned. This causes only the summary info to
/// be loaded. This can be limited
// by the SDK.</param>
/// <param name="collection">leaderboard collection: public or social</param>
/// <param name="timeSpan">leaderboard timespan</param>
/// <param name="callback">callback with the scores, and a page token.
/// The token can be used to load next/prev pages.</param>
void LoadScores(string leaderboardId, LeaderboardStart start,
int rowCount, LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback);
/// <summary>
/// Loads the more scores for the leaderboard.
/// </summary>
/// <remarks>The token is accessed
/// by calling LoadScores() with a positive row count.
/// </remarks>
/// <param name="token">Token for tracking the score loading.</param>
/// <param name="rowCount">max number of scores to return.
/// This can be limited by the SDK.</param>
/// <param name="callback">Callback.</param>
void LoadMoreScores(ScorePageToken token, int rowCount,
Action<LeaderboardScoreData> callback);
/// <summary>
/// Returns the max number of scores returned per call.
/// </summary>
/// <returns>The max results.</returns>
int LeaderboardMaxResults();
/// <summary>
/// Submits the passed score to the passed leaderboard.
/// </summary>
/// <remarks>This operation will immediately fail
/// if the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>).
/// </remarks>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void SubmitScore(string leaderboardId, long score,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Submits the score for the currently signed-in player.
/// </summary>
/// <param name="score">Score.</param>
/// <param name="board">leaderboard id.</param>
/// <param name="metadata">metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
void SubmitScore(string leaderboardId, long score, string metadata,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Returns a real-time multiplayer client.
/// </summary>
/// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"/>
/// <returns>The rtmp client.</returns>
IRealTimeMultiplayerClient GetRtmpClient();
/// <summary>
/// Returns a turn-based multiplayer client.
/// </summary>
/// <returns>The tbmp client.</returns>
ITurnBasedMultiplayerClient GetTbmpClient();
/// <summary>
/// Gets the saved game client.
/// </summary>
/// <returns>The saved game client.</returns>
SavedGame.ISavedGameClient GetSavedGameClient();
/// <summary>
/// Gets the events client.
/// </summary>
/// <returns>The events client.</returns>
Events.IEventsClient GetEventsClient();
/// <summary>
/// Gets the quests client.
/// </summary>
/// <returns>The quests client.</returns>
Quests.IQuestsClient GetQuestsClient();
/// <summary>
/// Registers the invitation delegate.
/// </summary>
/// <param name="invitationDelegate">Invitation delegate.</param>
void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate);
IUserProfile[] GetFriends();
/// <summary>
/// Gets the Android API client. Returns null on non-Android players.
/// </summary>
/// <returns>The API client.</returns>
IntPtr GetApiClient();
}
/// <summary>
/// Delegate that handles an incoming invitation (for both RTMP and TBMP).
/// </summary>
/// <param name="invitation">The invitation received.</param>
/// <param name="shouldAutoAccept">If this is true, then the game should immediately
/// accept the invitation and go to the game screen without prompting the user. If
/// false, you should prompt the user before accepting the invitation. As an example,
/// when a user taps on the "Accept" button on a notification in Android, it is
/// clear that they want to accept that invitation right away, so the plugin calls this
/// delegate with shouldAutoAccept = true. However, if we receive an incoming invitation
/// that the player hasn't specifically indicated they wish to accept (for example,
/// we received one in the background from the server), this delegate will be called
/// with shouldAutoAccept=false to indicate that you should confirm with the user
/// to see if they wish to accept or decline the invitation.</param>
public delegate void InvitationReceivedDelegate(Invitation invitation, bool shouldAutoAccept);
}
#endif
| |
//-----------------------------------------------------------------------
// <copyright file="OutputStreamSourceSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.IO;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.IO;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.IO
{
public class OutputStreamSourceSpec : AkkaSpec
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3);
private readonly ActorMaterializer _materializer;
private readonly byte[] _bytesArray;
private readonly ByteString _byteString;
public OutputStreamSourceSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper)
{
Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig());
var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher");
_materializer = Sys.Materializer(settings);
_bytesArray = new[]
{
Convert.ToByte(new Random().Next(256)),
Convert.ToByte(new Random().Next(256)),
Convert.ToByte(new Random().Next(256))
};
_byteString = ByteString.Create(_bytesArray);
}
private void ExpectTimeout(Task f, TimeSpan duration) => f.Wait(duration).Should().BeFalse();
private void ExpectSuccess<T>(Task<T> f, T value)
{
f.Wait(RemainingOrDefault).Should().BeTrue();
f.Result.Should().Be(value);
}
[Fact]
public void OutputStreamSource_must_read_bytes_from_OutputStream()
{
this.AssertAllStagesStopped(() =>
{
var t = StreamConverters.AsOutputStream()
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = t.Item1;
var probe = t.Item2;
var s = probe.ExpectSubscription();
outputStream.Write(_bytesArray, 0, _bytesArray.Length);
s.Request(1);
probe.ExpectNext(_byteString);
outputStream.Dispose();
probe.ExpectComplete();
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_block_flush_call_until_send_all_buffer_to_downstream()
{
this.AssertAllStagesStopped(() =>
{
var t = StreamConverters.AsOutputStream()
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = t.Item1;
var probe = t.Item2;
var s = probe.ExpectSubscription();
outputStream.Write(_bytesArray, 0, _bytesArray.Length);
var f = Task.Run(() =>
{
outputStream.Flush();
return NotUsed.Instance;
});
ExpectTimeout(f, Timeout);
probe.ExpectNoMsg(TimeSpan.MinValue);
s.Request(1);
ExpectSuccess(f, NotUsed.Instance);
probe.ExpectNext(_byteString);
outputStream.Dispose();
probe.ExpectComplete();
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_not_block_flushes_when_buffer_is_empty()
{
this.AssertAllStagesStopped(() =>
{
var t = StreamConverters.AsOutputStream()
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = t.Item1;
var probe = t.Item2;
var s = probe.ExpectSubscription();
outputStream.Write(_bytesArray, 0, _byteString.Count);
var f = Task.Run(() =>
{
outputStream.Flush();
return NotUsed.Instance;
});
s.Request(1);
ExpectSuccess(f, NotUsed.Instance);
probe.ExpectNext(_byteString);
var f2 = Task.Run(() =>
{
outputStream.Flush();
return NotUsed.Instance;
});
ExpectSuccess(f2, NotUsed.Instance);
outputStream.Dispose();
probe.ExpectComplete();
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_block_writes_when_buffer_is_full()
{
this.AssertAllStagesStopped(() =>
{
var t = StreamConverters.AsOutputStream()
.WithAttributes(Attributes.CreateInputBuffer(16, 16))
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = t.Item1;
var probe = t.Item2;
var s = probe.ExpectSubscription();
for (var i = 1; i <= 16; i++)
outputStream.Write(_bytesArray, 0, _byteString.Count);
//blocked call
var f = Task.Run(() =>
{
outputStream.Write(_bytesArray, 0, _byteString.Count);
return NotUsed.Instance;
});
ExpectTimeout(f, Timeout);
probe.ExpectNoMsg(TimeSpan.MinValue);
s.Request(17);
ExpectSuccess(f, NotUsed.Instance);
probe.ExpectNextN(Enumerable.Repeat(_byteString, 17).ToList());
outputStream.Dispose();
probe.ExpectComplete();
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_throw_error_when_writer_after_stream_is_closed()
{
this.AssertAllStagesStopped(() =>
{
var t = StreamConverters.AsOutputStream()
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = t.Item1;
var probe = t.Item2;
probe.ExpectSubscription();
outputStream.Dispose();
probe.ExpectComplete();
outputStream.Invoking(s => s.Write(_bytesArray, 0, _byteString.Count)).ShouldThrow<IOException>();
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_use_dedicated_default_blocking_io_dispatcher_by_default()
{
this.AssertAllStagesStopped(() =>
{
var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig);
var materializer = sys.Materializer();
try
{
StreamConverters.AsOutputStream().RunWith(this.SinkProbe<ByteString>(), materializer);
((ActorMaterializerImpl) materializer).Supervisor.Tell(StreamSupervisor.GetChildren.Instance,
TestActor);
var actorRef = ExpectMsg<StreamSupervisor.Children>()
.Refs.First(c => c.Path.ToString().Contains("outputStreamSource"));
Utils.AssertDispatcher(actorRef, "akka.stream.default-blocking-io-dispatcher");
}
finally
{
Shutdown(sys);
}
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_throw_IOException_when_writing_to_the_stream_after_the_subscriber_has_cancelled_the_reactive_stream()
{
this.AssertAllStagesStopped(() =>
{
var sourceProbe = CreateTestProbe();
var t =
TestSourceStage<ByteString, Stream>.Create(new OutputStreamSourceStage(Timeout), sourceProbe)
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = t.Item1;
var probe = t.Item2;
var s = probe.ExpectSubscription();
outputStream.Write(_bytesArray, 0, _bytesArray.Length);
s.Request(1);
sourceProbe.ExpectMsg<GraphStageMessages.Pull>();
probe.ExpectNext(_byteString);
s.Cancel();
sourceProbe.ExpectMsg<GraphStageMessages.DownstreamFinish>();
Thread.Sleep(500);
outputStream.Invoking(os => os.Write(_bytesArray, 0, _bytesArray.Length)).ShouldThrow<IOException>();
}, _materializer);
}
[Fact]
public void OutputStreamSource_must_fail_to_materialize_with_zero_sized_input_buffer()
{
new Action(
() =>
StreamConverters.AsOutputStream(Timeout)
.WithAttributes(Attributes.CreateInputBuffer(0, 0))
.RunWith(Sink.First<ByteString>(), _materializer)).ShouldThrow<ArgumentException>();
/*
With Sink.First we test the code path in which the source
itself throws an exception when being materialized. If
Sink.Ignore is used, the same exception is thrown by
Materializer.
*/
}
[Fact]
public void OutputStreamSource_must_not_leave_blocked_threads()
{
var tuple =
StreamConverters.AsOutputStream(Timeout)
.ToMaterialized(this.SinkProbe<ByteString>(), Keep.Both)
.Run(_materializer);
var outputStream = tuple.Item1;
var probe = tuple.Item2;
var sub = probe.ExpectSubscription();
// triggers a blocking read on the queue
// and then cancel the stage before we got anything
sub.Request(1);
sub.Cancel();
//we need to make sure that the underling BlockingCollection isn't blocked after the stream has finished,
//the jvm way isn't working so we need to use reflection and check the collection directly
//def threadsBlocked =
//ManagementFactory.getThreadMXBean.dumpAllThreads(true, true).toSeq
// .filter(t => t.getThreadName.startsWith("OutputStreamSourceSpec") &&
//t.getLockName != null &&
//t.getLockName.startsWith("java.util.concurrent.locks.AbstractQueuedSynchronizer"))
//awaitAssert(threadsBlocked should === (Seq()), 3.seconds)
var bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static;
var field = typeof(OutputStreamAdapter).GetField("_dataQueue", bindFlags);
var blockingCollection = field.GetValue(outputStream) as BlockingCollection<ByteString>;
//give the stage enough time to finish, otherwise it may take the hello message
Thread.Sleep(1000);
// if a take operation is pending inside the stage it will steal this one and the next take will not succeed
blockingCollection.Add(ByteString.FromString("hello"));
ByteString result;
blockingCollection.TryTake(out result, TimeSpan.FromSeconds(3)).Should().BeTrue();
result.DecodeString().Should().Be("hello");
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using HtcSharp.HttpModule.Core.Internal.Http;
namespace HtcSharp.HttpModule.Core.Internal.Http2 {
// SourceTools-Start
// Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Http2\Http2FrameReader.cs
// Start-At-Remote-Line 12
// SourceTools-End
internal static class Http2FrameReader {
/* https://tools.ietf.org/html/rfc7540#section-4.1
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+=+=============================================================+
| Frame Payload (0...) ...
+---------------------------------------------------------------+
*/
public const int HeaderLength = 9;
private const int TypeOffset = 3;
private const int FlagsOffset = 4;
private const int StreamIdOffset = 5;
public const int SettingSize = 6; // 2 bytes for the id, 4 bytes for the value.
public static bool ReadFrame(in ReadOnlySequence<byte> readableBuffer, Http2Frame frame, uint maxFrameSize, out ReadOnlySequence<byte> framePayload) {
framePayload = ReadOnlySequence<byte>.Empty;
if (readableBuffer.Length < HeaderLength) {
return false;
}
var headerSlice = readableBuffer.Slice(0, HeaderLength);
var header = headerSlice.ToSpan();
var payloadLength = (int)Bitshifter.ReadUInt24BigEndian(header);
if (payloadLength > maxFrameSize) {
throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorFrameOverLimit(payloadLength, maxFrameSize), Http2ErrorCode.FRAME_SIZE_ERROR);
}
// Make sure the whole frame is buffered
var frameLength = HeaderLength + payloadLength;
if (readableBuffer.Length < frameLength) {
return false;
}
frame.PayloadLength = payloadLength;
frame.Type = (Http2FrameType)header[TypeOffset];
frame.Flags = header[FlagsOffset];
frame.StreamId = (int)Bitshifter.ReadUInt31BigEndian(header.Slice(StreamIdOffset));
var extendedHeaderLength = ReadExtendedFields(frame, readableBuffer);
// The remaining payload minus the extra fields
framePayload = readableBuffer.Slice(HeaderLength + extendedHeaderLength, payloadLength - extendedHeaderLength);
return true;
}
private static int ReadExtendedFields(Http2Frame frame, in ReadOnlySequence<byte> readableBuffer) {
// Copy in any extra fields for the given frame type
var extendedHeaderLength = GetPayloadFieldsLength(frame);
if (extendedHeaderLength > frame.PayloadLength) {
throw new Http2ConnectionErrorException(
CoreStrings.FormatHttp2ErrorUnexpectedFrameLength(frame.Type, expectedLength: extendedHeaderLength), Http2ErrorCode.FRAME_SIZE_ERROR);
}
var extendedHeaders = readableBuffer.Slice(HeaderLength, extendedHeaderLength).ToSpan();
// Parse frame type specific fields
switch (frame.Type) {
/*
+---------------+
|Pad Length? (8)|
+---------------+-----------------------------------------------+
| Data (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
*/
case Http2FrameType.DATA: // Variable 0 or 1
frame.DataPadLength = frame.DataHasPadding ? extendedHeaders[0] : (byte)0;
break;
/* https://tools.ietf.org/html/rfc7540#section-6.2
+---------------+
|Pad Length? (8)|
+-+-------------+-----------------------------------------------+
|E| Stream Dependency? (31) |
+-+-------------+-----------------------------------------------+
| Weight? (8) |
+-+-------------+-----------------------------------------------+
| Header Block Fragment (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
*/
case Http2FrameType.HEADERS:
if (frame.HeadersHasPadding) {
frame.HeadersPadLength = extendedHeaders[0];
extendedHeaders = extendedHeaders.Slice(1);
} else {
frame.HeadersPadLength = 0;
}
if (frame.HeadersHasPriority) {
frame.HeadersStreamDependency = (int)Bitshifter.ReadUInt31BigEndian(extendedHeaders);
frame.HeadersPriorityWeight = extendedHeaders.Slice(4)[0];
} else {
frame.HeadersStreamDependency = 0;
frame.HeadersPriorityWeight = 0;
}
break;
/* https://tools.ietf.org/html/rfc7540#section-6.8
+-+-------------------------------------------------------------+
|R| Last-Stream-ID (31) |
+-+-------------------------------------------------------------+
| Error Code (32) |
+---------------------------------------------------------------+
| Additional Debug Data (*) |
+---------------------------------------------------------------+
*/
case Http2FrameType.GOAWAY:
frame.GoAwayLastStreamId = (int)Bitshifter.ReadUInt31BigEndian(extendedHeaders);
frame.GoAwayErrorCode = (Http2ErrorCode)BinaryPrimitives.ReadUInt32BigEndian(extendedHeaders.Slice(4));
break;
/* https://tools.ietf.org/html/rfc7540#section-6.3
+-+-------------------------------------------------------------+
|E| Stream Dependency (31) |
+-+-------------+-----------------------------------------------+
| Weight (8) |
+-+-------------+
*/
case Http2FrameType.PRIORITY:
frame.PriorityStreamDependency = (int)Bitshifter.ReadUInt31BigEndian(extendedHeaders);
frame.PriorityWeight = extendedHeaders.Slice(4)[0];
break;
/* https://tools.ietf.org/html/rfc7540#section-6.4
+---------------------------------------------------------------+
| Error Code (32) |
+---------------------------------------------------------------+
*/
case Http2FrameType.RST_STREAM:
frame.RstStreamErrorCode = (Http2ErrorCode)BinaryPrimitives.ReadUInt32BigEndian(extendedHeaders);
break;
/* https://tools.ietf.org/html/rfc7540#section-6.9
+-+-------------------------------------------------------------+
|R| Window Size Increment (31) |
+-+-------------------------------------------------------------+
*/
case Http2FrameType.WINDOW_UPDATE:
frame.WindowUpdateSizeIncrement = (int)Bitshifter.ReadUInt31BigEndian(extendedHeaders);
break;
case Http2FrameType.PING: // Opaque payload 8 bytes long
case Http2FrameType.SETTINGS: // Settings are general payload
case Http2FrameType.CONTINUATION: // None
case Http2FrameType.PUSH_PROMISE: // Not implemented frames are ignored at this phase
default:
return 0;
}
return extendedHeaderLength;
}
// The length in bytes of additional fields stored in the payload section.
// This may be variable based on flags, but should be no more than 8 bytes.
public static int GetPayloadFieldsLength(Http2Frame frame) {
switch (frame.Type) {
// TODO: Extract constants
case Http2FrameType.DATA: // Variable 0 or 1
return frame.DataHasPadding ? 1 : 0;
case Http2FrameType.HEADERS:
return (frame.HeadersHasPadding ? 1 : 0) + (frame.HeadersHasPriority ? 5 : 0); // Variable 0 to 6
case Http2FrameType.GOAWAY:
return 8; // Last stream id and error code.
case Http2FrameType.PRIORITY:
return 5; // Stream dependency and weight
case Http2FrameType.RST_STREAM:
return 4; // Error code
case Http2FrameType.WINDOW_UPDATE:
return 4; // Update size
case Http2FrameType.PING: // 8 bytes of opaque data
case Http2FrameType.SETTINGS: // Settings are general payload
case Http2FrameType.CONTINUATION: // None
case Http2FrameType.PUSH_PROMISE: // Not implemented frames are ignored at this phase
default:
return 0;
}
}
public static IList<Http2PeerSetting> ReadSettings(in ReadOnlySequence<byte> payload) {
var data = payload.ToSpan();
Debug.Assert(data.Length % SettingSize == 0, "Invalid settings payload length");
var settingsCount = data.Length / SettingSize;
var settings = new Http2PeerSetting[settingsCount];
for (int i = 0; i < settings.Length; i++) {
settings[i] = ReadSetting(data);
data = data.Slice(SettingSize);
}
return settings;
}
private static Http2PeerSetting ReadSetting(ReadOnlySpan<byte> payload) {
var id = (Http2SettingsParameter)BinaryPrimitives.ReadUInt16BigEndian(payload);
var value = BinaryPrimitives.ReadUInt32BigEndian(payload.Slice(2));
return new Http2PeerSetting(id, value);
}
}
}
| |
namespace System.Text
{
public class UTF32Encoding : Encoding
{
private bool bigEndian;
private bool byteOrderMark;
private bool throwOnInvalid;
public UTF32Encoding() : this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark) : this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes)
{
this.bigEndian = bigEndian;
this.byteOrderMark = byteOrderMark;
this.throwOnInvalid = throwOnInvalidBytes;
this.fallbackCharacter = '\uFFFD';
}
public override int CodePage => this.bigEndian ? 1201 : 1200;
public override string EncodingName => this.bigEndian ? "Unicode (UTF-32 Big-Endian)" : "Unicode (UTF-32)";
private char[] ToCodePoints(string str)
{
char surrogate_1st = '\u0000';
char[] unicode_codes = new char[0];
Action fallback = () =>
{
if (this.throwOnInvalid)
{
throw new System.Exception("Invalid character in UTF32 text");
}
unicode_codes.Push(this.fallbackCharacter);
};
for (var i = 0; i < str.Length; ++i)
{
var utf16_code = str[i];
if (surrogate_1st != 0)
{
if (utf16_code >= 0xDC00 && utf16_code <= 0xDFFF)
{
var surrogate_2nd = utf16_code;
var unicode_code = (surrogate_1st - 0xD800) * (1 << 10) + (1 << 16) +
(surrogate_2nd - 0xDC00);
unicode_codes.Push(unicode_code.As<char>());
}
else
{
fallback();
i--;
}
surrogate_1st = '\u0000';
}
else if (utf16_code >= 0xD800 && utf16_code <= 0xDBFF)
{
surrogate_1st = utf16_code;
}
else if ((utf16_code >= 0xDC00) && (utf16_code <= 0xDFFF))
{
fallback();
}
else
{
unicode_codes.Push(utf16_code);
}
}
if (surrogate_1st != 0)
{
fallback();
}
return unicode_codes;
}
protected override byte[] Encode(string s, byte[] outputBytes, int outputIndex, out int writtenBytes)
{
var hasBuffer = outputBytes != null;
var recorded = 0;
Action<byte> write = (ch) =>
{
if (hasBuffer)
{
if (outputIndex >= outputBytes.Length)
{
throw new System.ArgumentException("bytes");
}
outputBytes[outputIndex++] = ch;
}
else
{
outputBytes.Push(ch);
}
recorded++;
};
Action<uint> write32 = (a) =>
{
var r = new byte[4];
r[0] = (a & 0xFF).As<byte>();
r[1] = ((a & 0xFF00) >> 8).As<byte>();
r[2] = ((a & 0xFF0000) >> 16).As<byte>();
r[3] = ((a & 0xFF000000) >> 24).As<byte>();
if (this.bigEndian)
{
r.Reverse();
}
write(r[0]);
write(r[1]);
write(r[2]);
write(r[3]);
};
if (!hasBuffer)
{
outputBytes = new byte[0];
}
var unicode_codes = this.ToCodePoints(s);
for (var i = 0; i < unicode_codes.Length; ++i)
{
write32(unicode_codes[i]);
}
writtenBytes = recorded;
if (hasBuffer)
{
return null;
}
return outputBytes;
}
protected override string Decode(byte[] bytes, int index, int count, char[] chars, int charIndex)
{
var position = index;
var result = "";
var endpoint = position + count;
this._hasError = false;
Action fallback = () =>
{
if (this.throwOnInvalid)
{
throw new System.Exception("Invalid character in UTF32 text");
}
result += this.fallbackCharacter.ToString();
};
Func<uint?> read32 = () =>
{
if ((position + 4) > endpoint)
{
position = position + 4;
return null;
}
var a = bytes[position++];
var b = bytes[position++];
var c = bytes[position++];
var d = bytes[position++];
if (this.bigEndian)
{
var tmp = b;
b = c;
c = tmp;
tmp = a;
a = d;
d = tmp;
}
return ((d << 24) | (c << 16) | (b << 8) | a).As<uint>();
};
while (position < endpoint)
{
var unicode_code = read32();
if (unicode_code == null)
{
fallback();
this._hasError = true;
continue;
}
if (unicode_code < 0x10000 || unicode_code > 0x10FFFF)
{
if (unicode_code < 0 || unicode_code > 0x10FFFF || (unicode_code >= 0xD800 && unicode_code <= 0xDFFF))
{
fallback();
}
else
{
result += unicode_code.As<char>().ToString();
}
}
else
{
result += (((unicode_code - (1 << 16)) / (1 << 10)) + 0xD800).As<char>().ToString();
result += ((unicode_code % (1 << 10)) + 0xDC00).As<char>().ToString();
}
}
return result;
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
{
throw new System.ArgumentOutOfRangeException("charCount");
}
var byteCount = (long)charCount + 1;
byteCount *= 4;
if (byteCount > 0x7fffffff)
{
throw new System.ArgumentOutOfRangeException("charCount");
}
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
{
throw new System.ArgumentOutOfRangeException("byteCount");
}
var charCount = byteCount / 2 + 2;
if (charCount > 0x7fffffff)
{
throw new System.ArgumentOutOfRangeException("byteCount");
}
return charCount;
}
}
}
| |
using J2N.Numerics;
using System;
namespace YAF.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.
*/
using FilteredTermsEnum = YAF.Lucene.Net.Index.FilteredTermsEnum;
using TermsEnum = YAF.Lucene.Net.Index.TermsEnum;
/// <summary>
/// This is a helper class to generate prefix-encoded representations for numerical values
/// and supplies converters to represent float/double values as sortable integers/longs.
///
/// <para/>To quickly execute range queries in Apache Lucene, a range is divided recursively
/// into multiple intervals for searching: The center of the range is searched only with
/// the lowest possible precision in the trie, while the boundaries are matched
/// more exactly. this reduces the number of terms dramatically.
///
/// <para/>This class generates terms to achieve this: First the numerical integer values need to
/// be converted to bytes. For that integer values (32 bit or 64 bit) are made unsigned
/// and the bits are converted to ASCII chars with each 7 bit. The resulting byte[] is
/// sortable like the original integer value (even using UTF-8 sort order). Each value is also
/// prefixed (in the first char) by the <c>shift</c> value (number of bits removed) used
/// during encoding.
///
/// <para/>To also index floating point numbers, this class supplies two methods to convert them
/// to integer values by changing their bit layout: <see cref="DoubleToSortableInt64(double)"/>,
/// <see cref="SingleToSortableInt32(float)"/>. You will have no precision loss by
/// converting floating point numbers to integers and back (only that the integer form
/// is not usable). Other data types like dates can easily converted to <see cref="long"/>s or <see cref="int"/>s (e.g.
/// date to long: <see cref="DateTime.Ticks"/>).
///
/// <para/>For easy usage, the trie algorithm is implemented for indexing inside
/// <see cref="Analysis.NumericTokenStream"/> that can index <see cref="int"/>, <see cref="long"/>,
/// <see cref="float"/>, and <see cref="double"/>. For querying,
/// <see cref="Search.NumericRangeQuery"/> and <see cref="Search.NumericRangeFilter"/> implement the query part
/// for the same data types.
///
/// <para/>This class can also be used, to generate lexicographically sortable (according to
/// <see cref="BytesRef.UTF8SortedAsUTF16Comparer"/>) representations of numeric data
/// types for other usages (e.g. sorting).
///
/// <para/>
/// @lucene.internal
/// @since 2.9, API changed non backwards-compliant in 4.0
/// </summary>
public sealed class NumericUtils
{
private NumericUtils() // no instance!
{
}
/// <summary>
/// The default precision step used by <see cref="Documents.Int32Field"/>,
/// <see cref="Documents.SingleField"/>, <see cref="Documents.Int64Field"/>,
/// <see cref="Documents.DoubleField"/>, <see cref="Analysis.NumericTokenStream"/>,
/// <see cref="Search.NumericRangeQuery"/>, and <see cref="Search.NumericRangeFilter"/>.
/// </summary>
public const int PRECISION_STEP_DEFAULT = 4;
/// <summary>
/// Longs are stored at lower precision by shifting off lower bits. The shift count is
/// stored as <c>SHIFT_START_INT64+shift</c> in the first byte
/// <para/>
/// NOTE: This was SHIFT_START_LONG in Lucene
/// </summary>
public const char SHIFT_START_INT64 = (char)0x20;
/// <summary>
/// The maximum term length (used for <see cref="T:byte[]"/> buffer size)
/// for encoding <see cref="long"/> values.
/// <para/>
/// NOTE: This was BUF_SIZE_LONG in Lucene
/// </summary>
/// <seealso cref="Int64ToPrefixCodedBytes(long, int, BytesRef)"/>
public const int BUF_SIZE_INT64 = 63 / 7 + 2;
/// <summary>
/// Integers are stored at lower precision by shifting off lower bits. The shift count is
/// stored as <c>SHIFT_START_INT32+shift</c> in the first byte
/// <para/>
/// NOTE: This was SHIFT_START_INT in Lucene
/// </summary>
public const byte SHIFT_START_INT32 = 0x60;
/// <summary>
/// The maximum term length (used for <see cref="T:byte[]"/> buffer size)
/// for encoding <see cref="int"/> values.
/// <para/>
/// NOTE: This was BUF_SIZE_INT in Lucene
/// </summary>
/// <seealso cref="Int32ToPrefixCodedBytes(int, int, BytesRef)"/>
public const int BUF_SIZE_INT32 = 31 / 7 + 2;
/// <summary>
/// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits.
/// This is method is used by <see cref="Analysis.NumericTokenStream"/>.
/// After encoding, <c>bytes.Offset</c> will always be 0.
/// <para/>
/// NOTE: This was longToPrefixCoded() in Lucene
/// </summary>
/// <param name="val"> The numeric value </param>
/// <param name="shift"> How many bits to strip from the right </param>
/// <param name="bytes"> Will contain the encoded value </param>
public static void Int64ToPrefixCoded(long val, int shift, BytesRef bytes)
{
Int64ToPrefixCodedBytes(val, shift, bytes);
}
/// <summary>
/// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits.
/// This is method is used by <see cref="Analysis.NumericTokenStream"/>.
/// After encoding, <c>bytes.Offset</c> will always be 0.
/// <para/>
/// NOTE: This was intToPrefixCoded() in Lucene
/// </summary>
/// <param name="val"> The numeric value </param>
/// <param name="shift"> How many bits to strip from the right </param>
/// <param name="bytes"> Will contain the encoded value </param>
public static void Int32ToPrefixCoded(int val, int shift, BytesRef bytes)
{
Int32ToPrefixCodedBytes(val, shift, bytes);
}
/// <summary>
/// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits.
/// This is method is used by <see cref="Analysis.NumericTokenStream"/>.
/// After encoding, <c>bytes.Offset</c> will always be 0.
/// <para/>
/// NOTE: This was longToPrefixCodedBytes() in Lucene
/// </summary>
/// <param name="val"> The numeric value </param>
/// <param name="shift"> How many bits to strip from the right </param>
/// <param name="bytes"> Will contain the encoded value </param>
public static void Int64ToPrefixCodedBytes(long val, int shift, BytesRef bytes)
{
if ((shift & ~0x3f) != 0) // ensure shift is 0..63
{
throw new System.ArgumentException("Illegal shift value, must be 0..63");
}
int nChars = (((63 - shift) * 37) >> 8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63
bytes.Offset = 0;
bytes.Length = nChars + 1; // one extra for the byte that contains the shift info
if (bytes.Bytes.Length < bytes.Length)
{
bytes.Bytes = new byte[NumericUtils.BUF_SIZE_INT64]; // use the max
}
bytes.Bytes[0] = (byte)(SHIFT_START_INT64 + shift);
ulong sortableBits = BitConverter.ToUInt64(BitConverter.GetBytes(val), 0) ^ 0x8000000000000000L; // LUCENENET TODO: Performance - Benchmark this
sortableBits = sortableBits >> shift;
while (nChars > 0)
{
// Store 7 bits per byte for compatibility
// with UTF-8 encoding of terms
bytes.Bytes[nChars--] = (byte)(sortableBits & 0x7f);
sortableBits = sortableBits >> 7;
}
}
/// <summary>
/// Returns prefix coded bits after reducing the precision by <paramref name="shift"/> bits.
/// This is method is used by <see cref="Analysis.NumericTokenStream"/>.
/// After encoding, <c>bytes.Offset</c> will always be 0.
/// <para/>
/// NOTE: This was intToPrefixCodedBytes() in Lucene
/// </summary>
/// <param name="val"> The numeric value </param>
/// <param name="shift"> How many bits to strip from the right </param>
/// <param name="bytes"> Will contain the encoded value </param>
public static void Int32ToPrefixCodedBytes(int val, int shift, BytesRef bytes)
{
if ((shift & ~0x1f) != 0) // ensure shift is 0..31
{
throw new System.ArgumentException("Illegal shift value, must be 0..31");
}
int nChars = (((31 - shift) * 37) >> 8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63
bytes.Offset = 0;
bytes.Length = nChars + 1; // one extra for the byte that contains the shift info
if (bytes.Bytes.Length < bytes.Length)
{
bytes.Bytes = new byte[NumericUtils.BUF_SIZE_INT64]; // use the max
}
bytes.Bytes[0] = (byte)(SHIFT_START_INT32 + shift);
int sortableBits = val ^ unchecked((int)0x80000000);
sortableBits = sortableBits.TripleShift(shift);
while (nChars > 0)
{
// Store 7 bits per byte for compatibility
// with UTF-8 encoding of terms
bytes.Bytes[nChars--] = (byte)(sortableBits & 0x7f);
sortableBits = sortableBits.TripleShift(7);
}
}
/// <summary>
/// Returns the shift value from a prefix encoded <see cref="long"/>.
/// <para/>
/// NOTE: This was getPrefixCodedLongShift() in Lucene
/// </summary>
/// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is
/// not correctly prefix encoded. </exception>
public static int GetPrefixCodedInt64Shift(BytesRef val)
{
int shift = val.Bytes[val.Offset] - SHIFT_START_INT64;
if (shift > 63 || shift < 0)
{
throw new System.FormatException("Invalid shift value (" + shift + ") in prefixCoded bytes (is encoded value really an INT?)");
}
return shift;
}
/// <summary>
/// Returns the shift value from a prefix encoded <see cref="int"/>.
/// <para/>
/// NOTE: This was getPrefixCodedIntShift() in Lucene
/// </summary>
/// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is
/// not correctly prefix encoded. </exception>
public static int GetPrefixCodedInt32Shift(BytesRef val)
{
int shift = val.Bytes[val.Offset] - SHIFT_START_INT32;
if (shift > 31 || shift < 0)
{
throw new System.FormatException("Invalid shift value in prefixCoded bytes (is encoded value really an INT?)");
}
return shift;
}
/// <summary>
/// Returns a <see cref="long"/> from prefixCoded bytes.
/// Rightmost bits will be zero for lower precision codes.
/// This method can be used to decode a term's value.
/// <para/>
/// NOTE: This was prefixCodedToLong() in Lucene
/// </summary>
/// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is
/// not correctly prefix encoded. </exception>
/// <seealso cref="Int64ToPrefixCodedBytes(long, int, BytesRef)"/>
public static long PrefixCodedToInt64(BytesRef val)
{
long sortableBits = 0L;
for (int i = val.Offset + 1, limit = val.Offset + val.Length; i < limit; i++)
{
sortableBits <<= 7;
var b = val.Bytes[i];
if (b < 0)
{
throw new System.FormatException("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)");
}
sortableBits |= (byte)b;
}
return (long)((ulong)(sortableBits << GetPrefixCodedInt64Shift(val)) ^ 0x8000000000000000L); // LUCENENET TODO: Is the casting here necessary?
}
/// <summary>
/// Returns an <see cref="int"/> from prefixCoded bytes.
/// Rightmost bits will be zero for lower precision codes.
/// This method can be used to decode a term's value.
/// <para/>
/// NOTE: This was prefixCodedToInt() in Lucene
/// </summary>
/// <exception cref="FormatException"> if the supplied <see cref="BytesRef"/> is
/// not correctly prefix encoded. </exception>
/// <seealso cref="Int32ToPrefixCodedBytes(int, int, BytesRef)"/>
public static int PrefixCodedToInt32(BytesRef val)
{
long sortableBits = 0;
for (int i = val.Offset, limit = val.Offset + val.Length; i < limit; i++)
{
sortableBits <<= 7;
var b = val.Bytes[i];
if (b < 0)
{
throw new System.FormatException("Invalid prefixCoded numerical value representation (byte " + (b & 0xff).ToString("x") + " at position " + (i - val.Offset) + " is invalid)");
}
sortableBits |= b;
}
return (int)((sortableBits << GetPrefixCodedInt32Shift(val)) ^ 0x80000000);
}
/// <summary>
/// Converts a <see cref="double"/> value to a sortable signed <see cref="long"/>.
/// The value is converted by getting their IEEE 754 floating-point "double format"
/// bit layout and then some bits are swapped, to be able to compare the result as <see cref="long"/>.
/// By this the precision is not reduced, but the value can easily used as a <see cref="long"/>.
/// The sort order (including <see cref="double.NaN"/>) is defined by
/// <see cref="double.CompareTo(double)"/>; <c>NaN</c> is greater than positive infinity.
/// <para/>
/// NOTE: This was doubleToSortableLong() in Lucene
/// </summary>
/// <seealso cref="SortableInt64ToDouble(long)"/>
public static long DoubleToSortableInt64(double val)
{
long f = J2N.BitConversion.DoubleToInt64Bits(val);
if (f < 0)
{
f ^= 0x7fffffffffffffffL;
}
return f;
}
/// <summary>
/// Converts a sortable <see cref="long"/> back to a <see cref="double"/>.
/// <para/>
/// NOTE: This was sortableLongToDouble() in Lucene
/// </summary>
/// <seealso cref="DoubleToSortableInt64(double)"/>
public static double SortableInt64ToDouble(long val)
{
if (val < 0)
{
val ^= 0x7fffffffffffffffL;
}
return J2N.BitConversion.Int64BitsToDouble(val);
}
/// <summary>
/// Converts a <see cref="float"/> value to a sortable signed <see cref="int"/>.
/// The value is converted by getting their IEEE 754 floating-point "float format"
/// bit layout and then some bits are swapped, to be able to compare the result as <see cref="int"/>.
/// By this the precision is not reduced, but the value can easily used as an <see cref="int"/>.
/// The sort order (including <see cref="float.NaN"/>) is defined by
/// <seealso cref="float.CompareTo(float)"/>; <c>NaN</c> is greater than positive infinity.
/// <para/>
/// NOTE: This was floatToSortableInt() in Lucene
/// </summary>
/// <seealso cref="SortableInt32ToSingle(int)"/>
public static int SingleToSortableInt32(float val)
{
int f = J2N.BitConversion.SingleToInt32Bits(val);
if (f < 0)
{
f ^= 0x7fffffff;
}
return f;
}
/// <summary>
/// Converts a sortable <see cref="int"/> back to a <see cref="float"/>.
/// <para/>
/// NOTE: This was sortableIntToFloat() in Lucene
/// </summary>
/// <seealso cref="SingleToSortableInt32"/>
public static float SortableInt32ToSingle(int val)
{
if (val < 0)
{
val ^= 0x7fffffff;
}
return J2N.BitConversion.Int32BitsToSingle(val);
}
/// <summary>
/// Splits a long range recursively.
/// You may implement a builder that adds clauses to a
/// <see cref="Lucene.Net.Search.BooleanQuery"/> for each call to its
/// <see cref="Int64RangeBuilder.AddRange(BytesRef, BytesRef)"/>
/// method.
/// <para/>
/// This method is used by <see cref="Search.NumericRangeQuery"/>.
/// <para/>
/// NOTE: This was splitLongRange() in Lucene
/// </summary>
public static void SplitInt64Range(Int64RangeBuilder builder, int precisionStep, long minBound, long maxBound)
{
SplitRange(builder, 64, precisionStep, minBound, maxBound);
}
/// <summary>
/// Splits an <see cref="int"/> range recursively.
/// You may implement a builder that adds clauses to a
/// <see cref="Lucene.Net.Search.BooleanQuery"/> for each call to its
/// <see cref="Int32RangeBuilder.AddRange(BytesRef, BytesRef)"/>
/// method.
/// <para/>
/// This method is used by <see cref="Search.NumericRangeQuery"/>.
/// <para/>
/// NOTE: This was splitIntRange() in Lucene
/// </summary>
public static void SplitInt32Range(Int32RangeBuilder builder, int precisionStep, int minBound, int maxBound)
{
SplitRange(builder, 32, precisionStep, minBound, maxBound);
}
/// <summary>
/// This helper does the splitting for both 32 and 64 bit. </summary>
private static void SplitRange(object builder, int valSize, int precisionStep, long minBound, long maxBound)
{
if (precisionStep < 1)
{
throw new System.ArgumentException("precisionStep must be >=1");
}
if (minBound > maxBound)
{
return;
}
for (int shift = 0; ; shift += precisionStep)
{
// calculate new bounds for inner precision
long diff = 1L << (shift + precisionStep), mask = ((1L << precisionStep) - 1L) << shift;
bool hasLower = (minBound & mask) != 0L, hasUpper = (maxBound & mask) != mask;
long nextMinBound = (hasLower ? (minBound + diff) : minBound) & ~mask, nextMaxBound = (hasUpper ? (maxBound - diff) : maxBound) & ~mask;
bool lowerWrapped = nextMinBound < minBound, upperWrapped = nextMaxBound > maxBound;
if (shift + precisionStep >= valSize || nextMinBound > nextMaxBound || lowerWrapped || upperWrapped)
{
// We are in the lowest precision or the next precision is not available.
AddRange(builder, valSize, minBound, maxBound, shift);
// exit the split recursion loop
break;
}
if (hasLower)
{
AddRange(builder, valSize, minBound, minBound | mask, shift);
}
if (hasUpper)
{
AddRange(builder, valSize, maxBound & ~mask, maxBound, shift);
}
// recurse to next precision
minBound = nextMinBound;
maxBound = nextMaxBound;
}
}
/// <summary>
/// Helper that delegates to correct range builder. </summary>
private static void AddRange(object builder, int valSize, long minBound, long maxBound, int shift)
{
// for the max bound set all lower bits (that were shifted away):
// this is important for testing or other usages of the splitted range
// (e.g. to reconstruct the full range). The prefixEncoding will remove
// the bits anyway, so they do not hurt!
maxBound |= (1L << shift) - 1L;
// delegate to correct range builder
switch (valSize)
{
case 64:
((Int64RangeBuilder)builder).AddRange(minBound, maxBound, shift);
break;
case 32:
((Int32RangeBuilder)builder).AddRange((int)minBound, (int)maxBound, shift);
break;
default:
// Should not happen!
throw new System.ArgumentException("valSize must be 32 or 64.");
}
}
/// <summary>
/// Callback for <see cref="SplitInt64Range(Int64RangeBuilder, int, long, long)"/>.
/// You need to override only one of the methods.
/// <para/>
/// NOTE: This was LongRangeBuilder in Lucene
/// <para/>
/// @lucene.internal
/// @since 2.9, API changed non backwards-compliant in 4.0
/// </summary>
public abstract class Int64RangeBuilder
{
/// <summary>
/// Override this method, if you like to receive the already prefix encoded range bounds.
/// You can directly build classical (inclusive) range queries from them.
/// </summary>
public virtual void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
throw new System.NotSupportedException();
}
/// <summary>
/// Override this method, if you like to receive the raw long range bounds.
/// You can use this for e.g. debugging purposes (print out range bounds).
/// </summary>
public virtual void AddRange(long min, long max, int shift)
{
BytesRef minBytes = new BytesRef(BUF_SIZE_INT64), maxBytes = new BytesRef(BUF_SIZE_INT64);
Int64ToPrefixCodedBytes(min, shift, minBytes);
Int64ToPrefixCodedBytes(max, shift, maxBytes);
AddRange(minBytes, maxBytes);
}
}
/// <summary>
/// Callback for <see cref="SplitInt32Range(Int32RangeBuilder, int, int, int)"/>.
/// You need to override only one of the methods.
/// <para/>
/// NOTE: This was IntRangeBuilder in Lucene
///
/// @lucene.internal
/// @since 2.9, API changed non backwards-compliant in 4.0
/// </summary>
public abstract class Int32RangeBuilder
{
/// <summary>
/// Override this method, if you like to receive the already prefix encoded range bounds.
/// You can directly build classical range (inclusive) queries from them.
/// </summary>
public virtual void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
throw new System.NotSupportedException();
}
/// <summary>
/// Override this method, if you like to receive the raw int range bounds.
/// You can use this for e.g. debugging purposes (print out range bounds).
/// </summary>
public virtual void AddRange(int min, int max, int shift)
{
BytesRef minBytes = new BytesRef(BUF_SIZE_INT32), maxBytes = new BytesRef(BUF_SIZE_INT32);
Int32ToPrefixCodedBytes(min, shift, minBytes);
Int32ToPrefixCodedBytes(max, shift, maxBytes);
AddRange(minBytes, maxBytes);
}
}
/// <summary>
/// Filters the given <see cref="TermsEnum"/> by accepting only prefix coded 64 bit
/// terms with a shift value of <c>0</c>.
/// <para/>
/// NOTE: This was filterPrefixCodedLongs() in Lucene
/// </summary>
/// <param name="termsEnum">
/// The terms enum to filter </param>
/// <returns> A filtered <see cref="TermsEnum"/> that only returns prefix coded 64 bit
/// terms with a shift value of <c>0</c>. </returns>
public static TermsEnum FilterPrefixCodedInt64s(TermsEnum termsEnum)
{
return new FilteredTermsEnumAnonymousInnerClassHelper(termsEnum);
}
private class FilteredTermsEnumAnonymousInnerClassHelper : FilteredTermsEnum
{
public FilteredTermsEnumAnonymousInnerClassHelper(TermsEnum termsEnum)
: base(termsEnum, false)
{
}
protected override AcceptStatus Accept(BytesRef term)
{
return NumericUtils.GetPrefixCodedInt64Shift(term) == 0 ? AcceptStatus.YES : AcceptStatus.END;
}
}
/// <summary>
/// Filters the given <see cref="TermsEnum"/> by accepting only prefix coded 32 bit
/// terms with a shift value of <c>0</c>.
/// <para/>
/// NOTE: This was filterPrefixCodedInts() in Lucene
/// </summary>
/// <param name="termsEnum">
/// The terms enum to filter </param>
/// <returns> A filtered <see cref="TermsEnum"/> that only returns prefix coded 32 bit
/// terms with a shift value of <c>0</c>. </returns>
public static TermsEnum FilterPrefixCodedInt32s(TermsEnum termsEnum)
{
return new FilteredTermsEnumAnonymousInnerClassHelper2(termsEnum);
}
private class FilteredTermsEnumAnonymousInnerClassHelper2 : FilteredTermsEnum
{
public FilteredTermsEnumAnonymousInnerClassHelper2(TermsEnum termsEnum)
: base(termsEnum, false)
{
}
protected override AcceptStatus Accept(BytesRef term)
{
return NumericUtils.GetPrefixCodedInt32Shift(term) == 0 ? AcceptStatus.YES : AcceptStatus.END;
}
}
}
}
| |
// 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.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Microsoft.NodejsTools.Debugger.DebugEngine
{
// This class implements IDebugThread2 which represents a thread running in a program.
internal class AD7Thread : IDebugThread2, IDebugThread100
{
private readonly AD7Engine _engine;
private readonly NodeThread _debuggedThread;
public AD7Thread(AD7Engine engine, NodeThread debuggedThread)
{
this._engine = engine;
this._debuggedThread = debuggedThread;
}
private string GetCurrentLocation(bool fIncludeModuleName)
{
var topStackFrame = this._debuggedThread.TopStackFrame;
if (topStackFrame != null)
{
return topStackFrame.FunctionName;
}
return "<unknown location, not in Node.js code>";
}
internal NodeThread GetDebuggedThread()
{
return this._debuggedThread;
}
#region IDebugThread2 Members
// Determines whether the next statement can be set to the given stack frame and code context.
// NOTE: VS2013 and earlier do not use the result to disable the "set next statement" command
int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext)
{
return VSConstants.E_NOTIMPL;
}
// Retrieves a list of the stack frames for this thread.
// We currently call into the process and get the frames. We might want to cache the frame info.
int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject)
{
var stackFrames = this._debuggedThread.Frames;
if (stackFrames == null)
{
enumObject = null;
return VSConstants.E_FAIL;
}
var numStackFrames = stackFrames.Count;
var frameInfoArray = new FRAMEINFO[numStackFrames];
for (var i = 0; i < numStackFrames; i++)
{
var frame = new AD7StackFrame(this._engine, this, stackFrames[i]);
frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i]);
}
enumObject = new AD7FrameInfoEnum(frameInfoArray);
return VSConstants.S_OK;
}
// Get the name of the thread. For the sample engine, the name of the thread is always "Sample Engine Thread"
int IDebugThread2.GetName(out string threadName)
{
threadName = this._debuggedThread.Name;
return VSConstants.S_OK;
}
// Return the program that this thread belongs to.
int IDebugThread2.GetProgram(out IDebugProgram2 program)
{
program = this._engine;
return VSConstants.S_OK;
}
// Gets the system thread identifier.
int IDebugThread2.GetThreadId(out uint threadId)
{
threadId = (uint)this._debuggedThread.Id;
return VSConstants.S_OK;
}
// Gets properties that describe a thread.
int IDebugThread2.GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] propertiesArray)
{
var props = new THREADPROPERTIES();
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0)
{
props.dwThreadId = (uint)this._debuggedThread.Id;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0)
{
// sample debug engine doesn't support suspending threads
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0)
{
props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0)
{
props.bstrPriority = "Normal";
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0)
{
props.bstrName = this._debuggedThread.Name;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0)
{
props.bstrLocation = GetCurrentLocation(true);
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION;
}
propertiesArray[0] = props;
return VSConstants.S_OK;
}
// Resume a thread.
// This is called when the user chooses "Unfreeze" from the threads window when a thread has previously been frozen.
int IDebugThread2.Resume(out uint suspendCount)
{
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
internal const int E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = unchecked((int)0x80040105);
// Sets the next statement to the given stack frame and code context.
int IDebugThread2.SetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext)
{
return VSConstants.E_NOTIMPL;
}
// suspend a thread.
// This is called when the user chooses "Freeze" from the threads window
int IDebugThread2.Suspend(out uint suspendCount)
{
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IDebugThread100 Members
int IDebugThread100.SetThreadDisplayName(string name)
{
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadDisplayName(out string name)
{
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM, which calls GetThreadProperties100()
name = string.Empty;
return VSConstants.E_NOTIMPL;
}
// Returns whether this thread can be used to do function/property evaluation.
int IDebugThread100.CanDoFuncEval()
{
return VSConstants.S_FALSE;
}
int IDebugThread100.SetFlags(uint flags)
{
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetFlags(out uint flags)
{
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
flags = 0;
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadProperties100(uint dwFields, THREADPROPERTIES100[] props)
{
// Invoke GetThreadProperties to get the VS7/8/9 properties
var props90 = new THREADPROPERTIES[1];
var dwFields90 = (enum_THREADPROPERTY_FIELDS)(dwFields & 0x3f);
var hRes = ((IDebugThread2)this).GetThreadProperties(dwFields90, props90);
props[0].bstrLocation = props90[0].bstrLocation;
props[0].bstrName = props90[0].bstrName;
props[0].bstrPriority = props90[0].bstrPriority;
props[0].dwFields = (uint)props90[0].dwFields;
props[0].dwSuspendCount = props90[0].dwSuspendCount;
props[0].dwThreadId = props90[0].dwThreadId;
props[0].dwThreadState = props90[0].dwThreadState;
// Populate the new fields
if (hRes == VSConstants.S_OK && dwFields != (uint)dwFields90)
{
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME) != 0)
{
// Thread display name is being requested
props[0].bstrDisplayName = this._debuggedThread.Name;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME;
// Give this display name a higher priority than the default (0)
// so that it will actually be displayed
props[0].DisplayNamePriority = 10;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME_PRIORITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY) != 0)
{
// Thread category is being requested
if (this._debuggedThread.IsWorkerThread)
{
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Worker;
}
else
{
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Main;
}
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID) != 0)
{
// Thread category is being requested
props[0].dwThreadId = (uint)this._debuggedThread.Id;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY) != 0)
{
// Thread cpu affinity is being requested
props[0].AffinityMask = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID) != 0)
{
// Thread display name is being requested
props[0].priorityId = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID;
}
}
return hRes;
}
private enum enum_THREADCATEGORY
{
THREADCATEGORY_Worker = 0,
THREADCATEGORY_UI = (THREADCATEGORY_Worker + 1),
THREADCATEGORY_Main = (THREADCATEGORY_UI + 1),
THREADCATEGORY_RPC = (THREADCATEGORY_Main + 1),
THREADCATEGORY_Unknown = (THREADCATEGORY_RPC + 1)
}
#endregion
#region Uncalled interface methods
// These methods are not currently called by the Visual Studio debugger, so they don't need to be implemented
int IDebugThread2.GetLogicalThread(IDebugStackFrame2 stackFrame, out IDebugLogicalThread2 logicalThread)
{
Debug.Fail("This function is not called by the debugger");
logicalThread = null;
return VSConstants.E_NOTIMPL;
}
int IDebugThread2.SetThreadName(string name)
{
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
#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.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using Xunit;
using Microsoft.Win32;
namespace System.ServiceProcessServiceController.Tests
{
internal sealed class ServiceProvider
{
public readonly string TestMachineName;
public readonly TimeSpan ControlTimeout;
public readonly string TestServiceName;
public readonly string TestServiceDisplayName;
public readonly string DependentTestServiceNamePrefix;
public readonly string DependentTestServiceDisplayNamePrefix;
public readonly string TestServiceRegistryKey;
public ServiceProvider()
{
TestMachineName = ".";
ControlTimeout = TimeSpan.FromSeconds(3);
TestServiceName = Guid.NewGuid().ToString();
TestServiceDisplayName = "Test Service " + TestServiceName;
DependentTestServiceNamePrefix = TestServiceName + ".Dependent";
DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent";
TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName;
// Create the service
CreateTestServices();
}
private void CreateTestServices()
{
// Create the test service and its dependent services. Then, start the test service.
// All control tests assume that the test service is running when they are executed.
// So all tests should make sure to restart the service if they stop, pause, or shut
// it down.
RunServiceExecutable("create");
}
public void DeleteTestServices()
{
RunServiceExecutable("delete");
RegistryKey users = Registry.Users;
if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null)
users.DeleteSubKeyTree(".DEFAULT\\dotnetTests");
}
private void RunServiceExecutable(string action)
{
var process = new Process();
process.StartInfo.FileName = "NativeTestService.exe";
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action);
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("error: NativeTestService.exe failed with exit code " + process.ExitCode.ToString());
}
}
}
public class ServiceControllerTests : IDisposable
{
ServiceProvider _testService;
public ServiceControllerTests()
{
_testService = new ServiceProvider();
}
[Fact]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
}
[Fact]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
}
[Fact]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); });
}
[Fact]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.True(controller.CanStop);
Assert.True(controller.CanPauseAndContinue);
Assert.False(controller.CanShutdown);
}
[Fact]
public void StartWithArguments()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
var args = new[] { "a", "b", "c", "d", "e" };
controller.Start(args);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
// The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey.
// Read this key to verify that the arguments were properly passed to the service.
string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string;
Assert.Equal(string.Join(",", args), argsString);
}
[Fact]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[Fact]
public void PauseAndContinue()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Pause();
controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Paused, controller.Status);
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[Fact]
public void WaitForStatusTimeout()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Throws<System.ServiceProcess.TimeoutException>(() => controller.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.Zero));
}
[Fact]
public void GetServices()
{
bool foundTestService = false;
foreach (var service in ServiceController.GetServices())
{
if (service.ServiceName == _testService.TestServiceName)
{
foundTestService = true;
}
}
Assert.True(foundTestService, "Test service was not enumerated with all services");
}
[Fact]
public void GetDevices()
{
var devices = ServiceController.GetDevices();
Assert.True(devices.Length != 0);
const ServiceType SERVICE_TYPE_DRIVER =
ServiceType.FileSystemDriver |
ServiceType.KernelDriver |
ServiceType.RecognizerDriver;
foreach (var device in devices)
{
if ((int)(device.ServiceType & SERVICE_TYPE_DRIVER) == 0)
{
Assert.True(false, string.Format("Service '{0}' is of type '{1}' and is not a device driver.", device.ServiceName, device.ServiceType));
}
}
}
[Fact]
public void DependentServices()
{
// The test service creates a number of dependent services, each of which has no dependent services
var controller = new ServiceController(_testService.TestServiceName);
Assert.True(controller.DependentServices.Length > 0);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = controller.DependentServices[i];
Assert.True(dependent.ServiceName.StartsWith(_testService.DependentTestServiceNamePrefix));
Assert.True(dependent.DisplayName.StartsWith(_testService.DependentTestServiceDisplayNamePrefix));
Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType);
Assert.Equal(0, dependent.DependentServices.Length);
}
}
[Fact]
public void ServicesDependedOn()
{
// The test service creates a number of dependent services, each of these should depend on the test service
var controller = new ServiceController(_testService.TestServiceName);
Assert.True(controller.DependentServices.Length > 0);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = controller.DependentServices[i];
Assert.True(dependent.ServicesDependedOn.Length == 1);
var dependency = dependent.ServicesDependedOn[0];
Assert.Equal(_testService.TestServiceName, dependency.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, dependency.DisplayName);
}
}
public void Dispose()
{
_testService.DeleteTestServices();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Providers.Azure;
using Orleans.Persistence.AzureStorage;
using Orleans.Configuration.Overrides;
namespace Orleans.Storage
{
/// <summary>
/// Simple storage for writing grain state data to Azure table storage.
/// </summary>
public class AzureTableGrainStorage : IGrainStorage, IRestExceptionDecoder, ILifecycleParticipant<ISiloLifecycle>
{
private readonly AzureTableStorageOptions options;
private readonly ClusterOptions clusterOptions;
private readonly SerializationManager serializationManager;
private readonly IGrainFactory grainFactory;
private readonly ITypeResolver typeResolver;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger logger;
private GrainStateTableDataManager tableDataManager;
private JsonSerializerSettings JsonSettings;
// each property can hold 64KB of data and each entity can take 1MB in total, so 15 full properties take
// 15 * 64 = 960 KB leaving room for the primary key, timestamp etc
private const int MAX_DATA_CHUNK_SIZE = 64 * 1024;
private const int MAX_STRING_PROPERTY_LENGTH = 32 * 1024;
private const int MAX_DATA_CHUNKS_COUNT = 15;
private const string BINARY_DATA_PROPERTY_NAME = "Data";
private const string STRING_DATA_PROPERTY_NAME = "StringData";
private string name;
/// <summary> Default constructor </summary>
public AzureTableGrainStorage(string name, AzureTableStorageOptions options, IOptions<ClusterOptions> clusterOptions, SerializationManager serializationManager,
IGrainFactory grainFactory, ITypeResolver typeResolver, ILoggerFactory loggerFactory)
{
this.options = options;
this.clusterOptions = clusterOptions.Value;
this.name = name;
this.serializationManager = serializationManager;
this.grainFactory = grainFactory;
this.typeResolver = typeResolver;
this.loggerFactory = loggerFactory;
var loggerName = $"{typeof(AzureTableGrainStorageFactory).FullName}.{name}";
this.logger = this.loggerFactory.CreateLogger(loggerName);
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized");
string pk = GetKeyString(grainReference);
if(logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_ReadingData, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, pk, grainReference, this.options.TableName);
string partitionKey = pk;
string rowKey = grainType;
GrainStateRecord record = await tableDataManager.Read(partitionKey, rowKey).ConfigureAwait(false);
if (record != null)
{
var entity = record.Entity;
if (entity != null)
{
var loadedState = ConvertFromStorageFormat(entity, grainState.Type);
grainState.State = loadedState ?? Activator.CreateInstance(grainState.Type);
grainState.ETag = record.ETag;
}
}
// Else leave grainState in previous default condition
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized");
string pk = GetKeyString(grainReference);
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Writing: GrainType={0} Pk={1} Grainid={2} ETag={3} to Table={4}", grainType, pk, grainReference, grainState.ETag, this.options.TableName);
var entity = new DynamicTableEntity(pk, grainType);
ConvertToStorageFormat(grainState.State, entity);
var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag };
try
{
await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference, this.options.TableName, grainState.ETag).ConfigureAwait(false);
grainState.ETag = record.ETag;
}
catch (Exception exc)
{
logger.Error((int)AzureProviderErrorCode.AzureTableProvider_WriteError,
$"Error Writing: GrainType={grainType} Grainid={grainReference} ETag={grainState.ETag} to Table={this.options.TableName} Exception={exc.Message}", exc);
throw;
}
}
/// <summary> Clear / Delete state data function for this storage provider. </summary>
/// <remarks>
/// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row
/// for this grain will be deleted / removed, otherwise the table row will be
/// cleared by overwriting with default / null values.
/// </remarks>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized");
string pk = GetKeyString(grainReference);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, pk, grainReference, grainState.ETag, this.options.DeleteStateOnClear, this.options.TableName);
var entity = new DynamicTableEntity(pk, grainType);
var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag };
string operation = "Clearing";
try
{
if (this.options.DeleteStateOnClear)
{
operation = "Deleting";
await DoOptimisticUpdate(() => tableDataManager.Delete(record), grainType, grainReference, this.options.TableName, grainState.ETag).ConfigureAwait(false);
}
else
{
await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference, this.options.TableName, grainState.ETag).ConfigureAwait(false);
}
grainState.ETag = record.ETag; // Update in-memory data to the new ETag
}
catch (Exception exc)
{
logger.Error((int)AzureProviderErrorCode.AzureTableProvider_DeleteError, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}",
operation, grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc);
throw;
}
}
private static async Task DoOptimisticUpdate(Func<Task> updateOperation, string grainType, GrainReference grainReference, string tableName, string currentETag)
{
try
{
await updateOperation.Invoke().ConfigureAwait(false);
}
catch (StorageException ex) when (ex.IsPreconditionFailed() || ex.IsConflict())
{
throw new TableStorageUpdateConditionNotSatisfiedException(grainType, grainReference, tableName, "Unknown", currentETag, ex);
}
}
/// <summary>
/// Serialize to Azure storage format in either binary or JSON format.
/// </summary>
/// <param name="grainState">The grain state data to be serialized</param>
/// <param name="entity">The Azure table entity the data should be stored in</param>
/// <remarks>
/// See:
/// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
/// for more on the JSON serializer.
/// </remarks>
internal void ConvertToStorageFormat(object grainState, DynamicTableEntity entity)
{
int dataSize;
IEnumerable<EntityProperty> properties;
string basePropertyName;
if (this.options.UseJson)
{
// http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm
string data = Newtonsoft.Json.JsonConvert.SerializeObject(grainState, this.JsonSettings);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}",
data.Length, entity.PartitionKey, entity.RowKey);
// each Unicode character takes 2 bytes
dataSize = data.Length * 2;
properties = SplitStringData(data).Select(t => new EntityProperty(t));
basePropertyName = STRING_DATA_PROPERTY_NAME;
}
else
{
// Convert to binary format
byte[] data = this.serializationManager.SerializeToByteArray(grainState);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Writing binary data size = {0} for grain id = Partition={1} / Row={2}",
data.Length, entity.PartitionKey, entity.RowKey);
dataSize = data.Length;
properties = SplitBinaryData(data).Select(t => new EntityProperty(t));
basePropertyName = BINARY_DATA_PROPERTY_NAME;
}
CheckMaxDataSize(dataSize, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT);
foreach (var keyValuePair in properties.Zip(GetPropertyNames(basePropertyName),
(property, name) => new KeyValuePair<string, EntityProperty>(name, property)))
{
entity.Properties.Add(keyValuePair);
}
}
private void CheckMaxDataSize(int dataSize, int maxDataSize)
{
if (dataSize > maxDataSize)
{
var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, maxDataSize);
logger.Error(0, msg);
throw new ArgumentOutOfRangeException("GrainState.Size", msg);
}
}
private static IEnumerable<string> SplitStringData(string stringData)
{
var startIndex = 0;
while (startIndex < stringData.Length)
{
var chunkSize = Math.Min(MAX_STRING_PROPERTY_LENGTH, stringData.Length - startIndex);
yield return stringData.Substring(startIndex, chunkSize);
startIndex += chunkSize;
}
}
private static IEnumerable<byte[]> SplitBinaryData(byte[] binaryData)
{
var startIndex = 0;
while (startIndex < binaryData.Length)
{
var chunkSize = Math.Min(MAX_DATA_CHUNK_SIZE, binaryData.Length - startIndex);
var chunk = new byte[chunkSize];
Array.Copy(binaryData, startIndex, chunk, 0, chunkSize);
yield return chunk;
startIndex += chunkSize;
}
}
private static IEnumerable<string> GetPropertyNames(string basePropertyName)
{
yield return basePropertyName;
for (var i = 1; i < MAX_DATA_CHUNKS_COUNT; ++i)
{
yield return basePropertyName + i;
}
}
private static IEnumerable<byte[]> ReadBinaryDataChunks(DynamicTableEntity entity)
{
foreach (var binaryDataPropertyName in GetPropertyNames(BINARY_DATA_PROPERTY_NAME))
{
EntityProperty dataProperty;
if (entity.Properties.TryGetValue(binaryDataPropertyName, out dataProperty))
{
switch (dataProperty.PropertyType)
{
// if TablePayloadFormat.JsonNoMetadata is used
case EdmType.String:
var stringValue = dataProperty.StringValue;
if (!string.IsNullOrEmpty(stringValue))
{
yield return Convert.FromBase64String(stringValue);
}
break;
// if any payload type providing metadata is used
case EdmType.Binary:
var binaryValue = dataProperty.BinaryValue;
if (binaryValue != null && binaryValue.Length > 0)
{
yield return binaryValue;
}
break;
}
}
}
}
private static byte[] ReadBinaryData(DynamicTableEntity entity)
{
var dataChunks = ReadBinaryDataChunks(entity).ToArray();
var dataSize = dataChunks.Select(d => d.Length).Sum();
var result = new byte[dataSize];
var startIndex = 0;
foreach (var dataChunk in dataChunks)
{
Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length);
startIndex += dataChunk.Length;
}
return result;
}
private static IEnumerable<string> ReadStringDataChunks(DynamicTableEntity entity)
{
foreach (var stringDataPropertyName in GetPropertyNames(STRING_DATA_PROPERTY_NAME))
{
EntityProperty dataProperty;
if (entity.Properties.TryGetValue(stringDataPropertyName, out dataProperty))
{
var data = dataProperty.StringValue;
if (!string.IsNullOrEmpty(data))
{
yield return data;
}
}
}
}
private static string ReadStringData(DynamicTableEntity entity)
{
return string.Join(string.Empty, ReadStringDataChunks(entity));
}
/// <summary>
/// Deserialize from Azure storage format
/// </summary>
/// <param name="entity">The Azure table entity the stored data</param>
/// <param name="stateType">The state type</param>
internal object ConvertFromStorageFormat(DynamicTableEntity entity, Type stateType)
{
var binaryData = ReadBinaryData(entity);
var stringData = ReadStringData(entity);
object dataValue = null;
try
{
if (binaryData.Length > 0)
{
// Rehydrate
dataValue = this.serializationManager.DeserializeFromByteArray<object>(binaryData);
}
else if (!string.IsNullOrEmpty(stringData))
{
dataValue = Newtonsoft.Json.JsonConvert.DeserializeObject(stringData, stateType, this.JsonSettings);
}
// Else, no data found
}
catch (Exception exc)
{
var sb = new StringBuilder();
if (binaryData.Length > 0)
{
sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData);
}
else if (!string.IsNullOrEmpty(stringData))
{
sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData);
}
if (dataValue != null)
{
sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType());
}
logger.Error(0, sb.ToString(), exc);
throw new AggregateException(sb.ToString(), exc);
}
return dataValue;
}
private string GetKeyString(GrainReference grainReference)
{
var key = String.Format("{0}_{1}", this.clusterOptions.ServiceId, grainReference.ToKeyString());
return AzureStorageUtils.SanitizeTableProperty(key);
}
internal class GrainStateRecord
{
public string ETag { get; set; }
public DynamicTableEntity Entity { get; set; }
}
private class GrainStateTableDataManager
{
public string TableName { get; private set; }
private readonly AzureTableDataManager<DynamicTableEntity> tableManager;
private readonly ILogger logger;
public GrainStateTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger<GrainStateTableDataManager>();
TableName = tableName;
tableManager = new AzureTableDataManager<DynamicTableEntity>(tableName, storageConnectionString, loggerFactory);
}
public Task InitTableAsync()
{
return tableManager.InitTableAsync();
}
public async Task<GrainStateRecord> Read(string partitionKey, string rowKey)
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName);
try
{
Tuple<DynamicTableEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false);
if (data == null || data.Item1 == null)
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName);
return null;
}
DynamicTableEntity stateEntity = data.Item1;
var record = new GrainStateRecord { Entity = stateEntity, ETag = data.Item2 };
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag);
return record;
}
catch (Exception exc)
{
if (AzureStorageUtils.TableStorageDataNotFound(exc))
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, LogFormatter.PrintException(exc));
return null; // No data
}
throw;
}
}
public async Task Write(GrainStateRecord record)
{
var entity = record.Entity;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Writing: PartitionKey={0} RowKey={1} to Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag);
string eTag = String.IsNullOrEmpty(record.ETag) ?
await tableManager.CreateTableEntryAsync(entity).ConfigureAwait(false) :
await tableManager.UpdateTableEntryAsync(entity, record.ETag).ConfigureAwait(false);
record.ETag = eTag;
}
public async Task Delete(GrainStateRecord record)
{
var entity = record.Entity;
if (record.ETag == null)
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "Not attempting to delete non-existent persistent state: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag);
return;
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Deleting: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag);
await tableManager.DeleteTableEntryAsync(entity, record.ETag).ConfigureAwait(false);
record.ETag = null;
}
}
/// <summary> Decodes Storage exceptions.</summary>
public bool DecodeException(Exception e, out HttpStatusCode httpStatusCode, out string restStatus, bool getRESTErrors = false)
{
return AzureStorageUtils.EvaluateException(e, out httpStatusCode, out restStatus, getRESTErrors);
}
private async Task Init(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
try
{
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage {name} initializing: {this.options.ToString()}");
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, $"AzureTableGrainStorage {name} is using DataConnectionString: {ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString)}");
this.JsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);
this.options.ConfigureJsonSerializerSettings?.Invoke(this.JsonSettings);
this.tableDataManager = new GrainStateTableDataManager(this.options.TableName, this.options.ConnectionString, this.loggerFactory);
await this.tableDataManager.InitTableAsync();
stopWatch.Stop();
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
}
catch (Exception ex)
{
stopWatch.Stop();
this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex);
throw;
}
}
private Task Close(CancellationToken ct)
{
this.tableDataManager = null;
return Task.CompletedTask;
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureTableGrainStorage>(this.name), this.options.InitStage, Init, Close);
}
}
public static class AzureTableGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
var optionsSnapshot = services.GetRequiredService<IOptionsMonitor<AzureTableStorageOptions>>();
var clusterOptions = services.GetProviderClusterOptions(name);
return ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(services, name, optionsSnapshot.Get(name), clusterOptions);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
class ServiceOperationInvoker : IOperationInvoker
{
bool canCreateInstance;
bool completesInstance;
bool contractCausesSave;
IOperationInvoker innerInvoker;
public ServiceOperationInvoker(IOperationInvoker innerInvoker, bool completesInstance, bool canCreateInstance, bool contractCausesSave)
{
if (innerInvoker == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerInvoker");
}
this.innerInvoker = innerInvoker;
this.completesInstance = completesInstance;
this.canCreateInstance = canCreateInstance;
this.contractCausesSave = contractCausesSave;
}
public bool IsSynchronous
{
get { return this.innerInvoker.IsSynchronous; }
}
public object[] AllocateInputs()
{
return this.innerInvoker.AllocateInputs();
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
if (instance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instance");
}
ServiceDurableInstance durableInstance = instance as ServiceDurableInstance;
if (durableInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(SR2.InvokeCalledWithWrongType, typeof(DurableServiceAttribute).Name)));
}
object serviceInstance = durableInstance.StartOperation(this.canCreateInstance);
Exception operationException = null;
bool failFast = false;
try
{
return this.innerInvoker.Invoke(serviceInstance, inputs, out outputs);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
failFast = true;
throw;
}
operationException = e;
ServiceErrorHandler.MarkException(e);
throw;
}
finally
{
if (!failFast)
{
durableInstance.FinishOperation(this.completesInstance, this.contractCausesSave, operationException);
}
}
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
if (instance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instance");
}
ServiceDurableInstance durableInstance = instance as ServiceDurableInstance;
if (durableInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(SR2.InvokeCalledWithWrongType, typeof(DurableServiceAttribute).Name)));
}
return new InvokeAsyncResult(durableInstance, inputs, this, this.canCreateInstance, callback, state);
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
return InvokeAsyncResult.End(out outputs, result);
}
public class InvokeAsyncResult : AsyncResult
{
static AsyncCallback finishCallback = Fx.ThunkCallback(new AsyncCallback(FinishComplete));
static AsyncCallback invokeCallback = Fx.ThunkCallback(new AsyncCallback(InvokeComplete));
static AsyncCallback startCallback = Fx.ThunkCallback(new AsyncCallback(StartComplete));
Exception completionException;
ServiceDurableInstance durableInstance;
object[] inputs;
ServiceOperationInvoker invoker;
OperationContext operationContext;
object[] outputs;
object returnValue;
object serviceInstance;
public InvokeAsyncResult(ServiceDurableInstance instance, object[] inputs, ServiceOperationInvoker invoker, bool canCreateInstance, AsyncCallback callback, object state)
: base(callback, state)
{
this.invoker = invoker;
this.inputs = inputs;
this.durableInstance = instance;
this.operationContext = OperationContext.Current;
IAsyncResult result = this.durableInstance.BeginStartOperation(canCreateInstance, startCallback, this);
if (result.CompletedSynchronously)
{
this.serviceInstance = this.durableInstance.EndStartOperation(result);
if (DoInvoke())
{
Complete(true, this.completionException);
}
}
}
public static object End(out object[] outputs, IAsyncResult result)
{
InvokeAsyncResult invokeResult = AsyncResult.End<InvokeAsyncResult>(result);
outputs = invokeResult.outputs;
return invokeResult.returnValue;
}
// We pass the exception to another thread
[SuppressMessage("Reliability", "Reliability104")]
[SuppressMessage("Microsoft.Design", "CA1031")]
static void FinishComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
InvokeAsyncResult invokeResult = result.AsyncState as InvokeAsyncResult;
Fx.Assert(invokeResult != null, "Async state should have been of type InvokeAsyncResult.");
try
{
invokeResult.durableInstance.EndFinishOperation(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
invokeResult.completionException = e;
}
invokeResult.Complete(false, invokeResult.completionException);
}
// We pass the exception to another thread
[SuppressMessage("Reliability", "Reliability104")]
[SuppressMessage("Microsoft.Design", "CA1031")]
static void InvokeComplete(IAsyncResult resultParameter)
{
if (resultParameter.CompletedSynchronously)
{
return;
}
InvokeAsyncResult invokeResult = resultParameter.AsyncState as InvokeAsyncResult;
Fx.Assert(invokeResult != null,
"Async state should have been of type InvokeAsyncResult.");
try
{
invokeResult.returnValue = invokeResult.invoker.innerInvoker.InvokeEnd(invokeResult.serviceInstance, out invokeResult.outputs, resultParameter);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ServiceErrorHandler.MarkException(e);
invokeResult.completionException = e;
}
finally
{
if (invokeResult.DoFinish())
{
invokeResult.Complete(false, invokeResult.completionException);
}
}
}
// We pass the exception to another thread
[SuppressMessage("Reliability", "Reliability104")]
[SuppressMessage("Microsoft.Design", "CA1031")]
static void StartComplete(IAsyncResult resultParameter)
{
if (resultParameter.CompletedSynchronously)
{
return;
}
InvokeAsyncResult invokeResult = resultParameter.AsyncState as InvokeAsyncResult;
Fx.Assert(invokeResult != null,
"Async state should have been of type InvokeAsyncResult.");
try
{
invokeResult.serviceInstance = invokeResult.durableInstance.EndStartOperation(resultParameter);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
invokeResult.Complete(false, e);
return;
}
if (invokeResult.DoInvoke())
{
invokeResult.Complete(false, invokeResult.completionException);
}
}
// We pass the exception to another thread
[SuppressMessage("Reliability", "Reliability104")]
[SuppressMessage("Microsoft.Design", "CA1031")]
bool DoFinish()
{
try
{
IAsyncResult result = this.durableInstance.BeginFinishOperation(this.invoker.completesInstance, this.invoker.contractCausesSave, this.completionException, finishCallback, this);
if (result.CompletedSynchronously)
{
this.durableInstance.EndFinishOperation(result);
return true;
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.completionException = e;
return true;
}
return false;
}
// We pass the exception to another thread
[SuppressMessage("Reliability", "Reliability104")]
[SuppressMessage("Microsoft.Design", "CA1031")]
bool DoInvoke()
{
bool finishNow = false;
try
{
IAsyncResult result = null;
using (OperationContextScope operationScope = new OperationContextScope(this.operationContext))
{
result = this.invoker.innerInvoker.InvokeBegin(this.serviceInstance, this.inputs, invokeCallback, this);
}
if (result.CompletedSynchronously)
{
this.returnValue = this.invoker.innerInvoker.InvokeEnd(this.serviceInstance, out this.outputs, result);
finishNow = true;
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ServiceErrorHandler.MarkException(e);
this.completionException = e;
finishNow = true;
}
if (finishNow)
{
if (DoFinish())
{
return true;
}
}
return false;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System;
namespace AgentManagerNamespace
{
//! Class that identifies each agent that takes part in the agent system.
public class Agent
{
#region PUBLIC_MEMBER_VARIABLES
#endregion // PUBLIC_MEMBER_VARIABLES
#region PRIVATE_MEMBER_VARIABLES
// ID name for the agent
private string _name;
// Reference to the character GameObject
private GameObject _character;
// Possible animations in the Agent.
private Dictionary<string, int> _animationNames = new Dictionary<string, int> ();
// Is this animation needed to be reset.
private Dictionary<string, bool> _resetAnimationNames = new Dictionary<string, bool> ();
// Possible components in the Agent.
private Dictionary<System.Type, int> _actionTypes = new Dictionary<System.Type, int> ();
// Layers
private List<Layer> _layers = new List<Layer> ();
// First Update of Agent
private bool _firstTimeUpdate = true;
// Agent enabled
private bool _enabled;
// Animation controller
private AnimationController _animationController;
// Architectures
private List<IArchitertureConfiguration> _architectures = new List<IArchitertureConfiguration>();
// Architecture Perception
private List<IPerceptionAction> _architecturePerceptions = new List<IPerceptionAction>();
// Global Logic Controller
private LogicControllerAbstract _logicController;
#endregion // PRIVATE_MEMBER_VARIABLES
#region GETTERS_AND_SETTERS_METHODS
/// Enables the Agent.
public bool Enabled {
get { return _enabled; }
set {
if (!_enabled && value) {
_logicController.Start();
foreach (IPerceptionAction ip in _architecturePerceptions)
{
ip.CustomStart();
}
foreach (var layer in _layers) {
layer.Enabled = true;
}
}
if (_enabled && !value) {
foreach (var layer in _layers) {
layer.Enabled = false;
}
}
_enabled = value;
}
}
/// The Id name that identifies the Agent.
public string Name { get { return _name; } }
/// Agent that contains this state.
public AgentManager AgentManager { get; set; }
/// The Id name that identifies the Agent.
public AnimationController AnimationController { get { return _animationController; } }
//! Possible animations in this Agent.
public Dictionary<string, int> AnimationNames {
get { return _animationNames; }
}
//! Possible actions in this Agent.
public Dictionary<System.Type, int> ActionTypes {
get { return _actionTypes; }
}
//! Possible animations in this Agent.
public Dictionary<string, bool> ResetAnimationNames {
get { return _resetAnimationNames; }
}
/** @brief Get the Initial state of an agent layer.
*
* @param layer Agent layer wanted.
*/
public State GetInitialState (int layerId = 0)
{
return _layers [layerId].InitialState;
}
#endregion // GETTERS_AND_SETTERS_METHODS
#region PUBLIC_METHODS
//! Updates the state of the agent
public void Update ()
{
if (Enabled) {
_logicController.Update ();
foreach (Layer layerI in _layers) {
layerI.Update ();
}
}
}
/** \brief Creates an Agent object.
*
* @param agentName Id name for the agent.
*/
public Agent (string agentName)
{
_name = agentName;
}
/** \brief Creates an Agent object.
*
* @param agentName Id name for the agent.
* @param character GameObject to be associated to the Agent
*/
public Agent (string agentName, GameObject character)
{
_name = agentName;
_character = character;
_character.AddComponent<AgentIdentity> ().Initilize(agentName);
_animationController = new AnimationController (character);
}
/** \brief Equality between Agent and Object.
*
* @param obj Object to compare with.
*/
public override bool Equals (object obj)
{
if (obj == null)
return false;
Agent agent = obj as Agent;
if (agent == null)
return false;
else
return Equals (agent);
}
/** \brief Equality between Agents.
*
* @param agent Agent to compare with.
*/
public bool Equals (Agent agent)
{
if (agent == null)
return false;
return (this.Name.Equals (agent.Name));
}
public void AddLogicController<L>()
where L:LogicControllerAbstract, new()
{
_logicController = new L ();
_logicController.Initialize(this);
_logicController.Awake ();
}
public L GetLogicController<L>()
where L:LogicControllerAbstract, new()
{
if (_logicController.GetType () != typeof(L))
return null;
return (L)_logicController;
}
public void AddArchitecture<T> ()
where T:IArchitertureConfiguration, new()
{
IArchitertureConfiguration architecture = new T ();
architecture.Initialize (this, _character);
_architectures.Add (architecture);
IPerceptionAction perception = architecture.IPerceptionAction;
perception.Initialize(_character);
perception.CustomAwake();
_architecturePerceptions.Add(perception);
}
/** \brief Add an State to this Agent.
*
* @param stateName Id name for the state.
* @param layerId Adds the state in the state layer passed.
* @param bitmask Hide lower layers when it bit is 0
* @return A refence to de state created, null if it has not been created.
*/
public bool AddState (string stateName, int layerId = 0, int bitmask = 0, float fixedDuration = 0)
{
State newState = new State (stateName, _character, bitmask, fixedDuration);
if (AddState (newState, layerId))
return true;
return false;
}
/** \brief Add an State to this Agent.
*
* @param stateName Id name for the state.
* @param layerId Adds the state in the state layer passed.
* @param componentType The type component associated with this state
* @param animationName The animation name associated with this state
* @param bitmask Hide lower layers when it bit is 0
* @return A refence to de state created, null if it has not been created.
*/
public bool AddState<L> (string stateName, string animationName, int layerId = 0, int bitmask = 0, float fixedDuration = 0)
where L:ILogicAction, new()
{
State newState = new State (stateName, _character, bitmask, fixedDuration);
if (AddState (newState, layerId)) {
if (!newState.AddAction<L> ()) {
RemoveState (newState);
return false;
}
newState.SetAnimation (animationName);
return true;
}
return false;
}
/** \brief Add an State to this Agent.
*
* @param stateName Id name for the state.
* @param layerId Adds the state in the state layer passed.
* @param componentType The type component associated with this state
* @param bitmask Hide lower layers when it bit is 0
* @return A refence to de state created, null if it has not been created.
*/
public bool AddState<L> (string stateName, int layerId = 0, int bitmask = 0, float fixedDuration = 0)
where L:ILogicAction, new()
{
State newState = new State (stateName, _character, bitmask, fixedDuration);
if (AddState (newState, layerId)) {
if (!newState.AddAction<L> ()) {
RemoveState (newState);
return false;
}
return true;
}
return false;
}
/** \brief Add an State to this Agent.
*
* @param stateName Id name for the state.
* @param layerId Adds the state in the state layer passed.
* @param animationName The animation name associated with this state
* @param bitmask Hide lower layers when it bit is 0
* @return A refence to de state created, null if it has not been created.
*/
public bool AddState (string stateName, string animationName, int layerId = 0, int bitmask = 0, float fixedDuration = 0)
{
State newState = new State (stateName, _character, bitmask, fixedDuration);
if (AddState (newState, layerId)) {
newState.SetAnimation (animationName);
return true;
}
return false;
}
/** @brief Add a transition between two states.
*
* @param originStateName The name of the State to transitate from.
* @param targetStateName The name of the State to transitate to.
* @param trigget Trigger that determinates when to transitate.
* @param layerId The layer in which the states has to be found.
* @param priotity The prority to be actived.
* @return A reference to the transition created.
*/
public bool AddTransition (string originStateName, string targetStateName, TransitionTrigger trigger, int layerId = 0, int priority = 0)
{
Layer layerAux = FindLayer (layerId);
if (layerAux == null) {
Debug.LogWarningFormat ("The transition {0}-{1} has not been added, no exists state {2} in layer {3}.",
originStateName, targetStateName, originStateName, layerId);
return false;
}
Transition newTransition = layerAux.AddTransition (originStateName, targetStateName, trigger, priority);
if (newTransition == null)
Debug.LogWarningFormat ("The transition {0}-{1} has not been added to the state {2} in layer {3}.",
originStateName, targetStateName, originStateName, layerId);
return true;
}
/** @brief Add a Component(Script) to be enabled in a State.
*
* If the component is already created in the game object it returns it.
* @param typeComponent Script component to be enabled.
* @param stateName State to add the component.
* @param layerId Layer where the state is.
* @param reset Force to reenable a script if it were already actived
* @return Return true if the animation has been added.
*/
public bool AddAction<L> (string stateName, int layerId = 0)
where L: ILogicAction, new()
{
State state = FindState (stateName, layerId);
if (state == null) {
Debug.LogWarningFormat ("The state {0} could not be found in layer {1}.", stateName, layerId);
return false;
}
return state.AddAction<L> ();
}
/** @brief Add a animation name to the actived animations in a State.
*
* @param animationName The name of the animation to be actived.
* @param stateName State to add the animation.
* @param layerId Layer where the state is.
* @param reset Force to turn off the animation before activating it
* @return Return true if the animation has been added.
*/
public bool SetAnimation (string animationName, string stateName, int layerId = 0)
{
State auxState = FindState (stateName, layerId);
if (auxState == null) {
Debug.LogWarningFormat ("The state {0} could not be found in layer {1}.", stateName, layerId);
return false;
}
auxState.SetAnimation (animationName);
return true;
}
/** @brief Check if an state is activated with stateName in layerId.
*
* @param stateName State to check.
* @param layerId Layer where the state is.
* @return Return true if the state is actived.
*/
public bool IsStateActivated (string stateName, int layerId = 0)
{
State state = FindState (stateName, layerId);
if (state == null) {
Debug.LogWarningFormat ("The state {0} could not be found in layer {1}.", stateName, layerId);
return false;
}
return state.Actived;
}
/** @brief Check if the agent has any activated state in any layer with this name.
*
* @param stateName State to check.
* @return Return true if the state exists and is actived.
*/
public bool IsAnyActivatedState (string stateName)
{
List<State> states = FindState (stateName);
foreach (State state in states) {
if (state.Actived)
return true;
}
return false;
}
public bool SetInitialState (string stateName, int layerId = 0)
{
State stateAux = FindState (stateName, layerId);
if (stateAux == null) {
Debug.LogWarningFormat ("The state {0} could not be found in layer {1}.", stateName, layerId);
return false;
}
Layer layerAux = FindLayer (layerId);
if (layerAux == null) {
Debug.LogWarningFormat ("The Layer {0} could not be found in Agent {1}.", layerId, Name);
return false;
}
layerAux.InitialState = stateAux;
return true;
}
/** @brief Find a Layer in an Agent by Id.
*
* @param layerId The id of the Layer to be found.
* @return The Layer found or null if it does not exist.
*/
public Layer FindLayer (int layerId)
{
return _layers.Find (layer => layer.Id == layerId);
}
/** @brief Sends diffents messages types to state components
*
* @param agentName The agent to send the message
* @param msgType The type of message
* @param content The content of the message
* @return True if the message has been successfully sent
*/
public bool SendMsg (string stateName, object value, Agent sender = null, AgentManager.MsgType msgType = AgentManager.MsgType.STARDAR_MSG)
{
List<State> states = FindState (stateName);
if (states.Count == 0) {
Debug.LogWarningFormat ("The state {0} was not found to sent the message.", stateName);
return false;
}
if (msgType == AgentManager.MsgType.INTERRUPTING_MSG) {
foreach (State state in states) {
// It is needed to update changes made by the messages before checking transitions
state.Layer.ActiveInterruptingState (state, value, sender);
}
}
else {
foreach (State state in states) {
state.Layer.SendStandarMessage (state, value, sender);
}
}
return true;
}
/** @brief Sends diffents messages types to state components
*
* @param agentName The agent to send the message
* @param msgType The type of message
* @param content The content of the message
* @return True if the message has been successfully sent
*/
public bool SendMsg (string stateName, int layerId, object value, Agent sender = null, AgentManager.MsgType msgType = AgentManager.MsgType.STARDAR_MSG)
{
State state = FindState (stateName, layerId);
if (state == null) {
Debug.LogWarningFormat ("The state {0} was not found to sent the message.", stateName);
return false;
}
if (msgType == AgentManager.MsgType.INTERRUPTING_MSG) {
state.Layer.ActiveInterruptingState (state, value, sender);
}
else {
state.Layer.SendStandarMessage (state, value, sender);
}
return true;
}
#endregion // PUBLIC_METHODS
#region PRIVATE_METHODS
/** @brief Add an State to the Agent.
*
* @param state State object to be added.
* @param layerId Adds the state in the state layer passed.
* @return Returns true if the addition has been successfully done.
*/
private bool AddState (State state, int layerId = 0)
{
Layer layerAux = FindLayer (layerId);
if (layerAux == null)
layerAux = AddLayer (layerId);
if (layerAux.AddState (state))
return true;
Debug.LogWarningFormat ("The state {0} has not been added to layer {1}.", state.Name, layerId);
return false;
}
/** @brief Remove an State of the Agent.
*
* @param state State to remove
* @param layerId Layer to remove from.
* @return Returns true if the addition has been successfully done.
*/
private bool RemoveState (State state, int layerId = 0)
{
Layer layerAux = FindLayer (layerId);
if (layerAux == null)
return false;
return layerAux.RemoveState (state);
}
/** @brief Find a State in a Layer by name.
*
* @param stateName The name of the state to be found.
* @param layerId Layer to search in.
* @return The State searched or null if it does not exist.
*/
private State FindState (string stateName, int layerId)
{
Layer layerAux = FindLayer (layerId);
if (layerAux == null)
return null;
return layerAux.FindState (stateName);
}
/** @brief Find a State in an Agent by name.
*
* @param stateName The name of the state to be found.
* @return The States found or null if it does not exist.
*/
private List<State> FindState (string stateName)
{
List<State> result = new List<State> ();
foreach (Layer layerI in _layers) {
State stateFound = layerI.FindState (stateName);
if (stateFound != null) {
result.Add (stateFound);
}
}
return result;
}
/** @brief Add layer to this Agent
*
* @param layerId The id of the new Layer
*/
private Layer AddLayer (int layerId)
{
// Check if this layer alreary exists.
if (_layers.Find (layer => layer.Id == layerId) != null) {
Debug.LogWarningFormat ("The layer {0} does already exist in the agent {1}.", layerId, Name);
return null;
}
Layer newLayer = new Layer (layerId);
newLayer.Agent = this;
_layers.Add (newLayer);
_layers.Sort ();
return newLayer;
}
#endregion // PRIVATE_METHODS
}
}
| |
#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.Globalization;
using System.Reflection;
using System.Xml;
using log4net.Appender;
using log4net.Util;
using log4net.Core;
using log4net.ObjectRenderer;
namespace log4net.Repository.Hierarchy
{
/// <summary>
/// Initializes the log4net environment using an XML DOM.
/// </summary>
/// <remarks>
/// <para>
/// Configures a <see cref="Hierarchy"/> using an XML DOM.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class XmlHierarchyConfigurator
{
private enum ConfigUpdateMode
{
Merge,
Overwrite
}
#region Public Instance Constructors
/// <summary>
/// Construct the configurator for a hierarchy
/// </summary>
/// <param name="hierarchy">The hierarchy to build.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="XmlHierarchyConfigurator" /> class
/// with the specified <see cref="Hierarchy" />.
/// </para>
/// </remarks>
public XmlHierarchyConfigurator(Hierarchy hierarchy)
{
m_hierarchy = hierarchy;
m_appenderBag = new Hashtable();
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Configure the hierarchy by parsing a DOM tree of XML elements.
/// </summary>
/// <param name="element">The root element to parse.</param>
/// <remarks>
/// <para>
/// Configure the hierarchy by parsing a DOM tree of XML elements.
/// </para>
/// </remarks>
public void Configure(XmlElement element)
{
if (element == null || m_hierarchy == null)
{
return;
}
string rootElementName = element.LocalName;
if (rootElementName != CONFIGURATION_TAG)
{
LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element.");
return;
}
if (!LogLog.EmitInternalMessages)
{
// Look for a emitDebug attribute to enable internal debug
string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR);
LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "].");
if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null")
{
LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true);
}
else
{
LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute.");
}
}
if (!LogLog.InternalDebugging)
{
// Look for a debug attribute to enable internal debug
string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR);
LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR+" attribute [" + debugAttribute + "].");
if (debugAttribute.Length>0 && debugAttribute != "null")
{
LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true);
}
else
{
LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
}
string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR);
if (confDebug.Length>0 && confDebug != "null")
{
LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated.");
LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead.");
LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true);
}
}
// Default mode is merge
ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge;
// Look for the config update attribute
string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR);
if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0)
{
// Parse the attribute
try
{
configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute);
}
catch
{
LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]");
}
}
// IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0
LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "].");
// Only reset configuration if overwrite flag specified
if (configUpdateMode == ConfigUpdateMode.Overwrite)
{
// Reset to original unset configuration
m_hierarchy.ResetConfiguration();
LogLog.Debug(declaringType, "Configuration reset before reading config.");
}
/* Building Appender objects, placing them in a local namespace
for future reference */
/* Process all the top level elements */
foreach (XmlNode currentNode in element.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement)currentNode;
if (currentElement.LocalName == LOGGER_TAG)
{
ParseLogger(currentElement);
}
else if (currentElement.LocalName == CATEGORY_TAG)
{
// TODO: deprecated use of category
ParseLogger(currentElement);
}
else if (currentElement.LocalName == ROOT_TAG)
{
ParseRoot(currentElement);
}
else if (currentElement.LocalName == RENDERER_TAG)
{
ParseRenderer(currentElement);
}
else if (currentElement.LocalName == APPENDER_TAG)
{
// We ignore appenders in this pass. They will
// be found and loaded if they are referenced.
}
else
{
// Read the param tags and set properties on the hierarchy
SetParameter(currentElement, m_hierarchy);
}
}
}
// Lastly set the hierarchy threshold
string thresholdStr = element.GetAttribute(THRESHOLD_ATTR);
LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]");
if (thresholdStr.Length > 0 && thresholdStr != "null")
{
Level thresholdLevel = (Level) ConvertStringTo(typeof(Level), thresholdStr);
if (thresholdLevel != null)
{
m_hierarchy.Threshold = thresholdLevel;
}
else
{
LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)");
}
}
// Done reading config
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Parse appenders by IDREF.
/// </summary>
/// <param name="appenderRef">The appender ref element.</param>
/// <returns>The instance of the appender that the ref refers to.</returns>
/// <remarks>
/// <para>
/// Parse an XML element that represents an appender and return
/// the appender.
/// </para>
/// </remarks>
protected IAppender FindAppenderByReference(XmlElement appenderRef)
{
string appenderName = appenderRef.GetAttribute(REF_ATTR);
IAppender appender = (IAppender)m_appenderBag[appenderName];
if (appender != null)
{
return appender;
}
else
{
// Find the element with that id
XmlElement element = null;
if (appenderName != null && appenderName.Length > 0)
{
foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG))
{
if (curAppenderElement.GetAttribute("name") == appenderName)
{
element = curAppenderElement;
break;
}
}
}
if (element == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found.");
return null;
}
else
{
appender = ParseAppender(element);
if (appender != null)
{
m_appenderBag[appenderName] = appender;
}
return appender;
}
}
}
/// <summary>
/// Parses an appender element.
/// </summary>
/// <param name="appenderElement">The appender element.</param>
/// <returns>The appender instance or <c>null</c> when parsing failed.</returns>
/// <remarks>
/// <para>
/// Parse an XML element that represents an appender and return
/// the appender instance.
/// </para>
/// </remarks>
protected IAppender ParseAppender(XmlElement appenderElement)
{
string appenderName = appenderElement.GetAttribute(NAME_ATTR);
string typeName = appenderElement.GetAttribute(TYPE_ATTR);
LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]");
try
{
IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true));
appender.Name = appenderName;
foreach (XmlNode currentNode in appenderElement.ChildNodes)
{
/* We're only interested in Elements */
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement)currentNode;
// Look for the appender ref tag
if (currentElement.LocalName == APPENDER_REF_TAG)
{
string refName = currentElement.GetAttribute(REF_ATTR);
IAppenderAttachable appenderContainer = appender as IAppenderAttachable;
if (appenderContainer != null)
{
LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "].");
IAppender referencedAppender = FindAppenderByReference(currentElement);
if (referencedAppender != null)
{
appenderContainer.AddAppender(referencedAppender);
}
}
else
{
LogLog.Error(declaringType, "Requesting attachment of appender named ["+refName+ "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable.");
}
}
else
{
// For all other tags we use standard set param method
SetParameter(currentElement, appender);
}
}
}
IOptionHandler optionHandler = appender as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
LogLog.Debug(declaringType, "reated Appender [" + appenderName + "]");
return appender;
}
catch (Exception ex)
{
// Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender
LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex);
return null;
}
}
/// <summary>
/// Parses a logger element.
/// </summary>
/// <param name="loggerElement">The logger element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a logger.
/// </para>
/// </remarks>
protected void ParseLogger(XmlElement loggerElement)
{
// Create a new log4net.Logger object from the <logger> element.
string loggerName = loggerElement.GetAttribute(NAME_ATTR);
LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "].");
Logger log = m_hierarchy.GetLogger(loggerName) as Logger;
// Setting up a logger needs to be an atomic operation, in order
// to protect potential log operations while logger
// configuration is in progress.
lock(log)
{
bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true);
LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "].");
log.Additivity = additivity;
ParseChildrenOfLoggerElement(loggerElement, log, false);
}
}
/// <summary>
/// Parses the root logger element.
/// </summary>
/// <param name="rootElement">The root element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents the root logger.
/// </para>
/// </remarks>
protected void ParseRoot(XmlElement rootElement)
{
Logger root = m_hierarchy.Root;
// logger configuration needs to be atomic
lock(root)
{
ParseChildrenOfLoggerElement(rootElement, root, true);
}
}
/// <summary>
/// Parses the children of a logger element.
/// </summary>
/// <param name="catElement">The category element.</param>
/// <param name="log">The logger instance.</param>
/// <param name="isRoot">Flag to indicate if the logger is the root logger.</param>
/// <remarks>
/// <para>
/// Parse the child elements of a <logger> element.
/// </para>
/// </remarks>
protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot)
{
// Remove all existing appenders from log. They will be
// reconstructed if need be.
log.RemoveAllAppenders();
foreach (XmlNode currentNode in catElement.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement) currentNode;
if (currentElement.LocalName == APPENDER_REF_TAG)
{
IAppender appender = FindAppenderByReference(currentElement);
string refName = currentElement.GetAttribute(REF_ATTR);
if (appender != null)
{
LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "].");
log.AddAppender(appender);
}
else
{
LogLog.Error(declaringType, "Appender named [" + refName + "] not found.");
}
}
else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG)
{
ParseLevel(currentElement, log, isRoot);
}
else
{
SetParameter(currentElement, log);
}
}
}
IOptionHandler optionHandler = log as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
}
/// <summary>
/// Parses an object renderer.
/// </summary>
/// <param name="element">The renderer element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a renderer.
/// </para>
/// </remarks>
protected void ParseRenderer(XmlElement element)
{
string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR);
string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR);
LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "].");
IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null);
if (renderer == null)
{
LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "].");
return;
}
else
{
try
{
m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer);
}
catch(Exception e)
{
LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e);
}
}
}
/// <summary>
/// Parses a level element.
/// </summary>
/// <param name="element">The level element.</param>
/// <param name="log">The logger object to set the level on.</param>
/// <param name="isRoot">Flag to indicate if the logger is the root logger.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a level.
/// </para>
/// </remarks>
protected void ParseLevel(XmlElement element, Logger log, bool isRoot)
{
string loggerName = log.Name;
if (isRoot)
{
loggerName = "root";
}
string levelStr = element.GetAttribute(VALUE_ATTR);
LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "].");
if (INHERITED == levelStr)
{
if (isRoot)
{
LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive.");
}
else
{
LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent.");
log.Level = null;
}
}
else
{
log.Level = log.Hierarchy.LevelMap[levelStr];
if (log.Level == null)
{
LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "].");
}
else
{
LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "].");
}
}
}
/// <summary>
/// Sets a parameter on an object.
/// </summary>
/// <param name="element">The parameter element.</param>
/// <param name="target">The object to set the parameter on.</param>
/// <remarks>
/// The parameter name must correspond to a writable property
/// on the object. The value of the parameter is a string,
/// therefore this function will attempt to set a string
/// property first. If unable to set a string property it
/// will inspect the property and its argument type. It will
/// attempt to call a static method called <c>Parse</c> on the
/// type of the property. This method will take a single
/// string argument and return a value that can be used to
/// set the property.
/// </remarks>
protected void SetParameter(XmlElement element, object target)
{
// Get the property name
string name = element.GetAttribute(NAME_ATTR);
// If the name attribute does not exist then use the name of the element
if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
{
name = element.LocalName;
}
// Look for the property on the target object
Type targetType = target.GetType();
Type propertyType = null;
PropertyInfo propInfo = null;
MethodInfo methInfo = null;
// Try to find a writable property
propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (propInfo != null && propInfo.CanWrite)
{
// found a property
propertyType = propInfo.PropertyType;
}
else
{
propInfo = null;
// look for a method with the signature Add<property>(type)
methInfo = FindMethodInfo(targetType, name);
if (methInfo != null)
{
propertyType = methInfo.GetParameters()[0].ParameterType;
}
}
if (propertyType == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
}
else
{
string propertyValue = null;
if (element.GetAttributeNode(VALUE_ATTR) != null)
{
propertyValue = element.GetAttribute(VALUE_ATTR);
}
else if (element.HasChildNodes)
{
// Concatenate the CDATA and Text nodes together
foreach(XmlNode childNode in element.ChildNodes)
{
if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text)
{
if (propertyValue == null)
{
propertyValue = childNode.InnerText;
}
else
{
propertyValue += childNode.InnerText;
}
}
}
}
if(propertyValue != null)
{
#if !NETCF
try
{
// Expand environment variables in the string.
propertyValue = OptionConverter.SubstituteVariables(propertyValue, Environment.GetEnvironmentVariables());
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// unrestricted environment permission. If this occurs the expansion
// will be skipped with the following warning message.
LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
}
#endif
Type parsedObjectConversionTargetType = null;
// Check if a specific subtype is specified on the element using the 'type' attribute
string subTypeString = element.GetAttribute(TYPE_ATTR);
if (subTypeString != null && subTypeString.Length > 0)
{
// Read the explicit subtype
try
{
Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true);
LogLog.Debug(declaringType, "Parameter ["+name+"] specified subtype ["+subType.FullName+"]");
if (!propertyType.IsAssignableFrom(subType))
{
// Check if there is an appropriate type converter
if (OptionConverter.CanConvertTypeTo(subType, propertyType))
{
// Must re-convert to the real property type
parsedObjectConversionTargetType = propertyType;
// Use sub type as intermediary type
propertyType = subType;
}
else
{
LogLog.Error(declaringType, "subtype ["+subType.FullName+"] set on ["+name+"] is not a subclass of property type ["+propertyType.FullName+"] and there are no acceptable type conversions.");
}
}
else
{
// The subtype specified is found and is actually a subtype of the property
// type, therefore we can switch to using this type.
propertyType = subType;
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to find type ["+subTypeString+"] set on ["+name+"]", ex);
}
}
// Now try to convert the string value to an acceptable type
// to pass to this property.
object convertedValue = ConvertStringTo(propertyType, propertyValue);
// Check if we need to do an additional conversion
if (convertedValue != null && parsedObjectConversionTargetType != null)
{
LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]");
convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType);
}
if (convertedValue != null)
{
if (propInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");
try
{
// Pass to the property
propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
}
}
else if (methInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");
try
{
// Pass to the property
methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {convertedValue}, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
}
}
}
else
{
LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
}
}
else
{
object createdObject = null;
if (propertyType == typeof(string) && !HasAttributesOrElements(element))
{
// If the property is a string and the element is empty (no attributes
// or child elements) then we special case the object value to an empty string.
// This is necessary because while the String is a class it does not have
// a default constructor that creates an empty string, which is the behavior
// we are trying to simulate and would be expected from CreateObjectFromXml
createdObject = "";
}
else
{
// No value specified
Type defaultObjectType = null;
if (IsTypeConstructible(propertyType))
{
defaultObjectType = propertyType;
}
createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType);
}
if (createdObject == null)
{
LogLog.Error(declaringType, "Failed to create object to set param: "+name);
}
else
{
if (propInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Property ["+ propInfo.Name +"] to object ["+ createdObject +"]");
try
{
// Pass to the property
propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
}
}
else if (methInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Collection Property ["+ methInfo.Name +"] to object ["+ createdObject +"]");
try
{
// Pass to the property
methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {createdObject}, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
}
}
}
}
}
}
/// <summary>
/// Test if an element has no attributes or child elements
/// </summary>
/// <param name="element">the element to inspect</param>
/// <returns><c>true</c> if the element has any attributes or child elements, <c>false</c> otherwise</returns>
private bool HasAttributesOrElements(XmlElement element)
{
foreach(XmlNode node in element.ChildNodes)
{
if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element)
{
return true;
}
}
return false;
}
/// <summary>
/// Test if a <see cref="Type"/> is constructible with <c>Activator.CreateInstance</c>.
/// </summary>
/// <param name="type">the type to inspect</param>
/// <returns><c>true</c> if the type is creatable using a default constructor, <c>false</c> otherwise</returns>
private static bool IsTypeConstructible(Type type)
{
if (type.IsClass && !type.IsAbstract)
{
ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]);
if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate)
{
return true;
}
}
return false;
}
/// <summary>
/// Look for a method on the <paramref name="targetType"/> that matches the <paramref name="name"/> supplied
/// </summary>
/// <param name="targetType">the type that has the method</param>
/// <param name="name">the name of the method</param>
/// <returns>the method info found</returns>
/// <remarks>
/// <para>
/// The method must be a public instance method on the <paramref name="targetType"/>.
/// The method must be named <paramref name="name"/> or "Add" followed by <paramref name="name"/>.
/// The method must take a single parameter.
/// </para>
/// </remarks>
private MethodInfo FindMethodInfo(Type targetType, string name)
{
string requiredMethodNameA = name;
string requiredMethodNameB = "Add" + name;
MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach(MethodInfo methInfo in methods)
{
if (!methInfo.IsStatic)
{
if (string.Compare(methInfo.Name, requiredMethodNameA, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ||
string.Compare(methInfo.Name, requiredMethodNameB, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
// Found matching method name
// Look for version with one arg only
System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters();
if (methParams.Length == 1)
{
return methInfo;
}
}
}
}
return null;
}
/// <summary>
/// Converts a string value to a target type.
/// </summary>
/// <param name="type">The type of object to convert the string to.</param>
/// <param name="value">The string value to use as the value of the object.</param>
/// <returns>
/// <para>
/// An object of type <paramref name="type"/> with value <paramref name="value"/> or
/// <c>null</c> when the conversion could not be performed.
/// </para>
/// </returns>
protected object ConvertStringTo(Type type, string value)
{
// Hack to allow use of Level in property
if (typeof(Level) == type)
{
// Property wants a level
Level levelValue = m_hierarchy.LevelMap[value];
if (levelValue == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified ["+ value +"]");
}
return levelValue;
}
return OptionConverter.ConvertStringTo(type, value);
}
/// <summary>
/// Creates an object as specified in XML.
/// </summary>
/// <param name="element">The XML element that contains the definition of the object.</param>
/// <param name="defaultTargetType">The object type to use if not explicitly specified.</param>
/// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param>
/// <returns>The object or <c>null</c></returns>
/// <remarks>
/// <para>
/// Parse an XML element and create an object instance based on the configuration
/// data.
/// </para>
/// <para>
/// The type of the instance may be specified in the XML. If not
/// specified then the <paramref name="defaultTargetType"/> is used
/// as the type. However the type is specified it must support the
/// <paramref name="typeConstraint"/> type.
/// </para>
/// </remarks>
protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
{
Type objectType = null;
// Get the object type
string objectTypeString = element.GetAttribute(TYPE_ATTR);
if (objectTypeString == null || objectTypeString.Length == 0)
{
if (defaultTargetType == null)
{
LogLog.Error(declaringType, "Object type not specified. Cannot create object of type ["+typeConstraint.FullName+"]. Missing Value or Type.");
return null;
}
else
{
// Use the default object type
objectType = defaultTargetType;
}
}
else
{
// Read the explicit object type
try
{
objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to find type ["+objectTypeString+"]", ex);
return null;
}
}
bool requiresConversion = false;
// Got the object type. Check that it meets the typeConstraint
if (typeConstraint != null)
{
if (!typeConstraint.IsAssignableFrom(objectType))
{
// Check if there is an appropriate type converter
if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint))
{
requiresConversion = true;
}
else
{
LogLog.Error(declaringType, "Object type ["+objectType.FullName+"] is not assignable to type ["+typeConstraint.FullName+"]. There are no acceptable type conversions.");
return null;
}
}
}
// Create using the default constructor
object createdObject = null;
try
{
createdObject = Activator.CreateInstance(objectType);
}
catch(Exception createInstanceEx)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: "+createInstanceEx.ToString());
}
// Set any params on object
foreach (XmlNode currentNode in element.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
SetParameter((XmlElement)currentNode, createdObject);
}
}
// Check if we need to call ActivateOptions
IOptionHandler optionHandler = createdObject as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
// Ok object should be initialized
if (requiresConversion)
{
// Convert the object type
return OptionConverter.ConvertTypeTo(createdObject, typeConstraint);
}
else
{
// The object is of the correct type
return createdObject;
}
}
#endregion Protected Instance Methods
#region Private Constants
// String constants used while parsing the XML data
private const string CONFIGURATION_TAG = "log4net";
private const string RENDERER_TAG = "renderer";
private const string APPENDER_TAG = "appender";
private const string APPENDER_REF_TAG = "appender-ref";
private const string PARAM_TAG = "param";
// TODO: Deprecate use of category tags
private const string CATEGORY_TAG = "category";
// TODO: Deprecate use of priority tag
private const string PRIORITY_TAG = "priority";
private const string LOGGER_TAG = "logger";
private const string NAME_ATTR = "name";
private const string TYPE_ATTR = "type";
private const string VALUE_ATTR = "value";
private const string ROOT_TAG = "root";
private const string LEVEL_TAG = "level";
private const string REF_ATTR = "ref";
private const string ADDITIVITY_ATTR = "additivity";
private const string THRESHOLD_ATTR = "threshold";
private const string CONFIG_DEBUG_ATTR = "configDebug";
private const string INTERNAL_DEBUG_ATTR = "debug";
private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug";
private const string CONFIG_UPDATE_MODE_ATTR = "update";
private const string RENDERING_TYPE_ATTR = "renderingClass";
private const string RENDERED_TYPE_ATTR = "renderedClass";
// flag used on the level element
private const string INHERITED = "inherited";
#endregion Private Constants
#region Private Instance Fields
/// <summary>
/// key: appenderName, value: appender.
/// </summary>
private Hashtable m_appenderBag;
/// <summary>
/// The Hierarchy being configured.
/// </summary>
private readonly Hierarchy m_hierarchy;
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the XmlHierarchyConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(XmlHierarchyConfigurator);
#endregion Private Static Fields
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type long with 3 components, used for implementing swizzling for lvec3.
/// </summary>
[Serializable]
[DataContract(Namespace = "swizzle")]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_lvec3
{
#region Fields
/// <summary>
/// x-component
/// </summary>
[DataMember]
internal readonly long x;
/// <summary>
/// y-component
/// </summary>
[DataMember]
internal readonly long y;
/// <summary>
/// z-component
/// </summary>
[DataMember]
internal readonly long z;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_lvec3.
/// </summary>
internal swizzle_lvec3(long x, long y, long z)
{
this.x = x;
this.y = y;
this.z = z;
}
#endregion
#region Properties
/// <summary>
/// Returns lvec3.xx swizzling.
/// </summary>
public lvec2 xx => new lvec2(x, x);
/// <summary>
/// Returns lvec3.rr swizzling (equivalent to lvec3.xx).
/// </summary>
public lvec2 rr => new lvec2(x, x);
/// <summary>
/// Returns lvec3.xxx swizzling.
/// </summary>
public lvec3 xxx => new lvec3(x, x, x);
/// <summary>
/// Returns lvec3.rrr swizzling (equivalent to lvec3.xxx).
/// </summary>
public lvec3 rrr => new lvec3(x, x, x);
/// <summary>
/// Returns lvec3.xxxx swizzling.
/// </summary>
public lvec4 xxxx => new lvec4(x, x, x, x);
/// <summary>
/// Returns lvec3.rrrr swizzling (equivalent to lvec3.xxxx).
/// </summary>
public lvec4 rrrr => new lvec4(x, x, x, x);
/// <summary>
/// Returns lvec3.xxxy swizzling.
/// </summary>
public lvec4 xxxy => new lvec4(x, x, x, y);
/// <summary>
/// Returns lvec3.rrrg swizzling (equivalent to lvec3.xxxy).
/// </summary>
public lvec4 rrrg => new lvec4(x, x, x, y);
/// <summary>
/// Returns lvec3.xxxz swizzling.
/// </summary>
public lvec4 xxxz => new lvec4(x, x, x, z);
/// <summary>
/// Returns lvec3.rrrb swizzling (equivalent to lvec3.xxxz).
/// </summary>
public lvec4 rrrb => new lvec4(x, x, x, z);
/// <summary>
/// Returns lvec3.xxy swizzling.
/// </summary>
public lvec3 xxy => new lvec3(x, x, y);
/// <summary>
/// Returns lvec3.rrg swizzling (equivalent to lvec3.xxy).
/// </summary>
public lvec3 rrg => new lvec3(x, x, y);
/// <summary>
/// Returns lvec3.xxyx swizzling.
/// </summary>
public lvec4 xxyx => new lvec4(x, x, y, x);
/// <summary>
/// Returns lvec3.rrgr swizzling (equivalent to lvec3.xxyx).
/// </summary>
public lvec4 rrgr => new lvec4(x, x, y, x);
/// <summary>
/// Returns lvec3.xxyy swizzling.
/// </summary>
public lvec4 xxyy => new lvec4(x, x, y, y);
/// <summary>
/// Returns lvec3.rrgg swizzling (equivalent to lvec3.xxyy).
/// </summary>
public lvec4 rrgg => new lvec4(x, x, y, y);
/// <summary>
/// Returns lvec3.xxyz swizzling.
/// </summary>
public lvec4 xxyz => new lvec4(x, x, y, z);
/// <summary>
/// Returns lvec3.rrgb swizzling (equivalent to lvec3.xxyz).
/// </summary>
public lvec4 rrgb => new lvec4(x, x, y, z);
/// <summary>
/// Returns lvec3.xxz swizzling.
/// </summary>
public lvec3 xxz => new lvec3(x, x, z);
/// <summary>
/// Returns lvec3.rrb swizzling (equivalent to lvec3.xxz).
/// </summary>
public lvec3 rrb => new lvec3(x, x, z);
/// <summary>
/// Returns lvec3.xxzx swizzling.
/// </summary>
public lvec4 xxzx => new lvec4(x, x, z, x);
/// <summary>
/// Returns lvec3.rrbr swizzling (equivalent to lvec3.xxzx).
/// </summary>
public lvec4 rrbr => new lvec4(x, x, z, x);
/// <summary>
/// Returns lvec3.xxzy swizzling.
/// </summary>
public lvec4 xxzy => new lvec4(x, x, z, y);
/// <summary>
/// Returns lvec3.rrbg swizzling (equivalent to lvec3.xxzy).
/// </summary>
public lvec4 rrbg => new lvec4(x, x, z, y);
/// <summary>
/// Returns lvec3.xxzz swizzling.
/// </summary>
public lvec4 xxzz => new lvec4(x, x, z, z);
/// <summary>
/// Returns lvec3.rrbb swizzling (equivalent to lvec3.xxzz).
/// </summary>
public lvec4 rrbb => new lvec4(x, x, z, z);
/// <summary>
/// Returns lvec3.xy swizzling.
/// </summary>
public lvec2 xy => new lvec2(x, y);
/// <summary>
/// Returns lvec3.rg swizzling (equivalent to lvec3.xy).
/// </summary>
public lvec2 rg => new lvec2(x, y);
/// <summary>
/// Returns lvec3.xyx swizzling.
/// </summary>
public lvec3 xyx => new lvec3(x, y, x);
/// <summary>
/// Returns lvec3.rgr swizzling (equivalent to lvec3.xyx).
/// </summary>
public lvec3 rgr => new lvec3(x, y, x);
/// <summary>
/// Returns lvec3.xyxx swizzling.
/// </summary>
public lvec4 xyxx => new lvec4(x, y, x, x);
/// <summary>
/// Returns lvec3.rgrr swizzling (equivalent to lvec3.xyxx).
/// </summary>
public lvec4 rgrr => new lvec4(x, y, x, x);
/// <summary>
/// Returns lvec3.xyxy swizzling.
/// </summary>
public lvec4 xyxy => new lvec4(x, y, x, y);
/// <summary>
/// Returns lvec3.rgrg swizzling (equivalent to lvec3.xyxy).
/// </summary>
public lvec4 rgrg => new lvec4(x, y, x, y);
/// <summary>
/// Returns lvec3.xyxz swizzling.
/// </summary>
public lvec4 xyxz => new lvec4(x, y, x, z);
/// <summary>
/// Returns lvec3.rgrb swizzling (equivalent to lvec3.xyxz).
/// </summary>
public lvec4 rgrb => new lvec4(x, y, x, z);
/// <summary>
/// Returns lvec3.xyy swizzling.
/// </summary>
public lvec3 xyy => new lvec3(x, y, y);
/// <summary>
/// Returns lvec3.rgg swizzling (equivalent to lvec3.xyy).
/// </summary>
public lvec3 rgg => new lvec3(x, y, y);
/// <summary>
/// Returns lvec3.xyyx swizzling.
/// </summary>
public lvec4 xyyx => new lvec4(x, y, y, x);
/// <summary>
/// Returns lvec3.rggr swizzling (equivalent to lvec3.xyyx).
/// </summary>
public lvec4 rggr => new lvec4(x, y, y, x);
/// <summary>
/// Returns lvec3.xyyy swizzling.
/// </summary>
public lvec4 xyyy => new lvec4(x, y, y, y);
/// <summary>
/// Returns lvec3.rggg swizzling (equivalent to lvec3.xyyy).
/// </summary>
public lvec4 rggg => new lvec4(x, y, y, y);
/// <summary>
/// Returns lvec3.xyyz swizzling.
/// </summary>
public lvec4 xyyz => new lvec4(x, y, y, z);
/// <summary>
/// Returns lvec3.rggb swizzling (equivalent to lvec3.xyyz).
/// </summary>
public lvec4 rggb => new lvec4(x, y, y, z);
/// <summary>
/// Returns lvec3.xyz swizzling.
/// </summary>
public lvec3 xyz => new lvec3(x, y, z);
/// <summary>
/// Returns lvec3.rgb swizzling (equivalent to lvec3.xyz).
/// </summary>
public lvec3 rgb => new lvec3(x, y, z);
/// <summary>
/// Returns lvec3.xyzx swizzling.
/// </summary>
public lvec4 xyzx => new lvec4(x, y, z, x);
/// <summary>
/// Returns lvec3.rgbr swizzling (equivalent to lvec3.xyzx).
/// </summary>
public lvec4 rgbr => new lvec4(x, y, z, x);
/// <summary>
/// Returns lvec3.xyzy swizzling.
/// </summary>
public lvec4 xyzy => new lvec4(x, y, z, y);
/// <summary>
/// Returns lvec3.rgbg swizzling (equivalent to lvec3.xyzy).
/// </summary>
public lvec4 rgbg => new lvec4(x, y, z, y);
/// <summary>
/// Returns lvec3.xyzz swizzling.
/// </summary>
public lvec4 xyzz => new lvec4(x, y, z, z);
/// <summary>
/// Returns lvec3.rgbb swizzling (equivalent to lvec3.xyzz).
/// </summary>
public lvec4 rgbb => new lvec4(x, y, z, z);
/// <summary>
/// Returns lvec3.xz swizzling.
/// </summary>
public lvec2 xz => new lvec2(x, z);
/// <summary>
/// Returns lvec3.rb swizzling (equivalent to lvec3.xz).
/// </summary>
public lvec2 rb => new lvec2(x, z);
/// <summary>
/// Returns lvec3.xzx swizzling.
/// </summary>
public lvec3 xzx => new lvec3(x, z, x);
/// <summary>
/// Returns lvec3.rbr swizzling (equivalent to lvec3.xzx).
/// </summary>
public lvec3 rbr => new lvec3(x, z, x);
/// <summary>
/// Returns lvec3.xzxx swizzling.
/// </summary>
public lvec4 xzxx => new lvec4(x, z, x, x);
/// <summary>
/// Returns lvec3.rbrr swizzling (equivalent to lvec3.xzxx).
/// </summary>
public lvec4 rbrr => new lvec4(x, z, x, x);
/// <summary>
/// Returns lvec3.xzxy swizzling.
/// </summary>
public lvec4 xzxy => new lvec4(x, z, x, y);
/// <summary>
/// Returns lvec3.rbrg swizzling (equivalent to lvec3.xzxy).
/// </summary>
public lvec4 rbrg => new lvec4(x, z, x, y);
/// <summary>
/// Returns lvec3.xzxz swizzling.
/// </summary>
public lvec4 xzxz => new lvec4(x, z, x, z);
/// <summary>
/// Returns lvec3.rbrb swizzling (equivalent to lvec3.xzxz).
/// </summary>
public lvec4 rbrb => new lvec4(x, z, x, z);
/// <summary>
/// Returns lvec3.xzy swizzling.
/// </summary>
public lvec3 xzy => new lvec3(x, z, y);
/// <summary>
/// Returns lvec3.rbg swizzling (equivalent to lvec3.xzy).
/// </summary>
public lvec3 rbg => new lvec3(x, z, y);
/// <summary>
/// Returns lvec3.xzyx swizzling.
/// </summary>
public lvec4 xzyx => new lvec4(x, z, y, x);
/// <summary>
/// Returns lvec3.rbgr swizzling (equivalent to lvec3.xzyx).
/// </summary>
public lvec4 rbgr => new lvec4(x, z, y, x);
/// <summary>
/// Returns lvec3.xzyy swizzling.
/// </summary>
public lvec4 xzyy => new lvec4(x, z, y, y);
/// <summary>
/// Returns lvec3.rbgg swizzling (equivalent to lvec3.xzyy).
/// </summary>
public lvec4 rbgg => new lvec4(x, z, y, y);
/// <summary>
/// Returns lvec3.xzyz swizzling.
/// </summary>
public lvec4 xzyz => new lvec4(x, z, y, z);
/// <summary>
/// Returns lvec3.rbgb swizzling (equivalent to lvec3.xzyz).
/// </summary>
public lvec4 rbgb => new lvec4(x, z, y, z);
/// <summary>
/// Returns lvec3.xzz swizzling.
/// </summary>
public lvec3 xzz => new lvec3(x, z, z);
/// <summary>
/// Returns lvec3.rbb swizzling (equivalent to lvec3.xzz).
/// </summary>
public lvec3 rbb => new lvec3(x, z, z);
/// <summary>
/// Returns lvec3.xzzx swizzling.
/// </summary>
public lvec4 xzzx => new lvec4(x, z, z, x);
/// <summary>
/// Returns lvec3.rbbr swizzling (equivalent to lvec3.xzzx).
/// </summary>
public lvec4 rbbr => new lvec4(x, z, z, x);
/// <summary>
/// Returns lvec3.xzzy swizzling.
/// </summary>
public lvec4 xzzy => new lvec4(x, z, z, y);
/// <summary>
/// Returns lvec3.rbbg swizzling (equivalent to lvec3.xzzy).
/// </summary>
public lvec4 rbbg => new lvec4(x, z, z, y);
/// <summary>
/// Returns lvec3.xzzz swizzling.
/// </summary>
public lvec4 xzzz => new lvec4(x, z, z, z);
/// <summary>
/// Returns lvec3.rbbb swizzling (equivalent to lvec3.xzzz).
/// </summary>
public lvec4 rbbb => new lvec4(x, z, z, z);
/// <summary>
/// Returns lvec3.yx swizzling.
/// </summary>
public lvec2 yx => new lvec2(y, x);
/// <summary>
/// Returns lvec3.gr swizzling (equivalent to lvec3.yx).
/// </summary>
public lvec2 gr => new lvec2(y, x);
/// <summary>
/// Returns lvec3.yxx swizzling.
/// </summary>
public lvec3 yxx => new lvec3(y, x, x);
/// <summary>
/// Returns lvec3.grr swizzling (equivalent to lvec3.yxx).
/// </summary>
public lvec3 grr => new lvec3(y, x, x);
/// <summary>
/// Returns lvec3.yxxx swizzling.
/// </summary>
public lvec4 yxxx => new lvec4(y, x, x, x);
/// <summary>
/// Returns lvec3.grrr swizzling (equivalent to lvec3.yxxx).
/// </summary>
public lvec4 grrr => new lvec4(y, x, x, x);
/// <summary>
/// Returns lvec3.yxxy swizzling.
/// </summary>
public lvec4 yxxy => new lvec4(y, x, x, y);
/// <summary>
/// Returns lvec3.grrg swizzling (equivalent to lvec3.yxxy).
/// </summary>
public lvec4 grrg => new lvec4(y, x, x, y);
/// <summary>
/// Returns lvec3.yxxz swizzling.
/// </summary>
public lvec4 yxxz => new lvec4(y, x, x, z);
/// <summary>
/// Returns lvec3.grrb swizzling (equivalent to lvec3.yxxz).
/// </summary>
public lvec4 grrb => new lvec4(y, x, x, z);
/// <summary>
/// Returns lvec3.yxy swizzling.
/// </summary>
public lvec3 yxy => new lvec3(y, x, y);
/// <summary>
/// Returns lvec3.grg swizzling (equivalent to lvec3.yxy).
/// </summary>
public lvec3 grg => new lvec3(y, x, y);
/// <summary>
/// Returns lvec3.yxyx swizzling.
/// </summary>
public lvec4 yxyx => new lvec4(y, x, y, x);
/// <summary>
/// Returns lvec3.grgr swizzling (equivalent to lvec3.yxyx).
/// </summary>
public lvec4 grgr => new lvec4(y, x, y, x);
/// <summary>
/// Returns lvec3.yxyy swizzling.
/// </summary>
public lvec4 yxyy => new lvec4(y, x, y, y);
/// <summary>
/// Returns lvec3.grgg swizzling (equivalent to lvec3.yxyy).
/// </summary>
public lvec4 grgg => new lvec4(y, x, y, y);
/// <summary>
/// Returns lvec3.yxyz swizzling.
/// </summary>
public lvec4 yxyz => new lvec4(y, x, y, z);
/// <summary>
/// Returns lvec3.grgb swizzling (equivalent to lvec3.yxyz).
/// </summary>
public lvec4 grgb => new lvec4(y, x, y, z);
/// <summary>
/// Returns lvec3.yxz swizzling.
/// </summary>
public lvec3 yxz => new lvec3(y, x, z);
/// <summary>
/// Returns lvec3.grb swizzling (equivalent to lvec3.yxz).
/// </summary>
public lvec3 grb => new lvec3(y, x, z);
/// <summary>
/// Returns lvec3.yxzx swizzling.
/// </summary>
public lvec4 yxzx => new lvec4(y, x, z, x);
/// <summary>
/// Returns lvec3.grbr swizzling (equivalent to lvec3.yxzx).
/// </summary>
public lvec4 grbr => new lvec4(y, x, z, x);
/// <summary>
/// Returns lvec3.yxzy swizzling.
/// </summary>
public lvec4 yxzy => new lvec4(y, x, z, y);
/// <summary>
/// Returns lvec3.grbg swizzling (equivalent to lvec3.yxzy).
/// </summary>
public lvec4 grbg => new lvec4(y, x, z, y);
/// <summary>
/// Returns lvec3.yxzz swizzling.
/// </summary>
public lvec4 yxzz => new lvec4(y, x, z, z);
/// <summary>
/// Returns lvec3.grbb swizzling (equivalent to lvec3.yxzz).
/// </summary>
public lvec4 grbb => new lvec4(y, x, z, z);
/// <summary>
/// Returns lvec3.yy swizzling.
/// </summary>
public lvec2 yy => new lvec2(y, y);
/// <summary>
/// Returns lvec3.gg swizzling (equivalent to lvec3.yy).
/// </summary>
public lvec2 gg => new lvec2(y, y);
/// <summary>
/// Returns lvec3.yyx swizzling.
/// </summary>
public lvec3 yyx => new lvec3(y, y, x);
/// <summary>
/// Returns lvec3.ggr swizzling (equivalent to lvec3.yyx).
/// </summary>
public lvec3 ggr => new lvec3(y, y, x);
/// <summary>
/// Returns lvec3.yyxx swizzling.
/// </summary>
public lvec4 yyxx => new lvec4(y, y, x, x);
/// <summary>
/// Returns lvec3.ggrr swizzling (equivalent to lvec3.yyxx).
/// </summary>
public lvec4 ggrr => new lvec4(y, y, x, x);
/// <summary>
/// Returns lvec3.yyxy swizzling.
/// </summary>
public lvec4 yyxy => new lvec4(y, y, x, y);
/// <summary>
/// Returns lvec3.ggrg swizzling (equivalent to lvec3.yyxy).
/// </summary>
public lvec4 ggrg => new lvec4(y, y, x, y);
/// <summary>
/// Returns lvec3.yyxz swizzling.
/// </summary>
public lvec4 yyxz => new lvec4(y, y, x, z);
/// <summary>
/// Returns lvec3.ggrb swizzling (equivalent to lvec3.yyxz).
/// </summary>
public lvec4 ggrb => new lvec4(y, y, x, z);
/// <summary>
/// Returns lvec3.yyy swizzling.
/// </summary>
public lvec3 yyy => new lvec3(y, y, y);
/// <summary>
/// Returns lvec3.ggg swizzling (equivalent to lvec3.yyy).
/// </summary>
public lvec3 ggg => new lvec3(y, y, y);
/// <summary>
/// Returns lvec3.yyyx swizzling.
/// </summary>
public lvec4 yyyx => new lvec4(y, y, y, x);
/// <summary>
/// Returns lvec3.gggr swizzling (equivalent to lvec3.yyyx).
/// </summary>
public lvec4 gggr => new lvec4(y, y, y, x);
/// <summary>
/// Returns lvec3.yyyy swizzling.
/// </summary>
public lvec4 yyyy => new lvec4(y, y, y, y);
/// <summary>
/// Returns lvec3.gggg swizzling (equivalent to lvec3.yyyy).
/// </summary>
public lvec4 gggg => new lvec4(y, y, y, y);
/// <summary>
/// Returns lvec3.yyyz swizzling.
/// </summary>
public lvec4 yyyz => new lvec4(y, y, y, z);
/// <summary>
/// Returns lvec3.gggb swizzling (equivalent to lvec3.yyyz).
/// </summary>
public lvec4 gggb => new lvec4(y, y, y, z);
/// <summary>
/// Returns lvec3.yyz swizzling.
/// </summary>
public lvec3 yyz => new lvec3(y, y, z);
/// <summary>
/// Returns lvec3.ggb swizzling (equivalent to lvec3.yyz).
/// </summary>
public lvec3 ggb => new lvec3(y, y, z);
/// <summary>
/// Returns lvec3.yyzx swizzling.
/// </summary>
public lvec4 yyzx => new lvec4(y, y, z, x);
/// <summary>
/// Returns lvec3.ggbr swizzling (equivalent to lvec3.yyzx).
/// </summary>
public lvec4 ggbr => new lvec4(y, y, z, x);
/// <summary>
/// Returns lvec3.yyzy swizzling.
/// </summary>
public lvec4 yyzy => new lvec4(y, y, z, y);
/// <summary>
/// Returns lvec3.ggbg swizzling (equivalent to lvec3.yyzy).
/// </summary>
public lvec4 ggbg => new lvec4(y, y, z, y);
/// <summary>
/// Returns lvec3.yyzz swizzling.
/// </summary>
public lvec4 yyzz => new lvec4(y, y, z, z);
/// <summary>
/// Returns lvec3.ggbb swizzling (equivalent to lvec3.yyzz).
/// </summary>
public lvec4 ggbb => new lvec4(y, y, z, z);
/// <summary>
/// Returns lvec3.yz swizzling.
/// </summary>
public lvec2 yz => new lvec2(y, z);
/// <summary>
/// Returns lvec3.gb swizzling (equivalent to lvec3.yz).
/// </summary>
public lvec2 gb => new lvec2(y, z);
/// <summary>
/// Returns lvec3.yzx swizzling.
/// </summary>
public lvec3 yzx => new lvec3(y, z, x);
/// <summary>
/// Returns lvec3.gbr swizzling (equivalent to lvec3.yzx).
/// </summary>
public lvec3 gbr => new lvec3(y, z, x);
/// <summary>
/// Returns lvec3.yzxx swizzling.
/// </summary>
public lvec4 yzxx => new lvec4(y, z, x, x);
/// <summary>
/// Returns lvec3.gbrr swizzling (equivalent to lvec3.yzxx).
/// </summary>
public lvec4 gbrr => new lvec4(y, z, x, x);
/// <summary>
/// Returns lvec3.yzxy swizzling.
/// </summary>
public lvec4 yzxy => new lvec4(y, z, x, y);
/// <summary>
/// Returns lvec3.gbrg swizzling (equivalent to lvec3.yzxy).
/// </summary>
public lvec4 gbrg => new lvec4(y, z, x, y);
/// <summary>
/// Returns lvec3.yzxz swizzling.
/// </summary>
public lvec4 yzxz => new lvec4(y, z, x, z);
/// <summary>
/// Returns lvec3.gbrb swizzling (equivalent to lvec3.yzxz).
/// </summary>
public lvec4 gbrb => new lvec4(y, z, x, z);
/// <summary>
/// Returns lvec3.yzy swizzling.
/// </summary>
public lvec3 yzy => new lvec3(y, z, y);
/// <summary>
/// Returns lvec3.gbg swizzling (equivalent to lvec3.yzy).
/// </summary>
public lvec3 gbg => new lvec3(y, z, y);
/// <summary>
/// Returns lvec3.yzyx swizzling.
/// </summary>
public lvec4 yzyx => new lvec4(y, z, y, x);
/// <summary>
/// Returns lvec3.gbgr swizzling (equivalent to lvec3.yzyx).
/// </summary>
public lvec4 gbgr => new lvec4(y, z, y, x);
/// <summary>
/// Returns lvec3.yzyy swizzling.
/// </summary>
public lvec4 yzyy => new lvec4(y, z, y, y);
/// <summary>
/// Returns lvec3.gbgg swizzling (equivalent to lvec3.yzyy).
/// </summary>
public lvec4 gbgg => new lvec4(y, z, y, y);
/// <summary>
/// Returns lvec3.yzyz swizzling.
/// </summary>
public lvec4 yzyz => new lvec4(y, z, y, z);
/// <summary>
/// Returns lvec3.gbgb swizzling (equivalent to lvec3.yzyz).
/// </summary>
public lvec4 gbgb => new lvec4(y, z, y, z);
/// <summary>
/// Returns lvec3.yzz swizzling.
/// </summary>
public lvec3 yzz => new lvec3(y, z, z);
/// <summary>
/// Returns lvec3.gbb swizzling (equivalent to lvec3.yzz).
/// </summary>
public lvec3 gbb => new lvec3(y, z, z);
/// <summary>
/// Returns lvec3.yzzx swizzling.
/// </summary>
public lvec4 yzzx => new lvec4(y, z, z, x);
/// <summary>
/// Returns lvec3.gbbr swizzling (equivalent to lvec3.yzzx).
/// </summary>
public lvec4 gbbr => new lvec4(y, z, z, x);
/// <summary>
/// Returns lvec3.yzzy swizzling.
/// </summary>
public lvec4 yzzy => new lvec4(y, z, z, y);
/// <summary>
/// Returns lvec3.gbbg swizzling (equivalent to lvec3.yzzy).
/// </summary>
public lvec4 gbbg => new lvec4(y, z, z, y);
/// <summary>
/// Returns lvec3.yzzz swizzling.
/// </summary>
public lvec4 yzzz => new lvec4(y, z, z, z);
/// <summary>
/// Returns lvec3.gbbb swizzling (equivalent to lvec3.yzzz).
/// </summary>
public lvec4 gbbb => new lvec4(y, z, z, z);
/// <summary>
/// Returns lvec3.zx swizzling.
/// </summary>
public lvec2 zx => new lvec2(z, x);
/// <summary>
/// Returns lvec3.br swizzling (equivalent to lvec3.zx).
/// </summary>
public lvec2 br => new lvec2(z, x);
/// <summary>
/// Returns lvec3.zxx swizzling.
/// </summary>
public lvec3 zxx => new lvec3(z, x, x);
/// <summary>
/// Returns lvec3.brr swizzling (equivalent to lvec3.zxx).
/// </summary>
public lvec3 brr => new lvec3(z, x, x);
/// <summary>
/// Returns lvec3.zxxx swizzling.
/// </summary>
public lvec4 zxxx => new lvec4(z, x, x, x);
/// <summary>
/// Returns lvec3.brrr swizzling (equivalent to lvec3.zxxx).
/// </summary>
public lvec4 brrr => new lvec4(z, x, x, x);
/// <summary>
/// Returns lvec3.zxxy swizzling.
/// </summary>
public lvec4 zxxy => new lvec4(z, x, x, y);
/// <summary>
/// Returns lvec3.brrg swizzling (equivalent to lvec3.zxxy).
/// </summary>
public lvec4 brrg => new lvec4(z, x, x, y);
/// <summary>
/// Returns lvec3.zxxz swizzling.
/// </summary>
public lvec4 zxxz => new lvec4(z, x, x, z);
/// <summary>
/// Returns lvec3.brrb swizzling (equivalent to lvec3.zxxz).
/// </summary>
public lvec4 brrb => new lvec4(z, x, x, z);
/// <summary>
/// Returns lvec3.zxy swizzling.
/// </summary>
public lvec3 zxy => new lvec3(z, x, y);
/// <summary>
/// Returns lvec3.brg swizzling (equivalent to lvec3.zxy).
/// </summary>
public lvec3 brg => new lvec3(z, x, y);
/// <summary>
/// Returns lvec3.zxyx swizzling.
/// </summary>
public lvec4 zxyx => new lvec4(z, x, y, x);
/// <summary>
/// Returns lvec3.brgr swizzling (equivalent to lvec3.zxyx).
/// </summary>
public lvec4 brgr => new lvec4(z, x, y, x);
/// <summary>
/// Returns lvec3.zxyy swizzling.
/// </summary>
public lvec4 zxyy => new lvec4(z, x, y, y);
/// <summary>
/// Returns lvec3.brgg swizzling (equivalent to lvec3.zxyy).
/// </summary>
public lvec4 brgg => new lvec4(z, x, y, y);
/// <summary>
/// Returns lvec3.zxyz swizzling.
/// </summary>
public lvec4 zxyz => new lvec4(z, x, y, z);
/// <summary>
/// Returns lvec3.brgb swizzling (equivalent to lvec3.zxyz).
/// </summary>
public lvec4 brgb => new lvec4(z, x, y, z);
/// <summary>
/// Returns lvec3.zxz swizzling.
/// </summary>
public lvec3 zxz => new lvec3(z, x, z);
/// <summary>
/// Returns lvec3.brb swizzling (equivalent to lvec3.zxz).
/// </summary>
public lvec3 brb => new lvec3(z, x, z);
/// <summary>
/// Returns lvec3.zxzx swizzling.
/// </summary>
public lvec4 zxzx => new lvec4(z, x, z, x);
/// <summary>
/// Returns lvec3.brbr swizzling (equivalent to lvec3.zxzx).
/// </summary>
public lvec4 brbr => new lvec4(z, x, z, x);
/// <summary>
/// Returns lvec3.zxzy swizzling.
/// </summary>
public lvec4 zxzy => new lvec4(z, x, z, y);
/// <summary>
/// Returns lvec3.brbg swizzling (equivalent to lvec3.zxzy).
/// </summary>
public lvec4 brbg => new lvec4(z, x, z, y);
/// <summary>
/// Returns lvec3.zxzz swizzling.
/// </summary>
public lvec4 zxzz => new lvec4(z, x, z, z);
/// <summary>
/// Returns lvec3.brbb swizzling (equivalent to lvec3.zxzz).
/// </summary>
public lvec4 brbb => new lvec4(z, x, z, z);
/// <summary>
/// Returns lvec3.zy swizzling.
/// </summary>
public lvec2 zy => new lvec2(z, y);
/// <summary>
/// Returns lvec3.bg swizzling (equivalent to lvec3.zy).
/// </summary>
public lvec2 bg => new lvec2(z, y);
/// <summary>
/// Returns lvec3.zyx swizzling.
/// </summary>
public lvec3 zyx => new lvec3(z, y, x);
/// <summary>
/// Returns lvec3.bgr swizzling (equivalent to lvec3.zyx).
/// </summary>
public lvec3 bgr => new lvec3(z, y, x);
/// <summary>
/// Returns lvec3.zyxx swizzling.
/// </summary>
public lvec4 zyxx => new lvec4(z, y, x, x);
/// <summary>
/// Returns lvec3.bgrr swizzling (equivalent to lvec3.zyxx).
/// </summary>
public lvec4 bgrr => new lvec4(z, y, x, x);
/// <summary>
/// Returns lvec3.zyxy swizzling.
/// </summary>
public lvec4 zyxy => new lvec4(z, y, x, y);
/// <summary>
/// Returns lvec3.bgrg swizzling (equivalent to lvec3.zyxy).
/// </summary>
public lvec4 bgrg => new lvec4(z, y, x, y);
/// <summary>
/// Returns lvec3.zyxz swizzling.
/// </summary>
public lvec4 zyxz => new lvec4(z, y, x, z);
/// <summary>
/// Returns lvec3.bgrb swizzling (equivalent to lvec3.zyxz).
/// </summary>
public lvec4 bgrb => new lvec4(z, y, x, z);
/// <summary>
/// Returns lvec3.zyy swizzling.
/// </summary>
public lvec3 zyy => new lvec3(z, y, y);
/// <summary>
/// Returns lvec3.bgg swizzling (equivalent to lvec3.zyy).
/// </summary>
public lvec3 bgg => new lvec3(z, y, y);
/// <summary>
/// Returns lvec3.zyyx swizzling.
/// </summary>
public lvec4 zyyx => new lvec4(z, y, y, x);
/// <summary>
/// Returns lvec3.bggr swizzling (equivalent to lvec3.zyyx).
/// </summary>
public lvec4 bggr => new lvec4(z, y, y, x);
/// <summary>
/// Returns lvec3.zyyy swizzling.
/// </summary>
public lvec4 zyyy => new lvec4(z, y, y, y);
/// <summary>
/// Returns lvec3.bggg swizzling (equivalent to lvec3.zyyy).
/// </summary>
public lvec4 bggg => new lvec4(z, y, y, y);
/// <summary>
/// Returns lvec3.zyyz swizzling.
/// </summary>
public lvec4 zyyz => new lvec4(z, y, y, z);
/// <summary>
/// Returns lvec3.bggb swizzling (equivalent to lvec3.zyyz).
/// </summary>
public lvec4 bggb => new lvec4(z, y, y, z);
/// <summary>
/// Returns lvec3.zyz swizzling.
/// </summary>
public lvec3 zyz => new lvec3(z, y, z);
/// <summary>
/// Returns lvec3.bgb swizzling (equivalent to lvec3.zyz).
/// </summary>
public lvec3 bgb => new lvec3(z, y, z);
/// <summary>
/// Returns lvec3.zyzx swizzling.
/// </summary>
public lvec4 zyzx => new lvec4(z, y, z, x);
/// <summary>
/// Returns lvec3.bgbr swizzling (equivalent to lvec3.zyzx).
/// </summary>
public lvec4 bgbr => new lvec4(z, y, z, x);
/// <summary>
/// Returns lvec3.zyzy swizzling.
/// </summary>
public lvec4 zyzy => new lvec4(z, y, z, y);
/// <summary>
/// Returns lvec3.bgbg swizzling (equivalent to lvec3.zyzy).
/// </summary>
public lvec4 bgbg => new lvec4(z, y, z, y);
/// <summary>
/// Returns lvec3.zyzz swizzling.
/// </summary>
public lvec4 zyzz => new lvec4(z, y, z, z);
/// <summary>
/// Returns lvec3.bgbb swizzling (equivalent to lvec3.zyzz).
/// </summary>
public lvec4 bgbb => new lvec4(z, y, z, z);
/// <summary>
/// Returns lvec3.zz swizzling.
/// </summary>
public lvec2 zz => new lvec2(z, z);
/// <summary>
/// Returns lvec3.bb swizzling (equivalent to lvec3.zz).
/// </summary>
public lvec2 bb => new lvec2(z, z);
/// <summary>
/// Returns lvec3.zzx swizzling.
/// </summary>
public lvec3 zzx => new lvec3(z, z, x);
/// <summary>
/// Returns lvec3.bbr swizzling (equivalent to lvec3.zzx).
/// </summary>
public lvec3 bbr => new lvec3(z, z, x);
/// <summary>
/// Returns lvec3.zzxx swizzling.
/// </summary>
public lvec4 zzxx => new lvec4(z, z, x, x);
/// <summary>
/// Returns lvec3.bbrr swizzling (equivalent to lvec3.zzxx).
/// </summary>
public lvec4 bbrr => new lvec4(z, z, x, x);
/// <summary>
/// Returns lvec3.zzxy swizzling.
/// </summary>
public lvec4 zzxy => new lvec4(z, z, x, y);
/// <summary>
/// Returns lvec3.bbrg swizzling (equivalent to lvec3.zzxy).
/// </summary>
public lvec4 bbrg => new lvec4(z, z, x, y);
/// <summary>
/// Returns lvec3.zzxz swizzling.
/// </summary>
public lvec4 zzxz => new lvec4(z, z, x, z);
/// <summary>
/// Returns lvec3.bbrb swizzling (equivalent to lvec3.zzxz).
/// </summary>
public lvec4 bbrb => new lvec4(z, z, x, z);
/// <summary>
/// Returns lvec3.zzy swizzling.
/// </summary>
public lvec3 zzy => new lvec3(z, z, y);
/// <summary>
/// Returns lvec3.bbg swizzling (equivalent to lvec3.zzy).
/// </summary>
public lvec3 bbg => new lvec3(z, z, y);
/// <summary>
/// Returns lvec3.zzyx swizzling.
/// </summary>
public lvec4 zzyx => new lvec4(z, z, y, x);
/// <summary>
/// Returns lvec3.bbgr swizzling (equivalent to lvec3.zzyx).
/// </summary>
public lvec4 bbgr => new lvec4(z, z, y, x);
/// <summary>
/// Returns lvec3.zzyy swizzling.
/// </summary>
public lvec4 zzyy => new lvec4(z, z, y, y);
/// <summary>
/// Returns lvec3.bbgg swizzling (equivalent to lvec3.zzyy).
/// </summary>
public lvec4 bbgg => new lvec4(z, z, y, y);
/// <summary>
/// Returns lvec3.zzyz swizzling.
/// </summary>
public lvec4 zzyz => new lvec4(z, z, y, z);
/// <summary>
/// Returns lvec3.bbgb swizzling (equivalent to lvec3.zzyz).
/// </summary>
public lvec4 bbgb => new lvec4(z, z, y, z);
/// <summary>
/// Returns lvec3.zzz swizzling.
/// </summary>
public lvec3 zzz => new lvec3(z, z, z);
/// <summary>
/// Returns lvec3.bbb swizzling (equivalent to lvec3.zzz).
/// </summary>
public lvec3 bbb => new lvec3(z, z, z);
/// <summary>
/// Returns lvec3.zzzx swizzling.
/// </summary>
public lvec4 zzzx => new lvec4(z, z, z, x);
/// <summary>
/// Returns lvec3.bbbr swizzling (equivalent to lvec3.zzzx).
/// </summary>
public lvec4 bbbr => new lvec4(z, z, z, x);
/// <summary>
/// Returns lvec3.zzzy swizzling.
/// </summary>
public lvec4 zzzy => new lvec4(z, z, z, y);
/// <summary>
/// Returns lvec3.bbbg swizzling (equivalent to lvec3.zzzy).
/// </summary>
public lvec4 bbbg => new lvec4(z, z, z, y);
/// <summary>
/// Returns lvec3.zzzz swizzling.
/// </summary>
public lvec4 zzzz => new lvec4(z, z, z, z);
/// <summary>
/// Returns lvec3.bbbb swizzling (equivalent to lvec3.zzzz).
/// </summary>
public lvec4 bbbb => new lvec4(z, z, z, z);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using NUnit.Framework;
namespace Narkhedegs.Tests
{
[TestFixture]
public class PipeTest
{
[Test]
public void SimpleTest()
{
var pipe = new Pipe();
pipe.WriteText("abc");
Assert.AreEqual("abc", pipe.ReadTextAsync(3).Result);
pipe.WriteText("1");
pipe.WriteText("2");
pipe.WriteText("3");
Assert.AreEqual("123", pipe.ReadTextAsync(3).Result);
var asyncRead = pipe.ReadTextAsync(100);
Assert.AreEqual(false, asyncRead.Wait(TimeSpan.FromSeconds(.01)),
asyncRead.IsCompleted ? "Found: " + (asyncRead.Result ?? "null") : "not complete");
pipe.WriteText("x");
Assert.AreEqual(false, asyncRead.Wait(TimeSpan.FromSeconds(.01)),
asyncRead.IsCompleted ? "Found: " + (asyncRead.Result ?? "null") : "not complete");
pipe.WriteText(new string('y', 100));
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(5)),
asyncRead.IsCompleted ? "Found: " + (asyncRead.Result ?? "null") : "not complete");
Assert.AreEqual("x" + new string('y', 99), asyncRead.Result);
}
[Test]
public void TestLargeStreamWithFixedLength()
{
var pipe = new Pipe();
pipe.SetFixedLength();
var bytes = Enumerable.Range(0, 5*Pipe.ByteBufferSize)
.Select(b => (byte) (b%256))
.ToArray();
var asyncWrite = pipe.InputStream.WriteAsync(bytes, 0, bytes.Length)
.ContinueWith(_ => pipe.InputStream.Close());
var memoryStream = new MemoryStream();
var buffer = new byte[777];
int bytesRead;
while ((bytesRead = pipe.OutputStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
Assert.AreEqual(true, asyncWrite.Wait(TimeSpan.FromSeconds(1)));
Assert.That(memoryStream.ToArray().SequenceEqual(bytes));
}
[Test]
public void TimeoutTest()
{
var pipe = new Pipe {OutputStream = {ReadTimeout = 0}};
Assert.Throws<TimeoutException>(() => pipe.OutputStream.ReadByte());
pipe.WriteText(new string('a', 2048));
Assert.AreEqual(new string('a', 2048), pipe.ReadTextAsync(2048).Result);
}
[Test]
public void TestWriteTimeout()
{
var pipe = new Pipe {InputStream = {WriteTimeout = 0}};
pipe.SetFixedLength();
pipe.WriteText(new string('a', 2*Pipe.ByteBufferSize));
var asyncWrite = pipe.InputStream.WriteAsync(new byte[1], 0, 1);
Assert.AreEqual(true, asyncWrite.ContinueWith(_ => { }).Wait(TimeSpan.FromSeconds(.01)));
Assert.AreEqual(true, asyncWrite.IsFaulted);
Assert.IsInstanceOf<TimeoutException>(asyncWrite.Exception.InnerException);
}
[Test]
public void TestPartialWriteDoesNotTimeout()
{
var pipe = new Pipe {InputStream = {WriteTimeout = 0}, OutputStream = {ReadTimeout = 1000}};
pipe.SetFixedLength();
var text = Enumerable.Repeat((byte) 't', 3*Pipe.ByteBufferSize).ToArray();
var asyncWrite = pipe.InputStream.WriteAsync(text, 0, text.Length);
Assert.AreEqual(false, asyncWrite.Wait(TimeSpan.FromSeconds(.01)));
Assert.AreEqual(new string(text.Select(b => (char) b).ToArray()), pipe.ReadTextAsync(text.Length).Result);
}
[Test]
public void TestCancel()
{
var pipe = new Pipe();
var cancellationTokenSource = new CancellationTokenSource();
var asyncRead = pipe.ReadTextAsync(1, cancellationTokenSource.Token);
Assert.AreEqual(false, asyncRead.Wait(TimeSpan.FromSeconds(.01)));
cancellationTokenSource.Cancel();
Assert.AreEqual(true, asyncRead.ContinueWith(_ => { }).Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual(true, asyncRead.IsCanceled);
pipe.WriteText("aaa");
Assert.AreEqual("aa", pipe.ReadTextAsync(2).Result);
asyncRead = pipe.ReadTextAsync(1, cancellationTokenSource.Token);
Assert.AreEqual(true, asyncRead.ContinueWith(_ => { }).Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual(true, asyncRead.IsCanceled);
}
[Test]
public void TestCancelWrite()
{
var pipe = new Pipe();
var cancellationTokenSource = new CancellationTokenSource();
pipe.WriteText(new string('a', 2*Pipe.ByteBufferSize));
pipe.SetFixedLength();
var bytes = Enumerable.Repeat((byte) 'b', Pipe.ByteBufferSize).ToArray();
var asyncWrite = pipe.InputStream.WriteAsync(bytes, 0, bytes.Length, cancellationTokenSource.Token);
Assert.AreEqual(false, asyncWrite.Wait(TimeSpan.FromSeconds(.01)));
cancellationTokenSource.Cancel();
Assert.AreEqual(true, asyncWrite.ContinueWith(_ => { }).Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual(true, asyncWrite.IsCanceled);
}
[Test]
public void TestPartialWriteDoesNotCancel()
{
var pipe = new Pipe();
var cancellationTokenSource = new CancellationTokenSource();
pipe.WriteText(new string('a', 2*Pipe.ByteBufferSize));
var asyncRead = pipe.ReadTextAsync(1);
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual("a", asyncRead.Result);
pipe.SetFixedLength();
var bytes = Enumerable.Repeat((byte) 'b', Pipe.ByteBufferSize).ToArray();
var asyncWrite = pipe.InputStream.WriteAsync(bytes, 0, bytes.Length, cancellationTokenSource.Token);
Assert.AreEqual(false, asyncWrite.Wait(TimeSpan.FromSeconds(.01)));
cancellationTokenSource.Cancel();
Assert.AreEqual(false, asyncWrite.Wait(TimeSpan.FromSeconds(.01)));
asyncRead = pipe.ReadTextAsync((3*Pipe.ByteBufferSize) - 1);
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual(
new string('a', (2*Pipe.ByteBufferSize) - 1) + new string('b', Pipe.ByteBufferSize),
asyncRead.Result);
}
[Test]
public void TestCloseWriteSide()
{
var pipe = new Pipe();
pipe.WriteText("123456");
pipe.InputStream.Close();
Assert.Throws<ObjectDisposedException>(() => pipe.InputStream.WriteByte(1));
Assert.AreEqual("12345", pipe.ReadTextAsync(5).Result);
Assert.AreEqual(null, pipe.ReadTextAsync(2).Result);
pipe = new Pipe();
var asyncRead = pipe.ReadTextAsync(1);
Assert.AreEqual(false, asyncRead.Wait(TimeSpan.FromSeconds(.01)));
pipe.InputStream.Close();
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(5)));
}
[Test]
public void TestCloseReadSide()
{
var pipe = new Pipe();
pipe.WriteText("abc");
Assert.AreEqual("ab", pipe.ReadTextAsync(2).Result);
pipe.OutputStream.Close();
Assert.Throws<ObjectDisposedException>(() => pipe.OutputStream.ReadByte());
var largeBytes = new byte[10*1024];
var initialMemory = GC.GetTotalMemory(forceFullCollection: true);
for (var i = 0; i < int.MaxValue/1024; ++i)
{
pipe.InputStream.Write(largeBytes, 0, largeBytes.Length);
}
var finalMemory = GC.GetTotalMemory(forceFullCollection: true);
Assert.IsTrue(finalMemory - initialMemory < 10*largeBytes.Length,
"final = " + finalMemory + " initial = " + initialMemory);
Assert.Throws<ObjectDisposedException>(() => pipe.OutputStream.ReadByte());
pipe.InputStream.Close();
}
[Test]
public void TestConcurrentReads()
{
var pipe = new Pipe();
var asyncRead = pipe.ReadTextAsync(1);
Assert.Throws<InvalidOperationException>(() => pipe.OutputStream.ReadByte());
pipe.InputStream.Close();
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(5)));
}
[Test]
public void TestConcurrentWrites()
{
var pipe = new Pipe();
pipe.SetFixedLength();
var longText = new string('x', (2*Pipe.ByteBufferSize) + 1);
var asyncWrite = pipe.WriteTextAsync(longText);
Assert.AreEqual(false, asyncWrite.Wait(TimeSpan.FromSeconds(.01)));
Assert.Throws<InvalidOperationException>(() => pipe.InputStream.WriteByte(101));
pipe.OutputStream.Close();
Assert.AreEqual(true, asyncWrite.Wait(TimeSpan.FromSeconds(5)));
}
[Test]
public void TestChainedPipes()
{
var pipes = CreatePipeChain(100);
// short write
pipes[0].InputStream.WriteByte(100);
var buffer = new byte[1];
Assert.AreEqual(true, pipes.Last().OutputStream.ReadAsync(buffer, 0, buffer.Length)
.Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual((byte) 100, buffer[0]);
// long write
var longText = new string('y', 3*Pipe.CharBufferSize);
var asyncWrite = pipes[0].WriteTextAsync(longText);
Assert.AreEqual(true, asyncWrite.Wait(TimeSpan.FromSeconds(5)));
var asyncRead = pipes.Last().ReadTextAsync(longText.Length);
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(5)));
Assert.AreEqual(longText, asyncRead.Result);
}
[Test]
public void TestPipeChainWithFixedLengthPipes()
{
var pipes = CreatePipeChain(2);
// note that this needs to be >> larger than the capacity to block all the pipes,
// since we can store bytes in each pipe in the chain + each buffer between pipes
var longText = new string('z', 8*Pipe.ByteBufferSize + 1);
pipes.ForEach(p => p.SetFixedLength());
var asyncWrite = pipes[0].WriteTextAsync(longText);
Assert.AreEqual(false, asyncWrite.Wait(TimeSpan.FromSeconds(.01)));
var asyncRead = pipes.Last().ReadTextAsync(longText.Length);
Assert.AreEqual(true, asyncWrite.Wait(TimeSpan.FromSeconds(10)));
Assert.AreEqual(true, asyncRead.Wait(TimeSpan.FromSeconds(10)));
Assert.IsNotNull(asyncRead.Result);
Assert.AreEqual(longText.Length, asyncRead.Result.Length);
Assert.AreEqual(longText, asyncRead.Result);
}
private static List<Pipe> CreatePipeChain(int length)
{
var pipes = Enumerable.Range(0, length).Select(_ => new Pipe())
.ToList();
for (var i = 0; i < pipes.Count - 1; ++i)
{
var fromPipe = pipes[i];
var toPipe = pipes[i + 1];
fromPipe.OutputStream.CopyToAsync(toPipe.InputStream)
.ContinueWith(_ =>
{
fromPipe.OutputStream.Close();
toPipe.InputStream.Close();
});
}
return pipes;
}
[Test]
public void FuzzTest()
{
const int ByteCount = 100000;
var pipe = new Pipe();
var writeTask = Task.Run(async () =>
{
var memoryStream = new MemoryStream();
var random = new Random(1234);
var bytesWritten = 0;
while (bytesWritten < ByteCount)
{
//Console.WriteLine("Writing " + memoryStream.Length);
switch (random.Next(10))
{
case 1:
//Console.WriteLine("SETTING FIXED LENGTH");
pipe.SetFixedLength();
break;
case 2:
case 3:
await Task.Delay(1);
break;
default:
var bufferLength = random.Next(0, 5000);
var offset = random.Next(0, bufferLength + 1);
var count = random.Next(0, bufferLength - offset + 1);
var buffer = new byte[bufferLength];
random.NextBytes(buffer);
memoryStream.Write(buffer, offset, count);
//Console.WriteLine("WRITE START");
await pipe.InputStream.WriteAsync(buffer, offset, count);
//Console.WriteLine("WRITE END");
bytesWritten += count;
break;
}
}
//Console.WriteLine("WRITER ALL DONE");
pipe.InputStream.Close();
return memoryStream;
});
var readTask = Task.Run(async () =>
{
var memoryStream = new MemoryStream();
var random = new Random(5678);
while (true)
{
//Console.WriteLine("Reading " + memoryStream.Length);
if (random.Next(10) == 1)
{
await Task.Delay(1);
}
var bufferLength = random.Next(0, 5000);
var offset = random.Next(0, bufferLength + 1);
var count = random.Next(0, bufferLength - offset + 1);
var buffer = new byte[bufferLength];
//Console.WriteLine("READ START");
var bytesRead = await pipe.OutputStream.ReadAsync(buffer, offset, count);
//Console.WriteLine("READ END");
if (bytesRead == 0 && count > 0)
{
// if we tried to read more than 1 byte and we got 0, the pipe is done
//Console.WriteLine("READER ALL DONE");
return memoryStream;
}
memoryStream.Write(buffer, offset, bytesRead);
}
});
Assert.AreEqual(true, Task.WhenAll(writeTask, readTask).Wait(TimeSpan.FromSeconds(5)));
CollectionAssert.AreEqual(writeTask.Result.ToArray(), readTask.Result.ToArray());
}
}
internal static class PipeExtensions
{
public static void WriteText(this Pipe @this, string text)
{
new StreamWriter(@this.InputStream) {AutoFlush = true}.Write(text);
}
public static Task WriteTextAsync(this Pipe @this, string text)
{
return new StreamWriter(@this.InputStream) {AutoFlush = true}.WriteAsync(text);
}
public static async Task<string> ReadTextAsync(this Pipe @this, int count,
CancellationToken token = default(CancellationToken))
{
var bytes = new byte[count];
var bytesRead = 0;
while (bytesRead < count)
{
var result =
await
@this.OutputStream.ReadAsync(bytes, offset: bytesRead, count: count - bytesRead,
cancellationToken: token);
if (result == 0)
{
return null;
}
bytesRead += result;
}
return new string(Encoding.Default.GetChars(bytes));
}
}
}
| |
namespace Petstore
{
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>
/// UsageOperations operations.
/// </summary>
internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations
{
/// <summary>
/// Initializes a new instance of the UsageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal UsageOperations(StorageManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Gets the current usage count and the limit for the resources under the
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Usage>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.Collections.Generic;
class ModData
{
public static Dictionary<string,HashSet<string>> VersionData=new Dictionary<string,HashSet<string>>
{
["Current"]=new HashSet<string>
{
"System.Collections.*, mscorlib",
"System.Collections.Generic.*, System.Core",
"System.Collections.Generic.*, System",
"System.Collections.Generic.*, mscorlib",
"System.Text.*, mscorlib",
"System.Text.RegularExpressions.*, System",
"System.Globalization.*, mscorlib",
"System.Linq.*, System.Core",
"System.Collections.Concurrent.*, System",
"System.Collections.Concurrent.*, mscorlib",
"System.Timers.*, System",
"System.Diagnostics.TraceEventType+*, System",
"System.Reflection.AssemblyProductAttribute+*, mscorlib",
"System.Reflection.AssemblyDescriptionAttribute+*, mscorlib",
"System.Reflection.AssemblyConfigurationAttribute+*, mscorlib",
"System.Reflection.AssemblyCompanyAttribute+*, mscorlib",
"System.Reflection.AssemblyCultureAttribute+*, mscorlib",
"System.Reflection.AssemblyVersionAttribute+*, mscorlib",
"System.Reflection.AssemblyFileVersionAttribute+*, mscorlib",
"System.Reflection.AssemblyCopyrightAttribute+*, mscorlib",
"System.Reflection.AssemblyTrademarkAttribute+*, mscorlib",
"System.Reflection.AssemblyTitleAttribute+*, mscorlib",
"System.Runtime.InteropServices.ComVisibleAttribute+*, mscorlib",
"System.ComponentModel.DefaultValueAttribute+*, System",
"System.SerializableAttribute+*, mscorlib",
"System.Runtime.InteropServices.GuidAttribute+*, mscorlib",
"System.Runtime.InteropServices.StructLayoutAttribute+*, mscorlib",
"System.Runtime.InteropServices.LayoutKind+*, mscorlib",
"System.Guid+*, mscorlib",
"object+*, mscorlib",
"System.IDisposable+*, mscorlib",
"string+*, mscorlib",
"System.StringComparison+*, mscorlib",
"System.Math+*, mscorlib",
"System.Enum+*, mscorlib",
"int+*, mscorlib",
"short+*, mscorlib",
"long+*, mscorlib",
"uint+*, mscorlib",
"ushort+*, mscorlib",
"ulong+*, mscorlib",
"double+*, mscorlib",
"float+*, mscorlib",
"bool+*, mscorlib",
"char+*, mscorlib",
"byte+*, mscorlib",
"sbyte+*, mscorlib",
"decimal+*, mscorlib",
"System.DateTime+*, mscorlib",
"System.TimeSpan+*, mscorlib",
"System.Array+*, mscorlib",
"System.Xml.Serialization.XmlElementAttribute+*, System.Xml",
"System.Xml.Serialization.XmlAttributeAttribute+*, System.Xml",
"System.Xml.Serialization.XmlArrayAttribute+*, System.Xml",
"System.Xml.Serialization.XmlArrayItemAttribute+*, System.Xml",
"System.Xml.Serialization.XmlAnyAttributeAttribute+*, System.Xml",
"System.Xml.Serialization.XmlAnyElementAttribute+*, System.Xml",
"System.Xml.Serialization.XmlAnyElementAttributes+*, System.Xml",
"System.Xml.Serialization.XmlArrayItemAttributes+*, System.Xml",
"System.Xml.Serialization.XmlAttributeEventArgs+*, System.Xml",
"System.Xml.Serialization.XmlAttributeOverrides+*, System.Xml",
"System.Xml.Serialization.XmlAttributes+*, System.Xml",
"System.Xml.Serialization.XmlChoiceIdentifierAttribute+*, System.Xml",
"System.Xml.Serialization.XmlElementAttributes+*, System.Xml",
"System.Xml.Serialization.XmlElementEventArgs+*, System.Xml",
"System.Xml.Serialization.XmlEnumAttribute+*, System.Xml",
"System.Xml.Serialization.XmlIgnoreAttribute+*, System.Xml",
"System.Xml.Serialization.XmlIncludeAttribute+*, System.Xml",
"System.Xml.Serialization.XmlRootAttribute+*, System.Xml",
"System.Xml.Serialization.XmlTextAttribute+*, System.Xml",
"System.Xml.Serialization.XmlTypeAttribute+*, System.Xml",
"System.Runtime.CompilerServices.RuntimeHelpers+*, mscorlib",
"System.IO.BinaryReader+*, mscorlib",
"System.IO.BinaryWriter+*, mscorlib",
"System.NullReferenceException+*, mscorlib",
"System.ArgumentException+*, mscorlib",
"System.ArgumentNullException+*, mscorlib",
"System.InvalidOperationException+*, mscorlib",
"System.FormatException+*, mscorlib",
"System.Exception+*, mscorlib",
"System.DivideByZeroException+*, mscorlib",
"System.InvalidCastException+*, mscorlib",
"System.IO.FileNotFoundException+*, mscorlib",
"System.NotSupportedException+*, mscorlib",
"System.Nullable<T>+*, mscorlib",
"System.StringComparer+*, mscorlib",
"System.IEquatable<T>+*, mscorlib",
"System.IComparable+*, mscorlib",
"System.IComparable<T>+*, mscorlib",
"System.BitConverter+*, mscorlib",
"System.FlagsAttribute+*, mscorlib",
"System.IO.Path+*, mscorlib",
"System.Random+*, mscorlib",
"System.Convert+*, mscorlib",
"System.StringSplitOptions+*, mscorlib",
"System.DateTimeKind+*, mscorlib",
"System.MidpointRounding+*, mscorlib",
"System.EventArgs+*, mscorlib",
"System.Buffer+*, mscorlib",
"System.IO.Stream+*, mscorlib",
"System.IO.TextWriter+*, mscorlib",
"System.IO.TextReader+*, mscorlib",
"System.Reflection.MemberInfo, mscorlib",
"System.Reflection.MemberInfo.Name, mscorlib",
"System.Type, mscorlib",
"System.Type.FullName, mscorlib",
"System.Type.GetTypeFromHandle(System.RuntimeTypeHandle), mscorlib",
"System.Type.GetFields(System.Reflection.BindingFlags), mscorlib",
"System.Type.IsEquivalentTo(System.Type), mscorlib",
"System.Type.operator ==(System.Type, System.Type), mscorlib",
"System.Type.ToString(), mscorlib",
"System.ValueType, mscorlib",
"System.ValueType.Equals(object), mscorlib",
"System.ValueType.GetHashCode(), mscorlib",
"System.ValueType.ToString(), mscorlib",
"System.Environment, mscorlib",
"System.Environment.CurrentManagedThreadId, mscorlib",
"System.Environment.NewLine, mscorlib",
"System.Environment.ProcessorCount, mscorlib",
"System.RuntimeType, mscorlib",
"System.RuntimeType.operator !=(System.RuntimeType, System.RuntimeType), mscorlib",
"System.RuntimeType.GetFields(System.Reflection.BindingFlags), mscorlib",
"System.Delegate, mscorlib",
"System.Delegate.DynamicInvoke(params object[]), mscorlib",
"System.Delegate.Equals(object), mscorlib",
"System.Delegate.GetHashCode(), mscorlib",
"System.Delegate.Combine(System.Delegate, System.Delegate), mscorlib",
"System.Delegate.Combine(params System.Delegate[]), mscorlib",
"System.Delegate.GetInvocationList(), mscorlib",
"System.Delegate.Remove(System.Delegate, System.Delegate), mscorlib",
"System.Delegate.RemoveAll(System.Delegate, System.Delegate), mscorlib",
"System.Delegate.Clone(), mscorlib",
"System.Delegate.operator ==(System.Delegate, System.Delegate), mscorlib",
"System.Delegate.operator !=(System.Delegate, System.Delegate), mscorlib",
"System.Delegate.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext), mscorlib",
"System.Delegate.Method, mscorlib",
"System.Delegate.Target, mscorlib",
"System.Action+*, mscorlib",
"System.Action<T>+*, mscorlib",
"System.Action<T1, T2>+*, mscorlib",
"System.Action<T1, T2, T3>+*, mscorlib",
"System.Action<T1, T2, T3, T4>+*, mscorlib",
"System.Action<T1, T2, T3, T4, T5>+*, mscorlib",
"System.Action<T1, T2, T3, T4, T5, T6>+*, mscorlib",
"System.Action<T1, T2, T3, T4, T5, T6, T7>+*, mscorlib",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8>+*, mscorlib",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>+*, System.Core",
"System.Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>+*, System.Core",
"System.Func<TResult>+*, mscorlib",
"System.Func<T, TResult>+*, mscorlib",
"System.Func<T1, T2, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, T4, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, T4, T5, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, T4, T5, T6, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, T4, T5, T6, T7, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>+*, mscorlib",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>+*, System.Core",
"System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>+*, System.Core",
"SpaceEngineers.Game.ModAPI.Ingame.*, SpaceEngineers.Game",
"SpaceEngineers.Game.ModAPI.Ingame.*, SpaceEngineers.ObjectBuilders",
"SpaceEngineers.Game.ModAPI.*, SpaceEngineers.Game",
"SpaceEngineers.Game.Definitions.SafeZone.*, SpaceEngineers.Game",
"Sandbox.Game.Entities.MyCubeBuilder, Sandbox.Game",
"Sandbox.Game.Entities.MyCubeBuilder.Static, Sandbox.Game",
"Sandbox.Game.Entities.MyCubeBuilder.CubeBuilderState, Sandbox.Game",
"Sandbox.Game.Entities.Cube.CubeBuilder.MyCubeBuilderState, Sandbox.Game",
"Sandbox.Game.Entities.Cube.CubeBuilder.MyCubeBuilderState.CurrentBlockDefinition, Sandbox.Game",
"Sandbox.Game.Gui.MyHud, Sandbox.Game",
"Sandbox.Game.Gui.MyHud.BlockInfo, Sandbox.Game",
"Sandbox.Game.Gui.MyHudBlockInfo+*, Sandbox.Game",
"Sandbox.Game.Gui.MyHudBlockInfo.ComponentInfo+*, Sandbox.Game",
"VRage.Game.ObjectBuilders.Definitions.SessionComponents.MyObjectBuilder_CubeBuilderDefinition+*, VRage.Game",
"VRage.Game.ObjectBuilders.Definitions.SessionComponents.MyPlacementSettings+*, VRage.Game",
"VRage.Game.ObjectBuilders.Definitions.SessionComponents.MyGridPlacementSettings+*, VRage.Game",
"VRage.Game.ObjectBuilders.Definitions.SessionComponents.SnapMode+*, VRage.Game",
"VRage.Game.ObjectBuilders.Definitions.SessionComponents.VoxelPlacementMode+*, VRage.Game",
"VRage.Game.ObjectBuilders.Definitions.SessionComponents.VoxelPlacementSettings+*, VRage.Game",
"System.Collections.Generic.*, VRage.Library",
"VRage.Game.ModAPI.Ingame.*, VRage.Game",
"VRage.Game.ModAPI.Ingame.Utilities.*, VRage.Game",
"Sandbox.ModAPI.Ingame.*, Sandbox.Common",
"VRageMath.*, VRage.Math",
"VRage.Game.GUI.TextPanel.*, VRage.Game",
"Sandbox.ModAPI.*, Sandbox.Game",
"Sandbox.ModAPI.Interfaces.*, Sandbox.Common",
"Sandbox.ModAPI.Interfaces.Terminal.*, Sandbox.Common",
"VRage.Game.ModAPI.*, VRage.Game",
"Sandbox.ModAPI.*, Sandbox.Common",
"VRage.Game.ModAPI.Interfaces.*, VRage.Game",
"VRage.ModAPI.*, VRage.Game",
"VRage.Game.Entity.*, VRage.Game",
"Sandbox.Game.Entities.*, Sandbox.Game",
"VRage.Game.*, VRage.Game",
"VRage.Game.ObjectBuilders.Definitions.*, VRage.Game",
"Sandbox.Common.ObjectBuilders.*, SpaceEngineers.ObjectBuilders",
"Sandbox.Common.ObjectBuilders.Definitions.*, SpaceEngineers.ObjectBuilders",
"VRage.Game.ObjectBuilders.ComponentSystem.*, VRage.Game",
"VRage.ObjectBuilders.*, VRage.Game",
"VRage.Game.Components.*, VRage.Game",
"Sandbox.Game.EntityComponents.*, Sandbox.Game",
"Sandbox.Game.Entities.Character.Components.*, Sandbox.Game",
"VRage.Game.Entity.UseObject.*, VRage.Game",
"VRage.Game.ModAPI.*, VRage.Render",
"Sandbox.Game.GameSystems.TextSurfaceScripts.*, Sandbox.Game",
"ObjectBuilders.SafeZone.*, SpaceEngineers.ObjectBuilders",
"VRageRender.MyBillboard.BlendTypeEnum+*, VRage.Render",
"VRage.Game.ObjectBuilders.*, VRage.Game",
"Sandbox.Game.*, Sandbox.Game",
"Sandbox.Game.Components.*, Sandbox.Game",
"Sandbox.Game.WorldEnvironment.*, Sandbox.Game",
"VRage.*, VRage",
"Sandbox.Definitions.*, Sandbox.Game",
"VRage.*, VRage.Library",
"VRage.Collections.*, VRage.Library",
"VRage.Voxels.*, VRage",
"VRage.Utils.*, VRage",
"VRage.Utils.*, VRage.Library",
"VRage.Library.Utils.*, VRage.Library",
"Sandbox.Game.Lights.*, Sandbox.Game",
"Sandbox.ModAPI.Weapons.*, Sandbox.Game",
"Sandbox.ModAPI.Contracts.*, Sandbox.Game",
"Sandbox.Engine.Utils.MySpectatorCameraController, Sandbox.Game",
"Sandbox.Engine.Utils.MySpectatorCameraController.IsLightOn, Sandbox.Game",
"Sandbox.Game.Gui.TerminalActionExtensions+*, Sandbox.Game",
"Sandbox.ModAPI.Interfaces.ITerminalAction+*, Sandbox.Common",
"Sandbox.ModAPI.Interfaces.ITerminalProperty+*, Sandbox.Common",
"Sandbox.ModAPI.Interfaces.ITerminalProperty<TValue>+*, Sandbox.Common",
"Sandbox.ModAPI.Interfaces.TerminalPropertyExtensions+*, Sandbox.Common",
"Sandbox.Game.Localization.MySpaceTexts+*, Sandbox.Game",
"System.Text.StringBuilderExtensions_Format+*, VRage.Library",
"VRage.MyFixedPoint+*, VRage.Library",
"VRage.MyTuple+*, VRage.Library",
"VRage.MyTuple<T1>+*, VRage.Library",
"VRage.MyTuple<T1, T2>+*, VRage.Library",
"VRage.MyTuple<T1, T2, T3>+*, VRage.Library",
"VRage.MyTuple<T1, T2, T3, T4>+*, VRage.Library",
"VRage.MyTuple<T1, T2, T3, T4, T5>+*, VRage.Library",
"VRage.MyTuple<T1, T2, T3, T4, T5, T6>+*, VRage.Library",
"VRage.MyTupleComparer<T1, T2>+*, VRage.Library",
"VRage.MyTupleComparer<T1, T2, T3>+*, VRage.Library",
"VRage.MyTexts.MyLanguageDescription+*, VRage",
"VRage.MyLanguagesEnum+*, VRage",
"VRage.ModAPI.*, VRage.Input",
"VRage.Input.MyInputExtensions+*, Sandbox.Game",
"VRage.Input.MyKeys+*, VRage.Input",
"VRage.Input.MyJoystickAxesEnum+*, VRage",
"VRage.Input.MyJoystickButtonsEnum+*, VRage.Input",
"VRage.Input.MyMouseButtonsEnum+*, VRage.Input",
"VRage.Input.MySharedButtonsEnum+*, VRage.Input",
"VRage.Input.MyGuiControlTypeEnum+*, VRage.Input",
"VRage.Input.MyGuiInputDeviceEnum+*, VRage.Input",
"VRage.Game.Components.MyComponentContainer, VRage.Game",
"VRage.Game.Components.MyComponentContainer.TryGet<T>(out T), VRage.Game",
"VRage.Game.Components.MyComponentContainer.Has<T>(), VRage.Game",
"VRage.Game.Components.MyComponentContainer.Get<T>(), VRage.Game",
"VRage.Game.Components.MyComponentContainer.TryGet(System.Type, out VRage.Game.Components.MyComponentBase), VRage.Game",
"Sandbox.Engine.Physics.MyPhysicsHelper+*, Sandbox.Game",
"Sandbox.Engine.Physics.MyPhysics.CollisionLayers+*, Sandbox.Game",
"VRageRender.MyLodTypeEnum+*, VRage.Render",
"VRageRender.MyMaterialsSettings+*, Sandbox.Game",
"VRageRender.MyShadowsSettings+*, VRage.Render",
"VRageRender.MyPostprocessSettings+*, VRage.Render",
"VRageRender.Messages.MyHBAOData+*, VRage.Render",
"VRageRender.MySSAOSettings+*, VRage.Render",
"VRageRender.MyEnvironmentLightData+*, VRage.Render",
"VRageRender.MyEnvironmentData+*, VRage.Render",
"VRageRender.MyPostprocessSettings.Layout+*, VRage.Render",
"VRageRender.MySSAOSettings.Layout+*, VRage.Render",
"VRageRender.MyShadowsSettings.Struct+*, VRage.Render",
"VRageRender.MyShadowsSettings.Cascade+*, VRage.Render",
"VRageRender.MyMaterialsSettings.Struct+*, Sandbox.Game",
"VRageRender.MyMaterialsSettings.MyChangeableMaterial+*, Sandbox.Game",
"VRageRender.Lights.MyGlareTypeEnum+*, VRage.Render",
"VRage.Serialization.SerializableDictionary<T, U>+*, VRage.Library",
"Sandbox.Game.Weapons.MyToolBase+*, Sandbox.Game",
"Sandbox.Game.Weapons.MyGunBase+*, Sandbox.Game",
"Sandbox.Game.Weapons.MyDeviceBase+*, Sandbox.Game",
"System.Diagnostics.Stopwatch+*, System",
"System.Diagnostics.ConditionalAttribute+*, mscorlib",
"System.Version+*, mscorlib",
"System.ObsoleteAttribute+*, mscorlib",
"ParallelTasks.IWork+*, VRage.Library",
"ParallelTasks.Task+*, VRage.Library",
"ParallelTasks.WorkOptions+*, VRage.Library",
"VRage.Library.Threading.SpinLock+*, VRage.Library",
"VRage.Library.Threading.SpinLockRef+*, VRage.Library",
"System.Threading.Monitor+*, mscorlib",
"System.Threading.AutoResetEvent+*, mscorlib",
"System.Threading.ManualResetEvent+*, mscorlib",
"System.Threading.Interlocked+*, mscorlib",
"ProtoBuf.ProtoMemberAttribute+*, ProtoBuf.Net.Core",
"ProtoBuf.ProtoContractAttribute+*, ProtoBuf.Net.Core",
"ProtoBuf.ProtoIncludeAttribute+*, ProtoBuf.Net.Core",
"ProtoBuf.ProtoIgnoreAttribute+*, ProtoBuf.Net.Core",
"ProtoBuf.ProtoEnumAttribute+*, ProtoBuf.Net.Core",
"ProtoBuf.MemberSerializationOptions+*, ProtoBuf.Net.Core",
"ProtoBuf.DataFormat+*, ProtoBuf.Net.Core",
"ParallelTasks.WorkData, VRage.Library",
"ParallelTasks.WorkData.FlagAsFailed(), VRage.Library",
"System.ArrayExtensions, VRage.Library",
"System.ArrayExtensions.Contains<T>(T[], T), VRage.Library",
"VRage.Game.ModAPI.Ingame.MyPhysicalInventoryItemExtensions_ModAPI+*, Sandbox.Game",
"System.Collections.Immutable.*, System.Collections.Immutable",
},
};
public static Dictionary<string,HashSet<string>> VersionBlackData=new Dictionary<string,HashSet<string>>
{
["Current"]=new HashSet<string>
{
},
};
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
#if FEATURE_MPCONTRACT
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // FEATURE_MPCONTRACT
#if !NET35 && !UNITY
#if !WINDOWS_PHONE
#if !UNITY || MSGPACK_UNITY_FULL
using System.Numerics;
#endif // !WINDOWS_PHONE
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !NET35 && !UNITY
namespace MsgPack
{
partial struct Timestamp
{
#if !NET35 && !UNITY
#if !WINDOWS_PHONE
#if !UNITY || MSGPACK_UNITY_FULL
private static readonly BigInteger NanoToSecondsAsBigInteger = new BigInteger( 1000 * 1000 * 1000 );
#endif // !WINDOWS_PHONE
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !NET35 && !UNITY
/// <summary>
/// Adds a specified <see cref="TimeSpan"/> to this instance.
/// </summary>
/// <param name="offset">A <see cref="TimeSpan"/> which represents offset. Note that this value can be negative.</param>
/// <returns>The result <see cref="Timestamp"/>.</returns>
/// <exception cref="OverflowException">
/// The result of calculation overflows <see cref="MaxValue"/> or underflows <see cref="MinValue"/>.
/// </exception>
public Timestamp Add( TimeSpan offset )
{
long secondsOffset;
int nanosOffset;
FromOffsetTicks( offset.Ticks, out secondsOffset, out nanosOffset );
var seconds = checked( this.unixEpochSeconds + secondsOffset );
var nanos = this.nanoseconds + nanosOffset;
if ( nanos > MaxNanoSeconds )
{
checked
{
seconds++;
}
nanos -= ( MaxNanoSeconds + 1 );
}
else if ( nanos < 0 )
{
checked
{
seconds--;
}
nanos = ( MaxNanoSeconds + 1 ) + nanos;
}
return new Timestamp( seconds, unchecked(( int )nanos) );
}
/// <summary>
/// Subtracts a specified <see cref="TimeSpan"/> from this instance.
/// </summary>
/// <param name="offset">A <see cref="TimeSpan"/> which represents offset. Note that this value can be negative.</param>
/// <returns>The result <see cref="Timestamp"/>.</returns>
/// <exception cref="OverflowException">
/// The result of calculation overflows <see cref="MaxValue"/> or underflows <see cref="MinValue"/>.
/// </exception>
public Timestamp Subtract( TimeSpan offset )
{
return this.Add( -offset );
}
#if !NET35 && !UNITY
#if !WINDOWS_PHONE
#if !UNITY || MSGPACK_UNITY_FULL
/// <summary>
/// Adds a specified nanoseconds represented as a <see cref="BigInteger"/> from this instance.
/// </summary>
/// <param name="offsetNanoseconds">A <see cref="BigInteger"/> which represents offset. Note that this value can be negative.</param>
/// <returns>The result <see cref="Timestamp"/>.</returns>
/// <exception cref="OverflowException">
/// The result of calculation overflows <see cref="MaxValue"/> or underflows <see cref="MinValue"/>.
/// </exception>
public Timestamp Add( BigInteger offsetNanoseconds )
{
BigInteger nanosecondsOffset;
var secondsOffset = ( long )BigInteger.DivRem( offsetNanoseconds, NanoToSecondsAsBigInteger, out nanosecondsOffset );
var seconds = checked( this.unixEpochSeconds + secondsOffset );
var nanos = this.nanoseconds + unchecked( ( int )nanosecondsOffset );
if ( nanos > MaxNanoSeconds )
{
checked
{
seconds++;
}
nanos -= ( MaxNanoSeconds + 1 );
}
else if ( nanos < 0 )
{
checked
{
seconds--;
}
nanos = ( MaxNanoSeconds + 1 ) + nanos;
}
return new Timestamp( seconds, unchecked(( int )nanos) );
}
/// <summary>
/// Subtracts a specified nanoseconds represented as a <see cref="BigInteger"/> from this instance.
/// </summary>
/// <param name="offsetNanoseconds">A <see cref="BigInteger"/> which represents offset. Note that this value can be negative.</param>
/// <returns>The result <see cref="Timestamp"/>.</returns>
/// <exception cref="OverflowException">
/// The result of calculation overflows <see cref="MaxValue"/> or underflows <see cref="MinValue"/>.
/// </exception>
public Timestamp Subtract( BigInteger offsetNanoseconds )
{
return this.Add( -offsetNanoseconds );
}
/// <summary>
/// Calculates a difference this instance and a specified <see cref="Timestamp"/> in nanoseconds.
/// </summary>
/// <param name="other">A <see cref="Timestamp"/> to be differentiated.</param>
/// <returns>A <see cref="BigInteger"/> which represents difference in nanoseconds.</returns>
public BigInteger Subtract( Timestamp other )
{
var seconds = new BigInteger( this.unixEpochSeconds ) - other.unixEpochSeconds;
var nanos = ( long )this.nanoseconds - other.nanoseconds;
#if DEBUG
Contract.Assert( nanos <= MaxNanoSeconds, nanos + " <= MaxNanoSeconds" );
#endif // DEBUG
if ( nanos < 0 )
{
// move down
seconds--;
nanos = ( MaxNanoSeconds + 1 ) + nanos;
}
return seconds * SecondsToNanos + nanos;
}
#endif // !WINDOWS_PHONE
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !NET35 && !UNITY
/// <summary>
/// Calculates a <see cref="Timestamp"/> with specified <see cref="Timestamp"/> and an offset represented as <see cref="TimeSpan"/>.
/// </summary>
/// <param name="value">A <see cref="Timestamp"/>.</param>
/// <param name="offset">An offset in <see cref="TimeSpan"/>. This value can be negative.</param>
/// <returns>A <see cref="Timestamp"/>.</returns>
public static Timestamp operator +( Timestamp value, TimeSpan offset )
{
return value.Add( offset );
}
/// <summary>
/// Calculates a <see cref="Timestamp"/> with specified <see cref="Timestamp"/> and an offset represented as <see cref="TimeSpan"/>.
/// </summary>
/// <param name="value">A <see cref="Timestamp"/>.</param>
/// <param name="offset">An offset in <see cref="TimeSpan"/>. This value can be negative.</param>
/// <returns>A <see cref="Timestamp"/>.</returns>
public static Timestamp operator -( Timestamp value, TimeSpan offset )
{
return value.Subtract( offset );
}
#if !NET35 && !UNITY
#if !WINDOWS_PHONE
#if !UNITY || MSGPACK_UNITY_FULL
/// <summary>
/// Calculates a <see cref="Timestamp"/> with specified <see cref="Timestamp"/> and a nanoseconds offset represented as <see cref="BigInteger"/>.
/// </summary>
/// <param name="value">A <see cref="Timestamp"/>.</param>
/// <param name="offsetNanoseconds">An offset in nanoseconds as <see cref="BigInteger"/>. This value can be negative.</param>
/// <returns>A <see cref="Timestamp"/>.</returns>
public static Timestamp operator +( Timestamp value, BigInteger offsetNanoseconds )
{
return value.Add( offsetNanoseconds );
}
/// <summary>
/// Calculates a <see cref="Timestamp"/> with specified <see cref="Timestamp"/> and a nanoseconds represented as <see cref="BigInteger"/>.
/// </summary>
/// <param name="value">A <see cref="Timestamp"/>.</param>
/// <param name="offsetNanoseconds">An offset in nanoseconds as <see cref="BigInteger"/>. This value can be negative.</param>
/// <returns>A <see cref="Timestamp"/>.</returns>
public static Timestamp operator -( Timestamp value, BigInteger offsetNanoseconds )
{
return value.Subtract( offsetNanoseconds );
}
/// <summary>
/// Calculates a difference between specified two <see cref="Timestamp"/>s in nanoseconds.
/// </summary>
/// <param name="left">A <see cref="Timestamp"/>.</param>
/// <param name="right">A <see cref="Timestamp"/>.</param>
/// <returns>A <see cref="BigInteger"/> which represents difference in nanoseconds.</returns>
public static BigInteger operator -( Timestamp left, Timestamp right )
{
return left.Subtract( right );
}
#endif // !WINDOWS_PHONE
#endif // !UNITY || MSGPACK_UNITY_FULL
#endif // !NET35 && !UNITY
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using FTF.Web.Areas.HelpPage.ModelDescriptions;
using FTF.Web.Areas.HelpPage.Models;
using FTF.Web.Areas.HelpPage.SampleGeneration;
namespace FTF.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) 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 Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpevor
{
public class RdpevorServer
{
#region Varibles
const int sizeOfVideoPacketFixedFields = 41; //The total size in bytes of TSMM_VIDEO_DATA fixed fields is 41.
const int sizeOfPresentationFixedFields = 69; //The total size in bytes of TSMM_PRESENTATION_REQUEST fixed fields is 69.
const byte FrameRate = 0x1D; //reuse the data by Windows.
const ushort AverageBitrateKbps = 0x12C0;//reuse the data by Windows.
ulong lastPacketTimestamp;
private RdpedycServer rdpedycServer;
const string RdpevorControlChannelName = "Microsoft::Windows::RDS::Video::Control::v08.01";
const string RdpevorDataChannelName = "Microsoft::Windows::RDS::Video::Data::v08.01";
DynamicVirtualChannel rdpevorControlDVC;
DynamicVirtualChannel rdpevorDataDVC;
List<RdpevorPdu> receivedList;
#endregion Variables
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="rdpedycServer"></param>
public RdpevorServer(RdpedycServer rdpedycServer)
{
this.rdpedycServer = rdpedycServer;
receivedList = new List<RdpevorPdu>();
}
#endregion Constructor
/// <summary>
/// Create dynamic virtual channel.
/// </summary>
/// <param name="transportType">selected transport type for created channels</param>
/// <param name="timeout">Timeout</param>
/// <returns>true if client supports this protocol; otherwise, return false.</returns>
public bool CreateRdpevorDvc(TimeSpan timeout, DynamicVC_TransportType transportType = DynamicVC_TransportType.RDP_TCP)
{
const ushort priority = 0;
rdpevorControlDVC = rdpedycServer.CreateChannel(timeout, priority, RdpevorControlChannelName, transportType, OnDataReceived);
rdpevorDataDVC = rdpedycServer.CreateChannel(timeout, priority, RdpevorDataChannelName, transportType, OnDataReceived);
if (rdpevorControlDVC != null && rdpevorDataDVC != null)
{
return true;
}
return false;
}
#region Send/Receive Methods
/// <summary>
/// Send a RDPEVOR packet through control channel
/// </summary>
/// <param name="evorPdu"></param>
public void SendRdpevorControlPdu(RdpevorServerPdu evorPdu)
{
byte[] data = PduMarshaler.Marshal(evorPdu);
if (rdpevorControlDVC == null)
{
throw new InvalidOperationException("Control DVC instance of RDPEVOR is null, Dynamic virtual channel must be created before sending data.");
}
rdpevorControlDVC.Send(data);
}
/// <summary>
/// Send a RDPEVOR packet through data channel
/// </summary>
/// <param name="evorPdu"></param>
public void SendRdpevorDataPdu(RdpevorServerPdu evorPdu)
{
byte[] data = PduMarshaler.Marshal(evorPdu);
if (rdpevorDataDVC == null)
{
throw new InvalidOperationException("Data DVC instance of RDPEVOR is null, Dynamic virtual channel must be created before sending data.");
}
rdpevorDataDVC.Send(data);
}
/// <summary>
/// Method to expect a RdpevorPdu.
/// </summary>
/// <param name="timeout">Timeout</param>
public T ExpectRdpevorPdu<T>(TimeSpan timeout) where T : RdpevorPdu
{
DateTime endTime = DateTime.Now + timeout;
while (endTime > DateTime.Now)
{
if (receivedList.Count > 0)
{
lock (receivedList)
{
foreach (RdpevorPdu pdu in receivedList)
{
T response = pdu as T;
if (response != null)
{
receivedList.Remove(pdu);
return response;
}
}
}
}
System.Threading.Thread.Sleep(100);
}
return null;
}
#endregion Send/Receive Methods
#region Create methods
/// <summary>
/// Method to create a TSMM_PRESENTATION_REQUEST packet.
/// </summary>
/// <param name="presentationId">A number that uniquely identifies the video stream on the server.</param>
/// <param name="command">A number that identifies which operation the client is to perform. </param>
/// <param name="srcWidth">This is the width of the video stream after scaling back to the original resolution.</param>
/// <param name="srcHeight">This is the height of the video stream after scaling back to the original resolution.</param>
/// <param name="scaledWidth">This is the width of the video stream.</param>
/// <param name="scaledHeight">This is the height of the video stream.</param>
/// <param name="geometryId">This field is used to correlate this video data with its geometry.</param>
/// <param name="videoSubTypeId">This field identifies the Media Foundation video subtype of the video stream.</param>
public TSMM_PRESENTATION_REQUEST CreatePresentationRequest(
byte presentationId,
CommandValues command,
uint srcWidth,
uint srcHeight,
uint scaledWidth,
uint scaledHeight,
UInt64 geometryId,
VideoSubtype videoSubType,
byte[] extraData)
{
TSMM_PRESENTATION_REQUEST request = new TSMM_PRESENTATION_REQUEST();
request.Header.PacketType = PacketTypeValues.TSMM_PACKET_TYPE_PRESENTATION_REQUEST;
request.PresentatioinId = presentationId;
request.Version = RdpevorVersionValues.RDP8;
request.Command = command;
//The InvalidCommand packet is just for negative test, all other fiels are set same as Start packet.
if (command == CommandValues.Start || command == CommandValues.InvalidCommand)
{
request.FrameRate = FrameRate;
request.AverageBitrateKbps = AverageBitrateKbps;
request.Reserved = 0;
request.SourceWidth = srcWidth;
request.SourceHeight = srcHeight;
request.ScaledWidth = srcWidth;
request.ScaledHeight = srcHeight;
request.hnsTimestampOffset = (ulong)DateTime.Now.ToFileTimeUtc();
request.GeometryMappingId = geometryId;
request.VideoSubtypeId = RdpevorTestData.GetH264VideoSubtypeId();
if (videoSubType == VideoSubtype.MFVideoFormat_H264)
{
request.VideoSubtypeId = RdpevorTestData.GetH264VideoSubtypeId();
}
request.pExtraData = extraData;
request.cbExtra = (uint)extraData.Length;
request.Reserved2 = 0;
request.Header.cbSize = (uint)(sizeOfPresentationFixedFields + request.pExtraData.Length);
}
else if (command == CommandValues.Stop)
{
request.Header.cbSize = 0x45;
//If the command is to stop the presentation, only the Header, PresentationId, Version, and Command fields are valid.
//So set all other fields to 0.
request.FrameRate = 0;
request.AverageBitrateKbps = 0;
request.Reserved = 0;
request.SourceWidth = 0;
request.SourceHeight = 0;
request.ScaledWidth = 0;
request.ScaledHeight = 0;
request.hnsTimestampOffset = 0;
request.GeometryMappingId = 0;
request.VideoSubtypeId = new byte[16];
request.cbExtra = 0;
request.pExtraData = null;//TDI
request.Reserved2 = 0;
}
return request;
}
/// <summary>
/// Method to create a TSMM_VIDEO_DATA packet.
/// </summary>
/// <param name="presentationId">This is the same number as the PresentationId field in the TSMM_PRESENTATION_REQUEST message.</param>
/// <param name="flags">The bits of this integer indicate attributes of this message. </param>
/// <param name="packetIndex">This field contains the index of the current packet within the larger sample. </param>
/// <param name="totalPacketsInSample">This field contains the number of packets that make up the current sample.</param>
/// <param name="SampleNumber">The sample index in this presentation.</param>
/// <param name="videoData">The video data to be sent.</param>
public TSMM_VIDEO_DATA CreateVideoDataPacket(byte presentationId, TsmmVideoData_FlagsValues flags, ushort packetIndex, ushort totalPacketsInSample, uint SampleNumber, byte[] videoRawData, ulong timeStamp)
{
TSMM_VIDEO_DATA videoData = new TSMM_VIDEO_DATA();
videoData.Header.PacketType = PacketTypeValues.TSMM_PACKET_TYPE_VIDEO_DATA;
videoData.PresentatioinId = presentationId;
videoData.Version = RdpevorVersionValues.RDP8;
videoData.Flags = flags;
videoData.Reserved = 0;
if (packetIndex != totalPacketsInSample)
{
//HnsTimestamp and HnsDuration are only effective in the last packet of a sample.
videoData.HnsTimestamp = 0;
videoData.HnsDuration = 0;
}
else
{
videoData.HnsTimestamp = timeStamp;
videoData.HnsDuration = timeStamp - lastPacketTimestamp;
lastPacketTimestamp = videoData.HnsTimestamp;
}
videoData.CurrentPacketIndex = packetIndex;
videoData.PacketsInSample = totalPacketsInSample;
videoData.SampleNumber = SampleNumber;
if (videoRawData != null)
{
videoData.pSample = new byte[videoRawData.Length];
Array.Copy(videoRawData, videoData.pSample, videoRawData.Length);
videoData.Header.cbSize = (uint)(sizeOfVideoPacketFixedFields + videoData.pSample.Length);
videoData.cbSample = (uint)videoData.pSample.Length;
}
else
{
videoData.pSample = null;
videoData.Header.cbSize = sizeOfVideoPacketFixedFields;
videoData.cbSample = 0;
}
videoData.Reserved2 = 0;
return videoData;
}
#endregion Create Methods
#region Private Methods
/// <summary>
/// The callback method to receive data from transport layer.
/// </summary>
private void OnDataReceived(byte[] data, uint channelId)
{
lock (receivedList)
{
RdpevorPdu pdu = new RdpevorPdu();
bool fSucceed = false;
bool fResult = PduMarshaler.Unmarshal(data, pdu);
if (fResult)
{
byte[] pduData = new byte[pdu.Header.cbSize];
Array.Copy(data, pduData, pduData.Length);
if (pdu.Header.PacketType == PacketTypeValues.TSMM_PACKET_TYPE_PRESENTATION_RESPONSE)
{
TSMM_PRESENTATION_RESPONSE request = new TSMM_PRESENTATION_RESPONSE();
try
{
fSucceed = PduMarshaler.Unmarshal(pduData, request);
receivedList.Add(request);
}
catch (PDUDecodeException decodeExceptioin)
{
RdpevorUnkownPdu unkown = new RdpevorUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(decodeExceptioin.DecodingData, unkown);
receivedList.Add(unkown);
}
}
else if (pdu.Header.PacketType == PacketTypeValues.TSMM_PACKET_TYPE_CLIENT_NOTIFICATION)
{
TSMM_CLIENT_NOTIFICATION notficatioin = new TSMM_CLIENT_NOTIFICATION();
try
{
fSucceed = PduMarshaler.Unmarshal(pduData, notficatioin);
receivedList.Add(notficatioin);
}
catch (PDUDecodeException decodeExceptioin)
{
RdpevorUnkownPdu unkown = new RdpevorUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(decodeExceptioin.DecodingData, unkown);
receivedList.Add(unkown);
}
}
}
if (!fResult || !fSucceed)
{
RdpevorUnkownPdu unkown = new RdpevorUnkownPdu();
PduMarshaler.Unmarshal(data, unkown);
receivedList.Add(unkown);
}
}
}
#endregion Private Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.Serialization;
using Funq;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Web;
using ServiceStack.Configuration;
using ServiceStack.DataAnnotations;
using ServiceStack.Logging;
using ServiceStack.Logging.Support.Logging;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Tests.IntegrationTests;
namespace ServiceStack.WebHost.Endpoints.Tests.Support.Host
{
[RestService("/factorial/{ForNumber}")]
[DataContract]
public class GetFactorial
{
[DataMember]
public long ForNumber { get; set; }
}
[DataContract]
public class GetFactorialResponse
{
[DataMember]
public long Result { get; set; }
}
public class GetFactorialService
: IService<GetFactorial>
{
public object Execute(GetFactorial request)
{
return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) };
}
public static long GetFactorial(long n)
{
return n > 1 ? n * GetFactorial(n - 1) : 1;
}
}
[DataContract]
public class AlwaysThrows { }
[DataContract]
public class AlwaysThrowsResponse : IHasResponseStatus
{
[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}
public class AlwaysThrowsService
: ServiceBase<AlwaysThrows>
{
protected override object Run(AlwaysThrows request)
{
throw new ArgumentException("This service always throws an error");
}
}
[RestService("/movies", "POST,PUT")]
[RestService("/movies/{Id}")]
[DataContract]
public class Movie
{
public Movie()
{
this.Genres = new List<string>();
}
[DataMember]
[AutoIncrement]
public int Id { get; set; }
[DataMember]
public string ImdbId { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public decimal Rating { get; set; }
[DataMember]
public string Director { get; set; }
[DataMember]
public DateTime ReleaseDate { get; set; }
[DataMember]
public string TagLine { get; set; }
[DataMember]
public List<string> Genres { get; set; }
#region AutoGen ReSharper code, only required by tests
public bool Equals(Movie other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.ImdbId, ImdbId)
&& Equals(other.Title, Title)
&& other.Rating == Rating
&& Equals(other.Director, Director)
&& other.ReleaseDate.Equals(ReleaseDate)
&& Equals(other.TagLine, TagLine)
&& Genres.EquivalentTo(other.Genres);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Movie)) return false;
return Equals((Movie)obj);
}
public override int GetHashCode()
{
return ImdbId != null ? ImdbId.GetHashCode() : 0;
}
#endregion
}
[DataContract]
public class MovieResponse
{
[DataMember]
public Movie Movie { get; set; }
}
public class MovieService : RestServiceBase<Movie>
{
public IDbConnectionFactory DbFactory { get; set; }
/// <summary>
/// GET /movies/{Id}
/// </summary>
public override object OnGet(Movie movie)
{
return new MovieResponse
{
Movie = DbFactory.Exec(dbCmd => dbCmd.GetById<Movie>(movie.Id))
};
}
/// <summary>
/// POST /movies
/// </summary>
public override object OnPost(Movie movie)
{
var newMovieId = DbFactory.Exec(dbCmd =>
{
dbCmd.Insert(movie);
return dbCmd.GetLastInsertId();
});
var newMovie = new MovieResponse
{
Movie = DbFactory.Exec(dbCmd => dbCmd.GetById<Movie>(newMovieId))
};
return new HttpResult(newMovie)
{
StatusCode = HttpStatusCode.Created,
Headers = {
{ HttpHeaders.Location, this.RequestContext.AbsoluteUri.WithTrailingSlash() + newMovieId }
}
};
}
/// <summary>
/// PUT /movies
/// </summary>
public override object OnPut(Movie movie)
{
DbFactory.Exec(dbCmd => dbCmd.Save(movie));
return new MovieResponse();
}
/// <summary>
/// DELETE /movies/{Id}
/// </summary>
public override object OnDelete(Movie request)
{
DbFactory.Exec(dbCmd => dbCmd.DeleteById<Movie>(request.Id));
return new MovieResponse();
}
}
[DataContract]
[RestService("/movies", "GET")]
[RestService("/movies/genres/{Genre}")]
public class Movies
{
[DataMember]
public string Genre { get; set; }
[DataMember]
public Movie Movie { get; set; }
}
[DataContract]
public class MoviesResponse
{
public MoviesResponse()
{
Movies = new List<Movie>();
}
[DataMember]
public List<Movie> Movies { get; set; }
}
public class MoviesService : RestServiceBase<Movies>
{
public IDbConnectionFactory DbFactory { get; set; }
/// <summary>
/// GET /movies
/// GET /movies/genres/{Genre}
/// </summary>
public override object OnGet(Movies request)
{
var response = new MoviesResponse
{
Movies = request.Genre.IsNullOrEmpty()
? DbFactory.Exec(dbCmd => dbCmd.Select<Movie>())
: DbFactory.Exec(dbCmd => dbCmd.Select<Movie>("Genres LIKE {0}", "%" + request.Genre + "%"))
};
return response;
}
}
public class MoviesZip
{
public string Genre { get; set; }
public Movie Movie { get; set; }
}
public class MoviesZipResponse
{
public MoviesZipResponse()
{
Movies = new List<Movie>();
}
public List<Movie> Movies { get; set; }
}
public class MoviesZipService : RestServiceBase<MoviesZip>
{
public IDbConnectionFactory DbFactory { get; set; }
public override object OnGet(MoviesZip request)
{
return OnPost(request);
}
public override object OnPost(MoviesZip request)
{
var response = new MoviesZipResponse
{
Movies = request.Genre.IsNullOrEmpty()
? DbFactory.Exec(dbCmd => dbCmd.Select<Movie>())
: DbFactory.Exec(dbCmd => dbCmd.Select<Movie>("Genres LIKE {0}", "%" + request.Genre + "%"))
};
return RequestContext.ToOptimizedResult(response);
}
}
[DataContract]
[RestService("/reset-movies")]
public class ResetMovies { }
[DataContract]
public class ResetMoviesResponse
: IHasResponseStatus
{
public ResetMoviesResponse()
{
this.ResponseStatus = new ResponseStatus();
}
[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}
public class ResetMoviesService : RestServiceBase<ResetMovies>
{
public static List<Movie> Top5Movies = new List<Movie>
{
new Movie { ImdbId = "tt0111161", Title = "The Shawshank Redemption", Rating = 9.2m, Director = "Frank Darabont", ReleaseDate = new DateTime(1995,2,17), TagLine = "Fear can hold you prisoner. Hope can set you free.", Genres = new List<string>{"Crime","Drama"}, },
new Movie { ImdbId = "tt0068646", Title = "The Godfather", Rating = 9.2m, Director = "Francis Ford Coppola", ReleaseDate = new DateTime(1972,3,24), TagLine = "An offer you can't refuse.", Genres = new List<string> {"Crime","Drama", "Thriller"}, },
new Movie { ImdbId = "tt1375666", Title = "Inception", Rating = 9.2m, Director = "Christopher Nolan", ReleaseDate = new DateTime(2010,7,16), TagLine = "Your mind is the scene of the crime", Genres = new List<string>{"Action", "Mystery", "Sci-Fi", "Thriller"}, },
new Movie { ImdbId = "tt0071562", Title = "The Godfather: Part II", Rating = 9.0m, Director = "Francis Ford Coppola", ReleaseDate = new DateTime(1974,12,20), Genres = new List<string> {"Crime","Drama", "Thriller"}, },
new Movie { ImdbId = "tt0060196", Title = "The Good, the Bad and the Ugly", Rating = 9.0m, Director = "Sergio Leone", ReleaseDate = new DateTime(1967,12,29), TagLine = "They formed an alliance of hate to steal a fortune in dead man's gold", Genres = new List<string>{"Adventure","Western"}, },
};
public IDbConnectionFactory DbFactory { get; set; }
public override object OnPost(ResetMovies request)
{
DbFactory.Exec(dbCmd =>
{
const bool overwriteTable = true;
dbCmd.CreateTable<Movie>(overwriteTable);
dbCmd.SaveAll(Top5Movies);
});
return new ResetMoviesResponse();
}
}
public class ExampleAppHostHttpListener
: AppHostHttpListenerBase
{
//private static ILog log;
public ExampleAppHostHttpListener()
: base("ServiceStack Examples", typeof(GetFactorialService).Assembly)
{
LogManager.LogFactory = new DebugLogFactory();
//log = LogManager.GetLogger(typeof(ExampleAppHostHttpListener));
}
public override void Configure(Container container)
{
EndpointHostConfig.Instance.GlobalResponseHeaders.Clear();
//Signal advanced web browsers what HTTP Methods you accept
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders =
{
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
},
WsdlServiceNamespace = "http://www.servicestack.net/types",
LogFactory = new ConsoleLogFactory(),
DebugMode = true,
});
Routes
.Add<Movies>("/custom-movies", "GET")
.Add<Movies>("/custom-movies/genres/{Genre}")
.Add<Movie>("/custom-movies", "POST,PUT")
.Add<Movie>("/custom-movies/{Id}")
.Add<GetFactorial>("/fact/{ForNumber}")
.Add<MoviesZip>("/movies.zip")
;
container.Register<IResourceManager>(new ConfigurationResourceManager());
//var appSettings = container.Resolve<IResourceManager>();
container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));
//var appConfig = container.Resolve<ExampleConfig>();
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(
":memory:", false,
SqliteOrmLiteDialectProvider.Instance));
var resetMovies = container.Resolve<ResetMoviesService>();
resetMovies.Post(null);
//var movies = container.Resolve<IDbConnectionFactory>().Exec(x => x.Select<Movie>());
//Console.WriteLine(movies.Dump());
}
}
}
| |
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay
//
//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.
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections.Generic;
using System.Text;
using Thrift.Protocol;
namespace Netfox.SnooperMessenger.Protocol
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class MNMessagesSyncDeltaDeliveryReceipt : TBase
{
private MNMessagesSyncThreadKey _ThreadKey;
private long _ActorFbId;
private string _DeviceId;
private long _AppId;
private long _TimestampMs;
private List<string> _MessageIds;
private long _DeliveredWatermarkTimestampMs;
public MNMessagesSyncThreadKey ThreadKey
{
get
{
return _ThreadKey;
}
set
{
__isset.ThreadKey = true;
this._ThreadKey = value;
}
}
public long ActorFbId
{
get
{
return _ActorFbId;
}
set
{
__isset.ActorFbId = true;
this._ActorFbId = value;
}
}
public string DeviceId
{
get
{
return _DeviceId;
}
set
{
__isset.DeviceId = true;
this._DeviceId = value;
}
}
public long AppId
{
get
{
return _AppId;
}
set
{
__isset.AppId = true;
this._AppId = value;
}
}
public long TimestampMs
{
get
{
return _TimestampMs;
}
set
{
__isset.TimestampMs = true;
this._TimestampMs = value;
}
}
public List<string> MessageIds
{
get
{
return _MessageIds;
}
set
{
__isset.MessageIds = true;
this._MessageIds = value;
}
}
public long DeliveredWatermarkTimestampMs
{
get
{
return _DeliveredWatermarkTimestampMs;
}
set
{
__isset.DeliveredWatermarkTimestampMs = true;
this._DeliveredWatermarkTimestampMs = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool ThreadKey;
public bool ActorFbId;
public bool DeviceId;
public bool AppId;
public bool TimestampMs;
public bool MessageIds;
public bool DeliveredWatermarkTimestampMs;
}
public MNMessagesSyncDeltaDeliveryReceipt() {
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.Struct) {
ThreadKey = new MNMessagesSyncThreadKey();
ThreadKey.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.I64) {
ActorFbId = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.String) {
DeviceId = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.I64) {
AppId = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.I64) {
TimestampMs = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 6:
if (field.Type == TType.List) {
{
MessageIds = new List<string>();
TList _list107 = iprot.ReadListBegin();
for( int _i108 = 0; _i108 < _list107.Count; ++_i108)
{
string _elem109;
_elem109 = iprot.ReadString();
MessageIds.Add(_elem109);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 7:
if (field.Type == TType.I64) {
DeliveredWatermarkTimestampMs = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("MNMessagesSyncDeltaDeliveryReceipt");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (ThreadKey != null && __isset.ThreadKey) {
field.Name = "ThreadKey";
field.Type = TType.Struct;
field.ID = 1;
oprot.WriteFieldBegin(field);
ThreadKey.Write(oprot);
oprot.WriteFieldEnd();
}
if (__isset.ActorFbId) {
field.Name = "ActorFbId";
field.Type = TType.I64;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteI64(ActorFbId);
oprot.WriteFieldEnd();
}
if (DeviceId != null && __isset.DeviceId) {
field.Name = "DeviceId";
field.Type = TType.String;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteString(DeviceId);
oprot.WriteFieldEnd();
}
if (__isset.AppId) {
field.Name = "AppId";
field.Type = TType.I64;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteI64(AppId);
oprot.WriteFieldEnd();
}
if (__isset.TimestampMs) {
field.Name = "TimestampMs";
field.Type = TType.I64;
field.ID = 5;
oprot.WriteFieldBegin(field);
oprot.WriteI64(TimestampMs);
oprot.WriteFieldEnd();
}
if (MessageIds != null && __isset.MessageIds) {
field.Name = "MessageIds";
field.Type = TType.List;
field.ID = 6;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.String, MessageIds.Count));
foreach (string _iter110 in MessageIds)
{
oprot.WriteString(_iter110);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (__isset.DeliveredWatermarkTimestampMs) {
field.Name = "DeliveredWatermarkTimestampMs";
field.Type = TType.I64;
field.ID = 7;
oprot.WriteFieldBegin(field);
oprot.WriteI64(DeliveredWatermarkTimestampMs);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("MNMessagesSyncDeltaDeliveryReceipt(");
bool __first = true;
if (ThreadKey != null && __isset.ThreadKey) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ThreadKey: ");
__sb.Append(ThreadKey== null ? "<null>" : ThreadKey.ToString());
}
if (__isset.ActorFbId) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ActorFbId: ");
__sb.Append(ActorFbId);
}
if (DeviceId != null && __isset.DeviceId) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("DeviceId: ");
__sb.Append(DeviceId);
}
if (__isset.AppId) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("AppId: ");
__sb.Append(AppId);
}
if (__isset.TimestampMs) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("TimestampMs: ");
__sb.Append(TimestampMs);
}
if (MessageIds != null && __isset.MessageIds) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("MessageIds: ");
__sb.Append(MessageIds);
}
if (__isset.DeliveredWatermarkTimestampMs) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("DeliveredWatermarkTimestampMs: ");
__sb.Append(DeliveredWatermarkTimestampMs);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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: this is heavily modified version of TextUI.cs
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using NUnit.Framework.Api;
using NUnit.Framework.Internal;
namespace NUnitLite.Runner
{
/// <summary>
/// TextUI is a general purpose class that runs tests and
/// outputs to a TextWriter.
///
/// Call it from your Main like this:
/// new TextUI(textWriter).Execute(args);
/// OR
/// new TextUI().Execute(args);
/// The provided TextWriter is used by default, unless the
/// arguments to Execute override it using -out. The second
/// form uses the Console, provided it exists on the platform.
/// </summary>
public class NUnitStreamUI
{
private int reportCount = 0;
// private NUnit.ObjectList assemblies = new NUnit.ObjectList();
private TextWriter writer;
private ITestAssemblyRunner runner;
public ResultSummary Summary { get; private set; }
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TextUI"/> class.
/// </summary>
/// <param name="writer">The TextWriter to use.</param>
public NUnitStreamUI(TextWriter writer)
{
// Set the default writer - may be overridden by the args specified
this.writer = writer;
this.runner = new NUnitLiteTestAssemblyRunner(new NUnitLiteTestAssemblyBuilder());
}
#endregion
#region Public Methods
/// <summary>
/// Execute a test run based on the aruments passed
/// from Main.
/// </summary>
/// <param name="args">An array of arguments</param>
public void Execute(Assembly assembly)
{
try
{
IDictionary loadOptions = new Hashtable();
if (!runner.Load(assembly, loadOptions))
{
writer.WriteLine("No tests found in assembly {0}", assembly.GetName().Name);
return;
}
writer.Write(assembly.GetName().Name + ": ");
RunTests();
}
#pragma warning disable 168
catch (NullReferenceException ex)
#pragma warning restore 168
{
}
catch (Exception ex)
{
writer.WriteLine(ex.Message);
}
finally
{
writer.Close();
}
}
private void RunTests()
{
ITestResult result = runner.Run(TestListener.NULL, TestFilter.Empty);
ReportResults(result);
}
/// <summary>
/// Reports the results.
/// </summary>
/// <param name="result">The result.</param>
private void ReportResults( ITestResult result )
{
Summary = new ResultSummary(result);
writer.WriteLine("{0} Tests : {1} Failures, {2} Errors, {3} Not Run",
Summary.TestCount, Summary.FailureCount, Summary.ErrorCount, Summary.NotRunCount);
if (Summary.FailureCount > 0 || Summary.ErrorCount > 0)
PrintErrorReport(result);
if (Summary.NotRunCount > 0)
PrintNotRunReport(result);
}
#endregion
#region Helper Methods
private void PrintErrorReport(ITestResult result)
{
reportCount = 0;
writer.WriteLine();
writer.WriteLine("Errors and Failures:");
PrintErrorResults(result);
}
private void PrintErrorResults(ITestResult result)
{
if (result.HasChildren)
foreach (ITestResult r in result.Children)
PrintErrorResults(r);
else if (result.ResultState == ResultState.Error || result.ResultState == ResultState.Failure)
{
writer.WriteLine();
writer.WriteLine("{0}) {1} ({2})", ++reportCount, result.Name, result.FullName);
writer.WriteLine(result.Message);
writer.WriteLine(result.StackTrace);
}
}
private void PrintNotRunReport(ITestResult result)
{
reportCount = 0;
writer.WriteLine();
writer.WriteLine("Tests Not Run:");
PrintNotRunResults(result);
}
private void PrintNotRunResults(ITestResult result)
{
if (result.HasChildren)
foreach (ITestResult r in result.Children)
PrintNotRunResults(r);
else if (result.ResultState == ResultState.Ignored || result.ResultState == ResultState.NotRunnable || result.ResultState == ResultState.Skipped)
{
writer.WriteLine();
writer.WriteLine("{0}) {1} ({2}) : {3}", ++reportCount, result.Name, result.FullName, result.Message);
}
}
private void PrintFullReport(ITestResult result)
{
writer.WriteLine();
writer.WriteLine("All Test Results:");
PrintAllResults(result, " ");
}
private void PrintAllResults(ITestResult result, string indent)
{
string status = null;
switch (result.ResultState.Status)
{
case TestStatus.Failed:
status = "FAIL";
break;
case TestStatus.Skipped:
status = "SKIP";
break;
case TestStatus.Inconclusive:
status = "INC ";
break;
case TestStatus.Passed:
status = "OK ";
break;
}
writer.Write(status);
writer.Write(indent);
writer.WriteLine(result.Name);
if (result.HasChildren)
foreach (ITestResult r in result.Children)
PrintAllResults(r, indent + " ");
}
#endregion
}
}
| |
namespace SqlStreamStore
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using MySqlConnector;
using SqlStreamStore.MySqlScripts;
using SqlStreamStore.Streams;
partial class MySqlStreamStore
{
protected override async Task<ReadAllPage> ReadAllForwardsInternal(
long fromPositionExclusive,
int maxCount,
bool prefetch,
ReadNextAllPage readNext,
CancellationToken cancellationToken)
{
maxCount = maxCount == int.MaxValue ? maxCount - 1 : maxCount;
try
{
var commandText = prefetch
? _schema.ReadAllForwardsWithData
: _schema.ReadAllForwards;
using (var connection = await OpenConnection(cancellationToken))
using (var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false))
using (var command = BuildStoredProcedureCall(
commandText,
transaction,
Parameters.Count(maxCount + 1),
Parameters.Position(fromPositionExclusive)))
using (var reader = await command
.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken)
.ConfigureAwait(false))
{
if (!reader.HasRows)
{
return new ReadAllPage(
fromPositionExclusive,
fromPositionExclusive,
true,
ReadDirection.Forward,
readNext,
Array.Empty<StreamMessage>());
}
var messages = new List<(StreamMessage message, int? maxAge)>();
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
if (messages.Count == maxCount)
{
messages.Add(default);
}
else
{
var streamIdInfo = new StreamIdInfo(reader.GetString(0));
var (message, maxAge, _) =
await ReadAllStreamMessage(reader, streamIdInfo.MySqlStreamId, prefetch);
messages.Add((message, maxAge));
}
}
bool isEnd = true;
if (messages.Count == maxCount + 1) // An extra row was read, we're not at the end
{
isEnd = false;
messages.RemoveAt(maxCount);
}
var filteredMessages = FilterExpired(messages);
var nextPosition = filteredMessages[filteredMessages.Count - 1].Position + 1;
return new ReadAllPage(
fromPositionExclusive,
nextPosition,
isEnd,
ReadDirection.Forward,
readNext,
filteredMessages.ToArray());
}
}
catch(MySqlException exception) when(exception.InnerException is ObjectDisposedException disposedException)
{
throw new ObjectDisposedException(disposedException.Message, exception);
}
}
protected override async Task<ReadAllPage> ReadAllBackwardsInternal(
long fromPositionExclusive,
int maxCount,
bool prefetch,
ReadNextAllPage readNext,
CancellationToken cancellationToken)
{
maxCount = maxCount == int.MaxValue ? maxCount - 1 : maxCount;
var ordinal = fromPositionExclusive == Position.End ? long.MaxValue - 1 : fromPositionExclusive;
try
{
var commandText = prefetch
? _schema.ReadAllBackwardsWithData
: _schema.ReadAllBackwards;
using (var connection = await OpenConnection(cancellationToken))
using (var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false))
using (var command = BuildStoredProcedureCall(
commandText,
transaction,
Parameters.Count(maxCount + 1),
Parameters.Position(ordinal)))
using (var reader = await command
.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken)
.ConfigureAwait(false))
{
if(!reader.HasRows)
{
// When reading backwards and there are no more items, then next position is LongPosition.Start,
// regardless of what the fromPosition is.
return new ReadAllPage(
Position.Start,
Position.Start,
true,
ReadDirection.Backward,
readNext,
Array.Empty<StreamMessage>());
}
var messages = new List<(StreamMessage message, int? maxAge)>();
long lastOrdinal = 0;
while(await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
var streamIdInfo = new StreamIdInfo(reader.GetString(0));
var (message, maxAge, position) =
await ReadAllStreamMessage(reader, streamIdInfo.MySqlStreamId, prefetch);
messages.Add((message, maxAge));
lastOrdinal = position;
}
bool isEnd = true;
var nextPosition = lastOrdinal;
if(messages.Count == maxCount + 1) // An extra row was read, we're not at the end
{
isEnd = false;
messages.RemoveAt(maxCount);
}
var filteredMessages = FilterExpired(messages);
fromPositionExclusive = filteredMessages.Count > 0 ? filteredMessages[0].Position : 0;
return new ReadAllPage(
fromPositionExclusive,
nextPosition,
isEnd,
ReadDirection.Backward,
readNext,
filteredMessages.ToArray());
}
}
catch(MySqlException exception) when(exception.InnerException is ObjectDisposedException disposedException)
{
throw new ObjectDisposedException(disposedException.Message, exception);
}
}
private async Task<(StreamMessage message, int? maxAge, long position)> ReadAllStreamMessage(
DbDataReader reader,
MySqlStreamId streamId,
bool prefetch)
{
async Task<string> ReadString(int ordinal)
{
if (await reader.IsDBNullAsync(ordinal))
{
return null;
}
using (var textReader = reader.GetTextReader(ordinal))
{
return await textReader.ReadToEndAsync().ConfigureAwait(false);
}
}
var maxAge = await reader.IsDBNullAsync(1).ConfigureAwait(false)
? default
: reader.GetInt32(1);
var messageId = reader.GetGuid(2);
var streamVersion = reader.GetInt32(3);
var position = reader.GetInt64(4);
var createdUtc = reader.GetDateTime(5);
var type = reader.GetString(6);
var jsonMetadata = await ReadString(7);
StreamMessage streamMessage;
if (prefetch)
{
var jsonData = await ReadString(8);
streamMessage = new StreamMessage(
streamId.IdOriginal,
messageId,
streamVersion,
position,
createdUtc,
type,
jsonMetadata,
jsonData);
}
else
{
streamMessage = new StreamMessage(
streamId.IdOriginal,
messageId,
streamVersion,
position,
createdUtc,
type,
jsonMetadata,
ct => GetJsonData(streamId, streamVersion)(ct));
}
return (streamMessage, maxAge, position);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
public class MessageTransferModule : IRegionModule, IMessageTransferModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static IMuteListModule m_muteListModule = null;
// private bool m_Enabled = false;
protected bool m_Gridmode = false;
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, ulong> m_UserRegionMap = new Dictionary<UUID, ulong>();
public event UndeliveredMessage OnUndeliveredMessage;
private int m_DebugLevel = 0;
public virtual void Initialize(Scene scene, IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null)
{
if (cnf.GetString("MessageTransferModule", "MessageTransferModule") != "MessageTransferModule")
return;
m_DebugLevel = cnf.GetInt("Debug", m_DebugLevel);
}
cnf = config.Configs["Startup"];
if (cnf != null)
m_Gridmode = cnf.GetBoolean("gridmode", false);
// m_Enabled = true;
lock (m_Scenes)
{
if (m_Scenes.Count == 0)
{
scene.CommsManager.HttpServer.AddXmlRPCHandler("grid_instant_message", processXMLRPCGridInstantMessage);
scene.CommsManager.HttpServer.AddXmlRPCHandler("gridwide_host_ban", processGridwideHostBan);
// New Style
scene.CommsManager.HttpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("grid_instant_message"), processXMLRPCGridInstantMessage));
scene.CommsManager.HttpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("gridwide_host_ban"), processGridwideHostBan));
}
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialize()
{
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "MessageTransferModule"; }
}
public virtual bool IsSharedModule
{
get { return true; }
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID fromAgentID = new UUID(im.fromAgentID);
UUID toAgentID = new UUID(im.toAgentID);
foreach (Scene scene in m_Scenes)
{
if (!scene.EventManager.TriggerOnBeforeSendInstantMessage(im))
{
m_log.WarnFormat("[INSTANT MESSAGE]: Outbound IM blocked by module");
return;
}
// Check for muted senders in specific IM cases.
if (m_muteListModule == null)
m_muteListModule = scene.RequestModuleInterface<IMuteListModule>();
if (m_muteListModule != null)
if ((im.dialog == (int)InstantMessageDialog.MessageFromAgent) || (im.dialog == (int)InstantMessageDialog.MessageFromObject))
if (m_muteListModule.IsMuted(fromAgentID, toAgentID)) // owner ID is in fromAgentID in case of IMs from objects
return; // recipient has sender muted.
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Attempting delivery of IM from {0} to {1}", im.fromAgentName, toAgentID.ToString());
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
if (scene.Entities.ContainsKey(toAgentID) &&
scene.Entities[toAgentID] is ScenePresence)
{
//m_log.DebugFormat("[INSTANT MESSAGE]: Looking for {0} in {1}", toAgentID.ToString(), scene.RegionInfo.RegionName);
// Local message
ScenePresence user = (ScenePresence) scene.Entities[toAgentID];
if (!user.IsChildAgent)
{
//m_log.DebugFormat("[INSTANT MESSAGE]: Delivering to client");
user.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
if (scene.Entities.ContainsKey(toAgentID) &&
scene.Entities[toAgentID] is ScenePresence)
{
// Local message
ScenePresence user = (ScenePresence) scene.Entities[toAgentID];
//m_log.DebugFormat("[INSTANT MESSAGE]: Delivering to client");
user.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
if (m_Gridmode)
{
//m_log.DebugFormat("[INSTANT MESSAGE]: Delivering via grid");
// Still here, try send via Grid
SendGridInstantMessageViaXMLRPC(im, result);
return;
}
HandleUndeliveredMessage(im, result);
return;
}
private void HandleUndeliveredMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then the IM will be considered
// delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
result(true);
return;
}
m_log.WarnFormat("[INSTANT MESSAGE]: Message undeliverable and no undeliverable message handler for message from {0} to {1}", im.fromAgentID, im.toAgentID);
result(false);
}
protected virtual XmlRpcResponse processGridwideHostBan(XmlRpcRequest request, IPEndPoint remoteClient)
{
return null;
}
/// <summary>
/// Process a XMLRPC Grid Instant Message
/// </summary>
/// <param name="request">XMLRPC parameters
/// </param>
/// <returns>Nothing much</returns>
protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
// TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
// happen here and aren't caught and log them.
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = String.Empty;
string message = String.Empty;
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID=0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero ;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_x = (uint)Convert.ToDouble((string)requestData["position_x"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_y = (uint)Convert.ToDouble((string)requestData["position_y"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_z = (uint)Convert.ToDouble((string)requestData["position_z"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
// Trigger the Instant message in the scene.
foreach (Scene scene in m_Scenes)
{
if (scene.Entities.ContainsKey(toAgentID) &&
scene.Entities[toAgentID] is ScenePresence)
{
ScenePresence user =
(ScenePresence)scene.Entities[toAgentID];
if (!user.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
/// <summary>
/// delegate for sending a grid instant message asynchronously
/// </summary>
public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, ulong prevRegionHandle, int tries);
protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
{
try
{
GridInstantMessageDelegate icon =
(GridInstantMessageDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
catch (System.Net.Sockets.SocketException e)
{
m_log.ErrorFormat("[INSTANT MESSAGE]: Network error sending instant message: {0}", e.Message);
}
catch (Exception e)
{
m_log.ErrorFormat("[INSTANT MESSAGE]: Sending instant message failed {0}", e);
}
}
protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
{
GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
d.BeginInvoke(im, result, 0, 0, GridInstantMessageCompleted, d);
}
/// <summary>
/// Recursive SendGridInstantMessage over XMLRPC method.
/// This is called from within a dedicated thread.
/// The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from
/// itself, prevRegionHandle will be the last region handle that we tried to send.
/// If the handles are the same, we look up the user's location using the grid.
/// If the handles are still the same, we end. The send failed.
/// </summary>
/// <param name="prevRegionHandle">
/// Pass in 0 the first time this method is called. It will be called recursively with the last
/// regionhandle tried
/// </param>
protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result,
ulong prevRegionHandle, int tries)
{
UserAgentData upd = null;
bool lookupAgent = false;
UUID toAgentID = new UUID(im.toAgentID);
if (tries > 5)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Retries exhausted - Unable to deliver an instant message to {0}", toAgentID.ToString());
return;
}
if (m_DebugLevel >= 2)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} tries={1}", prevRegionHandle, tries);
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
upd = new UserAgentData();
upd.AgentOnline = true;
upd.Handle = m_UserRegionMap[toAgentID];
// We need to compare the current regionhandle with the previous region handle
// or the recursive loop will never end because it will never try to lookup the agent again
if (prevRegionHandle == upd.Handle)
{
lookupAgent = true;
if (m_DebugLevel >= 2)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} tries={1} in region map, same region, requires lookup", prevRegionHandle, tries);
}
else
if (prevRegionHandle == 0)
{
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} tries={1} in region map, using {2}, no lookup", prevRegionHandle, tries, upd.Handle);
}
else
{
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} tries={1} in region map, different region, no lookup", prevRegionHandle, tries);
}
}
else
{
lookupAgent = true;
if (m_DebugLevel >= 2)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} tries={1} not in region map, requires lookup", prevRegionHandle, tries);
}
}
// Are we needing to look-up an agent?
if (lookupAgent)
{
// Non-cached user agent lookup.
upd = m_Scenes[0].CommsManager.UserService.GetUserAgent(toAgentID,true);
if (upd != null)
{
// check if we've tried this before..
// This is one way to end the recursive loop
//
if (upd.Handle == prevRegionHandle)
{
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} still, tries={1}", upd.Handle, tries);
HandleUndeliveredMessage(im, result);
return;
}
else
{
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} now, tries={1} lookup success", upd.Handle, tries);
}
}
else
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Unable to deliver an instant message to {0} (user lookup failed).", toAgentID.ToString());
HandleUndeliveredMessage(im, result);
return;
}
}
if (upd != null)
{
if (upd.AgentOnline)
{
RegionInfo reginfo = m_Scenes[0].SceneGridService.RequestNeighbouringRegionInfo(upd.Handle);
if (reginfo != null)
{
if (m_DebugLevel >= 2)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} now, sending grid IM", upd.Handle);
Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
// Not actually used anymore, left in for compatibility
// Remove at next interface change
//
msgdata["region_handle"] = 0;
bool imresult = doIMSending(reginfo, msgdata);
if (imresult)
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
m_UserRegionMap[toAgentID] = upd.Handle;
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} success, updating map", upd.Handle);
}
else
{
m_UserRegionMap.Add(toAgentID, upd.Handle);
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} success, adding to map", upd.Handle);
}
}
result(true);
}
else
{
// try again, but lookup user this time.
// Warning, this must call the Async version
// of this method or we'll be making thousands of threads
// The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
// The version that spawns the thread is SendGridInstantMessageViaXMLRPC
// This is recursive!!!!!
if (m_DebugLevel >= 2)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} failed, retrying recursively", upd.Handle);
SendGridInstantMessageViaXMLRPCAsync(im, result, upd.Handle, ++tries);
}
}
else
{
if (m_DebugLevel >= 2)
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}, will retry", upd.Handle);
SendGridInstantMessageViaXMLRPCAsync(im, result, upd.Handle, ++tries);
}
}
else
{
if (m_DebugLevel >= 1)
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: region={0} user offline.", upd.Handle);
HandleUndeliveredMessage(im, result);
}
}
else
{
if (m_DebugLevel >= 1)
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find user {0}", toAgentID);
HandleUndeliveredMessage(im, result);
}
}
/// <summary>
/// This actually does the XMLRPC Request
/// </summary>
/// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
/// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
/// <returns>Bool if the message was successfully delivered at the other side.</returns>
protected virtual bool doIMSending(RegionInfo reginfo, Hashtable xmlrpcdata)
{
try
{
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
string url = "http://" + reginfo.ExternalHostName + ":" + reginfo.HttpPort;
string methodName = "grid_instant_message";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(url, methodName), 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("success"))
{
if ((string)responseData["success"] == "TRUE")
return true;
else
return false;
}
else
{
return false;
}
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to http://{0}:{1} the host didn't respond ({2})",
reginfo.ExternalHostName, reginfo.HttpPort, e.Message);
}
catch (System.IO.IOException e)
{
//this can be thrown, for some reason WSACancelBlockingCall is sometimes called here
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to http://{0}:{1} the host didn't respond ({2})",
reginfo.ExternalHostName, reginfo.HttpPort, e.Message);
}
return false;
}
/// <summary>
/// Get ulong region handle for region by it's Region UUID.
/// We use region handles over grid comms because there's all sorts of free and cool caching.
/// </summary>
/// <param name="regionID">UUID of region to get the region handle for</param>
/// <returns></returns>
// private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
// {
// ulong returnhandle = 0;
//
// lock (m_Scenes)
// {
// foreach (Scene sn in m_Scenes)
// {
// if (sn.RegionInfo.RegionID == regionID)
// {
// returnhandle = sn.RegionInfo.RegionHandle;
// break;
// }
// }
// }
// return returnhandle;
// }
/// <summary>
/// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
/// </summary>
/// <param name="msg">The GridInstantMessage object</param>
/// <returns>Hashtable containing the XMLRPC request</returns>
protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
{
Hashtable gim = new Hashtable();
gim["from_agent_id"] = msg.fromAgentID.ToString();
// Kept for compatibility
gim["from_agent_session"] = UUID.Zero.ToString();
gim["to_agent_id"] = msg.toAgentID.ToString();
gim["im_session_id"] = msg.imSessionID.ToString();
gim["timestamp"] = msg.timestamp.ToString();
gim["from_agent_name"] = msg.fromAgentName;
gim["message"] = msg.message;
byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog;
gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None);
if (msg.fromGroup)
gim["from_group"] = "TRUE";
else
gim["from_group"] = "FALSE";
byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
gim["parent_estate_id"] = msg.ParentEstateID.ToString();
gim["position_x"] = msg.Position.X.ToString();
gim["position_y"] = msg.Position.Y.ToString();
gim["position_z"] = msg.Position.Z.ToString();
gim["region_id"] = msg.RegionID.ToString();
gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None);
return gim;
}
}
}
| |
// 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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Buffers;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
public abstract partial class TextReader : MarshalByRefObject, IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n;
for (n = 0; n < count; n++)
{
int ch = Read();
if (ch == -1) break;
buffer[index + n] = (char)ch;
}
return n;
}
// Reads a span of characters. This method will read up to
// count characters from this TextReader into the
// span of characters Returns the actual number of characters read.
//
public virtual int Read(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = Read(array, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Blocking version of read for span of characters. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = ReadBlock(array, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string> ReadLineAsync()
{
return Task<string>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public async virtual Task<string> ReadToEndAsync()
{
var sb = new StringBuilder(4096);
char[] chars = ArrayPool<char>.Shared.Rent(4096);
try
{
int len;
while ((len = await ReadAsyncInternal(chars, default).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadAsync(array.Array, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state;
return t.Item1.Read(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
var tuple = new Tuple<TextReader, Memory<char>>(this, buffer);
return new ValueTask<int>(Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state;
return t.Item1.Read(t.Item2.Span);
},
tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadBlockAsync(array.Array, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state;
return t.Item1.ReadBlock(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
int n = 0, i;
do
{
i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false);
n += i;
} while (i > 0 && n < buffer.Length);
return n;
}
#endregion
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string ReadLine()
{
return null;
}
}
public static TextReader Synchronized(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return reader is SyncTextReader ? reader : new SyncTextReader(reader);
}
internal sealed class SyncTextReader : TextReader
{
internal readonly TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => _in.Close();
[MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Peek() => _in.Peek();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read() => _in.Read();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadLine() => _in.ReadLine();
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadToEnd() => _in.ReadToEnd();
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadLineAsync() => Task.FromResult(ReadLine());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(ReadBlock(buffer, index, count));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace OpenQA.Selenium
{
[TestFixture]
public class TypingTest : DriverTestFixture
{
[Test]
[Category("Javascript")]
public void ShouldFireKeyPressEvents()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("a");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(result.Text.Contains("press:"));
}
[Test]
[Category("Javascript")]
public void ShouldFireKeyDownEvents()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("I");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(result.Text.Contains("down:"));
}
[Test]
[Category("Javascript")]
public void ShouldFireKeyUpEvents()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("a");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(result.Text.Contains("up:"));
}
[Test]
public void ShouldTypeLowerCaseLetters()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("abc def");
Assert.AreEqual(keyReporter.GetAttribute("value"), "abc def");
}
[Test]
public void ShouldBeAbleToTypeCapitalLetters()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("ABC DEF");
Assert.AreEqual(keyReporter.GetAttribute("value"), "ABC DEF");
}
[Test]
public void ShouldBeAbleToTypeQuoteMarks()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("\"");
Assert.AreEqual(keyReporter.GetAttribute("value"), "\"");
}
[Test]
public void ShouldBeAbleToTypeTheAtCharacter()
{
// simon: I tend to use a US/UK or AUS keyboard layout with English
// as my primary language. There are consistent reports that we're
// not handling i18nised keyboards properly. This test exposes this
// in a lightweight manner when my keyboard is set to the DE mapping
// and we're using IE.
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("@");
Assert.AreEqual(keyReporter.GetAttribute("value"), "@");
}
[Test]
public void ShouldBeAbleToMixUpperAndLowerCaseLetters()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("me@eXample.com");
Assert.AreEqual(keyReporter.GetAttribute("value"), "me@eXample.com");
}
[Test]
[Category("Javascript")]
public void ArrowKeysShouldNotBePrintable()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys(Keys.ArrowLeft);
Assert.AreEqual(keyReporter.GetAttribute("value"), "");
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldBeAbleToUseArrowKeys()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("Tet" + Keys.ArrowLeft + "s");
Assert.AreEqual(keyReporter.GetAttribute("value"), "Test");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyUpWhenEnteringTextIntoInputElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyUp"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.AreEqual(result.Text, "I like cheese");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyDownWhenEnteringTextIntoInputElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyDown"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyPressWhenEnteringTextIntoInputElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyPress"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyUpWhenEnteringTextIntoTextAreas()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyUpArea"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.AreEqual(result.Text, "I like cheese");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyDownWhenEnteringTextIntoTextAreas()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyDownArea"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyPressWhenEnteringTextIntoTextAreas()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyPressArea"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Firefox, "Firefox demands to have the focus on the window already.")]
public void ShouldFireFocusKeyEventsInTheRightOrder()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("theworks"));
element.SendKeys("a");
Assert.AreEqual(result.Text.Trim(), "focus keydown keypress keyup");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")]
[IgnoreBrowser(Browser.HtmlUnit, "firefox-specific")]
[IgnoreBrowser(Browser.Chrome, "Firefox-specific test. Chrome does not report key press event.")]
[IgnoreBrowser(Browser.PhantomJS, "Firefox-specific test. PhantomJS does not report key press event.")]
public void ShouldReportKeyCodeOfArrowKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys(Keys.ArrowDown);
Assert.AreEqual(result.Text.Trim(), "down: 40 press: 40 up: 40");
element.SendKeys(Keys.ArrowUp);
Assert.AreEqual(result.Text.Trim(), "down: 38 press: 38 up: 38");
element.SendKeys(Keys.ArrowLeft);
Assert.AreEqual(result.Text.Trim(), "down: 37 press: 37 up: 37");
element.SendKeys(Keys.ArrowRight);
Assert.AreEqual(result.Text.Trim(), "down: 39 press: 39 up: 39");
// And leave no rubbish/printable keys in the "keyReporter"
Assert.AreEqual(element.GetAttribute("value"), "");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "untested user agents")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ShouldReportKeyCodeOfArrowKeysUpDownEvents()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys(Keys.ArrowDown);
Assert.IsTrue(result.Text.Trim().Contains("down: 40"));
Assert.IsTrue(result.Text.Trim().Contains("up: 40"));
element.SendKeys(Keys.ArrowUp);
Assert.IsTrue(result.Text.Trim().Contains("down: 38"));
Assert.IsTrue(result.Text.Trim().Contains("up: 38"));
element.SendKeys(Keys.ArrowLeft);
Assert.IsTrue(result.Text.Trim().Contains("down: 37"));
Assert.IsTrue(result.Text.Trim().Contains("up: 37"));
element.SendKeys(Keys.ArrowRight);
Assert.IsTrue(result.Text.Trim().Contains("down: 39"));
Assert.IsTrue(result.Text.Trim().Contains("up: 39"));
// And leave no rubbish/printable keys in the "keyReporter"
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
}
[Test]
[Category("Javascript")]
public void NumericNonShiftKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String numericLineCharsNonShifted = "`1234567890-=[]\\;,.'/42";
element.SendKeys(numericLineCharsNonShifted);
Assert.AreEqual(element.GetAttribute("value"), numericLineCharsNonShifted);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void NumericShiftKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String numericShiftsEtc = "~!@#$%^&*()_+{}:\"<>?|END~";
element.SendKeys(numericShiftsEtc);
Assert.AreEqual(element.GetAttribute("value"), numericShiftsEtc);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
}
[Test]
[Category("Javascript")]
public void LowerCaseAlphaKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String lowerAlphas = "abcdefghijklmnopqrstuvwxyz";
element.SendKeys(lowerAlphas);
Assert.AreEqual(element.GetAttribute("value"), lowerAlphas);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void UppercaseAlphaKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
element.SendKeys(upperAlphas);
Assert.AreEqual(element.GetAttribute("value"), upperAlphas);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void AllPrintableKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String allPrintable =
"!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFGHIJKLMNO" +
"PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
element.SendKeys(allPrintable);
Assert.AreEqual(element.GetAttribute("value"), allPrintable);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ArrowKeysAndPageUpAndDown()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("a" + Keys.Left + "b" + Keys.Right +
Keys.Up + Keys.Down + Keys.PageUp + Keys.PageDown + "1");
Assert.AreEqual(element.GetAttribute("value"), "ba1");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void HomeAndEndAndPageUpAndPageDownKeys()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abc" + Keys.Home + "0" + Keys.Left + Keys.Right +
Keys.PageUp + Keys.PageDown + Keys.End + "1" + Keys.Home +
"0" + Keys.PageUp + Keys.End + "111" + Keys.Home + "00");
Assert.AreEqual(element.GetAttribute("value"), "0000abc1111");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void DeleteAndBackspaceKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcdefghi");
Assert.AreEqual(element.GetAttribute("value"), "abcdefghi");
element.SendKeys(Keys.Left + Keys.Left + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), "abcdefgi");
element.SendKeys(Keys.Left + Keys.Left + Keys.Backspace);
Assert.AreEqual(element.GetAttribute("value"), "abcdfgi");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void SpecialSpaceKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcd" + Keys.Space + "fgh" + Keys.Space + "ij");
Assert.AreEqual(element.GetAttribute("value"), "abcd fgh ij");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void NumberpadKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcd" + Keys.Multiply + Keys.Subtract + Keys.Add +
Keys.Decimal + Keys.Separator + Keys.NumberPad0 + Keys.NumberPad9 +
Keys.Add + Keys.Semicolon + Keys.Equal + Keys.Divide +
Keys.NumberPad3 + "abcd");
Assert.AreEqual(element.GetAttribute("value"), "abcd*-+.,09+;=/3abcd");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void NumberpadAndFunctionKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("FUNCTION" + Keys.F4 + "-KEYS" + Keys.F4);
element.SendKeys("" + Keys.F4 + "-TOO" + Keys.F4);
Assert.AreEqual(element.GetAttribute("value"), "FUNCTION-KEYS-TOO");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ShiftSelectionDeletes()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcd efgh");
Assert.AreEqual(element.GetAttribute("value"), "abcd efgh");
//Could be chord problem
element.SendKeys(Keys.Shift + Keys.Left + Keys.Left + Keys.Left);
element.SendKeys(Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), "abcd e");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ChordControlHomeShiftEndDelete()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG");
element.SendKeys(Keys.Home);
element.SendKeys("" + Keys.Shift + Keys.End + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
Assert.IsTrue(result.Text.Contains(" up: 16"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ChordReveseShiftHomeSelectionDeletes()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("done" + Keys.Home);
Assert.AreEqual(element.GetAttribute("value"), "done");
//Sending chords
element.SendKeys("" + Keys.Shift + "ALL " + Keys.Home);
Assert.AreEqual(element.GetAttribute("value"), "ALL done");
element.SendKeys(Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), "done");
element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home);
Assert.AreEqual(element.GetAttribute("value"), "done");
// Note: trailing SHIFT up here
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
element.SendKeys("" + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
}
// control-x control-v here for cut & paste tests, these work on windows
// and linux, but not on the MAC.
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ChordControlCutAndPaste()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
IWebElement result = driver.FindElement(By.Id("result"));
String paste = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG";
element.SendKeys(paste);
Assert.AreEqual(element.GetAttribute("value"), paste);
//Chords
element.SendKeys("" + Keys.Home + Keys.Shift + Keys.End);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
element.SendKeys(Keys.Control + "x");
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
element.SendKeys(Keys.Control + "v");
Assert.AreEqual(element.GetAttribute("value"), paste);
element.SendKeys("" + Keys.Left + Keys.Left + Keys.Left +
Keys.Shift + Keys.End);
element.SendKeys(Keys.Control + "x" + "v");
Assert.AreEqual(element.GetAttribute("value"), paste);
element.SendKeys(Keys.Home);
element.SendKeys(Keys.Control + "v");
element.SendKeys(Keys.Control + "v" + "v");
element.SendKeys(Keys.Control + "v" + "v" + "v");
Assert.AreEqual(element.GetAttribute("value"), "EFGEFGEFGEFGEFGEFG" + paste);
element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home +
Keys.Null + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
}
[Test]
[Category("Javascript")]
public void ShouldTypeIntoInputElementsThatHaveNoTypeAttribute()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("no-type"));
element.SendKeys("Should Say Cheese");
Assert.AreEqual(element.GetAttribute("value"), "Should Say Cheese");
}
[Test]
[Category("Javascript")]
public void ShouldNotTypeIntoElementsThatPreventKeyDownEvents()
{
driver.Url = javascriptPage;
IWebElement silent = driver.FindElement(By.Name("suppress"));
silent.SendKeys("s");
Assert.AreEqual(silent.GetAttribute("value"), string.Empty);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")]
[IgnoreBrowser(Browser.Chrome, "firefox-specific")]
[IgnoreBrowser(Browser.PhantomJS, "firefox-specific")]
public void GenerateKeyPressEventEvenWhenElementPreventsDefault()
{
driver.Url = javascriptPage;
IWebElement silent = driver.FindElement(By.Name("suppress"));
IWebElement result = driver.FindElement(By.Id("result"));
silent.SendKeys("s");
Assert.IsTrue(result.Text.Contains("press"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.IE, "IFrame content not updating in IE page.")]
[IgnoreBrowser(Browser.Chrome, "See crbug 20773")]
public void TypingIntoAnIFrameWithContentEditableOrDesignModeSet()
{
driver.Url = richTextPage;
driver.SwitchTo().Frame("editFrame");
IWebElement element = driver.SwitchTo().ActiveElement();
element.SendKeys("Fishy");
driver.SwitchTo().DefaultContent();
IWebElement trusted = driver.FindElement(By.Id("istrusted"));
IWebElement id = driver.FindElement(By.Id("tagId"));
Assert.AreEqual("[true]", trusted.Text);
Assert.AreEqual("[frameHtml]", id.Text);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void NonPrintableCharactersShouldWorkWithContentEditableOrDesignModeSet()
{
driver.Url = richTextPage;
// not tested on mac
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.SwitchTo().Frame("editFrame");
IWebElement element = driver.SwitchTo().ActiveElement();
//Chords
element.SendKeys("Dishy" + Keys.Backspace + Keys.Left + Keys.Left);
element.SendKeys(Keys.Left + Keys.Left + "F" + Keys.Delete + Keys.End + "ee!");
Assert.AreEqual("Fishee!", element.Text);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkGatewaysOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewaysOperations
{
/// <summary>
/// Creates or updates a virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network gateway by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </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<VirtualNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resets the primary of the virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of
/// the active-active feature enabled gateway.
/// </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<VirtualNetworkGateway>> ResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN client package for P2S client of the virtual network
/// gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP
/// peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </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<BgpPeerStatusListResult>> GetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway has learned, including routes learned from BGP peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </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<GatewayRouteListResult>> GetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway is advertising to the specified peer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer
/// </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<GatewayRouteListResult>> GetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </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 resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resets the primary of the virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of
/// the active-active feature enabled gateway.
/// </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<VirtualNetworkGateway>> BeginResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP
/// peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </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<BgpPeerStatusListResult>> BeginGetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway has learned, including routes learned from BGP peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </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<GatewayRouteListResult>> BeginGetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway is advertising to the specified peer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer
/// </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<GatewayRouteListResult>> BeginGetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent
{
using Microsoft.Azure.Management.AppService.Fluent.Models;
using System.Threading;
using System.Threading.Tasks;
internal partial class AppServiceDomainImpl
{
/// <summary>
/// Specifies if the registrant contact information is exposed publicly.
/// If domain privacy is turned on, the contact information will NOT be
/// available publicly.
/// </summary>
/// <param name="domainPrivacy">True if domain privacy is turned on.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Definition.IWithCreate AppServiceDomain.Definition.IWithDomainPrivacy.WithDomainPrivacyEnabled(bool domainPrivacy)
{
return this.WithDomainPrivacyEnabled(domainPrivacy);
}
/// <summary>
/// Specifies if the registrant contact information is exposed publicly.
/// If domain privacy is turned on, the contact information will NOT be
/// available publicly.
/// </summary>
/// <param name="domainPrivacy">True if domain privacy is turned on.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Update.IUpdate AppServiceDomain.Update.IWithDomainPrivacy.WithDomainPrivacyEnabled(bool domainPrivacy)
{
return this.WithDomainPrivacyEnabled(domainPrivacy);
}
/// <summary>
/// Specify the admin contact.
/// </summary>
/// <param name="contact">The admin contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Definition.IWithCreate AppServiceDomain.Definition.IWithAdminContact.WithAdminContact(Contact contact)
{
return this.WithAdminContact(contact);
}
/// <summary>
/// Specify the admin contact.
/// </summary>
/// <param name="contact">The admin contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Update.IUpdate AppServiceDomain.Update.IWithAdminContact.WithAdminContact(Contact contact)
{
return this.WithAdminContact(contact);
}
/// <summary>
/// Specify the tech contact.
/// </summary>
/// <param name="contact">The tech contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Definition.IWithCreate AppServiceDomain.Definition.IWithTechContact.WithTechContact(Contact contact)
{
return this.WithTechContact(contact);
}
/// <summary>
/// Specify the tech contact.
/// </summary>
/// <param name="contact">The tech contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Update.IUpdate AppServiceDomain.Update.IWithTechContact.WithTechContact(Contact contact)
{
return this.WithTechContact(contact);
}
/// <summary>
/// Specify the billing contact.
/// </summary>
/// <param name="contact">The billing contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Definition.IWithCreate AppServiceDomain.Definition.IWithBillingContact.WithBillingContact(Contact contact)
{
return this.WithBillingContact(contact);
}
/// <summary>
/// Specify the billing contact.
/// </summary>
/// <param name="contact">The billing contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Update.IUpdate AppServiceDomain.Update.IWithBillingContact.WithBillingContact(Contact contact)
{
return this.WithBillingContact(contact);
}
/// <summary>
/// Gets name servers.
/// </summary>
System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.NameServers
{
get
{
return this.NameServers();
}
}
/// <summary>
/// Gets admin contact information.
/// </summary>
Models.Contact Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.AdminContact
{
get
{
return this.AdminContact();
}
}
/// <summary>
/// Gets true if domain will renewed automatically.
/// </summary>
bool Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.AutoRenew
{
get
{
return this.AutoRenew();
}
}
/// <summary>
/// Gets technical contact information.
/// </summary>
Models.Contact Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.TechContact
{
get
{
return this.TechContact();
}
}
/// <summary>
/// Gets domain expiration timestamp.
/// </summary>
System.DateTime Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.ExpirationTime
{
get
{
return this.ExpirationTime();
}
}
/// <summary>
/// Gets timestamp when the domain was renewed last time.
/// </summary>
System.DateTime Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.LastRenewedTime
{
get
{
return this.LastRenewedTime();
}
}
/// <summary>
/// Gets domain creation timestamp.
/// </summary>
System.DateTime Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.CreatedTime
{
get
{
return this.CreatedTime();
}
}
/// <summary>
/// Gets billing contact information.
/// </summary>
Models.Contact Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.BillingContact
{
get
{
return this.BillingContact();
}
}
/// <summary>
/// Verifies the ownership of the domain for a certificate order bound to this domain.
/// </summary>
/// <param name="certificateOrderName">The name of the certificate order.</param>
/// <param name="domainVerificationToken">The domain verification token for the certificate order.</param>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.VerifyDomainOwnershipAsync(string certificateOrderName, string domainVerificationToken, CancellationToken cancellationToken)
{
await this.VerifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken, cancellationToken);
}
/// <summary>
/// Gets domain registration status.
/// </summary>
Models.DomainStatus Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.RegistrationStatus
{
get
{
return this.RegistrationStatus();
}
}
/// <summary>
/// Gets registrant contact information.
/// </summary>
Models.Contact Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.RegistrantContact
{
get
{
return this.RegistrantContact();
}
}
/// <summary>
/// Gets legal agreement consent.
/// </summary>
Models.DomainPurchaseConsent Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.Consent
{
get
{
return this.Consent();
}
}
/// <summary>
/// Gets all hostnames derived from the domain and assigned to Azure resources.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<string,Models.HostName> Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.ManagedHostNames
{
get
{
return this.ManagedHostNames();
}
}
/// <summary>
/// Verifies the ownership of the domain for a certificate order bound to this domain.
/// </summary>
/// <param name="certificateOrderName">The name of the certificate order.</param>
/// <param name="domainVerificationToken">The domain verification token for the certificate order.</param>
void Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.VerifyDomainOwnership(string certificateOrderName, string domainVerificationToken)
{
this.VerifyDomainOwnership(certificateOrderName, domainVerificationToken);
}
/// <summary>
/// Gets true if Azure can assign this domain to Web Apps. This value will
/// be true if domain registration status is active and it is hosted on
/// name servers Azure has programmatic access to.
/// </summary>
bool Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.ReadyForDnsRecordManagement
{
get
{
return this.ReadyForDnsRecordManagement();
}
}
/// <summary>
/// Gets true if domain privacy is enabled for this domain.
/// </summary>
bool Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain.Privacy
{
get
{
return this.Privacy();
}
}
/// <summary>
/// Specifies if the domain should be automatically renewed when it's
/// about to expire.
/// </summary>
/// <param name="autoRenew">True if the domain should be automatically renewed.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Definition.IWithCreate AppServiceDomain.Definition.IWithAutoRenew.WithAutoRenewEnabled(bool autoRenew)
{
return this.WithAutoRenewEnabled(autoRenew);
}
/// <summary>
/// Specifies if the domain should be automatically renewed when it's
/// about to expire.
/// </summary>
/// <param name="autoRenew">True if the domain should be automatically renewed.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Update.IUpdate AppServiceDomain.Update.IWithAutoRenew.WithAutoRenewEnabled(bool autoRenew)
{
return this.WithAutoRenewEnabled(autoRenew);
}
/// <summary>
/// Specify the registrant contact. By default, this is also the contact for
/// admin, billing, and tech.
/// </summary>
/// <param name="contact">The registrant contact.</param>
/// <return>The next stage of domain definition.</return>
AppServiceDomain.Definition.IWithCreate AppServiceDomain.Definition.IWithRegistrantContact.WithRegistrantContact(Contact contact)
{
return this.WithRegistrantContact(contact);
}
/// <summary>
/// Starts the definition of a new domain contact.
/// </summary>
/// <return>The first stage of the domain contact definition.</return>
DomainContact.Definition.IBlank<AppServiceDomain.Definition.IWithCreate> AppServiceDomain.Definition.IWithRegistrantContact.DefineRegistrantContact()
{
return this.DefineRegistrantContact();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using GoCardless.Internals;
using GoCardless.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GoCardless.Services
{
/// <summary>
/// Service class for working with payer authorisation resources.
///
/// <p class="restricted-notice">
/// Payer Authorisations is deprecated in favour of
/// <a
/// href="https://developer.gocardless.com/getting-started/billing-requests/overview/">
/// Billing Requests</a>. Please consider using Billing Requests to build
/// any
/// future integrations.
/// </p>
///
/// Payer Authorisation resource acts as a wrapper for creating customer,
/// bank account and mandate details in a single request.
/// PayerAuthorisation API enables the integrators to build their own custom
/// payment pages.
///
/// The process to use the Payer Authorisation API is as follows:
///
/// 1. Create a Payer Authorisation, either empty or with already
/// available information
/// 2. Update the authorisation with additional information or fix any
/// mistakes
/// 3. Submit the authorisation, after the payer has reviewed their
/// information
/// 4. [coming soon] Redirect the payer to the verification mechanisms
/// from the response of the Submit request (this will be introduced as a
/// non-breaking change)
/// 5. Confirm the authorisation to indicate that the resources can be
/// created
///
/// After the Payer Authorisation is confirmed, resources will eventually be
/// created as it's an asynchronous process.
///
/// To retrieve the status and ID of the linked resources you can do one of
/// the following:
/// <ol>
/// <li> Listen to <code> payer_authorisation_completed </code> <a
/// href="#appendix-webhooks"> webhook</a> (recommended)</li>
/// <li> Poll the GET <a
/// href="#payer-authorisations-get-a-single-payer-authorisation">
/// endpoint</a></li>
/// <li> Poll the GET events API
/// <code>https://api.gocardless.com/events?payer_authorisation={id}&action=completed</code>
/// </li>
/// </ol>
///
/// <p class="notice">
/// Note that the `create` and `update` endpoints behave differently than
/// other existing `create` and `update` endpoints. The Payer
/// Authorisation is still saved if incomplete data is provided.
/// We return the list of incomplete data in the `incomplete_fields` along
/// with the resources in the body of the response.
/// The bank account details(account_number, bank_code & branch_code) must
/// be sent together rather than splitting across different request for both
/// `create` and `update` endpoints.
/// <br><br>
/// The API is designed to be flexible and allows you to collect
/// information in multiple steps without storing any sensitive data in the
/// browser or in your servers.
/// </p>
/// </summary>
public class PayerAuthorisationService
{
private readonly GoCardlessClient _goCardlessClient;
/// <summary>
/// Constructor. Users of this library should not call this. An instance of this
/// class can be accessed through an initialised GoCardlessClient.
/// </summary>
public PayerAuthorisationService(GoCardlessClient goCardlessClient)
{
_goCardlessClient = goCardlessClient;
}
/// <summary>
/// Retrieves the details of a single existing Payer Authorisation. It
/// can be used for polling the status of a Payer Authorisation.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "PA".</param>
/// <param name="request">An optional `PayerAuthorisationGetRequest` representing the query parameters for this get request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single payer authorisation resource</returns>
public Task<PayerAuthorisationResponse> GetAsync(string identity, PayerAuthorisationGetRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new PayerAuthorisationGetRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<PayerAuthorisationResponse>("GET", "/payer_authorisations/:identity", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Creates a Payer Authorisation. The resource is saved to the database
/// even if incomplete. An empty array of incomplete_fields means that
/// the resource is valid. The ID of the resource is used for the other
/// actions. This endpoint has been designed this way so you do not need
/// to save any payer data on your servers or the browser while still
/// being able to implement a progressive solution, such as a multi-step
/// form.
/// </summary>
/// <param name="request">An optional `PayerAuthorisationCreateRequest` representing the body for this create request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single payer authorisation resource</returns>
public Task<PayerAuthorisationResponse> CreateAsync(PayerAuthorisationCreateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new PayerAuthorisationCreateRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<PayerAuthorisationResponse>("POST", "/payer_authorisations", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "payer_authorisations", customiseRequestMessage);
}
/// <summary>
/// Updates a Payer Authorisation. Updates the Payer Authorisation with
/// the request data. Can be invoked as many times as needed. Only
/// fields present in the request will be modified. An empty array of
/// incomplete_fields means that the resource is valid. This endpoint
/// has been designed this way so you do not need to save any payer data
/// on your servers or the browser while still being able to implement a
/// progressive solution, such a multi-step form. <p class="notice">
/// Note that in order to update the `metadata` attribute values it must
/// be sent completely as it overrides the previously existing values.
/// </p>
/// </summary>
/// <param name="identity">Unique identifier, beginning with "PA".</param>
/// <param name="request">An optional `PayerAuthorisationUpdateRequest` representing the body for this update request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single payer authorisation resource</returns>
public Task<PayerAuthorisationResponse> UpdateAsync(string identity, PayerAuthorisationUpdateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new PayerAuthorisationUpdateRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<PayerAuthorisationResponse>("PUT", "/payer_authorisations/:identity", urlParams, request, null, "payer_authorisations", customiseRequestMessage);
}
/// <summary>
/// Submits all the data previously pushed to this PayerAuthorisation
/// for verification. This time, a 200 HTTP status is returned if the
/// resource is valid and a 422 error response in case of validation
/// errors. After it is successfully submitted, the Payer Authorisation
/// can no longer be edited.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "PA".</param>
/// <param name="request">An optional `PayerAuthorisationSubmitRequest` representing the body for this submit request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single payer authorisation resource</returns>
public Task<PayerAuthorisationResponse> SubmitAsync(string identity, PayerAuthorisationSubmitRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new PayerAuthorisationSubmitRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<PayerAuthorisationResponse>("POST", "/payer_authorisations/:identity/actions/submit", urlParams, request, null, "data", customiseRequestMessage);
}
/// <summary>
/// Confirms the Payer Authorisation, indicating that the resources are
/// ready to be created.
/// A Payer Authorisation cannot be confirmed if it hasn't been
/// submitted yet.
///
/// <p class="notice">
/// The main use of the confirm endpoint is to enable integrators to
/// acknowledge the end of the setup process.
/// They might want to make the payers go through some other steps
/// after they go through our flow or make them go through the necessary
/// verification mechanism (upcoming feature).
/// </p>
/// </summary>
/// <param name="identity">Unique identifier, beginning with "PA".</param>
/// <param name="request">An optional `PayerAuthorisationConfirmRequest` representing the body for this confirm request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single payer authorisation resource</returns>
public Task<PayerAuthorisationResponse> ConfirmAsync(string identity, PayerAuthorisationConfirmRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new PayerAuthorisationConfirmRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<PayerAuthorisationResponse>("POST", "/payer_authorisations/:identity/actions/confirm", urlParams, request, null, "data", customiseRequestMessage);
}
}
/// <summary>
/// Retrieves the details of a single existing Payer Authorisation. It can
/// be used for polling the status of a Payer Authorisation.
/// </summary>
public class PayerAuthorisationGetRequest
{
}
/// <summary>
/// Creates a Payer Authorisation. The resource is saved to the database
/// even if incomplete. An empty array of incomplete_fields means that the
/// resource is valid. The ID of the resource is used for the other actions.
/// This endpoint has been designed this way so you do not need to save any
/// payer data on your servers or the browser while still being able to
/// implement a progressive solution, such as a multi-step form.
/// </summary>
public class PayerAuthorisationCreateRequest : IHasIdempotencyKey
{
/// <summary>
/// All details required for the creation of a
/// [Customer Bank Account](#core-endpoints-customer-bank-accounts).
/// </summary>
[JsonProperty("bank_account")]
public PayerAuthorisationBankAccount BankAccount { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Customer Bank Account](#core-endpoints-customer-bank-accounts).
/// </summary>
public class PayerAuthorisationBankAccount
{
/// <summary>
/// Name of the account holder, as known by the bank. Usually this
/// is the same as the name stored with the linked
/// [creditor](#core-endpoints-creditors). This field will be
/// transliterated, upcased and truncated to 18 characters. This
/// field is required unless the request includes a [customer bank
/// account token](#javascript-flow-customer-bank-account-tokens).
/// </summary>
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
/// <summary>
/// Bank account number - see [local
/// details](#appendix-local-bank-details) for more information.
/// Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
/// <summary>
/// The last few digits of the account number. Currently 4 digits
/// for NZD bank accounts and 2 digits for other currencies.
/// </summary>
[JsonProperty("account_number_ending")]
public string AccountNumberEnding { get; set; }
/// <summary>
/// Account number suffix (only for bank accounts denominated in
/// NZD) - see [local details](#local-bank-details-new-zealand) for
/// more information.
/// </summary>
[JsonProperty("account_number_suffix")]
public string AccountNumberSuffix { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts.
/// Must not be provided for bank accounts in other currencies. See
/// [local details](#local-bank-details-united-states) for more
/// information.
/// </summary>
[JsonProperty("account_type")]
public PayerAuthorisationAccountType? AccountType { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts. Must
/// not be provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more information.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum PayerAuthorisationAccountType
{
/// <summary>`account_type` with a value of "savings"</summary>
[EnumMember(Value = "savings")]
Savings,
/// <summary>`account_type` with a value of "checking"</summary>
[EnumMember(Value = "checking")]
Checking,
}
/// <summary>
/// Bank code - see [local details](#appendix-local-bank-details)
/// for more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("bank_code")]
public string BankCode { get; set; }
/// <summary>
/// Branch code - see [local details](#appendix-local-bank-details)
/// for more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("branch_code")]
public string BranchCode { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).
/// Defaults to the country code of the `iban` if supplied,
/// otherwise is required.
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes)
/// currency code. Currently "AUD", "CAD", "DKK", "EUR", "GBP",
/// "NZD", "SEK" and "USD" are supported.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// International Bank Account Number. Alternatively you can provide
/// [local details](#appendix-local-bank-details). IBANs are not
/// accepted for Swedish bank accounts denominated in SEK - you must
/// supply [local details](#local-bank-details-sweden).
/// </summary>
[JsonProperty("iban")]
public string Iban { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with
/// key names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
}
/// <summary>
/// All details required for the creation of a
/// [Customer](#core-endpoints-customers).
/// </summary>
[JsonProperty("customer")]
public PayerAuthorisationCustomer Customer { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Customer](#core-endpoints-customers).
/// </summary>
public class PayerAuthorisationCustomer
{
/// <summary>
/// The first line of the customer's address.
/// </summary>
[JsonProperty("address_line1")]
public string AddressLine1 { get; set; }
/// <summary>
/// The second line of the customer's address.
/// </summary>
[JsonProperty("address_line2")]
public string AddressLine2 { get; set; }
/// <summary>
/// The third line of the customer's address.
/// </summary>
[JsonProperty("address_line3")]
public string AddressLine3 { get; set; }
/// <summary>
/// The city of the customer's address.
/// </summary>
[JsonProperty("city")]
public string City { get; set; }
/// <summary>
/// Customer's company name. Required unless a `given_name` and
/// `family_name` are provided. For Canadian customers, the use of a
/// `company_name` value will mean that any mandate created from
/// this customer will be considered to be a "Business PAD"
/// (otherwise, any mandate will be considered to be a "Personal
/// PAD").
/// </summary>
[JsonProperty("company_name")]
public string CompanyName { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code.](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements)
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// For Danish customers only. The civic/company number (CPR or CVR)
/// of the customer. Must be supplied if the customer's bank account
/// is denominated in Danish krone (DKK).
/// </summary>
[JsonProperty("danish_identity_number")]
public string DanishIdentityNumber { get; set; }
/// <summary>
/// Customer's email address. Required in most cases, as this allows
/// GoCardless to send notifications to this customer.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Customer's surname. Required unless a `company_name` is
/// provided.
/// </summary>
[JsonProperty("family_name")]
public string FamilyName { get; set; }
/// <summary>
/// Customer's first name. Required unless a `company_name` is
/// provided.
/// </summary>
[JsonProperty("given_name")]
public string GivenName { get; set; }
/// <summary>
/// An [IETF Language Tag](https://tools.ietf.org/html/rfc5646),
/// used for both language
/// and regional variations of our product.
///
/// </summary>
[JsonProperty("locale")]
public string Locale { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with
/// key names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// The customer's postal code.
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
/// <summary>
/// The customer's address region, county or department. For US
/// customers a 2 letter
/// [ISO3166-2:US](https://en.wikipedia.org/wiki/ISO_3166-2:US)
/// state code is required (e.g. `CA` for California).
/// </summary>
[JsonProperty("region")]
public string Region { get; set; }
/// <summary>
/// For Swedish customers only. The civic/company number
/// (personnummer, samordningsnummer, or organisationsnummer) of the
/// customer. Must be supplied if the customer's bank account is
/// denominated in Swedish krona (SEK). This field cannot be changed
/// once it has been set.
/// </summary>
[JsonProperty("swedish_identity_number")]
public string SwedishIdentityNumber { get; set; }
}
/// <summary>
/// All details required for the creation of a
/// [Mandate](#core-endpoints-mandates).
/// </summary>
[JsonProperty("mandate")]
public PayerAuthorisationMandate Mandate { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Mandate](#core-endpoints-mandates).
/// </summary>
public class PayerAuthorisationMandate
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with
/// key names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// For ACH customers only. Required for ACH customers. A string
/// containing the IP address of the payer to whom the mandate
/// belongs (i.e. as a result of their completion of a mandate setup
/// flow in their browser).
/// </summary>
[JsonProperty("payer_ip_address")]
public string PayerIpAddress { get; set; }
/// <summary>
/// Unique reference. Different schemes have different length and
/// [character set](#appendix-character-sets) requirements.
/// GoCardless will generate a unique reference satisfying the
/// different scheme requirements if this field is left blank.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs",
/// "becs", "becs_nz", "betalingsservice", "pad" and "sepa_core" are
/// supported.
/// </summary>
[JsonProperty("scheme")]
public PayerAuthorisationScheme? Scheme { get; set; }
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs",
/// "becs_nz", "betalingsservice", "pad" and "sepa_core" are supported.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum PayerAuthorisationScheme
{
/// <summary>`scheme` with a value of "ach"</summary>
[EnumMember(Value = "ach")]
Ach,
/// <summary>`scheme` with a value of "autogiro"</summary>
[EnumMember(Value = "autogiro")]
Autogiro,
/// <summary>`scheme` with a value of "bacs"</summary>
[EnumMember(Value = "bacs")]
Bacs,
/// <summary>`scheme` with a value of "becs"</summary>
[EnumMember(Value = "becs")]
Becs,
/// <summary>`scheme` with a value of "becs_nz"</summary>
[EnumMember(Value = "becs_nz")]
BecsNz,
/// <summary>`scheme` with a value of "betalingsservice"</summary>
[EnumMember(Value = "betalingsservice")]
Betalingsservice,
/// <summary>`scheme` with a value of "pad"</summary>
[EnumMember(Value = "pad")]
Pad,
/// <summary>`scheme` with a value of "sepa_core"</summary>
[EnumMember(Value = "sepa_core")]
SepaCore,
}
}
/// <summary>
/// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures.
/// Any requests, where supported, to create a resource with a key that has previously been used will not succeed.
/// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys
/// </summary>
[JsonIgnore]
public string IdempotencyKey { get; set; }
}
/// <summary>
/// Updates a Payer Authorisation. Updates the Payer Authorisation with the
/// request data. Can be invoked as many times as needed. Only fields
/// present in the request will be modified. An empty array of
/// incomplete_fields means that the resource is valid. This endpoint has
/// been designed this way so you do not need to save any payer data on your
/// servers or the browser while still being able to implement a progressive
/// solution, such a multi-step form. <p class="notice"> Note that in order
/// to update the `metadata` attribute values it must be sent completely as
/// it overrides the previously existing values. </p>
/// </summary>
public class PayerAuthorisationUpdateRequest
{
/// <summary>
/// All details required for the creation of a
/// [Customer Bank Account](#core-endpoints-customer-bank-accounts).
/// </summary>
[JsonProperty("bank_account")]
public PayerAuthorisationBankAccount BankAccount { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Customer Bank Account](#core-endpoints-customer-bank-accounts).
/// </summary>
public class PayerAuthorisationBankAccount
{
/// <summary>
/// Name of the account holder, as known by the bank. Usually this
/// is the same as the name stored with the linked
/// [creditor](#core-endpoints-creditors). This field will be
/// transliterated, upcased and truncated to 18 characters. This
/// field is required unless the request includes a [customer bank
/// account token](#javascript-flow-customer-bank-account-tokens).
/// </summary>
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
/// <summary>
/// Bank account number - see [local
/// details](#appendix-local-bank-details) for more information.
/// Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
/// <summary>
/// The last few digits of the account number. Currently 4 digits
/// for NZD bank accounts and 2 digits for other currencies.
/// </summary>
[JsonProperty("account_number_ending")]
public string AccountNumberEnding { get; set; }
/// <summary>
/// Account number suffix (only for bank accounts denominated in
/// NZD) - see [local details](#local-bank-details-new-zealand) for
/// more information.
/// </summary>
[JsonProperty("account_number_suffix")]
public string AccountNumberSuffix { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts.
/// Must not be provided for bank accounts in other currencies. See
/// [local details](#local-bank-details-united-states) for more
/// information.
/// </summary>
[JsonProperty("account_type")]
public PayerAuthorisationAccountType? AccountType { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts. Must
/// not be provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more information.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum PayerAuthorisationAccountType
{
/// <summary>`account_type` with a value of "savings"</summary>
[EnumMember(Value = "savings")]
Savings,
/// <summary>`account_type` with a value of "checking"</summary>
[EnumMember(Value = "checking")]
Checking,
}
/// <summary>
/// Bank code - see [local details](#appendix-local-bank-details)
/// for more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("bank_code")]
public string BankCode { get; set; }
/// <summary>
/// Branch code - see [local details](#appendix-local-bank-details)
/// for more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("branch_code")]
public string BranchCode { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).
/// Defaults to the country code of the `iban` if supplied,
/// otherwise is required.
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes)
/// currency code. Currently "AUD", "CAD", "DKK", "EUR", "GBP",
/// "NZD", "SEK" and "USD" are supported.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// International Bank Account Number. Alternatively you can provide
/// [local details](#appendix-local-bank-details). IBANs are not
/// accepted for Swedish bank accounts denominated in SEK - you must
/// supply [local details](#local-bank-details-sweden).
/// </summary>
[JsonProperty("iban")]
public string Iban { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with
/// key names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
}
/// <summary>
/// All details required for the creation of a
/// [Customer](#core-endpoints-customers).
/// </summary>
[JsonProperty("customer")]
public PayerAuthorisationCustomer Customer { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Customer](#core-endpoints-customers).
/// </summary>
public class PayerAuthorisationCustomer
{
/// <summary>
/// The first line of the customer's address.
/// </summary>
[JsonProperty("address_line1")]
public string AddressLine1 { get; set; }
/// <summary>
/// The second line of the customer's address.
/// </summary>
[JsonProperty("address_line2")]
public string AddressLine2 { get; set; }
/// <summary>
/// The third line of the customer's address.
/// </summary>
[JsonProperty("address_line3")]
public string AddressLine3 { get; set; }
/// <summary>
/// The city of the customer's address.
/// </summary>
[JsonProperty("city")]
public string City { get; set; }
/// <summary>
/// Customer's company name. Required unless a `given_name` and
/// `family_name` are provided. For Canadian customers, the use of a
/// `company_name` value will mean that any mandate created from
/// this customer will be considered to be a "Business PAD"
/// (otherwise, any mandate will be considered to be a "Personal
/// PAD").
/// </summary>
[JsonProperty("company_name")]
public string CompanyName { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code.](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements)
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// For Danish customers only. The civic/company number (CPR or CVR)
/// of the customer. Must be supplied if the customer's bank account
/// is denominated in Danish krone (DKK).
/// </summary>
[JsonProperty("danish_identity_number")]
public string DanishIdentityNumber { get; set; }
/// <summary>
/// Customer's email address. Required in most cases, as this allows
/// GoCardless to send notifications to this customer.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Customer's surname. Required unless a `company_name` is
/// provided.
/// </summary>
[JsonProperty("family_name")]
public string FamilyName { get; set; }
/// <summary>
/// Customer's first name. Required unless a `company_name` is
/// provided.
/// </summary>
[JsonProperty("given_name")]
public string GivenName { get; set; }
/// <summary>
/// An [IETF Language Tag](https://tools.ietf.org/html/rfc5646),
/// used for both language
/// and regional variations of our product.
///
/// </summary>
[JsonProperty("locale")]
public string Locale { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with
/// key names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// The customer's postal code.
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
/// <summary>
/// The customer's address region, county or department. For US
/// customers a 2 letter
/// [ISO3166-2:US](https://en.wikipedia.org/wiki/ISO_3166-2:US)
/// state code is required (e.g. `CA` for California).
/// </summary>
[JsonProperty("region")]
public string Region { get; set; }
/// <summary>
/// For Swedish customers only. The civic/company number
/// (personnummer, samordningsnummer, or organisationsnummer) of the
/// customer. Must be supplied if the customer's bank account is
/// denominated in Swedish krona (SEK). This field cannot be changed
/// once it has been set.
/// </summary>
[JsonProperty("swedish_identity_number")]
public string SwedishIdentityNumber { get; set; }
}
/// <summary>
/// All details required for the creation of a
/// [Mandate](#core-endpoints-mandates).
/// </summary>
[JsonProperty("mandate")]
public PayerAuthorisationMandate Mandate { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Mandate](#core-endpoints-mandates).
/// </summary>
public class PayerAuthorisationMandate
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with
/// key names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// For ACH customers only. Required for ACH customers. A string
/// containing the IP address of the payer to whom the mandate
/// belongs (i.e. as a result of their completion of a mandate setup
/// flow in their browser).
/// </summary>
[JsonProperty("payer_ip_address")]
public string PayerIpAddress { get; set; }
/// <summary>
/// Unique reference. Different schemes have different length and
/// [character set](#appendix-character-sets) requirements.
/// GoCardless will generate a unique reference satisfying the
/// different scheme requirements if this field is left blank.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs",
/// "becs", "becs_nz", "betalingsservice", "pad" and "sepa_core" are
/// supported.
/// </summary>
[JsonProperty("scheme")]
public PayerAuthorisationScheme? Scheme { get; set; }
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs",
/// "becs_nz", "betalingsservice", "pad" and "sepa_core" are supported.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum PayerAuthorisationScheme
{
/// <summary>`scheme` with a value of "ach"</summary>
[EnumMember(Value = "ach")]
Ach,
/// <summary>`scheme` with a value of "autogiro"</summary>
[EnumMember(Value = "autogiro")]
Autogiro,
/// <summary>`scheme` with a value of "bacs"</summary>
[EnumMember(Value = "bacs")]
Bacs,
/// <summary>`scheme` with a value of "becs"</summary>
[EnumMember(Value = "becs")]
Becs,
/// <summary>`scheme` with a value of "becs_nz"</summary>
[EnumMember(Value = "becs_nz")]
BecsNz,
/// <summary>`scheme` with a value of "betalingsservice"</summary>
[EnumMember(Value = "betalingsservice")]
Betalingsservice,
/// <summary>`scheme` with a value of "pad"</summary>
[EnumMember(Value = "pad")]
Pad,
/// <summary>`scheme` with a value of "sepa_core"</summary>
[EnumMember(Value = "sepa_core")]
SepaCore,
}
}
}
/// <summary>
/// Submits all the data previously pushed to this PayerAuthorisation for
/// verification. This time, a 200 HTTP status is returned if the resource
/// is valid and a 422 error response in case of validation errors. After it
/// is successfully submitted, the Payer Authorisation can no longer be
/// edited.
/// </summary>
public class PayerAuthorisationSubmitRequest
{
}
/// <summary>
/// Confirms the Payer Authorisation, indicating that the resources are
/// ready to be created.
/// A Payer Authorisation cannot be confirmed if it hasn't been submitted
/// yet.
///
/// <p class="notice">
/// The main use of the confirm endpoint is to enable integrators to
/// acknowledge the end of the setup process.
/// They might want to make the payers go through some other steps after
/// they go through our flow or make them go through the necessary
/// verification mechanism (upcoming feature).
/// </p>
/// </summary>
public class PayerAuthorisationConfirmRequest
{
}
/// <summary>
/// An API response for a request returning a single payer authorisation.
/// </summary>
public class PayerAuthorisationResponse : ApiResponse
{
/// <summary>
/// The payer authorisation from the response.
/// </summary>
[JsonProperty("payer_authorisations")]
public PayerAuthorisation PayerAuthorisation { get; private set; }
}
}
| |
using System;
using System.IO;
using System.Xml;
namespace Nucleo.Security
{
public class XmlSecurityUserManagementProvider : SecurityUserManagementProvider
{
private XmlDocument _dataSource = null;
private string _xmlFile = string.Empty;
#region " Constants "
private const string ROLE_ID_XPATH = "./Role[ID = '{0}']";
private const string RULE_ID_XPATH = "./Rule[ID = '{0}']";
private const string SUBSYSTEM_ID_XPATH = "./Subsystem[ID = '{0}']";
private const string USER_ID_XPATH = "./User[ID = '{0}']";
#endregion
#region " Properties "
protected XmlDocument DataSource
{
get
{
if (string.IsNullOrEmpty(_xmlFile))
throw new ArgumentNullException("_xmlFile");
if (_dataSource == null)
{
if (!File.Exists(_xmlFile))
{
using (StreamWriter writer = new StreamWriter(_xmlFile))
writer.Write("<Security><Users /><Roles /><Rules /><Subsystems /></Security>");
}
_dataSource = new XmlDocument();
_dataSource.Load(_xmlFile);
}
return _dataSource;
}
}
private XmlElement RelationshipsCollection
{
get { return (XmlElement)this.DataSource.DocumentElement.ChildNodes[1]; }
}
private XmlElement UsersCollection
{
get { return (XmlElement)this.DataSource.DocumentElement.ChildNodes[0]; }
}
#endregion
#region " Methods "
public override bool ChangeRolePermission(SecurityUser user, SecurityRole role, AuthorizationType authorization)
{
XmlElement userElement = (XmlElement)this.UsersCollection.SelectSingleNode(string.Format(USER_ID_XPATH, user.ID));
if (userElement == null)
throw new ArgumentException("The user does not exist in the data store", "user");
XmlElement rolesElement = this.DetermineIfCollectionNodeExists(userElement, "RoleAssociations");
XmlNode roleNode = rolesElement.SelectSingleNode(string.Format(ROLE_ID_XPATH, role.ID));
if (roleNode == null && authorization == AuthorizationType.Allow)
{
XmlElement roleElement = this.DataSource.CreateElement("Role");
roleElement.InnerText = role.ID.ToString();
rolesElement.AppendChild(roleElement);
return true;
}
else if (roleNode != null && authorization == AuthorizationType.Deny)
{
rolesElement.RemoveChild(roleNode);
return true;
}
else
return false;
}
public override bool ChangeRulePermission(SecurityUser user, SecurityRule rule, AuthorizationType authorization)
{
XmlElement userElement = (XmlElement)this.UsersCollection.SelectSingleNode(string.Format(USER_ID_XPATH, user.ID));
if (userElement == null)
throw new ArgumentException("The user does not exist in the data store", "user");
XmlElement rulesElement = this.DetermineIfCollectionNodeExists(userElement, "RuleAssociations");
XmlNode ruleNode = rulesElement.SelectSingleNode(string.Format(RULE_ID_XPATH, rule.ID));
if (ruleNode == null && authorization == AuthorizationType.Allow)
{
XmlElement ruleElement = this.DataSource.CreateElement("Rule");
ruleElement.InnerText = rule.ID.ToString();
rulesElement.AppendChild(ruleElement);
return true;
}
else if (ruleNode != null && authorization == AuthorizationType.Deny)
{
rulesElement.RemoveChild(ruleNode);
return true;
}
else
return false;
}
public override bool ChangeSubsystemPermission(SecurityUser user, SecuritySubsystem subsystem, AuthorizationType authorization)
{
XmlElement userElement = (XmlElement)this.UsersCollection.SelectSingleNode(string.Format(USER_ID_XPATH, user.ID));
if (userElement == null)
throw new ArgumentException("The user does not exist in the data store", "user");
XmlElement subsystemsElement = this.DetermineIfCollectionNodeExists(userElement, "SubsystemAssociations");
XmlNode subsystemNode = subsystemsElement.SelectSingleNode(string.Format(SUBSYSTEM_ID_XPATH, subsystem.ID));
if (subsystemNode == null && authorization == AuthorizationType.Allow)
{
XmlElement subsystemElement = this.DataSource.CreateElement("Subsystem");
subsystemElement.InnerText = subsystem.ID.ToString();
subsystemsElement.AppendChild(subsystemElement);
return true;
}
else if (subsystemNode != null && authorization == AuthorizationType.Deny)
{
subsystemsElement.RemoveChild(subsystemNode);
return true;
}
else
return false;
}
private bool ChangeUserLockedStatus(SecurityUser user, bool isLocked)
{
XmlNode userNode = this.UsersCollection.SelectSingleNode(string.Format(USER_ID_XPATH, user.ID));
if (userNode == null)
return false;
else
{
userNode["IsLockedOut"].InnerText = isLocked.ToString();
return true;
}
}
public override bool ContainsUser(string userName)
{
return (this.DataSource.SelectSingleNode("/Security/Users//User[./Name = '" + userName + "']") != null);
}
public override SecurityUser CreateUser(string userName, string fullName, string email, string phoneNumber, SecurityPassword password, out SecurityObjectCreationStatusType status)
{
XmlElement userElement = this.DataSource.CreateElement("User");
this.UsersCollection.AppendChild(userElement);
userElement.AppendChild(this.DataSource.CreateElement("ID"));
userElement.AppendChild(this.DataSource.CreateElement("Name"));
userElement.AppendChild(this.DataSource.CreateElement("FullName"));
userElement.AppendChild(this.DataSource.CreateElement("Email"));
userElement.AppendChild(this.DataSource.CreateElement("PhoneNumber"));
userElement.AppendChild(this.DataSource.CreateElement("Password"));
userElement.AppendChild(this.DataSource.CreateElement("CreationDate"));
userElement.AppendChild(this.DataSource.CreateElement("IsLockedOut"));
Guid id = Guid.NewGuid();
userElement["ID"].InnerText = id.ToString();
userElement["Name"].InnerText = userName;
userElement["FullName"].InnerText = fullName;
userElement["Email"].InnerText = email;
userElement["PhoneNumber"].InnerText = phoneNumber;
userElement["Password"].InnerText = password.Value;
userElement["CreationDate"].InnerText = DateTime.Now.ToString();
userElement["IsLockedOut"].InnerText = bool.FalseString;
status = SecurityObjectCreationStatusType.Success;
return base.CreateUserObject(id, userName, fullName, email, phoneNumber, password);
}
public override bool DeleteUser(SecurityUser user)
{
XmlNode userNode = this.UsersCollection.SelectSingleNode(string.Format(USER_ID_XPATH, user.ID));
if (userNode != null)
{
this.UsersCollection.RemoveChild(userNode);
return true;
}
else
return false;
}
public override bool DeleteUserAssociations(SecurityUser user)
{
throw new Exception("The method or operation is not implemented.");
}
private XmlElement DetermineIfCollectionNodeExists(XmlElement parentElement, string collectionName)
{
XmlElement collectionElement = null;
if (parentElement[collectionName] != null)
collectionElement = parentElement[collectionName];
else
{
collectionElement = this.DataSource.CreateElement(collectionName);
parentElement.AppendChild(collectionElement);
}
return collectionElement;
}
public override SecurityUser GetUser(string userName)
{
XmlNode userNode = this.UsersCollection.SelectSingleNode(string.Format(".//User[Name = '{0}']", userName));
if (userNode == null)
return null;
SecurityPassword password = new SecurityPassword();
password._value = userNode["Password"].InnerText;
SecurityUser user = base.CreateUserObject(
(Guid)Convert.ChangeType(userNode["ID"].InnerText,typeof(Guid)),
userNode["Name"].InnerText,
userNode["FullName"].InnerText,
userNode["Email"].InnerText,
userNode["PhoneNumber"].InnerText,
password);
foreach (XmlNode roleNode in userNode["RoleAssociations"].ChildNodes)
{
SecurityRole role = SecurityFramework.Roles.FindByGuid((Guid)Convert.ChangeType(roleNode.InnerText, typeof(Guid)));
if (role != null)
user.Roles.Add(role);
}
foreach (XmlNode ruleNode in userNode["RuleAssociations"].ChildNodes)
{
SecurityRule rule = SecurityFramework.Rules.FindByGuid((Guid)Convert.ChangeType(ruleNode.InnerText, typeof(Guid)));
if (rule != null)
user.Rules.Add(rule);
}
foreach (XmlNode subsystemNode in userNode["SubsystemAssociations"].ChildNodes)
{
SecuritySubsystem subsystem = SecurityFramework.Subsystems.FindByGuid((Guid)Convert.ChangeType(subsystemNode.InnerText, typeof(Guid)));
if (subsystem != null)
user.Subsystems.Add(subsystem);
}
return user;
}
public override int GetUserCount()
{
return this.UsersCollection.ChildNodes.Count;
}
public override bool LockoutUser(SecurityUser user)
{
return this.ChangeUserLockedStatus(user, true);
}
public override void SaveUserChanges(SecurityUser user)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool UnlockUser(SecurityUser user)
{
return this.ChangeUserLockedStatus(user, false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using KSP.Localization;
namespace KERBALISM
{
public class KerbalismScansat : PartModule
{
[KSPField] public string experimentType = string.Empty;
[KSPField] public double ec_rate = 0.0;
[KSPField(isPersistant = true)] private int sensorType = 0;
[KSPField(isPersistant = true)] private string body_name = string.Empty;
[KSPField(isPersistant = true)] private double body_coverage = 0.0;
[KSPField(isPersistant = true)] private double warp_buffer = 0.0;
private PartModule scanner = null;
ExperimentInfo expInfo;
public bool IsScanning { get; internal set; }
public override void OnStart(StartState state)
{
if (Lib.DisableScenario(this)) return;
if (Lib.IsEditor()) return;
foreach(var module in part.Modules)
{
if(module.moduleName == "SCANsat" || module.moduleName == "ModuleSCANresourceScanner")
{
scanner = module;
break;
}
}
if (scanner == null) return;
sensorType = Lib.ReflectionValue<int>(scanner, "sensorType");
expInfo = ScienceDB.GetExperimentInfo(experimentType);
}
public void FixedUpdate()
{
if (scanner == null) return;
if (!Features.Science) return;
IsScanning = SCANsat.IsScanning(scanner);
double new_coverage = SCANsat.Coverage(sensorType, vessel.mainBody);
if(body_name == vessel.mainBody.name && new_coverage < body_coverage)
{
// SCANsat sometimes reports a coverage of 0, which is wrong
new_coverage = body_coverage;
}
if (vessel.mainBody.name != body_name)
{
body_name = vessel.mainBody.name;
body_coverage = new_coverage;
}
else
{
double coverage_delta = new_coverage - body_coverage;
body_coverage = new_coverage;
VesselData vd = vessel.KerbalismData();
if (IsScanning)
{
Situation scanSatSituation = new Situation(vessel.mainBody.flightGlobalsIndex, ScienceSituation.InSpaceHigh);
SubjectData subject = ScienceDB.GetSubjectData(expInfo, scanSatSituation);
if (subject == null)
return;
double size = expInfo.DataSize * coverage_delta / 100.0; // coverage is 0-100%
size += warp_buffer;
size = Drive.StoreFile(vessel, subject, size);
if (size > double.Epsilon)
{
// we filled all drives up to the brim but were unable to store everything
if (warp_buffer < double.Epsilon)
{
// warp buffer is empty, so lets store the rest there
warp_buffer = size;
size = 0;
}
else
{
// warp buffer not empty. that's ok if we didn't get new data
if (coverage_delta < double.Epsilon)
{
size = 0;
}
// else we're scanning too fast. stop.
}
// cancel scanning and annoy the user
if (size > double.Epsilon)
{
warp_buffer = 0;
StopScan();
vd.scansat_id.Add(part.flightID);
Message.Post(Lib.Color(Local.Scansat_Scannerhalted, Lib.Kolor.Red, true), Local.Scansat_Scannerhalted_text.Format("<b>" + vessel.vesselName + "</b>"));//"Scanner halted""Scanner halted on <<1>>. No storage left on vessel."
}
}
}
else if(vd.scansat_id.Contains(part.flightID))
{
if (vd.DrivesFreeSpace / vd.DrivesCapacity > 0.9) // restart when 90% of capacity is available
{
StartScan();
vd.scansat_id.Remove(part.flightID);
if (vd.cfg_ec) Message.Post(Local.Scansat_sensorresumed.Format("<b>" + vessel.vesselName + "</b>"));//Lib.BuildString("SCANsat sensor resumed operations on <<1>>)
}
}
}
}
internal void StopScan()
{
if (scanner == null) return;
SCANsat.StopScan(scanner);
IsScanning = SCANsat.IsScanning(scanner);
}
internal void StartScan()
{
if (scanner == null) return;
SCANsat.StartScan(scanner);
IsScanning = SCANsat.IsScanning(scanner);
}
public static void BackgroundUpdate(Vessel vessel, ProtoPartSnapshot p, ProtoPartModuleSnapshot m, KerbalismScansat kerbalismScansat,
Part part_prefab, VesselData vd, ResourceInfo ec, double elapsed_s)
{
List<ProtoPartModuleSnapshot> scanners = Cache.VesselObjectsCache<List<ProtoPartModuleSnapshot>>(vessel, "scansat_" + p.flightID);
if(scanners == null)
{
scanners = Lib.FindModules(p, "SCANsat");
if (scanners.Count == 0) scanners = Lib.FindModules(p, "ModuleSCANresourceScanner");
Cache.SetVesselObjectsCache(vessel, "scansat_" + p.flightID, scanners);
}
if (scanners.Count == 0) return;
var scanner = scanners[0];
bool is_scanning = Lib.Proto.GetBool(scanner, "scanning");
if(is_scanning && kerbalismScansat.ec_rate > double.Epsilon)
ec.Consume(kerbalismScansat.ec_rate * elapsed_s, ResourceBroker.Scanner);
if (!Features.Science)
{
if(is_scanning && ec.Amount < double.Epsilon)
{
SCANsat.StopScanner(vessel, scanner, part_prefab);
is_scanning = false;
// remember disabled scanner
vd.scansat_id.Add(p.flightID);
// give the user some feedback
if (vd.cfg_ec) Message.Post(Local.Scansat_sensordisabled.Format("<b>"+vessel.vesselName+"</b>"));//Lib.BuildString("SCANsat sensor was disabled on <<1>>)
}
else if (vd.scansat_id.Contains(p.flightID))
{
// if there is enough ec
// note: comparing against amount in previous simulation step
// re-enable at 25% EC
if (ec.Level > 0.25)
{
// re-enable the scanner
SCANsat.ResumeScanner(vessel, m, part_prefab);
is_scanning = true;
// give the user some feedback
if (vd.cfg_ec) Message.Post(Local.Scansat_sensorresumed.Format("<b>"+vessel.vesselName+"</b>"));//Lib.BuildString("SCANsat sensor resumed operations on <<1>>)
}
}
// forget active scanners
if (is_scanning) vd.scansat_id.Remove(p.flightID);
return;
} // if(!Feature.Science)
string body_name = Lib.Proto.GetString(m, "body_name");
int sensorType = (int)Lib.Proto.GetUInt(m, "sensorType");
double body_coverage = Lib.Proto.GetDouble(m, "body_coverage");
double warp_buffer = Lib.Proto.GetDouble(m, "warp_buffer");
double new_coverage = SCANsat.Coverage(sensorType, vessel.mainBody);
if (body_name == vessel.mainBody.name && new_coverage < body_coverage)
{
// SCANsat sometimes reports a coverage of 0, which is wrong
new_coverage = body_coverage;
}
if (vessel.mainBody.name != body_name)
{
body_name = vessel.mainBody.name;
body_coverage = new_coverage;
}
else
{
double coverage_delta = new_coverage - body_coverage;
body_coverage = new_coverage;
if (is_scanning)
{
ExperimentInfo expInfo = ScienceDB.GetExperimentInfo(kerbalismScansat.experimentType);
SubjectData subject = ScienceDB.GetSubjectData(expInfo, vd.VesselSituations.GetExperimentSituation(expInfo));
if (subject == null)
return;
double size = expInfo.DataSize * coverage_delta / 100.0; // coverage is 0-100%
size += warp_buffer;
if (size > double.Epsilon)
{
// store what we can
foreach (var d in Drive.GetDrives(vd))
{
var available = d.FileCapacityAvailable();
var chunk = Math.Min(size, available);
if (!d.Record_file(subject, chunk, true))
break;
size -= chunk;
if (size < double.Epsilon)
break;
}
}
if (size > double.Epsilon)
{
// we filled all drives up to the brim but were unable to store everything
if (warp_buffer < double.Epsilon)
{
// warp buffer is empty, so lets store the rest there
warp_buffer = size;
size = 0;
}
else
{
// warp buffer not empty. that's ok if we didn't get new data
if (coverage_delta < double.Epsilon)
{
size = 0;
}
// else we're scanning too fast. stop.
}
}
// we filled all drives up to the brim but were unable to store everything
// cancel scanning and annoy the user
if (size > double.Epsilon || ec.Amount < double.Epsilon)
{
warp_buffer = 0;
SCANsat.StopScanner(vessel, scanner, part_prefab);
vd.scansat_id.Add(p.flightID);
if (vd.cfg_ec) Message.Post(Local.Scansat_sensordisabled.Format("<b>"+vessel.vesselName+"</b>"));//Lib.BuildString("SCANsat sensor was disabled on <<1>>)
}
}
else if (vd.scansat_id.Contains(p.flightID))
{
if (ec.Level >= 0.25 && (vd.DrivesFreeSpace / vd.DrivesCapacity > 0.9))
{
SCANsat.ResumeScanner(vessel, scanner, part_prefab);
vd.scansat_id.Remove(p.flightID);
if (vd.cfg_ec) Message.Post(Local.Scansat_sensorresumed.Format("<b>"+vessel.vesselName+"</b>"));//Lib.BuildString("SCANsat sensor resumed operations on <<1>>)
}
}
}
Lib.Proto.Set(m, "warp_buffer", warp_buffer);
Lib.Proto.Set(m, "body_coverage", body_coverage);
Lib.Proto.Set(m, "body_name", body_name);
}
}
}
| |
namespace InControl
{
using System;
using System.Text.RegularExpressions;
using UnityEngine;
/// <summary>
/// Encapsulates a comparable version number.
/// This version number generally conforms to the semantic version system,
/// at least as far as InControl versioning is concerned.
/// </summary>
public struct VersionInfo : IComparable<VersionInfo>
{
/// <summary>
/// The major version component.
/// This number changes when significant incompatible API changes are made.
/// </summary>
public int Major;
/// <summary>
/// The minor version component.
/// This number changes when significant functionality is added in a backwards-compatible manner.
/// </summary>
public int Minor;
/// <summary>
/// The patch version component.
/// This number is changed when bug fixes are added in a backwards-compatible manner.
/// </summary>
public int Patch;
/// <summary>
/// The build version component.
/// This number is incremented during development.
/// </summary>
public int Build;
/// <summary>
/// Initializes a new instance of the <see cref="InControl.VersionInfo"/> with
/// given version components.
/// </summary>
/// <param name="major">The major version component.</param>
/// <param name="minor">The minor version component.</param>
/// <param name="patch">The patch version component.</param>
/// <param name="build">The build version component.</param>
public VersionInfo(int major, int minor, int patch, int build)
{
Major = major;
Minor = minor;
Patch = patch;
Build = build;
}
/// <summary>
/// Initialize an instance of <see cref="InControl.VersionInfo"/> with
/// the current version of InControl.
/// </summary>
/// <returns>The current version of InControl.</returns>
public static VersionInfo InControlVersion()
{
return new VersionInfo()
{
Major = 1,
Minor = 6,
Patch = 16,
Build = 9119
};
}
/// <summary>
/// Initialize an instance of <see cref="InControl.VersionInfo"/> with
/// the current version of Unity.
/// </summary>
/// <returns>The current version of Unity.</returns>
public static VersionInfo UnityVersion()
{
var match = Regex.Match(Application.unityVersion, @"^(\d+)\.(\d+)\.(\d+)");
var build = 0;
return new VersionInfo()
{
Major = Convert.ToInt32(match.Groups[1].Value),
Minor = Convert.ToInt32(match.Groups[2].Value),
Patch = Convert.ToInt32(match.Groups[3].Value),
Build = build
};
}
/// <summary>
/// Generates the minimum possible version number.
/// </summary>
public static VersionInfo Min
{
get
{
return new VersionInfo(int.MinValue, int.MinValue, int.MinValue, int.MinValue);
}
}
/// <summary>
/// Generates the maximum possible version number.
/// </summary>
public static VersionInfo Max
{
get
{
return new VersionInfo(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);
}
}
/// <summary>
/// Returns the sort order of the current instance compared to the specified object.
/// </summary>
public int CompareTo(VersionInfo other)
{
if (Major < other.Major) return -1;
if (Major > other.Major) return +1;
if (Minor < other.Minor) return -1;
if (Minor > other.Minor) return +1;
if (Patch < other.Patch) return -1;
if (Patch > other.Patch) return +1;
if (Build < other.Build) return -1;
if (Build > other.Build) return +1;
return 0;
}
/// <summary>
/// Compares two instances of <see cref="InControl.VersionInfo"/> for equality.
/// </summary>
public static bool operator ==(VersionInfo a, VersionInfo b)
{
return a.CompareTo(b) == 0;
}
/// <summary>
/// Compares two instances of <see cref="InControl.VersionInfo"/> for inequality.
/// </summary>
public static bool operator !=(VersionInfo a, VersionInfo b)
{
return a.CompareTo(b) != 0;
}
/// <summary>
/// Compares two instances of <see cref="InControl.VersionInfo"/> to see if
/// the first is equal to or smaller than the second.
/// </summary>
public static bool operator <=(VersionInfo a, VersionInfo b)
{
return a.CompareTo(b) <= 0;
}
/// <summary>
/// Compares two instances of <see cref="InControl.VersionInfo"/> to see if
/// the first is equal to or larger than the second.
/// </summary>
public static bool operator >=(VersionInfo a, VersionInfo b)
{
return a.CompareTo(b) >= 0;
}
/// <summary>
/// Compares two instances of <see cref="InControl.VersionInfo"/> to see if
/// the first is smaller than the second.
/// </summary>
public static bool operator <(VersionInfo a, VersionInfo b)
{
return a.CompareTo(b) < 0;
}
/// <summary>
/// Compares two instances of <see cref="InControl.VersionInfo"/> to see if
/// the first is larger than the second.
/// </summary>
public static bool operator >(VersionInfo a, VersionInfo b)
{
return a.CompareTo(b) > 0;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="InControl.VersionInfo"/>.
/// </summary>
/// <param name="other">The <see cref="System.Object"/> to compare with the current <see cref="InControl.VersionInfo"/>.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current
/// <see cref="InControl.VersionInfo"/>; otherwise, <c>false</c>.</returns>
public override bool Equals(object other)
{
if (other is VersionInfo)
{
return this == ((VersionInfo)other);
}
return false;
}
/// <summary>
/// Serves as a hash function for a <see cref="InControl.VersionInfo"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms
/// and data structures such as a hash table.</returns>
public override int GetHashCode()
{
return Major.GetHashCode() ^ Minor.GetHashCode() ^ Patch.GetHashCode() ^ Build.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="InControl.VersionInfo"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="InControl.VersionInfo"/>.</returns>
public override string ToString()
{
if (Build == 0)
{
return string.Format("{0}.{1}.{2}", Major, Minor, Patch);
}
return string.Format("{0}.{1}.{2} build {3}", Major, Minor, Patch, Build);
}
/// <summary>
/// Returns a shorter <see cref="System.String"/> that represents the current <see cref="InControl.VersionInfo"/>.
/// </summary>
/// <returns>A shorter <see cref="System.String"/> that represents the current <see cref="InControl.VersionInfo"/>.</returns>
public string ToShortString()
{
if (Build == 0)
{
return string.Format("{0}.{1}.{2}", Major, Minor, Patch);
}
return string.Format("{0}.{1}.{2}b{3}", Major, Minor, Patch, Build);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Net.Tests
{
public class ServicePointManagerTest
{
[Fact]
public static void RequireEncryption_ExpectedDefault()
{
RemoteExecutor.Invoke(() => Assert.Equal(EncryptionPolicy.RequireEncryption, ServicePointManager.EncryptionPolicy)).Dispose();
}
[Fact]
public static void CheckCertificateRevocationList_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.False(ServicePointManager.CheckCertificateRevocationList);
ServicePointManager.CheckCertificateRevocationList = true;
Assert.True(ServicePointManager.CheckCertificateRevocationList);
ServicePointManager.CheckCertificateRevocationList = false;
Assert.False(ServicePointManager.CheckCertificateRevocationList);
}).Dispose();
}
[Fact]
public static void DefaultConnectionLimit_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
ServicePointManager.DefaultConnectionLimit = 20;
Assert.Equal(20, ServicePointManager.DefaultConnectionLimit);
ServicePointManager.DefaultConnectionLimit = 2;
Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
}).Dispose();
}
[Fact]
public static void DnsRefreshTimeout_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout);
ServicePointManager.DnsRefreshTimeout = 42;
Assert.Equal(42, ServicePointManager.DnsRefreshTimeout);
ServicePointManager.DnsRefreshTimeout = 120000;
Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout);
}).Dispose();
}
[Fact]
public static void EnableDnsRoundRobin_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.False(ServicePointManager.EnableDnsRoundRobin);
ServicePointManager.EnableDnsRoundRobin = true;
Assert.True(ServicePointManager.EnableDnsRoundRobin);
ServicePointManager.EnableDnsRoundRobin = false;
Assert.False(ServicePointManager.EnableDnsRoundRobin);
}).Dispose();
}
[Fact]
public static void Expect100Continue_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.True(ServicePointManager.Expect100Continue);
ServicePointManager.Expect100Continue = false;
Assert.False(ServicePointManager.Expect100Continue);
ServicePointManager.Expect100Continue = true;
Assert.True(ServicePointManager.Expect100Continue);
}).Dispose();
}
[Fact]
public static void MaxServicePointIdleTime_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime);
ServicePointManager.MaxServicePointIdleTime = 42;
Assert.Equal(42, ServicePointManager.MaxServicePointIdleTime);
ServicePointManager.MaxServicePointIdleTime = 100000;
Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime);
}).Dispose();
}
[Fact]
public static void MaxServicePoints_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(0, ServicePointManager.MaxServicePoints);
ServicePointManager.MaxServicePoints = 42;
Assert.Equal(42, ServicePointManager.MaxServicePoints);
ServicePointManager.MaxServicePoints = 0;
Assert.Equal(0, ServicePointManager.MaxServicePoints);
}).Dispose();
}
[Fact]
public static void ReusePort_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.False(ServicePointManager.ReusePort);
ServicePointManager.ReusePort = true;
Assert.True(ServicePointManager.ReusePort);
ServicePointManager.ReusePort = false;
Assert.False(ServicePointManager.ReusePort);
}).Dispose();
}
[Fact]
public static void SecurityProtocol_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
var orig = (SecurityProtocolType)0; // SystemDefault.
Assert.Equal(orig, ServicePointManager.SecurityProtocol);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
Assert.Equal(SecurityProtocolType.Tls11, ServicePointManager.SecurityProtocol);
ServicePointManager.SecurityProtocol = orig;
Assert.Equal(orig, ServicePointManager.SecurityProtocol);
}).Dispose();
}
[Fact]
public static void ServerCertificateValidationCallback_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
RemoteCertificateValidationCallback callback = delegate { return true; };
ServicePointManager.ServerCertificateValidationCallback = callback;
Assert.Same(callback, ServicePointManager.ServerCertificateValidationCallback);
ServicePointManager.ServerCertificateValidationCallback = null;
Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
}).Dispose();
}
[Fact]
public static void UseNagleAlgorithm_Roundtrips()
{
RemoteExecutor.Invoke(() =>
{
Assert.True(ServicePointManager.UseNagleAlgorithm);
ServicePointManager.UseNagleAlgorithm = false;
Assert.False(ServicePointManager.UseNagleAlgorithm);
ServicePointManager.UseNagleAlgorithm = true;
Assert.True(ServicePointManager.UseNagleAlgorithm);
}).Dispose();
}
[Fact]
public static void InvalidArguments_Throw()
{
RemoteExecutor.Invoke(() =>
{
const int ssl2Client = 0x00000008;
const int ssl2Server = 0x00000004;
const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server);
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = ssl2);
AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePoints = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.DefaultConnectionLimit = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePointIdleTime = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => ServicePointManager.SetTcpKeepAlive(true, -1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => ServicePointManager.SetTcpKeepAlive(true, 1, -1));
AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint(null));
AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null));
AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint((Uri)null, null));
Assert.Throws<NotSupportedException>(() => ServicePointManager.FindServicePoint("http://anything", new FixedWebProxy("https://anything")));
ServicePoint sp = ServicePointManager.FindServicePoint("http://" + Guid.NewGuid().ToString("N"), null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLeaseTimeout = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLimit = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.MaxIdleTime = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ReceiveBufferSize = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => sp.SetTcpKeepAlive(true, -1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => sp.SetTcpKeepAlive(true, 1, -1));
}).Dispose();
}
[Fact]
public static void SecurityProtocol_Ssl3_NotSupported()
{
RemoteExecutor.Invoke(() =>
{
const int ssl2Client = 0x00000008;
const int ssl2Server = 0x00000004;
const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server);
#pragma warning disable 0618 // Ssl2, Ssl3 are deprecated.
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3);
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | ssl2);
#pragma warning restore
}).Dispose();
}
[Fact]
public static void FindServicePoint_ReturnsCachedServicePoint()
{
RemoteExecutor.Invoke(() =>
{
const string Localhost = "http://localhost";
string address1 = "http://" + Guid.NewGuid().ToString("N");
string address2 = "http://" + Guid.NewGuid().ToString("N");
Assert.NotNull(ServicePointManager.FindServicePoint(new Uri(address1)));
Assert.Same(
ServicePointManager.FindServicePoint(address1, null),
ServicePointManager.FindServicePoint(address1, null));
Assert.Same(
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)));
Assert.Same(
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(address2, new FixedWebProxy(address1)));
Assert.Same(
ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address2)));
Assert.NotSame(
ServicePointManager.FindServicePoint(address1, null),
ServicePointManager.FindServicePoint(address2, null));
Assert.NotSame(
ServicePointManager.FindServicePoint(address1, null),
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)));
Assert.NotSame(
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address2)));
}).Dispose();
}
[Fact]
public static void FindServicePoint_Collectible()
{
RemoteExecutor.Invoke(() =>
{
string address = "http://" + Guid.NewGuid().ToString("N");
bool initial = GetExpect100Continue(address);
SetExpect100Continue(address, !initial);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Equal(initial, GetExpect100Continue(address));
}).Dispose();
}
[Fact]
public static void FindServicePoint_ReturnedServicePointMatchesExpectedValues()
{
RemoteExecutor.Invoke(() =>
{
string address = "http://" + Guid.NewGuid().ToString("N");
DateTime start = DateTime.Now;
ServicePoint sp = ServicePointManager.FindServicePoint(address, null);
Assert.InRange(sp.IdleSince, start, DateTime.MaxValue);
Assert.Equal(new Uri(address), sp.Address);
Assert.Null(sp.BindIPEndPointDelegate);
Assert.Null(sp.Certificate);
Assert.Null(sp.ClientCertificate);
Assert.Equal(-1, sp.ConnectionLeaseTimeout);
Assert.Equal("http", sp.ConnectionName);
Assert.Equal(0, sp.CurrentConnections);
Assert.Equal(true, sp.Expect100Continue);
Assert.Equal(100000, sp.MaxIdleTime);
Assert.Equal(new Version(1, 1), sp.ProtocolVersion);
Assert.Equal(-1, sp.ReceiveBufferSize);
Assert.True(sp.SupportsPipelining, "SupportsPipelining");
Assert.True(sp.UseNagleAlgorithm, "UseNagleAlgorithm");
}).Dispose();
}
[Fact]
public static void FindServicePoint_PropertiesRoundtrip()
{
RemoteExecutor.Invoke(() =>
{
string address = "http://" + Guid.NewGuid().ToString("N");
BindIPEndPoint expectedBindIPEndPointDelegate = delegate { return null; };
int expectedConnectionLeaseTimeout = 42;
int expectedConnectionLimit = 84;
bool expected100Continue = false;
int expectedMaxIdleTime = 200000;
int expectedReceiveBufferSize = 123;
bool expectedUseNagleAlgorithm = false;
ServicePoint sp1 = ServicePointManager.FindServicePoint(address, null);
sp1.BindIPEndPointDelegate = expectedBindIPEndPointDelegate;
sp1.ConnectionLeaseTimeout = expectedConnectionLeaseTimeout;
sp1.ConnectionLimit = expectedConnectionLimit;
sp1.Expect100Continue = expected100Continue;
sp1.MaxIdleTime = expectedMaxIdleTime;
sp1.ReceiveBufferSize = expectedReceiveBufferSize;
sp1.UseNagleAlgorithm = expectedUseNagleAlgorithm;
ServicePoint sp2 = ServicePointManager.FindServicePoint(address, null);
Assert.Same(expectedBindIPEndPointDelegate, sp2.BindIPEndPointDelegate);
Assert.Equal(expectedConnectionLeaseTimeout, sp2.ConnectionLeaseTimeout);
Assert.Equal(expectedConnectionLimit, sp2.ConnectionLimit);
Assert.Equal(expected100Continue, sp2.Expect100Continue);
Assert.Equal(expectedMaxIdleTime, sp2.MaxIdleTime);
Assert.Equal(expectedReceiveBufferSize, sp2.ReceiveBufferSize);
Assert.Equal(expectedUseNagleAlgorithm, sp2.UseNagleAlgorithm);
}).Dispose();
}
[Fact]
public static void FindServicePoint_NewServicePointsInheritCurrentValues()
{
RemoteExecutor.Invoke(() =>
{
string address1 = "http://" + Guid.NewGuid().ToString("N");
string address2 = "http://" + Guid.NewGuid().ToString("N");
bool orig100Continue = ServicePointManager.Expect100Continue;
bool origNagle = ServicePointManager.UseNagleAlgorithm;
ServicePointManager.Expect100Continue = false;
ServicePointManager.UseNagleAlgorithm = false;
ServicePoint sp1 = ServicePointManager.FindServicePoint(address1, null);
Assert.False(sp1.Expect100Continue);
Assert.False(sp1.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = true;
ServicePointManager.UseNagleAlgorithm = true;
ServicePoint sp2 = ServicePointManager.FindServicePoint(address2, null);
Assert.True(sp2.Expect100Continue);
Assert.True(sp2.UseNagleAlgorithm);
Assert.False(sp1.Expect100Continue);
Assert.False(sp1.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = orig100Continue;
ServicePointManager.UseNagleAlgorithm = origNagle;
}).Dispose();
}
// Separated out to avoid the JIT in debug builds interfering with object lifetimes
private static bool GetExpect100Continue(string address) =>
ServicePointManager.FindServicePoint(address, null).Expect100Continue;
private static void SetExpect100Continue(string address, bool value) =>
ServicePointManager.FindServicePoint(address, null).Expect100Continue = value;
private sealed class FixedWebProxy : IWebProxy
{
private readonly Uri _proxyAddress;
public FixedWebProxy(string proxyAddress) { _proxyAddress = new Uri(proxyAddress); }
public Uri GetProxy(Uri destination) => _proxyAddress;
public bool IsBypassed(Uri host) => false;
public ICredentials Credentials { get; set; }
}
}
}
| |
namespace GenCode128Tests
{
using GenCode128;
using NUnit.Framework;
/// <summary>
/// Summary description for Content.
/// </summary>
[TestFixture]
public class ContentTests
{
private const int CShift = 98;
private const int CCodeA = 101;
private const int CCodeB = 100;
[Test]
public void CharRangeTests()
{
Assert.AreEqual(
Code128Code.CodeSetAllowed.CodeAorB,
Code128Code.CodesetAllowedForChar(66),
"Incorrect codeset requirement returned");
Assert.AreEqual(
Code128Code.CodeSetAllowed.CodeA,
Code128Code.CodesetAllowedForChar(17),
"Incorrect codeset requirement returned");
Assert.AreEqual(
Code128Code.CodeSetAllowed.CodeB,
Code128Code.CodesetAllowedForChar(110),
"Incorrect codeset requirement returned");
}
[Test]
public void CharTranslationTests()
{
// in CodeA, thischar Either, nextchar Either
var thischar = 66;
var nextchar = 66;
var currentCodeSet = CodeSet.CodeA;
var origcs = currentCodeSet;
var resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeA, nextchar Either
thischar = 1; // "^A"
nextchar = 66;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(65, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeB, nextchar Either
thischar = 110; // "n"
nextchar = 66;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CShift, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(78, resultcodes[1], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar Either, nextchar -1
thischar = 66; // "B"
nextchar = -1;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeA, nextchar -1
thischar = 1; // "^A"
nextchar = -1;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(65, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeB, nextchar -1
thischar = 110; // "n"
nextchar = -1;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CShift, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(78, resultcodes[1], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar Either, nextchar CodeA
thischar = 66; // "B"
nextchar = 1;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeA, nextchar CodeA
thischar = 1; // "^A"
nextchar = 1;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(65, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeB, nextchar CodeA
thischar = 110; // "n"
nextchar = 1;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CShift, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(78, resultcodes[1], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar Either, nextchar CodeB
thischar = 66; // "B"
nextchar = 110;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeA, nextchar CodeB
thischar = 1; // "^A"
nextchar = 110;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(65, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeA, thischar CodeB, nextchar CodeB
thischar = 110; // "n"
nextchar = 110;
currentCodeSet = CodeSet.CodeA;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CCodeB, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(78, resultcodes[1], "Incorrect code returned");
Assert.AreNotEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar Either, nextchar Either
thischar = 66; // "B"
nextchar = 66;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeA, nextchar Either
thischar = 1; // "^A"
nextchar = 66;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CShift, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(65, resultcodes[1], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeB, nextchar Either
thischar = 110; // "n"
nextchar = 66;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(78, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar Either, nextchar -1
thischar = 66; // "B"
nextchar = -1;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeA, nextchar -1
thischar = 1; // "^A"
nextchar = -1;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CShift, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(65, resultcodes[1], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeB, nextchar -1
thischar = 110; // "n"
nextchar = -1;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(78, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar Either, nextchar CodeA
thischar = 66; // "B"
nextchar = 1;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeA, nextchar CodeA
thischar = 1; // "^A"
nextchar = 1;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CCodeA, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(65, resultcodes[1], "Incorrect code returned");
Assert.AreNotEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeB, nextchar CodeA
thischar = 110; // "n"
nextchar = 1;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(78, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar Either, nextchar CodeB
thischar = 66; // "B"
nextchar = 110;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(34, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeA, nextchar CodeB
thischar = 1; // "^A"
nextchar = 110;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(2, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(CShift, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(65, resultcodes[1], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
// in CodeB, thischar CodeB, nextchar CodeB
thischar = 110; // "n"
nextchar = 110;
currentCodeSet = CodeSet.CodeB;
origcs = currentCodeSet;
resultcodes = Code128Code.CodesForChar(thischar, nextchar, ref currentCodeSet);
Assert.IsNotNull(resultcodes, "No codes returned");
Assert.AreEqual(1, resultcodes.Length, "Incorrect number of codes returned");
Assert.AreEqual(78, resultcodes[0], "Incorrect code returned");
Assert.AreEqual(origcs, currentCodeSet, "Incorrect code set returned");
}
[Test]
public void CharCompatibilityTests()
{
var thischar = 66;
var currentCodeSet = CodeSet.CodeA;
Assert.AreEqual(true, Code128Code.CharCompatibleWithCodeset(thischar, currentCodeSet), "Compat test failed");
thischar = 66; // "B"
currentCodeSet = CodeSet.CodeB;
Assert.AreEqual(true, Code128Code.CharCompatibleWithCodeset(thischar, currentCodeSet), "Compat test failed");
thischar = 17; // "^Q"
currentCodeSet = CodeSet.CodeA;
Assert.AreEqual(true, Code128Code.CharCompatibleWithCodeset(thischar, currentCodeSet), "Compat test failed");
thischar = 17; // "^Q"
currentCodeSet = CodeSet.CodeB;
Assert.AreEqual(false, Code128Code.CharCompatibleWithCodeset(thischar, currentCodeSet), "Compat test failed");
thischar = 110; // "n"
currentCodeSet = CodeSet.CodeA;
Assert.AreEqual(false, Code128Code.CharCompatibleWithCodeset(thischar, currentCodeSet), "Compat test failed");
thischar = 110; // "n"
currentCodeSet = CodeSet.CodeB;
Assert.AreEqual(true, Code128Code.CharCompatibleWithCodeset(thischar, currentCodeSet), "Compat test failed");
}
[Test]
public void CharValueTranslationTests()
{
Assert.AreEqual(0, Code128Code.CodeValueForChar(32), "Code translation wrong");
Assert.AreEqual(31, Code128Code.CodeValueForChar(63), "Code translation wrong");
Assert.AreEqual(32, Code128Code.CodeValueForChar(64), "Code translation wrong");
Assert.AreEqual(63, Code128Code.CodeValueForChar(95), "Code translation wrong");
Assert.AreEqual(64, Code128Code.CodeValueForChar(96), "Code translation wrong");
Assert.AreEqual(64, Code128Code.CodeValueForChar(0), "Code translation wrong");
Assert.AreEqual(95, Code128Code.CodeValueForChar(31), "Code translation wrong");
}
[Test]
public void FullStringTest()
{
var content = new Code128Content("BarCode 1");
var result = content.Codes;
Assert.AreEqual(12, result.Length, "Wrong number of code values in result");
Assert.AreEqual(104, result[0], "Start code wrong");
Assert.AreEqual(34, result[1], "Code value #1 wrong");
Assert.AreEqual(65, result[2], "Code value #2 wrong");
Assert.AreEqual(82, result[3], "Code value #3 wrong");
Assert.AreEqual(35, result[4], "Code value #4 wrong");
Assert.AreEqual(79, result[5], "Code value #5 wrong");
Assert.AreEqual(68, result[6], "Code value #6 wrong");
Assert.AreEqual(69, result[7], "Code value #7 wrong");
Assert.AreEqual(0, result[8], "Code value #8 wrong");
Assert.AreEqual(17, result[9], "Code value #9 wrong");
Assert.AreEqual(33, result[10], "Checksum wrong");
Assert.AreEqual(106, result[11], "Stop character wrong");
content = new Code128Content("\x11S12345");
result = content.Codes;
Assert.AreEqual(10, result.Length, "Wrong number of code values in result");
}
[Test]
public void OneCharStringTest()
{
var content = new Code128Content("0");
var result = content.Codes;
Assert.AreEqual(4, result.Length, "Wrong number of code values in result");
Assert.AreEqual(104, result[0], "Start code wrong");
Assert.AreEqual(16, result[1], "Code value #1 wrong");
Assert.AreEqual(17, result[2], "Checksum wrong");
Assert.AreEqual(106, result[3], "Stop character wrong");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using NDesk.Options;
using GitTfs.Core;
using GitTfs.Util;
using StructureMap;
namespace GitTfs.Commands
{
[Pluggable("fetch")]
[Description("fetch [options] [tfs-remote-id]...")]
[RequiresValidGitRepository]
public class Fetch : GitTfsCommand
{
private readonly RemoteOptions _remoteOptions;
private readonly Globals _globals;
private readonly ConfigProperties _properties;
private readonly Labels _labels;
public Fetch(Globals globals, ConfigProperties properties, RemoteOptions remoteOptions, Labels labels)
{
_globals = globals;
_properties = properties;
_remoteOptions = remoteOptions;
_labels = labels;
upToChangeSet = -1;
BranchStrategy = BranchStrategy = BranchStrategy.Auto;
}
private bool FetchAll { get; set; }
private bool FetchLabels { get; set; }
private bool FetchParents { get; set; }
private bool IgnoreRestrictedChangesets { get; set; }
private string BareBranch { get; set; }
private bool ForceFetch { get; set; }
private bool ExportMetadatas { get; set; }
private string ExportMetadatasFile { get; set; }
public BranchStrategy BranchStrategy { get; set; }
private string IgnoreBranchesRegex { get; set; }
private bool IgnoreNotInitBranches { get; set; }
public string BatchSizeOption
{
set
{
int batchSize;
if (!int.TryParse(value, out batchSize))
throw new GitTfsException("error: batch size parameter should be an integer.");
_properties.BatchSize = batchSize;
}
}
private int upToChangeSet { get; set; }
public string UpToChangeSetOption
{
set
{
int changesetIdParsed;
if (!int.TryParse(value, out changesetIdParsed))
throw new GitTfsException("error: 'up-to' parameter should be an integer.");
upToChangeSet = changesetIdParsed;
}
}
protected int? InitialChangeset { get; set; }
public virtual OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "all|fetch-all", "Fetch TFS changesets of all the initialized tfs remotes",
v => FetchAll = v != null },
{ "parents", "Fetch TFS changesets of the parent(s) initialized tfs remotes",
v => FetchParents = v != null },
{ "l|with-labels|fetch-labels", "Fetch the labels also when fetching TFS changesets",
v => FetchLabels = v != null },
{ "b|bare-branch=", "The name of the branch on which the fetch will be done for a bare repository",
v => BareBranch = v },
{ "force", "Force fetch of tfs changesets when there is ahead commits (ahead commits will be lost!)",
v => ForceFetch = v != null },
{ "x|export", "Export metadata",
v => ExportMetadatas = v != null },
{ "export-work-item-mapping=", "Path to Work-items mapping export file",
v => ExportMetadatasFile = v },
{ "branches=", "Strategy to manage branches:"+
Environment.NewLine + "* auto:(default) Manage the encountered merged changesets and initialize only the merged branches"+
Environment.NewLine + "* none: Ignore branches and merge changesets, fetching only the cloned tfs path"+
Environment.NewLine + "* all: Manage merged changesets and initialize all the branches during the clone",
v =>
{
BranchStrategy branchStrategy;
if (Enum.TryParse(v, true, out branchStrategy))
BranchStrategy = branchStrategy;
else
throw new GitTfsException("error: 'branches' parameter should be of value none/auto/all.");
} },
{ "batch-size=", "Size of the batch of tfs changesets fetched (-1 for all in one batch)",
v => BatchSizeOption = v },
{ "c|changeset|from=", "The changeset to clone from (must be a number)",
v => InitialChangeset = Convert.ToInt32(v) },
{ "t|up-to|to=", "up-to changeset # (optional, -1 for up to maximum, must be a number, not prefixed with 'C')",
v => UpToChangeSetOption = v },
{ "ignore-branches-regex=", "Don't initialize branches that match given regex",
v => IgnoreBranchesRegex = v },
{ "ignore-not-init-branches", "Ignore not-initialized branches",
v => IgnoreNotInitBranches = v != null },
{ "ignore-restricted-changesets", "Ignore restricted changesets",
v => IgnoreRestrictedChangesets = v != null }
}.Merge(_remoteOptions.OptionSet);
}
}
public int Run()
{
return Run(_globals.RemoteId);
}
public void Run(bool stopOnFailMergeCommit)
{
Run(stopOnFailMergeCommit, _globals.RemoteId);
}
public int Run(params string[] args)
{
return Run(false, args);
}
private int Run(bool stopOnFailMergeCommit, params string[] args)
{
UseTheGitIgnoreFile(_remoteOptions.GitIgnorePath);
if (!FetchAll && BranchStrategy == BranchStrategy.None)
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, true);
if(!string.IsNullOrEmpty(IgnoreBranchesRegex))
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranchesRegex, IgnoreBranchesRegex);
_globals.Repository.SetConfig(GitTfsConstants.IgnoreNotInitBranches, IgnoreNotInitBranches);
var remotesToFetch = GetRemotesToFetch(args).ToList();
foreach (var remote in remotesToFetch)
{
FetchRemote(stopOnFailMergeCommit, remote);
}
return 0;
}
private void UseTheGitIgnoreFile(string pathToGitIgnoreFile)
{
if (string.IsNullOrWhiteSpace(pathToGitIgnoreFile))
{
Trace.WriteLine("No .gitignore file specified to use...");
return;
}
_globals.Repository.UseGitIgnore(pathToGitIgnoreFile);
}
private void FetchRemote(bool stopOnFailMergeCommit, IGitTfsRemote remote)
{
Trace.TraceInformation("Fetching from TFS remote '{0}'...", remote.Id);
DoFetch(remote, stopOnFailMergeCommit);
if (_labels != null && FetchLabels)
{
Trace.TraceInformation("Fetching labels from TFS remote '{0}'...", remote.Id);
_labels.Run(remote);
}
}
protected virtual void DoFetch(IGitTfsRemote remote, bool stopOnFailMergeCommit)
{
if (upToChangeSet != -1 && InitialChangeset.HasValue && InitialChangeset.Value > upToChangeSet)
throw new GitTfsException("error: up-to changeset # must not be less than the initial one");
var bareBranch = string.IsNullOrEmpty(BareBranch) ? remote.Id : BareBranch;
// It is possible that we have outdated refs/remotes/tfs/<id>.
// E.g. someone already fetched changesets from TFS into another git repository and we've pulled it since
// in that case tfs fetch will retrieve same changes again unnecessarily. To prevent it we will scan tree from HEAD and see if newer changesets from
// TFS exists (by checking git-tfs-id mark in commit's comments).
// The process is similar to bootstrapping.
if (!ForceFetch)
{
if (!remote.Repository.IsBare)
remote.Repository.MoveTfsRefForwardIfNeeded(remote);
else
remote.Repository.MoveTfsRefForwardIfNeeded(remote, bareBranch);
}
if (!ForceFetch &&
remote.Repository.IsBare &&
remote.Repository.HasRef(GitRepository.ShortToLocalName(bareBranch)) &&
remote.MaxCommitHash != remote.Repository.GetCommit(bareBranch).Sha)
{
throw new GitTfsException("error : fetch is not allowed when there is ahead commits!",
new[] { "Remove ahead commits and retry", "use the --force option (ahead commits will be lost!)" });
}
var metadataExportInitializer = new ExportMetadatasInitializer(_globals);
bool shouldExport = ExportMetadatas || remote.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true";
if (ExportMetadatas)
{
metadataExportInitializer.InitializeConfig(remote.Repository, ExportMetadatasFile);
}
metadataExportInitializer.InitializeRemote(remote, shouldExport);
try
{
if (InitialChangeset.HasValue)
{
_properties.InitialChangeset = InitialChangeset.Value;
_properties.PersistAllOverrides();
remote.QuickFetch(InitialChangeset.Value, IgnoreRestrictedChangesets);
remote.Fetch(stopOnFailMergeCommit, upToChangeSet);
}
else
{
remote.Fetch(stopOnFailMergeCommit, upToChangeSet);
}
}
finally
{
Trace.WriteLine("Cleaning...");
remote.CleanupWorkspaceDirectory();
if (remote.Repository.IsBare)
remote.Repository.UpdateRef(GitRepository.ShortToLocalName(bareBranch), remote.MaxCommitHash);
}
}
private IEnumerable<IGitTfsRemote> GetRemotesToFetch(IList<string> args)
{
IEnumerable<IGitTfsRemote> remotesToFetch;
if (FetchParents)
remotesToFetch = _globals.Repository.GetLastParentTfsCommits("HEAD").Select(commit => commit.Remote);
else if (FetchAll)
remotesToFetch = _globals.Repository.ReadAllTfsRemotes();
else
remotesToFetch = args.Select(arg => _globals.Repository.ReadTfsRemote(arg));
return remotesToFetch;
}
}
public enum BranchStrategy
{
None,
Auto,
All
}
}
| |
/*
Copyright (c) 2015, Lars Brubaker
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 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using ClipperLib;
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.VertexSource;
using MatterHackers.DataConverters2D;
using MatterHackers.VectorMath;
using System;
using System.Collections.Generic;
namespace MatterHackers.PolygonPathing
{
using Agg;
using Polygon = List<IntPoint>;
using Polygons = List<List<IntPoint>>;
public class PolygonPathingDemo : SystemWindow
{
private Vector2 lineStart = Vector2.Zero;
private Vector2 mousePosition;
private RGBA_Bytes pathColor = RGBA_Bytes.Green;
private RadioButtonGroup pathTypeRadioGroup = new RadioButtonGroup(new Vector2(555, 5), new Vector2(80, 130))
{
HAnchor = HAnchor.ParentRight | HAnchor.FitToChildren,
VAnchor = VAnchor.ParentBottom | VAnchor.FitToChildren,
Margin = new BorderDouble(5),
};
private RadioButtonGroup shapeTypeRadioGroup = new RadioButtonGroup(new Vector2(5, 5), new Vector2(205, 110))
{
HAnchor = HAnchor.ParentLeft | HAnchor.FitToChildren,
VAnchor = VAnchor.ParentBottom | VAnchor.FitToChildren,
Margin = new BorderDouble(5),
};
public PolygonPathingDemo()
: base(740, 520)
{
BackgroundColor = RGBA_Bytes.White;
pathTypeRadioGroup.AddRadioButton("Stay Inside");
pathTypeRadioGroup.AddRadioButton("Stay Outside");
pathTypeRadioGroup.SelectedIndex = 0;
AddChild(pathTypeRadioGroup);
shapeTypeRadioGroup.AddRadioButton("Simple Map");
shapeTypeRadioGroup.AddRadioButton("Multiple Pegs");
shapeTypeRadioGroup.AddRadioButton("Circle Holes");
shapeTypeRadioGroup.AddRadioButton("Great Britain");
shapeTypeRadioGroup.AddRadioButton("Arrows");
shapeTypeRadioGroup.AddRadioButton("Spiral");
shapeTypeRadioGroup.AddRadioButton("Glyph");
shapeTypeRadioGroup.SelectedIndex = 0;
AddChild(shapeTypeRadioGroup);
AnchorAll();
}
private RGBA_Bytes fillColor
{ get { return RGBA_Bytes.Pink; } }
[STAThread]
public static void Main(string[] args)
{
PolygonPathingDemo demo = new PolygonPathingDemo();
demo.ShowAsSystemWindow();
}
public override void OnDraw(Graphics2D graphics2D)
{
RenderPolygonToPathAgainst(graphics2D);
//graphics2D.Line(lineStart, mousePosition, RGBA_Bytes.Red);
base.OnDraw(graphics2D);
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
base.OnMouseDown(mouseEvent);
if (mouseEvent.Button == MouseButtons.Left && FirstWidgetUnderMouse)
{
lineStart = mousePosition = mouseEvent.Position;
Invalidate();
}
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
if (MouseCaptured)
{
mousePosition = mouseEvent.Position;
Invalidate();
}
base.OnMouseMove(mouseEvent);
}
private void CreateAndRenderPathing(Graphics2D graphics2D, Polygons polygonsToPathAround, Polygons travelPolysLine)
{
Polygons travelPolygons = CreateTravelPath(polygonsToPathAround, travelPolysLine);
PathStorage travelPath = VertexSourceToClipperPolygons.CreatePathStorage(travelPolygons);
travelPath.Add(0, 0, ShapePath.FlagsAndCommand.CommandStop);
graphics2D.Render(new Stroke(travelPath), pathColor);
//graphics2D.Render(optomizedTravelPath, optomizedPpathColor);
foreach (Polygon polygon in polygonsToPathAround)
{
for (int i = 0; i < polygon.Count; i++)
{
if (!polygon.IsVertexConcave(i))
{
graphics2D.Circle(polygon[i].X, polygon[i].Y, 4, RGBA_Bytes.Green);
}
}
}
}
private Polygons CreateTravelPath(Polygons polygonsToPathAround, Polygons travelPolysLine)
{
Clipper clipper = new Clipper();
clipper.AddPaths(travelPolysLine, PolyType.ptSubject, false);
clipper.AddPaths(polygonsToPathAround, PolyType.ptClip, true);
PolyTree clippedLine = new PolyTree();
//List<List<IntPoint>> intersectedPolys = new List<List<IntPoint>>();
//clipper.Execute(ClipType.ctDifference, intersectedPolys);
clipper.Execute(ClipType.ctDifference, clippedLine);
return Clipper.OpenPathsFromPolyTree(clippedLine);
}
private void make_arrows(PathStorage ps)
{
ps.remove_all();
ps.MoveTo(1330.6, 1282.4);
ps.LineTo(1377.4, 1282.4);
ps.LineTo(1361.8, 1298.0);
ps.LineTo(1393.0, 1313.6);
ps.LineTo(1361.8, 1344.8);
ps.LineTo(1346.2, 1313.6);
ps.LineTo(1330.6, 1329.2);
ps.ClosePolygon();
ps.MoveTo(1330.599999999999909, 1266.799999999999955);
ps.LineTo(1377.400000000000091, 1266.799999999999955);
ps.LineTo(1361.799999999999955, 1251.200000000000045);
ps.LineTo(1393.000000000000000, 1235.599999999999909);
ps.LineTo(1361.799999999999955, 1204.399999999999864);
ps.LineTo(1346.200000000000045, 1235.599999999999909);
ps.LineTo(1330.599999999999909, 1220.000000000000000);
ps.ClosePolygon();
ps.MoveTo(1315.000000000000000, 1282.399999999999864);
ps.LineTo(1315.000000000000000, 1329.200000000000045);
ps.LineTo(1299.400000000000091, 1313.599999999999909);
ps.LineTo(1283.799999999999955, 1344.799999999999955);
ps.LineTo(1252.599999999999909, 1313.599999999999909);
ps.LineTo(1283.799999999999955, 1298.000000000000000);
ps.LineTo(1268.200000000000045, 1282.399999999999864);
ps.ClosePolygon();
ps.MoveTo(1268.200000000000045, 1266.799999999999955);
ps.LineTo(1315.000000000000000, 1266.799999999999955);
ps.LineTo(1315.000000000000000, 1220.000000000000000);
ps.LineTo(1299.400000000000091, 1235.599999999999909);
ps.LineTo(1283.799999999999955, 1204.399999999999864);
ps.LineTo(1252.599999999999909, 1235.599999999999909);
ps.LineTo(1283.799999999999955, 1251.200000000000045);
ps.ClosePolygon();
}
private void RenderPolygonToPathAgainst(Graphics2D graphics2D)
{
IVertexSource pathToUse = null;
switch (shapeTypeRadioGroup.SelectedIndex)
{
case 0:// simple polygon map
{
PathStorage ps1 = new PathStorage();
ps1.MoveTo(85, 417);
ps1.LineTo(338, 428);
ps1.LineTo(344, 325);
ps1.LineTo(399, 324);
ps1.LineTo(400, 421);
ps1.LineTo(644, 415);
ps1.LineTo(664, 75);
ps1.LineTo(98, 81);
ps1.ClosePolygon();
ps1.MoveTo(343, 290);
ps1.LineTo(159, 235);
ps1.LineTo(154, 162);
ps1.LineTo(340, 114);
ps1.ClosePolygon();
ps1.MoveTo(406, 121);
ps1.LineTo(587, 158);
ps1.LineTo(591, 236);
ps1.LineTo(404, 291);
ps1.ClosePolygon();
pathToUse = ps1;
}
break;
case 1: // multiple pegs
{
PathStorage ps2 = new PathStorage();
double x = 0;
double y = 0;
ps2.MoveTo(100 + 32, 100 + 77);
ps2.LineTo(100 + 473, 100 + 263);
ps2.LineTo(100 + 351, 100 + 290);
ps2.LineTo(100 + 354, 100 + 374);
pathToUse = ps2;
}
break;
case 2:
{
// circle holes
PathStorage ps1 = new PathStorage();
double x = 0;
double y = 0;
ps1.MoveTo(x + 140, y + 145);
ps1.LineTo(x + 225, y + 44);
ps1.LineTo(x + 296, y + 219);
ps1.ClosePolygon();
ps1.LineTo(x + 226, y + 289);
ps1.LineTo(x + 82, y + 292);
ps1.ClosePolygon();
ps1.MoveTo(x + 220 - 50, y + 222);
ps1.LineTo(x + 265 - 50, y + 331);
ps1.LineTo(x + 363 - 50, y + 249);
ps1.ClosePolygon();
pathToUse = ps1;
}
break;
case 3: // Great Britain
{
PathStorage gb_poly = new PathStorage();
GreatBritanPathStorage.Make(gb_poly);
Affine mtx1 = Affine.NewIdentity();
Affine mtx2 = Affine.NewIdentity();
mtx1 *= Affine.NewTranslation(-1150, -1150);
mtx1 *= Affine.NewScaling(2.0);
mtx2 = mtx1;
mtx2 *= Affine.NewTranslation(Width / 2, Height / 2);
VertexSourceApplyTransform trans_gb_poly = new VertexSourceApplyTransform(gb_poly, mtx1);
pathToUse = trans_gb_poly;
}
break;
case 4: // Arrows
{
PathStorage arrows = new PathStorage();
make_arrows(arrows);
Affine mtx1 = Affine.NewIdentity();
mtx1 *= Affine.NewTranslation(-1150, -1150);
mtx1 *= Affine.NewScaling(2.0);
VertexSourceApplyTransform trans_arrows = new VertexSourceApplyTransform(arrows, mtx1);
pathToUse = trans_arrows;
}
break;
case 5: // Spiral
{
spiral sp = new spiral(Width / 2, Height / 2, 10, 150, 30, 0.0);
Stroke stroke = new Stroke(sp);
stroke.width(15.0);
Affine mtx = Affine.NewIdentity(); ;
mtx *= Affine.NewTranslation(-1150, -1150);
mtx *= Affine.NewScaling(2.0);
pathToUse = stroke;
}
break;
case 6: // Glyph
{
//------------------------------------
// Spiral and glyph
//
PathStorage glyph = new PathStorage();
glyph.MoveTo(28.47, 6.45);
glyph.curve3(21.58, 1.12, 19.82, 0.29);
glyph.curve3(17.19, -0.93, 14.21, -0.93);
glyph.curve3(9.57, -0.93, 6.57, 2.25);
glyph.curve3(3.56, 5.42, 3.56, 10.60);
glyph.curve3(3.56, 13.87, 5.03, 16.26);
glyph.curve3(7.03, 19.58, 11.99, 22.51);
glyph.curve3(16.94, 25.44, 28.47, 29.64);
glyph.LineTo(28.47, 31.40);
glyph.curve3(28.47, 38.09, 26.34, 40.58);
glyph.curve3(24.22, 43.07, 20.17, 43.07);
glyph.curve3(17.09, 43.07, 15.28, 41.41);
glyph.curve3(13.43, 39.75, 13.43, 37.60);
glyph.LineTo(13.53, 34.77);
glyph.curve3(13.53, 32.52, 12.38, 31.30);
glyph.curve3(11.23, 30.08, 9.38, 30.08);
glyph.curve3(7.57, 30.08, 6.42, 31.35);
glyph.curve3(5.27, 32.62, 5.27, 34.81);
glyph.curve3(5.27, 39.01, 9.57, 42.53);
glyph.curve3(13.87, 46.04, 21.63, 46.04);
glyph.curve3(27.59, 46.04, 31.40, 44.04);
glyph.curve3(34.28, 42.53, 35.64, 39.31);
glyph.curve3(36.52, 37.21, 36.52, 30.71);
glyph.LineTo(36.52, 15.53);
glyph.curve3(36.52, 9.13, 36.77, 7.69);
glyph.curve3(37.01, 6.25, 37.57, 5.76);
glyph.curve3(38.13, 5.27, 38.87, 5.27);
glyph.curve3(39.65, 5.27, 40.23, 5.62);
glyph.curve3(41.26, 6.25, 44.19, 9.18);
glyph.LineTo(44.19, 6.45);
glyph.curve3(38.72, -0.88, 33.74, -0.88);
glyph.curve3(31.35, -0.88, 29.93, 0.78);
glyph.curve3(28.52, 2.44, 28.47, 6.45);
glyph.ClosePolygon();
glyph.MoveTo(28.47, 9.62);
glyph.LineTo(28.47, 26.66);
glyph.curve3(21.09, 23.73, 18.95, 22.51);
glyph.curve3(15.09, 20.36, 13.43, 18.02);
glyph.curve3(11.77, 15.67, 11.77, 12.89);
glyph.curve3(11.77, 9.38, 13.87, 7.06);
glyph.curve3(15.97, 4.74, 18.70, 4.74);
glyph.curve3(22.41, 4.74, 28.47, 9.62);
glyph.ClosePolygon();
Affine mtx = Affine.NewIdentity();
mtx *= Affine.NewScaling(4.0);
mtx *= Affine.NewTranslation(220, 200);
VertexSourceApplyTransform trans = new VertexSourceApplyTransform(glyph, mtx);
FlattenCurves curve = new FlattenCurves(trans);
pathToUse = curve;
}
break;
}
graphics2D.Render(pathToUse, fillColor);
PathStorage travelLine = new PathStorage();
travelLine.MoveTo(lineStart);
travelLine.LineTo(mousePosition);
Polygons polygonsToPathAround = VertexSourceToClipperPolygons.CreatePolygons(pathToUse, 1);
polygonsToPathAround = FixWinding(polygonsToPathAround);
Polygons travelPolysLine = VertexSourceToClipperPolygons.CreatePolygons(travelLine, 1);
CreateAndRenderPathing(graphics2D, polygonsToPathAround, travelPolysLine);
}
private Polygons FixWinding(Polygons polygonsToPathAround)
{
polygonsToPathAround = Clipper.CleanPolygons(polygonsToPathAround);
Polygon boundsPolygon = new Polygon();
IntRect bounds = Clipper.GetBounds(polygonsToPathAround);
bounds.left -= 10;
bounds.bottom += 10;
bounds.right += 10;
bounds.top -= 10;
boundsPolygon.Add(new IntPoint(bounds.left, bounds.top));
boundsPolygon.Add(new IntPoint(bounds.right, bounds.top));
boundsPolygon.Add(new IntPoint(bounds.right, bounds.bottom));
boundsPolygon.Add(new IntPoint(bounds.left, bounds.bottom));
Clipper clipper = new Clipper();
clipper.AddPaths(polygonsToPathAround, PolyType.ptSubject, true);
clipper.AddPath(boundsPolygon, PolyType.ptClip, true);
PolyTree intersectionResult = new PolyTree();
clipper.Execute(ClipType.ctIntersection, intersectionResult);
Polygons outputPolygons = Clipper.ClosedPathsFromPolyTree(intersectionResult);
Clipper.ReversePaths(outputPolygons);
return outputPolygons;
}
}
public class spiral : IVertexSource
{
private double m_angle;
private double m_curr_r;
private double m_da;
private double m_dr;
private double m_r1;
private double m_r2;
private bool m_start;
private double m_start_angle;
private double m_step;
private double m_x;
private double m_y;
public spiral(double x, double y, double r1, double r2, double step, double start_angle = 0)
{
m_x = x;
m_y = y;
m_r1 = r1;
m_r2 = r2;
m_step = step;
m_start_angle = start_angle;
m_angle = start_angle;
m_da = agg_basics.deg2rad(4.0);
m_dr = m_step / 90.0;
}
public void rewind(int index)
{
m_angle = m_start_angle;
m_curr_r = m_r1;
m_start = true;
}
public ShapePath.FlagsAndCommand vertex(out double x, out double y)
{
x = 0;
y = 0;
if (m_curr_r > m_r2)
{
return ShapePath.FlagsAndCommand.CommandStop;
}
x = m_x + Math.Cos(m_angle) * m_curr_r;
y = m_y + Math.Sin(m_angle) * m_curr_r;
m_curr_r += m_dr;
m_angle += m_da;
if (m_start)
{
m_start = false;
return ShapePath.FlagsAndCommand.CommandMoveTo;
}
return ShapePath.FlagsAndCommand.CommandLineTo;
}
public IEnumerable<VertexData> Vertices()
{
throw new NotImplementedException();
}
}
internal class conv_poly_counter
{
private int m_contours;
private int m_points;
private conv_poly_counter(IVertexSource src)
{
m_contours = 0;
m_points = 0;
foreach (VertexData vertexData in src.Vertices())
{
if (ShapePath.is_vertex(vertexData.command))
{
++m_points;
}
if (ShapePath.is_move_to(vertexData.command))
{
++m_contours;
}
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContextWriter
{
public void Write(DependencyContext context, Stream stream)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
using (var writer = new StreamWriter(stream))
{
using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented })
{
Write(context).WriteTo(jsonWriter);
}
}
}
private JObject Write(DependencyContext context)
{
var contextObject = new JObject(
new JProperty(DependencyContextStrings.RuntimeTargetPropertyName, WriteRuntimeTargetInfo(context)),
new JProperty(DependencyContextStrings.CompilationOptionsPropertName, WriteCompilationOptions(context.CompilationOptions)),
new JProperty(DependencyContextStrings.TargetsPropertyName, WriteTargets(context)),
new JProperty(DependencyContextStrings.LibrariesPropertyName, WriteLibraries(context))
);
if (context.RuntimeGraph.Any())
{
contextObject.Add(new JProperty(DependencyContextStrings.RuntimesPropertyName, WriteRuntimeGraph(context)));
}
return contextObject;
}
private JObject WriteRuntimeTargetInfo(DependencyContext context)
{
return new JObject(
new JProperty(DependencyContextStrings.RuntimeTargetNamePropertyName,
context.Target.IsPortable ?
context.Target.Framework :
context.Target.Framework + DependencyContextStrings.VersionSeperator + context.Target.Runtime
),
new JProperty(DependencyContextStrings.RuntimeTargetSignaturePropertyName,
context.Target.RuntimeSignature
)
);
}
private JObject WriteRuntimeGraph(DependencyContext context)
{
return new JObject(
context.RuntimeGraph.Select(g => new JProperty(g.Runtime, new JArray(g.Fallbacks)))
);
}
private JObject WriteCompilationOptions(CompilationOptions compilationOptions)
{
var o = new JObject();
if (compilationOptions.Defines?.Any() == true)
{
o[DependencyContextStrings.DefinesPropertyName] = new JArray(compilationOptions.Defines);
}
AddPropertyIfNotNull(o, DependencyContextStrings.LanguageVersionPropertyName, compilationOptions.LanguageVersion);
AddPropertyIfNotNull(o, DependencyContextStrings.PlatformPropertyName, compilationOptions.Platform);
AddPropertyIfNotNull(o, DependencyContextStrings.AllowUnsafePropertyName, compilationOptions.AllowUnsafe);
AddPropertyIfNotNull(o, DependencyContextStrings.WarningsAsErrorsPropertyName, compilationOptions.WarningsAsErrors);
AddPropertyIfNotNull(o, DependencyContextStrings.OptimizePropertyName, compilationOptions.Optimize);
AddPropertyIfNotNull(o, DependencyContextStrings.KeyFilePropertyName, compilationOptions.KeyFile);
AddPropertyIfNotNull(o, DependencyContextStrings.DelaySignPropertyName, compilationOptions.DelaySign);
AddPropertyIfNotNull(o, DependencyContextStrings.PublicSignPropertyName, compilationOptions.PublicSign);
AddPropertyIfNotNull(o, DependencyContextStrings.EmitEntryPointPropertyName, compilationOptions.EmitEntryPoint);
AddPropertyIfNotNull(o, DependencyContextStrings.GenerateXmlDocumentationPropertyName, compilationOptions.GenerateXmlDocumentation);
AddPropertyIfNotNull(o, DependencyContextStrings.DebugTypePropertyName, compilationOptions.DebugType);
return o;
}
private void AddPropertyIfNotNull<T>(JObject o, string name, T value)
{
if (value != null)
{
o.Add(new JProperty(name, value));
}
}
private JObject WriteTargets(DependencyContext context)
{
if (context.Target.IsPortable)
{
return new JObject(
new JProperty(context.Target.Framework, WritePortableTarget(context.RuntimeLibraries, context.CompileLibraries))
);
}
return new JObject(
new JProperty(context.Target.Framework, WriteTarget(context.CompileLibraries)),
new JProperty(context.Target.Framework + DependencyContextStrings.VersionSeperator + context.Target.Runtime,
WriteTarget(context.RuntimeLibraries))
);
}
private JObject WriteTarget(IReadOnlyList<Library> libraries)
{
return new JObject(
libraries.Select(library =>
new JProperty(library.Name + DependencyContextStrings.VersionSeperator + library.Version, WriteTargetLibrary(library))));
}
private JObject WritePortableTarget(IReadOnlyList<RuntimeLibrary> runtimeLibraries, IReadOnlyList<CompilationLibrary> compilationLibraries)
{
var runtimeLookup = runtimeLibraries.ToDictionary(l => l.Name);
var compileLookup = compilationLibraries.ToDictionary(l => l.Name);
var targetObject = new JObject();
foreach (var packageName in runtimeLookup.Keys.Concat(compileLookup.Keys).Distinct())
{
RuntimeLibrary runtimeLibrary;
runtimeLookup.TryGetValue(packageName, out runtimeLibrary);
CompilationLibrary compilationLibrary;
compileLookup.TryGetValue(packageName, out compilationLibrary);
if (compilationLibrary != null && runtimeLibrary != null)
{
Debug.Assert(compilationLibrary.Serviceable == runtimeLibrary.Serviceable);
Debug.Assert(compilationLibrary.Version == runtimeLibrary.Version);
Debug.Assert(compilationLibrary.Hash == runtimeLibrary.Hash);
Debug.Assert(compilationLibrary.Type == runtimeLibrary.Type);
}
var library = (Library)compilationLibrary ?? (Library)runtimeLibrary;
targetObject.Add(
new JProperty(library.Name + DependencyContextStrings.VersionSeperator + library.Version,
WritePortableTargetLibrary(runtimeLibrary, compilationLibrary)
)
);
}
return targetObject;
}
private void AddCompilationAssemblies(JObject libraryObject, IEnumerable<string> compilationAssemblies)
{
if (!compilationAssemblies.Any())
{
return;
}
libraryObject.Add(new JProperty(DependencyContextStrings.CompileTimeAssembliesKey,
WriteAssetList(compilationAssemblies))
);
}
private void AddAssets(JObject libraryObject, string key, RuntimeAssetGroup group)
{
if (group == null || !group.AssetPaths.Any())
{
return;
}
libraryObject.Add(new JProperty(key,
WriteAssetList(group.AssetPaths))
);
}
private void AddDependencies(JObject libraryObject, IEnumerable<Dependency> dependencies)
{
if (!dependencies.Any())
{
return;
}
libraryObject.AddFirst(
new JProperty(DependencyContextStrings.DependenciesPropertyName,
new JObject(
dependencies.Select(dependency => new JProperty(dependency.Name, dependency.Version))))
);
}
private void AddResourceAssemblies(JObject libraryObject, IEnumerable<ResourceAssembly> resourceAssemblies)
{
if (!resourceAssemblies.Any())
{
return;
}
libraryObject.Add(DependencyContextStrings.ResourceAssembliesPropertyName,
new JObject(resourceAssemblies.Select(a =>
new JProperty(NormalizePath(a.Path), new JObject(new JProperty(DependencyContextStrings.LocalePropertyName, a.Locale))))
)
);
}
private JObject WriteTargetLibrary(Library library)
{
var runtimeLibrary = library as RuntimeLibrary;
if (runtimeLibrary != null)
{
var libraryObject = new JObject();
AddDependencies(libraryObject, runtimeLibrary.Dependencies);
// Add runtime-agnostic assets
AddAssets(libraryObject, DependencyContextStrings.RuntimeAssembliesKey, runtimeLibrary.RuntimeAssemblyGroups.GetDefaultGroup());
AddAssets(libraryObject, DependencyContextStrings.NativeLibrariesKey, runtimeLibrary.NativeLibraryGroups.GetDefaultGroup());
AddResourceAssemblies(libraryObject, runtimeLibrary.ResourceAssemblies);
return libraryObject;
}
var compilationLibrary = library as CompilationLibrary;
if (compilationLibrary != null)
{
var libraryObject = new JObject();
AddDependencies(libraryObject, compilationLibrary.Dependencies);
AddCompilationAssemblies(libraryObject, compilationLibrary.Assemblies);
return libraryObject;
}
throw new NotSupportedException();
}
private JObject WritePortableTargetLibrary(RuntimeLibrary runtimeLibrary, CompilationLibrary compilationLibrary)
{
var libraryObject = new JObject();
var dependencies = new HashSet<Dependency>();
if (runtimeLibrary != null)
{
// Add runtime-agnostic assets
AddAssets(libraryObject, DependencyContextStrings.RuntimeAssembliesKey, runtimeLibrary.RuntimeAssemblyGroups.GetDefaultGroup());
AddAssets(libraryObject, DependencyContextStrings.NativeLibrariesKey, runtimeLibrary.NativeLibraryGroups.GetDefaultGroup());
AddResourceAssemblies(libraryObject, runtimeLibrary.ResourceAssemblies);
// Add runtime-specific assets
var runtimeTargets = new JObject();
AddRuntimeSpecificAssetGroups(runtimeTargets, DependencyContextStrings.RuntimeAssetType, runtimeLibrary.RuntimeAssemblyGroups);
AddRuntimeSpecificAssetGroups(runtimeTargets, DependencyContextStrings.NativeAssetType, runtimeLibrary.NativeLibraryGroups);
if (runtimeTargets.Count > 0)
{
libraryObject.Add(DependencyContextStrings.RuntimeTargetsPropertyName, runtimeTargets);
}
dependencies.UnionWith(runtimeLibrary.Dependencies);
}
if (compilationLibrary != null)
{
AddCompilationAssemblies(libraryObject, compilationLibrary.Assemblies);
dependencies.UnionWith(compilationLibrary.Dependencies);
}
AddDependencies(libraryObject, dependencies);
if (compilationLibrary != null && runtimeLibrary == null)
{
libraryObject.Add(DependencyContextStrings.CompilationOnlyPropertyName, true);
}
return libraryObject;
}
private void AddRuntimeSpecificAssetGroups(JObject runtimeTargets, string assetType, IEnumerable<RuntimeAssetGroup> assetGroups)
{
foreach (var group in assetGroups.Where(g => !string.IsNullOrEmpty(g.Runtime)))
{
if (group.AssetPaths.Any())
{
AddRuntimeSpecificAssets(runtimeTargets, group.AssetPaths, group.Runtime, assetType);
}
else
{
// Add a placeholder item
// We need to generate a pseudo-path because there could be multiple different asset groups with placeholders
// Only the last path segment matters, the rest is basically just a GUID.
var pseudoPathFolder = assetType == DependencyContextStrings.RuntimeAssetType ?
"lib" :
"native";
runtimeTargets[$"runtime/{group.Runtime}/{pseudoPathFolder}/_._"] = new JObject(
new JProperty(DependencyContextStrings.RidPropertyName, group.Runtime),
new JProperty(DependencyContextStrings.AssetTypePropertyName, assetType));
}
}
}
private void AddRuntimeSpecificAssets(JObject target, IEnumerable<string> assets, string runtime, string assetType)
{
foreach (var asset in assets)
{
target.Add(new JProperty(NormalizePath(asset),
new JObject(
new JProperty(DependencyContextStrings.RidPropertyName, runtime),
new JProperty(DependencyContextStrings.AssetTypePropertyName, assetType)
)
));
}
}
private JObject WriteAssetList(IEnumerable<string> assetPaths)
{
return new JObject(assetPaths.Select(assembly => new JProperty(NormalizePath(assembly), new JObject())));
}
private JObject WriteLibraries(DependencyContext context)
{
var allLibraries =
context.RuntimeLibraries.Cast<Library>().Concat(context.CompileLibraries)
.GroupBy(library => library.Name + DependencyContextStrings.VersionSeperator + library.Version);
return new JObject(allLibraries.Select(libraries => new JProperty(libraries.Key, WriteLibrary(libraries.First()))));
}
private JObject WriteLibrary(Library library)
{
return new JObject(
new JProperty(DependencyContextStrings.TypePropertyName, library.Type),
new JProperty(DependencyContextStrings.ServiceablePropertyName, library.Serviceable),
new JProperty(DependencyContextStrings.Sha512PropertyName, library.Hash)
);
}
private string NormalizePath(string path)
{
return path.Replace('\\', '/');
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OleDbCommand.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.OleDb {
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Text;
[
DefaultEvent("RecordsAffected"),
ToolboxItem(true),
Designer("Microsoft.VSDesigner.Data.VS.OleDbCommandDesigner, " + AssemblyRef.MicrosoftVSDesigner)
]
public sealed class OleDbCommand : DbCommand, ICloneable, IDbCommand {
// command data
private string _commandText;
private CommandType _commandType;
private int _commandTimeout = ADP.DefaultCommandTimeout;
private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
private bool _designTimeInvisible;
private OleDbConnection _connection;
private OleDbTransaction _transaction;
private static int _objectTypeCount; // Bid counter
internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
private OleDbParameterCollection _parameters;
// native information
private UnsafeNativeMethods.ICommandText _icommandText;
// if executing with a different CommandBehavior.KeyInfo behavior
// original ICommandText must be released and a new ICommandText generated
private CommandBehavior commandBehavior;
private Bindings _dbBindings;
internal bool canceling; // MDAC 68964
private bool _isPrepared;
private bool _executeQuery;
private bool _trackingForClose;
private bool _hasDataReader;
private IntPtr _recordsAffected;
private int _changeID;
private int _lastChangeID;
public OleDbCommand() : base() {
GC.SuppressFinalize(this);
}
public OleDbCommand(string cmdText) : this() {
CommandText = cmdText;
}
public OleDbCommand(string cmdText, OleDbConnection connection) : this() {
CommandText = cmdText;
Connection = connection;
}
public OleDbCommand(string cmdText, OleDbConnection connection, OleDbTransaction transaction) : this() {
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
}
private OleDbCommand(OleDbCommand from) : this() { // Clone
CommandText = from.CommandText;
CommandTimeout = from.CommandTimeout;
CommandType = from.CommandType;
Connection = from.Connection;
DesignTimeVisible = from.DesignTimeVisible;
UpdatedRowSource = from.UpdatedRowSource;
Transaction = from.Transaction;
OleDbParameterCollection parameters = Parameters;
foreach(object parameter in from.Parameters) {
parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter);
}
}
private Bindings ParameterBindings {
get {
return _dbBindings;
}
set {
Bindings bindings = _dbBindings;
_dbBindings = value;
if ((null != bindings) && (value != bindings)) {
bindings.Dispose();
}
}
}
[
DefaultValue(""),
Editor("Microsoft.VSDesigner.Data.ADO.Design.OleDbCommandTextEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
RefreshProperties(RefreshProperties.All), // MDAC 67707
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandText),
]
override public string CommandText {
get {
string value = _commandText;
return ((null != value) ? value : ADP.StrEmpty);
}
set {
if (Bid.TraceOn) {
Bid.Trace("<oledb.OleDbCommand.set_CommandText|API> %d#, '", ObjectID);
Bid.PutStr(value); // Use PutStr to write out entire string
Bid.Trace("'\n");
}
if (0 != ADP.SrcCompare(_commandText, value)) {
PropertyChanging();
_commandText = value;
}
}
}
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandTimeout),
]
override public int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000
get {
return _commandTimeout;
}
set {
Bid.Trace("<oledb.OleDbCommand.set_CommandTimeout|API> %d#, %d\n", ObjectID, value);
if (value < 0) {
throw ADP.InvalidCommandTimeout(value);
}
if (value != _commandTimeout) {
PropertyChanging();
_commandTimeout = value;
}
}
}
public void ResetCommandTimeout() { // V1.2.3300
if (ADP.DefaultCommandTimeout != _commandTimeout) {
PropertyChanging();
_commandTimeout = ADP.DefaultCommandTimeout;
}
}
private bool ShouldSerializeCommandTimeout() { // V1.2.3300
return (ADP.DefaultCommandTimeout != _commandTimeout);
}
[
DefaultValue(System.Data.CommandType.Text),
RefreshProperties(RefreshProperties.All),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandType),
]
override public CommandType CommandType {
get {
CommandType cmdType = _commandType;
return ((0 != cmdType) ? cmdType : CommandType.Text);
}
set {
switch(value) { // @perfnote: Enum.IsDefined
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
PropertyChanging();
_commandType = value;
break;
default:
throw ADP.InvalidCommandType(value);
}
}
}
[
DefaultValue(null),
Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_Connection),
]
new public OleDbConnection Connection {
get {
return _connection;
}
set {
OleDbConnection connection = _connection;
if (value != connection) {
PropertyChanging();
ResetConnection();
_connection = value;
Bid.Trace("<oledb.OleDbCommand.set_Connection|API> %d#\n", ObjectID);
if (null != value) {
_transaction = OleDbTransaction.TransactionUpdate(_transaction); // MDAC 63226
}
}
}
}
private void ResetConnection() {
OleDbConnection connection = _connection;
if (null != connection) {
PropertyChanging();
CloseInternal();
if (_trackingForClose) {
connection.RemoveWeakReference(this);
_trackingForClose = false;
}
}
_connection = null;
}
override protected DbConnection DbConnection { // V1.2.3300
get {
return Connection;
}
set {
Connection = (OleDbConnection)value;
}
}
override protected DbParameterCollection DbParameterCollection { // V1.2.3300
get {
return Parameters;
}
}
override protected DbTransaction DbTransaction { // V1.2.3300
get {
return Transaction;
}
set {
Transaction = (OleDbTransaction)value;
}
}
// @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
// to limit the number of components that clutter the design surface,
// when the DataAdapter design wizard generates the insert/update/delete commands it will
// set the DesignTimeVisible property to false so that cmds won't appear as individual objects
[
DefaultValue(true),
DesignOnly(true),
Browsable(false),
EditorBrowsableAttribute(EditorBrowsableState.Never),
]
public override bool DesignTimeVisible { // V1.2.3300, XXXCommand V1.0.5000
get {
return !_designTimeInvisible;
}
set {
_designTimeInvisible = !value;
TypeDescriptor.Refresh(this); // VS7 208845
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_Parameters),
]
new public OleDbParameterCollection Parameters {
get {
OleDbParameterCollection value = _parameters;
if (null == value) {
// delay the creation of the OleDbParameterCollection
// until user actually uses the Parameters property
value = new OleDbParameterCollection();
_parameters = value;
}
return value;
}
}
private bool HasParameters() { // MDAC 65548
OleDbParameterCollection value = _parameters;
return (null != value) && (0 < value.Count); // VS 300569
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(Res.DbCommand_Transaction),
]
new public OleDbTransaction Transaction {
get {
// find the last non-zombied local transaction object, but not transactions
// that may have been started after the current local transaction
OleDbTransaction transaction = _transaction;
while ((null != transaction) && (null == transaction.Connection)) {
transaction = transaction.Parent;
_transaction = transaction;
}
return transaction;
}
set {
_transaction = value;
Bid.Trace("<oledb.OleDbCommand.set_Transaction|API> %d#\n", ObjectID);
}
}
[
DefaultValue(System.Data.UpdateRowSource.Both),
ResCategoryAttribute(Res.DataCategory_Update),
ResDescriptionAttribute(Res.DbCommand_UpdatedRowSource),
]
override public UpdateRowSource UpdatedRowSource { // V1.2.3300, XXXCommand V1.0.5000
get {
return _updatedRowSource;
}
set {
switch(value) { // @perfnote: Enum.IsDefined
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updatedRowSource = value;
break;
default:
throw ADP.InvalidUpdateRowSource(value);
}
}
}
// required interface, safe cast
private UnsafeNativeMethods.IAccessor IAccessor() {
Bid.Trace("<oledb.IUnknown.QueryInterface|API|OLEDB|command> %d#, IAccessor\n", ObjectID);
Debug.Assert(null != _icommandText, "IAccessor: null ICommandText");
return (UnsafeNativeMethods.IAccessor) _icommandText;
}
// required interface, safe cast
internal UnsafeNativeMethods.ICommandProperties ICommandProperties() {
Bid.Trace("<oledb.IUnknown.QueryInterface|API|OLEDB|command> %d#, ICommandProperties\n", ObjectID);
Debug.Assert(null != _icommandText, "ICommandProperties: null ICommandText");
return (UnsafeNativeMethods.ICommandProperties) _icommandText;
}
// optional interface, unsafe cast
private UnsafeNativeMethods.ICommandPrepare ICommandPrepare() {
Bid.Trace("<oledb.IUnknown.QueryInterface|API|OLEDB|command> %d#, ICommandPrepare\n", ObjectID);
Debug.Assert(null != _icommandText, "ICommandPrepare: null ICommandText");
return (_icommandText as UnsafeNativeMethods.ICommandPrepare);
}
// optional interface, unsafe cast
private UnsafeNativeMethods.ICommandWithParameters ICommandWithParameters() {
Bid.Trace("<oledb.IUnknown.QueryInterface|API|OLEDB|command> %d#, ICommandWithParameters\n", ObjectID);
Debug.Assert(null != _icommandText, "ICommandWithParameters: null ICommandText");
UnsafeNativeMethods.ICommandWithParameters value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters);
if (null == value) {
throw ODB.NoProviderSupportForParameters(_connection.Provider, (Exception)null);
}
return value;
}
private void CreateAccessor() {
Debug.Assert(System.Data.CommandType.Text == CommandType || System.Data.CommandType.StoredProcedure == CommandType, "CreateAccessor: incorrect CommandType");
Debug.Assert(null == _dbBindings, "CreateAccessor: already has dbBindings");
Debug.Assert(HasParameters(), "CreateAccessor: unexpected, no parameter collection");
// do this first in-case the command doesn't support parameters
UnsafeNativeMethods.ICommandWithParameters commandWithParameters = ICommandWithParameters();
OleDbParameterCollection collection = _parameters;
OleDbParameter[] parameters = new OleDbParameter[collection.Count];
collection.CopyTo(parameters, 0);
// _dbBindings is used as a switch during ExecuteCommand, so don't set it until everything okay
Bindings bindings = new Bindings(parameters, collection.ChangeID);
for (int i = 0; i < parameters.Length; ++i) {
bindings.ForceRebind |= parameters[i].BindParameter(i, bindings);
}
bindings.AllocateForAccessor(null, 0, 0);
ApplyParameterBindings(commandWithParameters, bindings.BindInfo);
UnsafeNativeMethods.IAccessor iaccessor = IAccessor();
OleDbHResult hr = bindings.CreateAccessor(iaccessor, ODB.DBACCESSOR_PARAMETERDATA);
if (hr < 0) {
ProcessResults(hr);
}
_dbBindings = bindings;
}
private void ApplyParameterBindings(UnsafeNativeMethods.ICommandWithParameters commandWithParameters, tagDBPARAMBINDINFO[] bindInfo) {
IntPtr[] ordinals = new IntPtr[bindInfo.Length];
for (int i = 0; i < ordinals.Length; ++i) {
ordinals[i] = (IntPtr)(i+1);
}
Bid.Trace("<oledb.ICommandWithParameters.SetParameterInfo|API|OLEDB> %d#\n", ObjectID);
OleDbHResult hr = commandWithParameters.SetParameterInfo((IntPtr)bindInfo.Length, ordinals, bindInfo);
Bid.Trace("<oledb.ICommandWithParameters.SetParameterInfo|API|OLEDB|RET> %08X{HRESULT}\n", hr);
if (hr < 0) {
ProcessResults(hr);
}
}
override public void Cancel() {
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<oledb.OleDbCommand.Cancel|API> %d#\n", ObjectID);
try {
unchecked { _changeID++; }
UnsafeNativeMethods.ICommandText icmdtxt = _icommandText;
if (null != icmdtxt) {
OleDbHResult hr = OleDbHResult.S_OK;
lock(icmdtxt) {
// lock the object to avoid race conditions between using the object and releasing the object
// after we acquire the lock, if the class has moved on don't actually call Cancel
if (icmdtxt == _icommandText) {
Bid.Trace("<oledb.ICommandText.Cancel|API|OLEDB> %d#\n", ObjectID);
hr = icmdtxt.Cancel();
Bid.Trace("<oledb.ICommandText.Cancel|API|OLEDB|RET> %08X{HRESULT}\n", hr);
}
}
if (OleDbHResult.DB_E_CANTCANCEL != hr) {
// if the provider can't cancel the command - don't cancel the DataReader
this.canceling = true;
}
// since cancel is allowed to occur at anytime we can't check the connection status
// since if it returns as closed then the connection will close causing the reader to close
// and that would introduce the possilbility of one thread reading and one thread closing at the same time
ProcessResultsNoReset(hr); // MDAC 72667
}
else {
this.canceling = true;
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
public OleDbCommand Clone() {
OleDbCommand clone = new OleDbCommand(this);
Bid.Trace("<oledb.OleDbCommand.Clone|API> %d#, clone=%d#\n", ObjectID, clone.ObjectID);
return clone;
}
object ICloneable.Clone() {
return Clone();
}
// Connection.Close & Connection.Dispose(true) notification
internal void CloseCommandFromConnection(bool canceling) {
this.canceling = canceling; // MDAC 71435
CloseInternal();
_trackingForClose = false;
_transaction = null;
//GC.SuppressFinalize(this);
}
internal void CloseInternal() {
Debug.Assert(null != _connection, "no connection, CloseInternal");
CloseInternalParameters();
CloseInternalCommand();
}
// may be called from either
// OleDbDataReader.Close/Dispose
// via OleDbCommand.Dispose or OleDbConnection.Close
internal void CloseFromDataReader(Bindings bindings) {
if (null != bindings) {
if (canceling) {
bindings.Dispose();
Debug.Assert(_dbBindings == bindings, "bindings with two owners");
}
else {
bindings.ApplyOutputParameters();
ParameterBindings = bindings;
}
}
_hasDataReader = false;
}
private void CloseInternalCommand() {
unchecked { _changeID++; }
this.commandBehavior = CommandBehavior.Default;
_isPrepared = false;
UnsafeNativeMethods.ICommandText ict = Interlocked.Exchange<UnsafeNativeMethods.ICommandText>(ref _icommandText, null);
if (null != ict) {
lock(ict) {
// lock the object to avoid race conditions between using the object and releasing the object
Marshal.ReleaseComObject(ict);
}
}
}
private void CloseInternalParameters() {
Debug.Assert(null != _connection, "no connection, CloseInternalParameters");
Bindings bindings = _dbBindings;
_dbBindings = null;
if (null != bindings) {
bindings.Dispose();
}
}
new public OleDbParameter CreateParameter() {
return new OleDbParameter();
}
override protected DbParameter CreateDbParameter() {
return CreateParameter();
}
override protected void Dispose(bool disposing) { // MDAC 65459
if (disposing) { // release mananged objects
// the DataReader takes ownership of the parameter Bindings
// this way they don't get destroyed when user calls OleDbCommand.Dispose
// when there is an open DataReader
unchecked { _changeID++; }
// in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset
ResetConnection();
_transaction = null;
_parameters = null;
CommandText = null;
}
// release unmanaged objects
base.Dispose(disposing); // notify base classes
}
new public OleDbDataReader ExecuteReader() {
return ExecuteReader(CommandBehavior.Default);
}
IDataReader IDbCommand.ExecuteReader() {
return ExecuteReader(CommandBehavior.Default);
}
new public OleDbDataReader ExecuteReader(CommandBehavior behavior) {
OleDbConnection.ExecutePermission.Demand();
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<oledb.OleDbCommand.ExecuteReader|API> %d#, behavior=%d{ds.CommandBehavior}\n", ObjectID, (int)behavior);
try {
_executeQuery = true;
return ExecuteReaderInternal(behavior, ADP.ExecuteReader);
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) {
return ExecuteReader(behavior);
}
override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) {
return ExecuteReader(behavior);
}
private OleDbDataReader ExecuteReaderInternal(CommandBehavior behavior, string method) {
OleDbDataReader dataReader = null;
OleDbException nextResultsFailure = null;
int state = ODB.InternalStateClosed;
try {
ValidateConnectionAndTransaction(method);
if (0 != (CommandBehavior.SingleRow & behavior)) {
// CommandBehavior.SingleRow implies CommandBehavior.SingleResult
behavior |= CommandBehavior.SingleResult;
}
object executeResult;
int resultType;
switch(CommandType) {
case 0: // uninitialized CommandType.Text
case CommandType.Text:
case CommandType.StoredProcedure:
resultType = ExecuteCommand(behavior, out executeResult);
break;
case CommandType.TableDirect:
resultType = ExecuteTableDirect(behavior, out executeResult);
break;
default:
throw ADP.InvalidCommandType(CommandType);
}
if (_executeQuery) {
try {
dataReader = new OleDbDataReader(_connection, this, 0, this.commandBehavior);
switch(resultType) {
case ODB.ExecutedIMultipleResults:
dataReader.InitializeIMultipleResults(executeResult);
dataReader.NextResult();
break;
case ODB.ExecutedIRowset:
dataReader.InitializeIRowset(executeResult, ChapterHandle.DB_NULL_HCHAPTER, _recordsAffected);
dataReader.BuildMetaInfo();
dataReader.HasRowsRead();
break;
case ODB.ExecutedIRow:
dataReader.InitializeIRow(executeResult, _recordsAffected);
dataReader.BuildMetaInfo();
break;
case ODB.PrepareICommandText:
if (!_isPrepared) {
PrepareCommandText(2);
}
OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText, behavior);
break;
default:
Debug.Assert(false, "ExecuteReaderInternal: unknown result type");
break;
}
executeResult = null;
_hasDataReader = true;
_connection.AddWeakReference(dataReader, OleDbReferenceCollection.DataReaderTag);
// command stays in the executing state until the connection
// has a datareader to track for it being closed
state = ODB.InternalStateOpen; // MDAC 72655
}
finally {
if (ODB.InternalStateOpen != state) {
this.canceling = true;
if (null != dataReader) {
((IDisposable) dataReader).Dispose();
dataReader = null;
}
}
}
Debug.Assert(null != dataReader, "ExecuteReader should never return a null DataReader");
}
else { // optimized code path for ExecuteNonQuery to not create a OleDbDataReader object
try {
if (ODB.ExecutedIMultipleResults == resultType) {
UnsafeNativeMethods.IMultipleResults multipleResults = (UnsafeNativeMethods.IMultipleResults) executeResult;
// may cause a Connection.ResetState which closes connection
nextResultsFailure = OleDbDataReader.NextResults(multipleResults, _connection, this, out _recordsAffected);
}
}
finally {
try {
if (null != executeResult) {
Marshal.ReleaseComObject(executeResult);
executeResult = null;
}
CloseFromDataReader(ParameterBindings);
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
if (null != nextResultsFailure) {
nextResultsFailure = new OleDbException(nextResultsFailure, e);
}
else {
throw;
}
}
}
}
}
finally { // finally clear executing state
try {
if ((null == dataReader) && (ODB.InternalStateOpen != state)) { // MDAC 67218
ParameterCleanup();
}
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
if (null != nextResultsFailure) {
nextResultsFailure = new OleDbException(nextResultsFailure, e);
}
else {
throw;
}
}
if (null != nextResultsFailure) {
throw nextResultsFailure;
}
}
return dataReader;
}
private int ExecuteCommand(CommandBehavior behavior, out object executeResult) {
if (InitializeCommand(behavior, false)) {
if (0 != (CommandBehavior.SchemaOnly & this.commandBehavior)) {
executeResult = null;
return ODB.PrepareICommandText;
}
return ExecuteCommandText(out executeResult);
}
return ExecuteTableDirect(behavior, out executeResult); // MDAC 57856
}
// dbindings handle can't be freed until the output parameters
// have been filled in which occurs after the last rowset is released
// dbbindings.FreeDataHandle occurs in Cloe
private int ExecuteCommandText(out object executeResult) {
int retcode;
tagDBPARAMS dbParams = null;
RowBinding rowbinding = null;
Bindings bindings = ParameterBindings;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
if (null != bindings) { // parameters may be suppressed
rowbinding = bindings.RowBinding();
rowbinding.DangerousAddRef(ref mustRelease);
// bindings can't be released until after last rowset is released
// that is when output parameters are populated
// initialize the input parameters to the input databuffer
bindings.ApplyInputParameters();
dbParams = new tagDBPARAMS();
dbParams.pData = rowbinding.DangerousGetDataPtr();
dbParams.cParamSets = 1;
dbParams.hAccessor = rowbinding.DangerousGetAccessorHandle();
}
if ((0 == (CommandBehavior.SingleResult & this.commandBehavior)) && _connection.SupportMultipleResults()) {
retcode = ExecuteCommandTextForMultpleResults(dbParams, out executeResult);
}
else if (0 == (CommandBehavior.SingleRow & this.commandBehavior) || !_executeQuery) {
retcode = ExecuteCommandTextForSingleResult(dbParams, out executeResult);
}
else {
retcode = ExecuteCommandTextForSingleRow(dbParams, out executeResult);
}
}
finally {
if (mustRelease) {
rowbinding.DangerousRelease();
}
}
return retcode;
}
private int ExecuteCommandTextForMultpleResults(tagDBPARAMS dbParams, out object executeResult) {
Debug.Assert(0 == (CommandBehavior.SingleRow & this.commandBehavior), "SingleRow implies SingleResult");
OleDbHResult hr;
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB> %d#, IID_IMultipleResults\n", ObjectID);
hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult);
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB|RET> %08X{HRESULT}, RecordsAffected=%Id\n", hr, _recordsAffected);
if (OleDbHResult.E_NOINTERFACE != hr) {
ExecuteCommandTextErrorHandling(hr);
return ODB.ExecutedIMultipleResults;
}
SafeNativeMethods.Wrapper.ClearErrorInfo();
return ExecuteCommandTextForSingleResult(dbParams, out executeResult);
}
private int ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, out object executeResult) {
OleDbHResult hr;
// MDAC 64465 (Microsoft.Jet.OLEDB.4.0 returns 0 for recordsAffected instead of -1)
if (_executeQuery) {
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB> %d#, IID_IRowset\n", ObjectID);
hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult);
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB|RET> %08X{HRESULT}, RecordsAffected=%Id\n", hr, _recordsAffected);
}
else {
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB> %d#, IID_NULL\n", ObjectID);
hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult);
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB|RET> %08X{HRESULT}, RecordsAffected=%Id\n", hr, _recordsAffected);
}
ExecuteCommandTextErrorHandling(hr);
return ODB.ExecutedIRowset;
}
private int ExecuteCommandTextForSingleRow(tagDBPARAMS dbParams, out object executeResult) {
Debug.Assert(_executeQuery, "ExecuteNonQuery should always use ExecuteCommandTextForSingleResult");
if (_connection.SupportIRow(this)) {
OleDbHResult hr;
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB> %d#, IID_IRow\n", ObjectID);
hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult);
Bid.Trace("<oledb.ICommandText.Execute|API|OLEDB|RET> %08X{HRESULT}, RecordsAffected=%Id\n", hr, _recordsAffected);
if (OleDbHResult.DB_E_NOTFOUND == hr) { // MDAC 76110
SafeNativeMethods.Wrapper.ClearErrorInfo();
return ODB.ExecutedIRow;
}
else if (OleDbHResult.E_NOINTERFACE != hr) {
ExecuteCommandTextErrorHandling(hr);
return ODB.ExecutedIRow;
}
}
SafeNativeMethods.Wrapper.ClearErrorInfo();
return ExecuteCommandTextForSingleResult(dbParams, out executeResult);
}
private void ExecuteCommandTextErrorHandling(OleDbHResult hr) {
Exception e = OleDbConnection.ProcessResults(hr, _connection, this);
if (null != e) {
e = ExecuteCommandTextSpecialErrorHandling(hr, e);
throw e;
}
}
private Exception ExecuteCommandTextSpecialErrorHandling(OleDbHResult hr, Exception e) {
if (((OleDbHResult.DB_E_ERRORSOCCURRED == hr) || (OleDbHResult.DB_E_BADBINDINFO == hr)) && (null != _dbBindings)) { // MDAC 66026, 67039
//
// this code exist to try for a better user error message by post-morten detection
// of invalid parameter types being passed to a provider that doesn't understand
// the user specified parameter OleDbType
Debug.Assert(null != e, "missing inner exception");
StringBuilder builder = new StringBuilder();
ParameterBindings.ParameterStatus(builder);
e = ODB.CommandParameterStatus(builder.ToString(), e);
}
return e;
}
override public int ExecuteNonQuery() {
OleDbConnection.ExecutePermission.Demand();
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<oledb.OleDbCommand.ExecuteNonQuery|API> %d#\n", ObjectID);
try {
_executeQuery = false;
ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteNonQuery);
return ADP.IntPtrToInt32(_recordsAffected);
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
override public object ExecuteScalar() {
OleDbConnection.ExecutePermission.Demand();
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<oledb.OleDbCommand.ExecuteScalar|API> %d#\n", ObjectID);
try {
object value = null;
_executeQuery = true;
using(OleDbDataReader reader = ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteScalar)) {
if (reader.Read() && (0 < reader.FieldCount)) {
value = reader.GetValue(0);
}
}
return value;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
private int ExecuteTableDirect(CommandBehavior behavior, out object executeResult) {
this.commandBehavior = behavior;
executeResult = null;
OleDbHResult hr = OleDbHResult.S_OK;
StringMemHandle sptr = null;
bool mustReleaseStringHandle = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
sptr = new StringMemHandle(ExpandCommandText());
sptr.DangerousAddRef(ref mustReleaseStringHandle);
if (mustReleaseStringHandle) {
tagDBID tableID = new tagDBID();
tableID.uGuid = Guid.Empty;
tableID.eKind = ODB.DBKIND_NAME;
tableID.ulPropid = sptr.DangerousGetHandle();
using(IOpenRowsetWrapper iopenRowset = _connection.IOpenRowset()) {
using(DBPropSet propSet = CommandPropertySets()) {
if (null != propSet) {
// MDAC 65279
Bid.Trace("<oledb.IOpenRowset.OpenRowset|API|OLEDB> %d#, IID_IRowset\n", ObjectID);
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
propSet.DangerousAddRef(ref mustRelease);
hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, propSet.PropertySetCount, propSet.DangerousGetHandle(), out executeResult);
}
finally {
if (mustRelease) {
propSet.DangerousRelease();
}
}
Bid.Trace("<oledb.IOpenRowset.OpenRowset|API|OLEDB|RET> %08X{HRESULT}", hr);
if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) {
Bid.Trace("<oledb.IOpenRowset.OpenRowset|API|OLEDB> %d#, IID_IRowset\n", ObjectID);
hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult);
Bid.Trace("<oledb.IOpenRowset.OpenRowset|API|OLEDB|RET> %08X{HRESULT}", hr);
}
}
else {
Bid.Trace("<oledb.IOpenRowset.OpenRowset|API|OLEDB> %d#, IID_IRowset\n", ObjectID);
hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult);
Bid.Trace("<oledb.IOpenRowset.OpenRowset|API|OLEDB|RET> %08X{HRESULT}", hr);
}
}
}
}
}
finally {
if (mustReleaseStringHandle) {
sptr.DangerousRelease();
}
}
ProcessResults(hr);
_recordsAffected = ADP.RecordsUnaffected;
return ODB.ExecutedIRowset;
}
private string ExpandCommandText() {
string cmdtxt = CommandText;
if (ADP.IsEmpty(cmdtxt)) {
return ADP.StrEmpty;
}
CommandType cmdtype = CommandType;
switch(cmdtype) {
case System.Data.CommandType.Text:
// do nothing, already expanded by user
return cmdtxt;
case System.Data.CommandType.StoredProcedure:
// { ? = CALL SPROC (? ?) }, { ? = CALL SPROC }, { CALL SPRC (? ?) }, { CALL SPROC }
return ExpandStoredProcedureToText(cmdtxt);
case System.Data.CommandType.TableDirect:
// @devnote: Provider=Jolt4.0 doesn't like quoted table names, SQOLEDB requires them
// Providers should not require table names to be quoted and should guarantee that
// unquoted table names correctly open the specified table, even if the table name
// contains special characters, as long as the table can be unambiguously identified
// without quoting.
return cmdtxt;
default:
throw ADP.InvalidCommandType(cmdtype);
}
}
private string ExpandOdbcMaximumToText(string sproctext, int parameterCount) {
StringBuilder builder = new StringBuilder();
if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) {
parameterCount--;
builder.Append("{ ? = CALL ");
}
else {
builder.Append("{ CALL ");
}
builder.Append(sproctext); // WebData 95634
switch(parameterCount) {
case 0:
builder.Append(" }");
break;
case 1:
builder.Append("( ? ) }");
break;
default:
builder.Append("( ?, ?");
for (int i = 2; i < parameterCount; ++i) {
builder.Append(", ?");
}
builder.Append(" ) }");
break;
}
return builder.ToString();
}
private string ExpandOdbcMinimumToText(string sproctext, int parameterCount) {
//if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) {
// Debug.Assert("doesn't support ReturnValue parameters");
//}
StringBuilder builder = new StringBuilder();
builder.Append("exec ");
builder.Append(sproctext);
if (0 < parameterCount) {
builder.Append(" ?");
for(int i = 1; i < parameterCount; ++i) {
builder.Append(", ?");
}
}
return builder.ToString();
}
private string ExpandStoredProcedureToText(string sproctext) {
Debug.Assert(null != _connection, "ExpandStoredProcedureToText: null Connection");
int parameterCount = (null != _parameters) ? _parameters.Count : 0;
if (0 == (ODB.DBPROPVAL_SQL_ODBC_MINIMUM & _connection.SqlSupport())) {
return ExpandOdbcMinimumToText(sproctext, parameterCount);
}
return ExpandOdbcMaximumToText(sproctext, parameterCount);
}
private void ParameterCleanup() {
Bindings bindings = ParameterBindings;
if (null != bindings) {
bindings.CleanupBindings();
}
}
private bool InitializeCommand(CommandBehavior behavior, bool throwifnotsupported) {
Debug.Assert(null != _connection, "InitializeCommand: null OleDbConnection");
int changeid = _changeID;
if ((0 != (CommandBehavior.KeyInfo & (this.commandBehavior ^ behavior))) || (_lastChangeID != changeid)) {
CloseInternalParameters(); // could optimize out
CloseInternalCommand();
}
this.commandBehavior = behavior;
changeid = _changeID;
if (!PropertiesOnCommand(false)) {
return false; // MDAC 57856
}
if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters)) {
CloseInternalParameters();
}
// if we already having bindings - don't create the accessor
// if _parameters is null - no parameters exist - don't create the collection
// do we actually have parameters since the collection exists
if ((null == _dbBindings) && HasParameters()) {
// if we setup the parameters before setting cmdtxt then named parameters can happen
CreateAccessor();
}
if (_lastChangeID != changeid) {
OleDbHResult hr;
String commandText = ExpandCommandText();
if (Bid.TraceOn) {
Bid.Trace("<oledb.ICommandText.SetCommandText|API|OLEDB> %d#, DBGUID_DEFAULT, CommandText='", ObjectID);
Bid.PutStr(commandText); // Use PutStr to write out entire string
Bid.Trace("'\n");
}
hr = _icommandText.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText);
Bid.Trace("<oledb.ICommandText.SetCommandText|API|OLEDB|RET> %08X{HRESULT}\n", hr);
if (hr < 0) {
ProcessResults(hr);
}
}
_lastChangeID = changeid;
return true;
}
private void PropertyChanging() {
unchecked { _changeID++; }
}
override public void Prepare() {
OleDbConnection.ExecutePermission.Demand();
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<oledb.OleDbCommand.Prepare|API> %d#\n", ObjectID);
try {
if (CommandType.TableDirect != CommandType) { // MDAC 70946, 71194
ValidateConnectionAndTransaction(ADP.Prepare);
_isPrepared = false;
if (CommandType.TableDirect != CommandType) {
InitializeCommand(0, true);
PrepareCommandText(1);
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
private void PrepareCommandText(int expectedExecutionCount) {
OleDbParameterCollection parameters = _parameters;
if (null != parameters) {
foreach(OleDbParameter parameter in parameters) {
if (parameter.IsParameterComputed()) {
// @devnote: use IsParameterComputed which is called in the normal case
// only to call Prepare to throw the specialized error message
// reducing the overall number of methods to actually jit
parameter.Prepare(this); // MDAC 70232
}
}
}
UnsafeNativeMethods.ICommandPrepare icommandPrepare = ICommandPrepare();
if (null != icommandPrepare) {
OleDbHResult hr;
Bid.Trace("<oledb.ICommandPrepare.Prepare|API|OLEDB> %d#, expectedExecutionCount=%d\n", ObjectID, expectedExecutionCount);
hr = icommandPrepare.Prepare(expectedExecutionCount);
Bid.Trace("<oledb.ICommandPrepare.Prepare|API|OLEDB|RET> %08X{HRESULT}\n", hr);
ProcessResults(hr);
}
// don't recompute bindings on prepared statements
_isPrepared = true;
}
private void ProcessResults(OleDbHResult hr) {
Exception e = OleDbConnection.ProcessResults(hr, _connection, this);
if (null != e) { throw e; }
}
private void ProcessResultsNoReset(OleDbHResult hr) {
Exception e = OleDbConnection.ProcessResults(hr, null, this);
if (null != e) { throw e; }
}
internal object GetPropertyValue(Guid propertySet, int propertyID) {
if (null != _icommandText) {
OleDbHResult hr;
tagDBPROP[] dbprops;
UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties();
using(PropertyIDSet propidset = new PropertyIDSet(propertySet, propertyID)) {
using(DBPropSet propset = new DBPropSet(icommandProperties, propidset, out hr)) {
if (hr < 0) {
// VSDD 621427: OLEDB Data Reader masks provider specific errors by raising "Internal .Net Framework Data Provider error 30."
// DBPropSet c-tor will register the exception and it will be raised at GetPropertySet call in case of failure
SafeNativeMethods.Wrapper.ClearErrorInfo();
}
dbprops = propset.GetPropertySet(0, out propertySet);
}
}
if (OleDbPropertyStatus.Ok == dbprops[0].dwStatus) {
return dbprops[0].vValue;
}
return dbprops[0].dwStatus;
}
return OleDbPropertyStatus.NotSupported;
}
private bool PropertiesOnCommand(bool throwNotSupported) {
if (null != _icommandText) {
return true;
}
Debug.Assert(!_isPrepared, "null command isPrepared");
OleDbConnection connection = _connection;
if (null == connection) {
connection.CheckStateOpen(ODB.Properties);
}
if (!_trackingForClose) {
_trackingForClose = true;
connection.AddWeakReference(this, OleDbReferenceCollection.CommandTag);
}
_icommandText = connection.ICommandText();
if (null == _icommandText) {
if (throwNotSupported || HasParameters()) {
throw ODB.CommandTextNotSupported(connection.Provider, null);
}
return false; // MDAC 57856
}
using(DBPropSet propSet = CommandPropertySets()) {
if (null != propSet) {
UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties();
Bid.Trace("<oledb.ICommandProperties.SetProperties|API|OLEDB> %d#\n", ObjectID);
OleDbHResult hr = icommandProperties.SetProperties(propSet.PropertySetCount, propSet);
Bid.Trace("<oledb.ICommandProperties.SetProperties|API|OLEDB|RET> %08X{HRESULT}\n", hr);
if (hr < 0) {
SafeNativeMethods.Wrapper.ClearErrorInfo();
}
}
}
return true;
}
private DBPropSet CommandPropertySets() {
DBPropSet propSet = null;
bool keyInfo = (0 != (CommandBehavior.KeyInfo & this.commandBehavior));
// always set the CommandTimeout value?
int count = (_executeQuery ? (keyInfo ? 4 : 2) : 1);
if (0 < count) {
propSet = new DBPropSet(1);
tagDBPROP[] dbprops = new tagDBPROP[count];
dbprops[0] = new tagDBPROP(ODB.DBPROP_COMMANDTIMEOUT, false, CommandTimeout);
if (_executeQuery) {
// 'Microsoft.Jet.OLEDB.4.0' default is DBPROPVAL_AO_SEQUENTIAL
dbprops[1] = new tagDBPROP(ODB.DBPROP_ACCESSORDER, false, ODB.DBPROPVAL_AO_RANDOM); // MDAC 73030
if (keyInfo) {
// 'Unique Rows' property required for SQLOLEDB to retrieve things like 'BaseTableName'
dbprops[2] = new tagDBPROP(ODB.DBPROP_UNIQUEROWS, false, keyInfo);
// otherwise 'Microsoft.Jet.OLEDB.4.0' doesn't support IColumnsRowset
dbprops[3] = new tagDBPROP(ODB.DBPROP_IColumnsRowset, false, true);
}
}
propSet.SetPropertySet(0, OleDbPropertySetGuid.Rowset, dbprops);
}
return propSet;
}
internal Bindings TakeBindingOwnerShip() {
Bindings bindings = _dbBindings;
_dbBindings = null;
return bindings;
}
private void ValidateConnection(string method) {
if (null == _connection) {
throw ADP.ConnectionRequired(method);
}
_connection.CheckStateOpen(method);
// user attempting to execute the command while the first dataReader hasn't returned
// use the connection reference collection to see if the dataReader referencing this
// command has been garbage collected or not.
if (_hasDataReader) {
if (_connection.HasLiveReader(this)) {
throw ADP.OpenReaderExists();
}
_hasDataReader = false;
}
}
private void ValidateConnectionAndTransaction(string method) {
ValidateConnection(method);
_transaction = _connection.ValidateTransaction(Transaction, method);
this.canceling = false;
}
}
}
| |
using System;
using System.Net.Sockets;
using System.Text;
namespace Kato
{
/// <summary>
/// Maintains the current state for a SMTP client connection.
/// </summary>
/// <remarks>
/// This class is similar to a HTTP Session. It is used to maintain all
/// the state information about the current connection.
/// </remarks>
public class SmtpContext
{
private const string Eol = "\r\n";
/// <summary>The unique ID assigned to this connection</summary>
private readonly long _connectionId;
/// <summary>The socket to the client.</summary>
private readonly Socket _socket;
private readonly ILog _logger;
/// <summary>Last successful command received.</summary>
private int _lastCommand;
/// <summary>The incoming message.</summary>
private SmtpMessageData _messageData;
/// <summary>Encoding to use to send/receive data from the socket.</summary>
private readonly Encoding _encoding;
/// <summary>
/// It is possible that more than one line will be in
/// the queue at any one time, so we need to store any input
/// that has been read from the socket but not requested by the
/// ReadLine command yet.
/// </summary>
private StringBuilder _inputBuffer;
/// <summary>
/// Initialize this context for a given socket connection.
/// </summary>
public SmtpContext(long connectionId, Socket socket, ILog logger)
{
_logger = logger ?? new NullLogger();
_logger.Debug("Connection {0}: New connection from client {1}", connectionId, socket.RemoteEndPoint);
_connectionId = connectionId;
_lastCommand = -1;
_socket = socket;
_messageData = new SmtpMessageData();
// Set the encoding to ASCII.
_encoding = Encoding.ASCII;
// Initialize the input buffer
_inputBuffer = new StringBuilder();
}
/// <summary>
/// The unique connection id.
/// </summary>
public long ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Last successful command received.
/// </summary>
public int LastCommand
{
get
{
return _lastCommand;
}
set
{
_lastCommand = value;
}
}
/// <summary>
/// The client domain, as specified by the helo command.
/// </summary>
public string ClientDomain { get; set; }
/// <summary>
/// The Socket that is connected to the client.
/// </summary>
public Socket Socket
{
get
{
return _socket;
}
}
/// <summary>
/// The SMTPMessage that is currently being received.
/// </summary>
public SmtpMessageData MessageData
{
get
{
return _messageData;
}
set
{
_messageData = value;
}
}
/// <summary>
/// Writes the string to the socket as an entire line. This
/// method will append the end of line characters, so the data
/// parameter should not contain them.
/// </summary>
/// <param name="data">The data to write the the client.</param>
public void WriteLine(string data)
{
_logger.Debug("Connection {0}: Wrote Line: {1}", _connectionId, data);
_socket.Send(_encoding.GetBytes(data + Eol));
}
/// <summary>
/// Reads an entire line from the socket. This method
/// will block until an entire line has been read.
/// </summary>
public string ReadLine()
{
// If we already buffered another line, just return
// from the buffer.
var output = ReadBuffer();
if (output != null)
{
return output;
}
// Otherwise, read more input.
var byteBuffer = new byte[80];
// Read from the socket until an entire line has been read.
do
{
// Read the input data.
var count = _socket.Receive(byteBuffer);
if (count == 0)
{
_logger.Debug("Socket closed before end of line received.");
return null;
}
_inputBuffer.Append(_encoding.GetString(byteBuffer, 0, count));
_logger.Debug("Connection {0}: Read: {1}", _connectionId, _inputBuffer);
}
while((output = ReadBuffer()) == null);
// IO Log statement is in ReadBuffer...
return output;
}
/// <summary>
/// Resets this context for a new message
/// </summary>
public void Reset()
{
_logger.Debug("Connection {0}: Reset", _connectionId);
_messageData = new SmtpMessageData();
_lastCommand = SmtpHandler.CommandHelo;
}
/// <summary>
/// Closes the socket connection to the client and performs any cleanup.
/// </summary>
public void Close()
{
_socket.Close();
}
/// <summary>
/// Helper method that returns the first full line in
/// the input buffer, or null if there is no line in the buffer.
/// If a line is found, it will also be removed from the buffer.
/// </summary>
private string ReadBuffer()
{
// If the buffer has data, check for a full line.
if (_inputBuffer.Length > 0)
{
var buffer = _inputBuffer.ToString();
var eolIndex = buffer.IndexOf(Eol);
if (eolIndex != -1)
{
var output = buffer.Substring(0, eolIndex);
_inputBuffer = new StringBuilder(buffer.Substring(eolIndex + 2));
_logger.Debug("Connection {0}: Read Line: {1}", _connectionId, output);
return output;
}
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using umbraco.interfaces;
using Umbraco.Core.Configuration;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Sync
{
/// <summary>
/// An <see cref="IServerMessenger"/> that works by storing messages in the database.
/// </summary>
//
// this messenger writes ALL instructions to the database,
// but only processes instructions coming from remote servers,
// thus ensuring that instructions run only once
//
public class DatabaseServerMessenger : ServerMessengerBase
{
private readonly ApplicationContext _appContext;
private readonly ManualResetEvent _syncIdle;
private readonly object _locko = new object();
private readonly ILogger _logger;
private int _lastId = -1;
private DateTime _lastSync;
private DateTime _lastPruned;
private bool _initialized;
private bool _syncing;
private bool _released;
private readonly ProfilingLogger _profilingLogger;
private readonly Lazy<string> _distCacheFilePath = new Lazy<string>(GetDistCacheFilePath);
protected DatabaseServerMessengerOptions Options { get; private set; }
protected ApplicationContext ApplicationContext { get { return _appContext; } }
public DatabaseServerMessenger(ApplicationContext appContext, bool distributedEnabled, DatabaseServerMessengerOptions options)
: base(distributedEnabled)
{
if (appContext == null) throw new ArgumentNullException("appContext");
if (options == null) throw new ArgumentNullException("options");
_appContext = appContext;
Options = options;
_lastPruned = _lastSync = DateTime.UtcNow;
_syncIdle = new ManualResetEvent(true);
_profilingLogger = appContext.ProfilingLogger;
_logger = appContext.ProfilingLogger.Logger;
}
#region Messenger
protected override bool RequiresDistributed(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType dispatchType)
{
// we don't care if there's servers listed or not,
// if distributed call is enabled we will make the call
return _initialized && DistributedEnabled;
}
protected override void DeliverRemote(
IEnumerable<IServerAddress> servers,
ICacheRefresher refresher,
MessageType messageType,
IEnumerable<object> ids = null,
string json = null)
{
var idsA = ids == null ? null : ids.ToArray();
Type idType;
if (GetArrayType(idsA, out idType) == false)
throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids");
var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);
var dto = new CacheInstructionDto
{
UtcStamp = DateTime.UtcNow,
Instructions = JsonConvert.SerializeObject(instructions, Formatting.None),
OriginIdentity = LocalIdentity
};
ApplicationContext.DatabaseContext.Database.Insert(dto);
}
#endregion
#region Sync
/// <summary>
/// Boots the messenger.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
protected void Boot()
{
// weight:10, must release *before* the facade service, because once released
// the service will *not* be able to properly handle our notifications anymore
const int weight = 10;
var registered = ApplicationContext.MainDom.Register(
() =>
{
lock (_locko)
{
_released = true; // no more syncs
}
// wait a max of 5 seconds and then return, so that we don't block
// the entire MainDom callbacks chain and prevent the AppDomain from
// properly releasing MainDom - a timeout here means that one refresher
// is taking too much time processing, however when it's done we will
// not update lastId and stop everything
var idle =_syncIdle.WaitOne(5000);
if (idle == false)
{
_logger.Warn<DatabaseServerMessenger>("The wait lock timed out, application is shutting down. The current instruction batch will be re-processed.");
}
},
weight);
if (registered == false)
return;
ReadLastSynced(); // get _lastId
EnsureInstructions(); // reset _lastId if instrs are missing
Initialize(); // boot
}
/// <summary>
/// Initializes a server that has never synchronized before.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
private void Initialize()
{
lock (_locko)
{
if (_released) return;
var coldboot = false;
if (_lastId < 0) // never synced before
{
// we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new
// server and it will need to rebuild it's own caches, eg Lucene or the xml cache file.
_logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install."
+ " The server will build its caches and indexes, and then adjust its last synced Id to the latest found in"
+ " the database and maintain cache updates based on that Id.");
coldboot = true;
}
else
{
//check for how many instructions there are to process
//TODO: In 7.6 we need to store the count of instructions per row since this is not affective because there can be far more than one (if not thousands)
// of instructions in a single row.
var count = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoCacheInstruction WHERE id > @lastId", new {lastId = _lastId});
if (count > Options.MaxProcessingInstructionCount)
{
//too many instructions, proceed to cold boot
_logger.Warn<DatabaseServerMessenger>("The instruction count ({0}) exceeds the specified MaxProcessingInstructionCount ({1})."
+ " The server will skip existing instructions, rebuild its caches and indexes entirely, adjust its last synced Id"
+ " to the latest found in the database and maintain cache updates based on that Id.",
() => count, () => Options.MaxProcessingInstructionCount);
coldboot = true;
}
}
if (coldboot)
{
// go get the last id in the db and store it
// note: do it BEFORE initializing otherwise some instructions might get lost
// when doing it before, some instructions might run twice - not an issue
var maxId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction");
//if there is a max currently, or if we've never synced
if (maxId > 0 || _lastId < 0)
SaveLastSynced(maxId);
// execute initializing callbacks
if (Options.InitializingCallbacks != null)
foreach (var callback in Options.InitializingCallbacks)
callback();
}
_initialized = true;
}
}
/// <summary>
/// Synchronize the server (throttled).
/// </summary>
protected void Sync()
{
lock (_locko)
{
if (_syncing)
return;
//Don't continue if we are released
if (_released)
return;
if ((DateTime.UtcNow - _lastSync).TotalSeconds <= Options.ThrottleSeconds)
return;
//Set our flag and the lock to be in it's original state (i.e. it can be awaited)
_syncing = true;
_syncIdle.Reset();
_lastSync = DateTime.UtcNow;
}
try
{
using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database..."))
{
ProcessDatabaseInstructions();
//Check for pruning throttling
if ((_released || (DateTime.UtcNow - _lastPruned).TotalSeconds <= Options.PruneThrottleSeconds))
return;
_lastPruned = _lastSync;
switch (_appContext.GetCurrentServerRole())
{
case ServerRole.Single:
case ServerRole.Master:
PruneOldInstructions();
break;
}
}
}
finally
{
lock (_locko)
{
//We must reset our flag and signal any waiting locks
_syncing = false;
}
_syncIdle.Set();
}
}
/// <summary>
/// Process instructions from the database.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
/// <returns>
/// Returns the number of processed instructions
/// </returns>
private void ProcessDatabaseInstructions()
{
// NOTE
// we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that
// would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests
// (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are
// pending requests after being processed, they'll just be processed on the next poll.
//
// FIXME not true if we're running on a background thread, assuming we can?
var sql = new Sql().Select("*")
.From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax)
.Where<CacheInstructionDto>(dto => dto.Id > _lastId)
.OrderBy<CacheInstructionDto>(dto => dto.Id, _appContext.DatabaseContext.SqlSyntax);
//only retrieve the top 100 (just in case there's tons)
// even though MaxProcessingInstructionCount is by default 1000 we still don't want to process that many
// rows in one request thread since each row can contain a ton of instructions (until 7.5.5 in which case
// a row can only contain MaxProcessingInstructionCount)
var topSql = _appContext.DatabaseContext.SqlSyntax.SelectTop(sql, 100);
// only process instructions coming from a remote server, and ignore instructions coming from
// the local server as they've already been processed. We should NOT assume that the sequence of
// instructions in the database makes any sense whatsoever, because it's all async.
var localIdentity = LocalIdentity;
var lastId = 0;
//tracks which ones have already been processed to avoid duplicates
var processed = new HashSet<RefreshInstruction>();
//It would have been nice to do this in a Query instead of Fetch using a data reader to save
// some memory however we cannot do thta because inside of this loop the cache refreshers are also
// performing some lookups which cannot be done with an active reader open
foreach (var dto in _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(topSql))
{
//If this flag gets set it means we're shutting down! In this case, we need to exit asap and cannot
// continue processing anything otherwise we'll hold up the app domain shutdown
if (_released)
{
break;
}
if (dto.OriginIdentity == localIdentity)
{
// just skip that local one but update lastId nevertheless
lastId = dto.Id;
continue;
}
// deserialize remote instructions & skip if it fails
JArray jsonA;
try
{
jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions);
}
catch (JsonException ex)
{
_logger.Error<DatabaseServerMessenger>(string.Format("Failed to deserialize instructions ({0}: \"{1}\").", dto.Id, dto.Instructions), ex);
lastId = dto.Id; // skip
continue;
}
var instructionBatch = GetAllInstructions(jsonA);
//process as per-normal
var success = ProcessDatabaseInstructions(instructionBatch, dto, processed, ref lastId);
//if they couldn't be all processed (i.e. we're shutting down) then exit
if (success == false)
{
_logger.Info<DatabaseServerMessenger>("The current batch of instructions was not processed, app is shutting down");
break;
}
}
if (lastId > 0)
SaveLastSynced(lastId);
}
/// <summary>
/// Processes the instruction batch and checks for errors
/// </summary>
/// <param name="instructionBatch"></param>
/// <param name="dto"></param>
/// <param name="processed">
/// Tracks which instructions have already been processed to avoid duplicates
/// </param>
/// <param name="lastId"></param>
/// <returns>
/// returns true if all instructions in the batch were processed, otherwise false if they could not be due to the app being shut down
/// </returns>
private bool ProcessDatabaseInstructions(IReadOnlyCollection<RefreshInstruction> instructionBatch, CacheInstructionDto dto, HashSet<RefreshInstruction> processed, ref int lastId)
{
// execute remote instructions & update lastId
try
{
var result = NotifyRefreshers(instructionBatch, processed);
if (result)
{
//if all instructions we're processed, set the last id
lastId = dto.Id;
}
return result;
}
//catch (ThreadAbortException ex)
//{
// //This will occur if the instructions processing is taking too long since this is occuring on a request thread.
// // Or possibly if IIS terminates the appdomain. In any case, we should deal with this differently perhaps...
//}
catch (Exception ex)
{
_logger.Error<DatabaseServerMessenger>(
string.Format("DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions (id: {0}, instruction count: {1}). Instruction is being skipped/ignored", dto.Id, instructionBatch.Count), ex);
//we cannot throw here because this invalid instruction will just keep getting processed over and over and errors
// will be thrown over and over. The only thing we can do is ignore and move on.
lastId = dto.Id;
return false;
}
////if this is returned it will not be saved
//return -1;
}
/// <summary>
/// Remove old instructions from the database
/// </summary>
/// <remarks>
/// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause
/// the site to cold boot if there's been no instruction activity for more than DaysToRetainInstructions.
/// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085
/// </remarks>
private void PruneOldInstructions()
{
var pruneDate = DateTime.UtcNow.AddDays(-Options.DaysToRetainInstructions);
// using 2 queries is faster than convoluted joins
var maxId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction;");
var delete = new Sql().Append(@"DELETE FROM umbracoCacheInstruction WHERE utcStamp < @pruneDate AND id < @maxId",
new { pruneDate, maxId });
_appContext.DatabaseContext.Database.Execute(delete);
}
/// <summary>
/// Ensure that the last instruction that was processed is still in the database.
/// </summary>
/// <remarks>
/// If the last instruction is not in the database anymore, then the messenger
/// should not try to process any instructions, because some instructions might be lost,
/// and it should instead cold-boot.
/// However, if the last synced instruction id is '0' and there are '0' records, then this indicates
/// that it's a fresh site and no user actions have taken place, in this circumstance we do not want to cold
/// boot. See: http://issues.umbraco.org/issue/U4-8627
/// </remarks>
private void EnsureInstructions()
{
if (_lastId == 0)
{
var sql = new Sql().Select("COUNT(*)")
.From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax);
var count = _appContext.DatabaseContext.Database.ExecuteScalar<int>(sql);
//if there are instructions but we haven't synced, then a cold boot is necessary
if (count > 0)
_lastId = -1;
}
else
{
var sql = new Sql().Select("*")
.From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax)
.Where<CacheInstructionDto>(dto => dto.Id == _lastId);
var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql);
//if the last synced instruction is not found in the db, then a cold boot is necessary
if (dtos.Count == 0)
_lastId = -1;
}
}
/// <summary>
/// Reads the last-synced id from file into memory.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void ReadLastSynced()
{
if (File.Exists(_distCacheFilePath.Value) == false) return;
var content = File.ReadAllText(_distCacheFilePath.Value);
int last;
if (int.TryParse(content, out last))
_lastId = last;
}
/// <summary>
/// Updates the in-memory last-synced id and persists it to file.
/// </summary>
/// <param name="id">The id.</param>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void SaveLastSynced(int id)
{
File.WriteAllText(_distCacheFilePath.Value, id.ToString(CultureInfo.InvariantCulture));
_lastId = id;
}
/// <summary>
/// Gets the unique local identity of the executing AppDomain.
/// </summary>
/// <remarks>
/// <para>It is not only about the "server" (machine name and appDomainappId), but also about
/// an AppDomain, within a Process, on that server - because two AppDomains running at the same
/// time on the same server (eg during a restart) are, practically, a LB setup.</para>
/// <para>Practically, all we really need is the guid, the other infos are here for information
/// and debugging purposes.</para>
/// </remarks>
protected static readonly string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER
+ "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT
+ " [P" + Process.GetCurrentProcess().Id // eg 1234
+ "/D" + AppDomain.CurrentDomain.Id // eg 22
+ "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique
private static string GetDistCacheFilePath()
{
var fileName = HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt";
string distCacheFilePath;
switch (GlobalSettings.LocalTempStorageLocation)
{
case LocalTempStorage.AspNetTemp:
distCacheFilePath = Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData", fileName);
break;
case LocalTempStorage.EnvironmentTemp:
var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1();
var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData",
//include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back
// to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not
// utilizing an old path
appDomainHash);
distCacheFilePath = Path.Combine(cachePath, fileName);
break;
case LocalTempStorage.Default:
default:
var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/DistCache");
distCacheFilePath = Path.Combine(tempFolder, fileName);
break;
}
//ensure the folder exists
var folder = Path.GetDirectoryName(distCacheFilePath);
if (folder == null)
throw new InvalidOperationException("The folder could not be determined for the file " + distCacheFilePath);
if (Directory.Exists(folder) == false)
Directory.CreateDirectory(folder);
return distCacheFilePath;
}
#endregion
#region Notify refreshers
private static ICacheRefresher GetRefresher(Guid id)
{
var refresher = CacheRefreshersResolver.Current.GetById(id);
if (refresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
return refresher;
}
private static IJsonCacheRefresher GetJsonRefresher(Guid id)
{
return GetJsonRefresher(GetRefresher(id));
}
private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
{
var jsonRefresher = refresher as IJsonCacheRefresher;
if (jsonRefresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + refresher.UniqueIdentifier + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
return jsonRefresher;
}
/// <summary>
/// Parses out the individual instructions to be processed
/// </summary>
/// <param name="jsonArray"></param>
/// <returns></returns>
private static List<RefreshInstruction> GetAllInstructions(IEnumerable<JToken> jsonArray)
{
var result = new List<RefreshInstruction>();
foreach (var jsonItem in jsonArray)
{
// could be a JObject in which case we can convert to a RefreshInstruction,
// otherwise it could be another JArray - in which case we'll iterate that.
var jsonObj = jsonItem as JObject;
if (jsonObj != null)
{
var instruction = jsonObj.ToObject<RefreshInstruction>();
result.Add(instruction);
}
else
{
var jsonInnerArray = (JArray)jsonItem;
result.AddRange(GetAllInstructions(jsonInnerArray)); // recurse
}
}
return result;
}
/// <summary>
/// executes the instructions against the cache refresher instances
/// </summary>
/// <param name="instructions"></param>
/// <param name="processed"></param>
/// <returns>
/// Returns true if all instructions were processed, otherwise false if the processing was interupted (i.e. app shutdown)
/// </returns>
private bool NotifyRefreshers(IEnumerable<RefreshInstruction> instructions, HashSet<RefreshInstruction> processed)
{
foreach (var instruction in instructions)
{
//Check if the app is shutting down, we need to exit if this happens.
if (_released)
{
return false;
}
//this has already been processed
if (processed.Contains(instruction))
continue;
switch (instruction.RefreshType)
{
case RefreshMethodType.RefreshAll:
RefreshAll(instruction.RefresherId);
break;
case RefreshMethodType.RefreshByGuid:
RefreshByGuid(instruction.RefresherId, instruction.GuidId);
break;
case RefreshMethodType.RefreshById:
RefreshById(instruction.RefresherId, instruction.IntId);
break;
case RefreshMethodType.RefreshByIds:
RefreshByIds(instruction.RefresherId, instruction.JsonIds);
break;
case RefreshMethodType.RefreshByJson:
RefreshByJson(instruction.RefresherId, instruction.JsonPayload);
break;
case RefreshMethodType.RemoveById:
RemoveById(instruction.RefresherId, instruction.IntId);
break;
}
processed.Add(instruction);
}
return true;
}
private static void RefreshAll(Guid uniqueIdentifier)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.RefreshAll();
}
private static void RefreshByGuid(Guid uniqueIdentifier, Guid id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds)
{
var refresher = GetRefresher(uniqueIdentifier);
foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds))
refresher.Refresh(id);
}
private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload)
{
var refresher = GetJsonRefresher(uniqueIdentifier);
refresher.Refresh(jsonPayload);
}
private static void RemoveById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Remove(id);
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.