context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse.StructuredData;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
namespace OpenSim.Framework.Monitoring
{
public class ServerStatsCollector
{
private readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly string LogHeader = "[SERVER STATS]";
public bool Enabled = false;
private static Dictionary<string, Stat> RegisteredStats = new Dictionary<string, Stat>();
public readonly string CategoryServer = "server";
public readonly string ContainerThreadpool = "threadpool";
public readonly string ContainerProcessor = "processor";
public readonly string ContainerMemory = "memory";
public readonly string ContainerNetwork = "network";
public readonly string ContainerProcess = "process";
public string NetworkInterfaceTypes = "Ethernet";
readonly int performanceCounterSampleInterval = 500;
// int lastperformanceCounterSampleTime = 0;
private class PerfCounterControl
{
public PerformanceCounter perfCounter;
public int lastFetch;
public string name;
public PerfCounterControl(PerformanceCounter pPc)
: this(pPc, String.Empty)
{
}
public PerfCounterControl(PerformanceCounter pPc, string pName)
{
perfCounter = pPc;
lastFetch = 0;
name = pName;
}
}
PerfCounterControl processorPercentPerfCounter = null;
// IRegionModuleBase.Initialize
public void Initialise(IConfigSource source)
{
IConfig cfg = source.Configs["Monitoring"];
if (cfg != null)
Enabled = cfg.GetBoolean("ServerStatsEnabled", true);
if (Enabled)
{
NetworkInterfaceTypes = cfg.GetString("NetworkInterfaceTypes", "Ethernet");
}
}
public void Start()
{
if (RegisteredStats.Count == 0)
RegisterServerStats();
}
public void Close()
{
if (RegisteredStats.Count > 0)
{
foreach (Stat stat in RegisteredStats.Values)
{
StatsManager.DeregisterStat(stat);
stat.Dispose();
}
RegisteredStats.Clear();
}
}
private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act)
{
MakeStat(pName, pDesc, pUnit, pContainer, act, MeasuresOfInterest.None);
}
private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act, MeasuresOfInterest moi)
{
string desc = pDesc;
if (desc == null)
desc = pName;
Stat stat = new Stat(pName, pName, desc, pUnit, CategoryServer, pContainer, StatType.Pull, moi, act, StatVerbosity.Debug);
StatsManager.RegisterStat(stat);
RegisteredStats.Add(pName, stat);
}
public void RegisterServerStats()
{
// lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
PerformanceCounter tempPC;
Stat tempStat;
string tempName;
try
{
tempName = "CPUPercent";
tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
processorPercentPerfCounter = new PerfCounterControl(tempPC);
// A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter, Util.IsWindows() ? 1 : -1); },
StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
RegisteredStats.Add(tempName, tempStat);
MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; });
MakeStat("UserProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().UserProcessorTime.TotalSeconds; });
MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds; });
MakeStat("Threads", null, "threads", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e);
}
MakeStat("BuiltinThreadpoolWorkerThreadsAvailable", null, "threads", ContainerThreadpool,
s =>
{
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
s.Value = workerThreads;
});
MakeStat("BuiltinThreadpoolIOCPThreadsAvailable", null, "threads", ContainerThreadpool,
s =>
{
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
s.Value = iocpThreads;
});
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool && Util.GetSmartThreadPoolInfo() != null)
{
MakeStat("STPMaxThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxThreads);
MakeStat("STPMinThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MinThreads);
MakeStat("STPConcurrency", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxConcurrentWorkItems);
MakeStat("STPActiveThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().ActiveThreads);
MakeStat("STPInUseThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().InUseThreads);
MakeStat("STPWorkItemsWaiting", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().WaitingCallbacks);
}
MakeStat(
"HTTPRequestsMade",
"Number of outbound HTTP requests made",
"requests",
ContainerNetwork,
s => s.Value = WebUtil.RequestNumber,
MeasuresOfInterest.AverageChangeOverTime);
try
{
List<string> okInterfaceTypes = new List<string>(NetworkInterfaceTypes.Split(','));
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (nic.OperationalStatus != OperationalStatus.Up)
continue;
string nicInterfaceType = nic.NetworkInterfaceType.ToString();
if (!okInterfaceTypes.Contains(nicInterfaceType))
{
m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.",
LogHeader, nic.Name, nicInterfaceType);
m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}",
LogHeader, NetworkInterfaceTypes);
continue;
}
if (nic.Supports(NetworkInterfaceComponent.IPv4))
{
IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics();
if (nicStats != null)
{
MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesReceived; }, 1024.0); });
MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesSent; }, 1024.0); });
MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesSent + ns.BytesReceived; }, 1024.0); });
}
}
// TODO: add IPv6 (it may actually happen someday)
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e);
}
MakeStat("ProcessMemory", null, "MB", ContainerMemory,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d, 3); });
MakeStat("HeapMemory", null, "MB", ContainerMemory,
(s) => { s.Value = Math.Round(GC.GetTotalMemory(false) / 1024d / 1024d, 3); });
MakeStat("LastHeapAllocationRate", null, "MB/sec", ContainerMemory,
(s) => { s.Value = Math.Round(MemoryWatchdog.LastHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
MakeStat("AverageHeapAllocationRate", null, "MB/sec", ContainerMemory,
(s) => { s.Value = Math.Round(MemoryWatchdog.AverageHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
}
// Notes on performance counters:
// "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
// "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
// "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
private delegate double PerfCounterNextValue();
private void GetNextValue(Stat stat, PerfCounterControl perfControl)
{
GetNextValue(stat, perfControl, 1.0);
}
private void GetNextValue(Stat stat, PerfCounterControl perfControl, double factor)
{
if (Environment.TickCount - perfControl.lastFetch > performanceCounterSampleInterval)
{
if (perfControl != null && perfControl.perfCounter != null)
{
try
{
// Kludge for factor to run double duty. If -1, subtract the value from one
if (factor == -1)
stat.Value = 1 - perfControl.perfCounter.NextValue();
else
stat.Value = perfControl.perfCounter.NextValue() / factor;
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
}
perfControl.lastFetch = Environment.TickCount;
}
}
}
// Lookup the nic that goes with this stat and set the value by using a fetch action.
// Not sure about closure with delegates inside delegates.
private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
{
// Get the one nic that has the name of this stat
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
(network) => network.Name == stat.Description);
try
{
foreach (NetworkInterface nic in nics)
{
IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
if (intrStats != null)
{
double newVal = Math.Round(getter(intrStats) / factor, 3);
stat.Value = newVal;
}
break;
}
}
catch
{
// There are times interfaces go away so we just won't update the stat for this
m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
}
}
}
public class ServerStatsAggregator : Stat
{
public ServerStatsAggregator(
string shortName,
string name,
string description,
string unitName,
string category,
string container
)
: base(
shortName,
name,
description,
unitName,
category,
container,
StatType.Push,
MeasuresOfInterest.None,
null,
StatVerbosity.Info)
{
}
public override string ToConsoleString()
{
StringBuilder sb = new StringBuilder();
return sb.ToString();
}
public override OSDMap ToOSDMap()
{
OSDMap ret = new OSDMap();
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
namespace Umbraco.Tests.PublishedContent
{
/// <summary>
/// Unit tests for IPublishedContent and extensions
/// </summary>
[TestFixture]
public class PublishedContentDataTableTests : BaseRoutingTest
{
public override void Initialize()
{
base.Initialize();
// need to specify a custom callback for unit tests
// AutoPublishedContentTypes generates properties automatically
var type = new AutoPublishedContentType(0, "anything", new PublishedPropertyType[] {});
PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
// need to specify a different callback for testing
PublishedContentExtensions.GetPropertyAliasesAndNames = s =>
{
var userFields = new Dictionary<string, string>()
{
{"property1", "Property 1"},
{"property2", "Property 2"}
};
if (s == "Child")
{
userFields.Add("property4", "Property 4");
}
else
{
userFields.Add("property3", "Property 3");
}
//ensure the standard fields are there
var allFields = new Dictionary<string, string>()
{
{"Id", "Id"},
{"NodeName", "NodeName"},
{"NodeTypeAlias", "NodeTypeAlias"},
{"CreateDate", "CreateDate"},
{"UpdateDate", "UpdateDate"},
{"CreatorName", "CreatorName"},
{"WriterName", "WriterName"},
{"Url", "Url"}
};
foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key)))
{
allFields.Add(f.Key, f.Value);
}
return allFields;
};
var routingContext = GetRoutingContext("/test");
//set the UmbracoContext.Current since the extension methods rely on it
UmbracoContext.Current = routingContext.UmbracoContext;
}
public override void TearDown()
{
base.TearDown();
Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null;
UmbracoContext.Current = null;
}
[Test]
public void To_DataTable()
{
var doc = GetContent(true, 1);
var dt = doc.ChildrenAsTable();
Assert.AreEqual(11, dt.Columns.Count);
Assert.AreEqual(3, dt.Rows.Count);
Assert.AreEqual("value4", dt.Rows[0]["Property 1"]);
Assert.AreEqual("value5", dt.Rows[0]["Property 2"]);
Assert.AreEqual("value6", dt.Rows[0]["Property 4"]);
Assert.AreEqual("value7", dt.Rows[1]["Property 1"]);
Assert.AreEqual("value8", dt.Rows[1]["Property 2"]);
Assert.AreEqual("value9", dt.Rows[1]["Property 4"]);
Assert.AreEqual("value10", dt.Rows[2]["Property 1"]);
Assert.AreEqual("value11", dt.Rows[2]["Property 2"]);
Assert.AreEqual("value12", dt.Rows[2]["Property 4"]);
}
[Test]
public void To_DataTable_With_Filter()
{
var doc = GetContent(true, 1);
//change a doc type alias
((TestPublishedContent) doc.Children.ElementAt(0)).DocumentTypeAlias = "DontMatch";
var dt = doc.ChildrenAsTable("Child");
Assert.AreEqual(11, dt.Columns.Count);
Assert.AreEqual(2, dt.Rows.Count);
Assert.AreEqual("value7", dt.Rows[0]["Property 1"]);
Assert.AreEqual("value8", dt.Rows[0]["Property 2"]);
Assert.AreEqual("value9", dt.Rows[0]["Property 4"]);
Assert.AreEqual("value10", dt.Rows[1]["Property 1"]);
Assert.AreEqual("value11", dt.Rows[1]["Property 2"]);
Assert.AreEqual("value12", dt.Rows[1]["Property 4"]);
}
[Test]
public void To_DataTable_No_Rows()
{
var doc = GetContent(false, 1);
var dt = doc.ChildrenAsTable();
//will return an empty data table
Assert.AreEqual(0, dt.Columns.Count);
Assert.AreEqual(0, dt.Rows.Count);
}
private IPublishedContent GetContent(bool createChildren, int indexVals)
{
var contentTypeAlias = createChildren ? "Parent" : "Child";
var d = new TestPublishedContent
{
CreateDate = DateTime.Now,
CreatorId = 1,
CreatorName = "Shannon",
DocumentTypeAlias = contentTypeAlias,
DocumentTypeId = 2,
Id = 3,
SortOrder = 4,
TemplateId = 5,
UpdateDate = DateTime.Now,
Path = "-1,3",
UrlName = "home-page",
Name = "Page" + Guid.NewGuid().ToString(),
Version = Guid.NewGuid(),
WriterId = 1,
WriterName = "Shannon",
Parent = null,
Level = 1,
Properties = new Collection<IPublishedProperty>(
new List<IPublishedProperty>()
{
new PropertyResult("property1", "value" + indexVals, Guid.NewGuid(), PropertyResultType.UserProperty),
new PropertyResult("property2", "value" + (indexVals + 1), Guid.NewGuid(), PropertyResultType.UserProperty)
}),
Children = new List<IPublishedContent>()
};
if (createChildren)
{
d.Children = new List<IPublishedContent>()
{
GetContent(false, indexVals + 3),
GetContent(false, indexVals + 6),
GetContent(false, indexVals + 9)
};
}
if (!createChildren)
{
//create additional columns, used to test the different columns for child nodes
d.Properties.Add(new PropertyResult("property4", "value" + (indexVals + 2), Guid.NewGuid(), PropertyResultType.UserProperty));
}
else
{
d.Properties.Add(new PropertyResult("property3", "value" + (indexVals + 2), Guid.NewGuid(), PropertyResultType.UserProperty));
}
return d;
}
// note - could probably rewrite those tests using SolidPublishedContentCache
// l8tr...
private class TestPublishedContent : IPublishedContent
{
public string Url { get; set; }
public PublishedItemType ItemType { get; set; }
IPublishedContent IPublishedContent.Parent
{
get { return Parent; }
}
IEnumerable<IPublishedContent> IPublishedContent.Children
{
get { return Children; }
}
public IPublishedContent Parent { get; set; }
public int Id { get; set; }
public int TemplateId { get; set; }
public int SortOrder { get; set; }
public string Name { get; set; }
public string UrlName { get; set; }
public string DocumentTypeAlias { get; set; }
public int DocumentTypeId { get; set; }
public string WriterName { get; set; }
public string CreatorName { get; set; }
public int WriterId { get; set; }
public int CreatorId { get; set; }
public string Path { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
public Guid Version { get; set; }
public int Level { get; set; }
public bool IsDraft { get; set; }
public int GetIndex() { throw new NotImplementedException();}
public ICollection<IPublishedProperty> Properties { get; set; }
public object this[string propertyAlias]
{
get { return GetProperty(propertyAlias).Value; }
}
public IEnumerable<IPublishedContent> Children { get; set; }
public IPublishedProperty GetProperty(string alias)
{
return Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias));
}
public IPublishedProperty GetProperty(string alias, bool recurse)
{
var property = GetProperty(alias);
if (recurse == false) return property;
IPublishedContent content = this;
while (content != null && (property == null || property.HasValue == false))
{
content = content.Parent;
property = content == null ? null : content.GetProperty(alias);
}
return property;
}
public IEnumerable<IPublishedContent> ContentSet
{
get { throw new NotImplementedException(); }
}
public PublishedContentType ContentType
{
get { throw new NotImplementedException(); }
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Type.cs
//
// 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.Reflection;
using Dot42;
using Dot42.Internal;
using Java.Lang.Reflect;
namespace System
{
/*abstract*/ partial class Type : ICustomAttributeProvider
{
/// <summary>
/// Gets the assembly-qualified name of the Type, which includes the name of the assembly from which the Type was loaded.
/// Not implemented.
/// </summary>
public string AssemblyQualifiedName
{
get { throw new NotImplementedException("System.Type.AssemblyQualifiedName"); }
}
/// <summary>
/// Gets the type name and namespace.
/// </summary>
public string FullName
{
get { return JavaGetName(); }
}
/// <summary>
/// Gets the type name without namespace.
/// </summary>
public string Name
{
get { return GetSimpleName(); }
}
/// <summary>
/// Is the given type a value type.
/// This will always return false, since Android does not support value types.
/// </summary>
public bool IsValueType
{
get { return false; }
}
public bool IsGenericType
{
get { return this.GetTypeParameters().Length > 0; }
}
/// <summary>
/// Is this a serializable type?
/// </summary>
/// <remarks>Not implemented, always returns false.</remarks>
public bool IsSerializable
{
get { return false; }
}
public bool IsSealed
{
get { return Modifier.IsFinal(this.GetModifiers()); }
}
public Type GetGenericTypeDefinition()
{
throw new NotImplementedException("System.Type.GetGenericTypeDefinition");
}
public Type[] GetGenericArguments()
{
throw new NotImplementedException("System.Type.GetGenericArguments");
}
public static TypeCode GetTypeCode(Type t)
{
throw new NotImplementedException("System.Type.GetTypeCode");
}
public Type MakeGenericType(params Type[] typeArguments)
{
throw new NotImplementedException("System.Type.MakeGenericType");
}
[DexNative]
public static Type GetTypeFromHandle(RuntimeTypeHandle handle)
{
return null;
}
/// <summary>
/// Returns an array of all attributes defined on this member.
/// Returns an empty array if no attributes are defined on this member.
/// </summary>
/// <param name="inherit">If true, look in base classes for inherited custom attributes.</param>
public object[] GetCustomAttributes(bool inherit)
{
return CustomAttributeProvider.GetCustomAttributes(this, inherit);
}
/// <summary>
/// Returns an array of all attributes defined on this member of the given attribute type.
/// Returns an empty array if no attributes are defined on this member.
/// </summary>
/// <param name="inherit">If true, look in base classes for inherited custom attributes.</param>
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return CustomAttributeProvider.GetCustomAttributes(this, attributeType, inherit);
}
/// <summary>
/// are one or more attributes of the given type defined on this member.
/// </summary>
/// <param name="attributeType">The type of the custom attribute</param>
/// <param name="inherit">If true, look in base classes for inherited custom attributes.</param>
public bool IsDefined(Type attributeType, bool inherit)
{
return CustomAttributeProvider.IsDefined(this, attributeType, inherit);
}
/// <summary>
/// Gets all public constructors of this type.
/// </summary>
public ConstructorInfo[] GetConstructors()
{
return JavaGetConstructors().Where(x => x.IsPublic);
}
/// <summary>
/// Gets all fields of this type that match the given binding flags.
/// </summary>
public ConstructorInfo[] GetConstructors(BindingFlags flags)
{
var ctors = ((flags & BindingFlags.DeclaredOnly) != 0) ? GetDeclaredConstructors() : JavaGetConstructors();
return ctors.Where(x => Matches(x.GetModifiers(), flags));
}
/// <summary>
/// Gets all public fields of this type.
/// </summary>
public FieldInfo[] GetFields()
{
return JavaGetFields().Where(x => x.IsPublic);
}
/// <summary>
/// Gets all fields of this type that match the given binding flags.
/// </summary>
public FieldInfo[] GetFields(BindingFlags flags)
{
var fields = ((flags & BindingFlags.DeclaredOnly) != 0) ? GetDeclaredFields() : JavaGetFields();
return fields.Where(x => Matches(x.GetModifiers(), flags));
}
/// <summary>
/// Gets all public methods of this type.
/// </summary>
public MethodInfo[] GetMethods()
{
return JavaGetMethods().Where(x => x.IsPublic);
}
/// <summary>
/// Gets all methods of this type that match the given binding flags.
/// </summary>
public MethodInfo[] GetMethods(BindingFlags flags)
{
var methods = ((flags & BindingFlags.DeclaredOnly) != 0) ? GetDeclaredMethods() : JavaGetMethods();
return methods.Where(x => Matches(x.GetModifiers(), flags));
}
/// <summary>
/// Gets all public properties of this type.
/// </summary>
public PropertyInfo[] GetProperties()
{
return PropertyInfoProvider.GetProperties(this);
}
/// <summary>
/// Do the given modifiers of a member match the given binding flags?
/// </summary>
private static bool Matches(int modifiers, BindingFlags flags)
{
// Exclude instance members?
if (((flags & BindingFlags.Instance) == 0) && !Modifier.IsStatic(modifiers)) return false;
// Exclude static members?
if (((flags & BindingFlags.Static) == 0) && Modifier.IsStatic(modifiers)) return false;
// Exclude public members?
if (((flags & BindingFlags.Public) == 0) && Modifier.IsPublic(modifiers)) return false;
// Exclude nonpublic members?
if (((flags & BindingFlags.NonPublic) == 0) && !Modifier.IsPublic(modifiers)) return false;
return true;
}
public /*virtual*/ bool IsInstanceOfType(Object o)
{
if (o == null) return false;
return IsAssignableFrom(o.Type);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
#if FEATURE_CORECLR
namespace System.Reflection.Emit
{
using System;
using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.SymbolStore;
//-----------------------------------------------------------------------------------
// On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit
// relies on that assembly to write out managed PDBs.
//
// This file implements the minimum subset of ISymWrapper.dll required to restore
// that functionality. Namely, the SymWriter and SymDocumentWriter objects.
//
// Ideally we wouldn't need ISymWrapper.dll on desktop either - it's an ugly piece
// of legacy. We could just use this (or COM-interop code) everywhere, but we might
// have to worry about compatibility.
//
// We've now got a real implementation even when no debugger is attached. It's
// up to the runtime to ensure it doesn't provide us with an insecure writer
// (eg. diasymreader) in the no-trust scenarios (no debugger, partial-trust code).
//-----------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// SymWrapperCore is never instantiated and is used as an encapsulation class.
// It is our "ISymWrapper.dll" assembly within an assembly.
//------------------------------------------------------------------------------
class SymWrapperCore
{
//------------------------------------------------------------------------------
// Block instantiation
//------------------------------------------------------------------------------
private SymWrapperCore()
{
}
//------------------------------------------------------------------------------
// Implements Telesto's version of SymDocumentWriter (in the desktop world,
// this type is exposed from ISymWrapper.dll.)
//
// The only thing user code can do with this wrapper is to receive it from
// SymWriter.DefineDocument and pass it back to SymWriter.DefineSequencePoints.
//------------------------------------------------------------------------------
private unsafe class SymDocumentWriter : ISymbolDocumentWriter
{
//------------------------------------------------------------------------------
// Ctor
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal SymDocumentWriter(PunkSafeHandle pDocumentWriterSafeHandle)
{
m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle;
// The handle is actually a pointer to a native ISymUnmanagedDocumentWriter.
m_pDocWriter = (ISymUnmanagedDocumentWriter *)m_pDocumentWriterSafeHandle.DangerousGetHandle();
m_vtable = (ISymUnmanagedDocumentWriterVTable)(Marshal.PtrToStructure(m_pDocWriter->m_unmanagedVTable, typeof(ISymUnmanagedDocumentWriterVTable)));
}
//------------------------------------------------------------------------------
// Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.)
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal PunkSafeHandle GetUnmanaged()
{
return m_pDocumentWriterSafeHandle;
}
//=========================================================================================
// Public interface methods start here. (Well actually, they're all NotSupported
// stubs since that's what they are on the real ISymWrapper.dll.)
//=========================================================================================
//------------------------------------------------------------------------------
// SetSource() wrapper
//------------------------------------------------------------------------------
void ISymbolDocumentWriter.SetSource(byte[] source)
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
//------------------------------------------------------------------------------
// SetCheckSum() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte [] checkSum)
{
int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
[System.Security.SecurityCritical]
private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter * pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum);
//------------------------------------------------------------------------------
// This layout must match the unmanaged ISymUnmanagedDocumentWriter* COM vtable
// exactly. If a member is declared as an IntPtr rather than a delegate, it means
// we don't call that particular member.
//------------------------------------------------------------------------------
[System.Security.SecurityCritical]
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriterVTable
{
internal IntPtr QueryInterface;
internal IntPtr AddRef;
internal IntPtr Release;
internal IntPtr SetSource;
#if FEATURE_CORECLR
[System.Security.SecurityCritical]
#endif
internal DSetCheckSum SetCheckSum;
}
//------------------------------------------------------------------------------
// This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter
// COM object.
//------------------------------------------------------------------------------
[System.Security.SecurityCritical]
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriter
{
internal IntPtr m_unmanagedVTable;
}
//------------------------------------------------------------------------------
// Stores underlying ISymUnmanagedDocumentWriter* pointer (wrapped in a safehandle.)
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private PunkSafeHandle m_pDocumentWriterSafeHandle;
[SecurityCritical]
private ISymUnmanagedDocumentWriter * m_pDocWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
[SecurityCritical]
private ISymUnmanagedDocumentWriterVTable m_vtable;
} // class SymDocumentWriter
//------------------------------------------------------------------------------
// Implements Telesto's version of SymWriter (in the desktop world,
// this type is expored from ISymWrapper.dll.)
//------------------------------------------------------------------------------
internal unsafe class SymWriter : ISymbolWriter
{
//------------------------------------------------------------------------------
// Creates a SymWriter. The SymWriter is a managed wrapper around the unmanaged
// symbol writer provided by the runtime (ildbsymlib or diasymreader.dll).
//------------------------------------------------------------------------------
internal static ISymbolWriter CreateSymWriter()
{
return new SymWriter();
}
//------------------------------------------------------------------------------
// Basic ctor. You'd think this ctor would take the unmanaged symwriter object as an argument
// but to fit in with existing desktop code, the unmanaged writer is passed in
// through a subsequent call to InternalSetUnderlyingWriter
//------------------------------------------------------------------------------
private SymWriter()
{
}
//=========================================================================================
// Public interface methods start here.
//=========================================================================================
//------------------------------------------------------------------------------
// Initialize() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.Initialize(IntPtr emitter, String filename, bool fFullBuild)
{
int hr = m_vtable.Initialize(m_pWriter, emitter, filename, (IntPtr)0, fFullBuild);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// DefineDocument() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
ISymbolDocumentWriter ISymbolWriter.DefineDocument(String url,
Guid language,
Guid languageVendor,
Guid documentType)
{
PunkSafeHandle psymUnmanagedDocumentWriter = new PunkSafeHandle();
int hr = m_vtable.DefineDocument(m_pWriter, url, ref language, ref languageVendor, ref documentType, out psymUnmanagedDocumentWriter);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
if (psymUnmanagedDocumentWriter.IsInvalid)
{
return null;
}
return new SymDocumentWriter(psymUnmanagedDocumentWriter);
}
//------------------------------------------------------------------------------
// SetUserEntryPoint() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.SetUserEntryPoint(SymbolToken entryMethod)
{
int hr = m_vtable.SetUserEntryPoint(m_pWriter, entryMethod.GetToken());
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// OpenMethod() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.OpenMethod(SymbolToken method)
{
int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken());
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// CloseMethod() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.CloseMethod()
{
int hr = m_vtable.CloseMethod(m_pWriter);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// DefineSequencePoints() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.DefineSequencePoints(ISymbolDocumentWriter document,
int[] offsets,
int[] lines,
int[] columns,
int[] endLines,
int[] endColumns)
{
int spCount = 0;
if (offsets != null)
{
spCount = offsets.Length;
}
else if (lines != null)
{
spCount = lines.Length;
}
else if (columns != null)
{
spCount = columns.Length;
}
else if (endLines != null)
{
spCount = endLines.Length;
}
else if (endColumns != null)
{
spCount = endColumns.Length;
}
if (spCount == 0)
{
return;
}
if ( (offsets != null && offsets.Length != spCount) ||
(lines != null && lines.Length != spCount) ||
(columns != null && columns.Length != spCount) ||
(endLines != null && endLines.Length != spCount) ||
(endColumns != null && endColumns.Length != spCount) )
{
throw new ArgumentException();
}
// Sure, claim to accept any type that implements ISymbolDocumentWriter but the only one that actually
// works is the one returned by DefineDocument. The desktop ISymWrapper commits the same signature fraud.
// Ideally we'd just return a sealed opaque cookie type, which had an internal accessor to
// get the writer out.
// Regardless, this cast is important for security - we cannot allow our caller to provide
// arbitrary instances of this interface.
SymDocumentWriter docwriter = (SymDocumentWriter)document;
int hr = m_vtable.DefineSequencePoints(m_pWriter, docwriter.GetUnmanaged(), spCount, offsets, lines, columns, endLines, endColumns);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// OpenScope() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
int ISymbolWriter.OpenScope(int startOffset)
{
int ret;
int hr = m_vtable.OpenScope(m_pWriter, startOffset, out ret);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
return ret;
}
//------------------------------------------------------------------------------
// CloseScope() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.CloseScope(int endOffset)
{
int hr = m_vtable.CloseScope(m_pWriter, endOffset);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// SetScopeRange() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.SetScopeRange(int scopeID, int startOffset, int endOffset)
{
int hr = m_vtable.SetScopeRange(m_pWriter, scopeID, startOffset, endOffset);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// DefineLocalVariable() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.DefineLocalVariable(String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3,
int startOffset,
int endOffset)
{
int hr = m_vtable.DefineLocalVariable(m_pWriter,
name,
(int)attributes,
signature.Length,
signature,
(int)addrKind,
addr1,
addr2,
addr3,
startOffset,
endOffset);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// DefineParameter() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.DefineParameter(String name,
ParameterAttributes attributes,
int sequence,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3)
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
//------------------------------------------------------------------------------
// DefineField() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.DefineField(SymbolToken parent,
String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3)
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
//------------------------------------------------------------------------------
// DefineGlobalVariable() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.DefineGlobalVariable(String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3)
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
//------------------------------------------------------------------------------
// Close() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.Close()
{
int hr = m_vtable.Close(m_pWriter);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// SetSymAttribute() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.SetSymAttribute(SymbolToken parent, String name, byte[] data)
{
int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// OpenNamespace() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.OpenNamespace(String name)
{
int hr = m_vtable.OpenNamespace(m_pWriter, name);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// CloseNamespace() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.CloseNamespace()
{
int hr = m_vtable.CloseNamespace(m_pWriter);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// UsingNamespace() wrapper
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void ISymbolWriter.UsingNamespace(String name)
{
int hr = m_vtable.UsingNamespace(m_pWriter, name);
if (hr < 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
//------------------------------------------------------------------------------
// SetMethodSourceRange() wrapper
//------------------------------------------------------------------------------
void ISymbolWriter.SetMethodSourceRange(ISymbolDocumentWriter startDoc,
int startLine,
int startColumn,
ISymbolDocumentWriter endDoc,
int endLine,
int endColumn)
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
//------------------------------------------------------------------------------
// SetUnderlyingWriter() wrapper.
//------------------------------------------------------------------------------
void ISymbolWriter.SetUnderlyingWriter(IntPtr ppUnderlyingWriter)
{
throw new NotSupportedException(); // Intentionally not supported on Telesto as it's a very unsafe api
}
//------------------------------------------------------------------------------
// InternalSetUnderlyingWriter() wrapper.
//
// Furnishes the native ISymUnmanagedWriter* pointer.
//
// The parameter is actually a pointer to a pointer to an ISymUnmanagedWriter. As
// with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers
// furnished through SetUnderlyingWriter. Lifetime management is entirely up to the caller.
//------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter)
{
m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter);
m_vtable = (ISymUnmanagedWriterVTable) (Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable)));
}
//------------------------------------------------------------------------------
// Define delegates for the unmanaged COM methods we invoke.
//------------------------------------------------------------------------------
[System.Security.SecurityCritical]
private delegate int DInitialize(ISymUnmanagedWriter* pthis,
IntPtr emitter, //IUnknown*
[MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR*
IntPtr pIStream, //IStream*
[MarshalAs(UnmanagedType.Bool)] bool fFullBuild
);
[System.Security.SecurityCritical]
private delegate int DDefineDocument(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String url,
[In] ref Guid language,
[In] ref Guid languageVender,
[In] ref Guid documentType,
[Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter
);
[System.Security.SecurityCritical]
private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod);
[System.Security.SecurityCritical]
private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod);
[System.Security.SecurityCritical]
private delegate int DCloseMethod(ISymUnmanagedWriter* pthis);
[System.Security.SecurityCritical]
private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis,
PunkSafeHandle document,
int spCount,
[In] int[] offsets,
[In] int[] lines,
[In] int[] columns,
[In] int[] endLines,
[In] int[] endColumns);
[System.Security.SecurityCritical]
private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval);
[System.Security.SecurityCritical]
private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset);
[System.Security.SecurityCritical]
private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset);
[System.Security.SecurityCritical]
private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String name,
int attributes,
int cSig,
[In] byte[] signature,
int addrKind,
int addr1,
int addr2,
int addr3,
int startOffset,
int endOffset
);
[System.Security.SecurityCritical]
private delegate int DClose(ISymUnmanagedWriter* pthis);
[System.Security.SecurityCritical]
private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis,
int parent,
[MarshalAs(UnmanagedType.LPWStr)] String name,
int cData,
[In] byte[] data
);
[System.Security.SecurityCritical]
private delegate int DOpenNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
[System.Security.SecurityCritical]
private delegate int DCloseNamespace(ISymUnmanagedWriter* pthis);
[System.Security.SecurityCritical]
private delegate int DUsingNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
//------------------------------------------------------------------------------
// This layout must match the unmanaged ISymUnmanagedWriter* COM vtable
// exactly. If a member is declared as an IntPtr rather than a delegate, it means
// we don't call that particular member.
//------------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedWriterVTable
{
internal IntPtr QueryInterface;
internal IntPtr AddRef;
internal IntPtr Release;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DDefineDocument DefineDocument;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DSetUserEntryPoint SetUserEntryPoint;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DOpenMethod OpenMethod;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DCloseMethod CloseMethod;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DOpenScope OpenScope;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DCloseScope CloseScope;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DSetScopeRange SetScopeRange;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DDefineLocalVariable DefineLocalVariable;
internal IntPtr DefineParameter;
internal IntPtr DefineField;
internal IntPtr DefineGlobalVariable;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DClose Close;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DSetSymAttribute SetSymAttribute;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DOpenNamespace OpenNamespace;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DCloseNamespace CloseNamespace;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DUsingNamespace UsingNamespace;
internal IntPtr SetMethodSourceRange;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DInitialize Initialize;
internal IntPtr GetDebugInfo;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal DDefineSequencePoints DefineSequencePoints;
}
//------------------------------------------------------------------------------
// This layout must match the (start) of the unmanaged ISymUnmanagedWriter
// COM object.
//------------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedWriter
{
internal IntPtr m_unmanagedVTable;
}
//------------------------------------------------------------------------------
// Stores native ISymUnmanagedWriter* pointer.
//
// As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer.
// Managing lifetime is up to the caller (coreclr.dll).
//------------------------------------------------------------------------------
[SecurityCritical]
private ISymUnmanagedWriter *m_pWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
private ISymUnmanagedWriterVTable m_vtable;
} // class SymWriter
} //class SymWrapperCore
//--------------------------------------------------------------------------------------
// SafeHandle for RAW MTA IUnknown's.
//
// ! Because the Release occurs in the finalizer thread, this safehandle really takes
// ! an ostrich approach to apartment issues. We only tolerate this here because we're emulating
// ! the desktop CLR's use of ISymWrapper which also pays lip service to COM apartment rules.
// !
// ! However, think twice about pulling this safehandle out for other uses.
//
// Had to make this a non-nested class since FCall's don't like to bind to nested classes.
//--------------------------------------------------------------------------------------
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
sealed class PunkSafeHandle : SafeHandle
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal PunkSafeHandle()
: base((IntPtr)0, true)
{
}
[SecurityCritical]
override protected bool ReleaseHandle()
{
m_Release(handle);
return true;
}
public override bool IsInvalid
{
[SecurityCritical]
get { return handle == ((IntPtr)0); }
}
private delegate void DRelease(IntPtr punk); // Delegate type for P/Invoking to coreclr.dll and doing an IUnknown::Release()
private static DRelease m_Release;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr nGetDReleaseTarget(); // FCall gets us the native DRelease target (so we don't need named dllexport from coreclr.dll)
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
static PunkSafeHandle()
{
m_Release = (DRelease)(Marshal.GetDelegateForFunctionPointer(nGetDReleaseTarget(), typeof(DRelease)));
m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation.
}
} // PunkSafeHandle
} //namespace System.Reflection.Emit
#endif //FEATURE_CORECLR
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
using OmniSharp.Models.FindImplementations;
using OmniSharp.Roslyn.CSharp.Services.Navigation;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class FindImplementationFacts : AbstractSingleRequestHandlerTestFixture<FindImplementationsService>
{
public FindImplementationFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.FindImplementations;
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindInterfaceTypeImplementation(string filename)
{
const string code = @"
public interface Som$$eInterface {}
public class SomeClass : SomeInterface {}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeClass", implementation.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindInterfaceMethodImplementation(string filename)
{
const string code = @"
public interface SomeInterface { void Some$$Method(); }
public class SomeClass : SomeInterface {
public void SomeMethod() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeMethod", implementation.Name);
Assert.Equal("SomeClass", implementation.ContainingType.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindInterfaceMethodOverride(string filename)
{
const string code = @"
public interface SomeInterface { void Some$$Method(); }
public class SomeClass : SomeInterface {
public virtual void SomeMethod() {}
}
public class SomeChildClass : SomeClass {
public override void SomeMethod() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
Assert.Equal(2, implementations.Count());
Assert.True(implementations.Any(x => x.ContainingType.Name == "SomeClass" && x.Name == "SomeMethod"), "Couldn't find SomeClass.SomeMethod in the discovered implementations");
Assert.True(implementations.Any(x => x.ContainingType.Name == "SomeChildClass" && x.Name == "SomeMethod"), "Couldn't find SomeChildClass.SomeMethod in the discovered implementations");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindOverride(string filename)
{
const string code = @"
public abstract class BaseClass { public abstract void Some$$Method(); }
public class SomeClass : BaseClass
{
public override void SomeMethod() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeMethod", implementation.Name);
Assert.Equal("SomeClass", implementation.ContainingType.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindSubclass(string filename)
{
const string code = @"
public abstract class BaseClass {}
public class SomeClass : Base$$Class {}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("SomeClass", implementation.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindTypeDeclaration(string filename)
{
const string code = @"
public class MyClass
{
public MyClass() { var other = new Other$$Class(); }
}
public class OtherClass
{
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("OtherClass", implementation.Name);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindMethodDeclaration(string filename)
{
const string code = @"
public class MyClass
{
public MyClass() { Fo$$o(); }
public void Foo() {}
}";
var implementations = await FindImplementationsAsync(code, filename);
var implementation = implementations.First();
Assert.Equal("Foo", implementation.Name);
Assert.Equal("MyClass", implementation.ContainingType.Name);
Assert.Equal(SymbolKind.Method, implementation.Kind);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindPartialClass(string filename)
{
const string code = @"
public partial class Some$$Class { void SomeMethod() {} }
public partial class SomeClass { void AnotherMethod() {} }";
var implementations = await FindImplementationsAsync(code, filename);
Assert.Equal(2, implementations.Count());
Assert.True(implementations.All(x => x.Name == "SomeClass"));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task CanFindPartialMethod(string filename)
{
const string code = @"
public partial class SomeClass { partial void Some$$Method(); }
public partial class SomeClass { partial void SomeMethod() { /* this is implementation of the partial method */ } }";
var implementations = await FindImplementationsAsync(code, filename);
Assert.Single(implementations);
var implementation = implementations.First();
Assert.Equal("SomeMethod", implementation.Name);
// Assert that the actual implementation part is returned.
Assert.True(implementation is IMethodSymbol method && method.PartialDefinitionPart != null && method.PartialImplementationPart == null);
}
private async Task<IEnumerable<ISymbol>> FindImplementationsAsync(string code, string filename)
{
var testFile = new TestFile(filename, code);
SharedOmniSharpTestHost.AddFilesToWorkspace(testFile);
var point = testFile.Content.GetPointFromPosition();
var requestHandler = GetRequestHandler(SharedOmniSharpTestHost);
var request = new FindImplementationsRequest
{
Line = point.Line,
Column = point.Offset,
FileName = testFile.FileName,
Buffer = testFile.Content.Code
};
var implementations = await requestHandler.Handle(request);
return await SymbolsFromQuickFixesAsync(SharedOmniSharpTestHost.Workspace, implementations.QuickFixes);
}
private async Task<IEnumerable<ISymbol>> SymbolsFromQuickFixesAsync(OmniSharpWorkspace workspace, IEnumerable<QuickFix> quickFixes)
{
var symbols = new List<ISymbol>();
foreach (var quickfix in quickFixes)
{
var document = workspace.GetDocument(Path.GetFileName(quickfix.FileName));
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(quickfix.Line, quickfix.Column));
var semanticModel = await document.GetSemanticModelAsync();
var symbol = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace);
symbols.Add(symbol);
}
return symbols;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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 NLog.Config;
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using Xunit;
public class TargetTests : NLogTestBase
{
[Fact]
public void InitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
// initialize was called once
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void InitializeFailedTest()
{
var target = new MyTarget();
target.ThrowOnInitialize = true;
LogManager.ThrowExceptions = true;
Assert.Throws<InvalidOperationException>(() => target.Initialize(null));
// after exception in Initialize(), the target becomes non-functional and all Write() operations
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(0, target.WriteCount);
Assert.Equal(1, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message);
Assert.Equal("Init error.", exceptions[0].InnerException.Message);
}
[Fact]
public void DoubleInitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Initialize(null);
// initialize was called once
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void DoubleCloseTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
target.Close();
// initialize and close were called once each
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void CloseWithoutInitializeTest()
{
var target = new MyTarget();
target.Close();
// nothing was called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void WriteWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
// write was not called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.Equal(4, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void WriteOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
// write was not called
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
// but all callbacks were invoked with null values
Assert.Equal(4, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void FlushTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Initialize(null);
target.Flush(exceptions.Add);
// flush was called
Assert.Equal(1, target.FlushCount);
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void FlushWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
// flush was not called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void FlushOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
// flush was not called
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void LockingTest()
{
var target = new MyTarget();
target.Initialize(null);
var mre = new ManualResetEvent(false);
Exception backgroundThreadException = null;
Thread t = new Thread(() =>
{
try
{
target.BlockingOperation(1000);
}
catch (Exception ex)
{
backgroundThreadException = ex;
}
finally
{
mre.Set();
}
});
target.Initialize(null);
t.Start();
Thread.Sleep(50);
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
target.Flush(exceptions.Add);
target.Close();
exceptions.ForEach(Assert.Null);
mre.WaitOne();
if (backgroundThreadException != null)
{
Assert.True(false, backgroundThreadException.ToString());
}
}
[Fact]
public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown()
{
var target = new MyTarget();
try
{
target.WriteAsyncLogEvents(null);
}
catch (Exception e)
{
Assert.True(false, "Exception thrown: " + e);
}
}
[Fact]
public void WriteFormattedStringEvent_WithNullArgument()
{
var target = new MyTarget();
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WriteFormattedStringEvent_EventWithNullArguments");
string t = null;
logger.Info("Testing null:{0}", t);
Assert.Equal(1, target.WriteCount);
}
public class MyTarget : Target
{
private int inBlockingOperation;
public int InitializeCount { get; set; }
public int CloseCount { get; set; }
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int WriteCount2 { get; set; }
public bool ThrowOnInitialize { get; set; }
public int WriteCount3 { get; set; }
protected override void InitializeTarget()
{
if (this.ThrowOnInitialize)
{
throw new InvalidOperationException("Init error.");
}
Assert.Equal(0, this.inBlockingOperation);
this.InitializeCount++;
base.InitializeTarget();
}
protected override void CloseTarget()
{
Assert.Equal(0, this.inBlockingOperation);
this.CloseCount++;
base.CloseTarget();
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Assert.Equal(0, this.inBlockingOperation);
this.FlushCount++;
base.FlushAsync(asyncContinuation);
}
protected override void Write(LogEventInfo logEvent)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount++;
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount2++;
base.Write(logEvent);
}
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount3++;
base.Write(logEvents);
}
public void BlockingOperation(int millisecondsTimeout)
{
lock (this.SyncRoot)
{
this.inBlockingOperation++;
Thread.Sleep(millisecondsTimeout);
this.inBlockingOperation--;
}
}
}
[Fact]
public void WrongMyTargetShouldThrowException()
{
Assert.Throws<NLogRuntimeException>(() =>
{
var target = new WrongMyTarget();
LogManager.ThrowExceptions = true;
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException");
logger.Info("Testing");
});
}
[Fact]
public void WrongMyTargetShouldNotThrowExceptionWhenThrowExceptionsIsFalse()
{
var target = new WrongMyTarget();
LogManager.ThrowExceptions = false;
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException");
logger.Info("Testing");
}
public class WrongMyTarget : Target
{
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected override void InitializeTarget()
{
//this is wrong. base.InitializeTarget() should be called
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.StaticWebAssets;
using Microsoft.AspNetCore.StaticWebAssets;
using Microsoft.Extensions.FileProviders;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Hosting.Tests.StaticWebAssets
{
public class ManifestStaticWebAssetsFileProviderTest
{
[Fact]
public void GetFileInfoPrefixRespectsOsCaseSensitivity()
{
// Arrange
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var expectedResult = OperatingSystem.IsWindows();
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new[] { Path.GetDirectoryName(typeof(ManifestStaticWebAssetsFileProviderTest).Assembly.Location) };
manifest.Root = new()
{
Children = new(comparer)
{
["_content"] = new()
{
Children = new(comparer)
{
["Microsoft.AspNetCore.Hosting.StaticWebAssets.xml"] = new()
{
Match = new()
{
ContentRoot = 0,
Path = "Microsoft.AspNetCore.Hosting.StaticWebAssets.xml"
}
}
}
}
}
};
var provider = new ManifestStaticWebAssetFileProvider(
manifest,
contentRoot => new PhysicalFileProvider(contentRoot));
// Act
var file = provider.GetFileInfo("/_CONTENT/Microsoft.AspNetCore.Hosting.StaticWebAssets.xml");
// Assert
Assert.Equal(expectedResult, file.Exists);
}
[Theory]
[InlineData("/img/icon.png", true)]
[InlineData("/Img/hero.gif", true)]
// Note that we've changed the casing of the first segment
[InlineData("/Img/icon.png", false)]
[InlineData("/img/hero.gif", false)]
public void ParseWorksWithNodesThatOnlyDifferOnCasing(string path, bool exists)
{
exists = exists | OperatingSystem.IsWindows();
// Arrange
using var memoryStream = new MemoryStream();
using var writer = new StreamWriter(memoryStream);
writer.Write(@"{
""ContentRoots"": [
""D:\\path\\"",
""D:\\other\\""
],
""Root"": {
""Children"": {
""img"": {
""Children"": {
""icon.png"": {
""Asset"": {
""ContentRootIndex"": 0,
""SubPath"": ""icon.png""
}
}
}
},
""Img"": {
""Children"": {
""hero.gif"": {
""Asset"": {
""ContentRootIndex"": 1,
""SubPath"": ""hero.gif""
}
}
}
}
}
}
}");
var first = new Mock<IFileProvider>();
first.Setup(s => s.GetFileInfo("icon.png")).Returns(new TestFileInfo() { Name = "icon.png", Exists = true });
var second = new Mock<IFileProvider>();
second.Setup(s => s.GetFileInfo("hero.gif")).Returns(new TestFileInfo() { Name = "hero.gif", Exists = true });
writer.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
var manifest = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.Parse(memoryStream);
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var provider = new ManifestStaticWebAssetFileProvider(
manifest,
contentRoot => contentRoot switch
{
"D:\\path\\" => first.Object,
"D:\\other\\" => second.Object,
_ => throw new InvalidOperationException("Unknown provider")
});
// Act
var file = provider.GetFileInfo(path);
// Assert
Assert.Equal(exists, file.Exists);
}
[Theory]
[InlineData("/img/Subdir/icon.png", true)]
[InlineData("/Img/subdir/hero.gif", true)]
// Note that we've changed the casing of the second segment
[InlineData("/img/subdir/icon.png", false)]
[InlineData("/Img/Subdir/hero.gif", false)]
public void ParseWorksWithMergesNodesRecursively(string path, bool exists)
{
// Arrange
exists = exists | OperatingSystem.IsWindows();
var firstLevelCount = OperatingSystem.IsWindows() ? 1 : 2;
using var memoryStream = new MemoryStream();
using var writer = new StreamWriter(memoryStream);
writer.Write(@"{
""ContentRoots"": [
""D:\\path\\"",
""D:\\other\\""
],
""Root"": {
""Children"": {
""img"": {
""Children"": {
""Subdir"": {
""Children"": {
""icon.png"": {
""Asset"": {
""ContentRootIndex"": 0,
""SubPath"": ""icon.png""
}
}
}
}
}
},
""Img"": {
""Children"": {
""subdir"": {
""Children"": {
""hero.gif"": {
""Asset"": {
""ContentRootIndex"": 1,
""SubPath"": ""hero.gif""
}
}
}
}
}
}
}
}
}");
var first = new Mock<IFileProvider>();
first.Setup(s => s.GetFileInfo("icon.png")).Returns(new TestFileInfo() { Name = "icon.png", Exists = true });
var second = new Mock<IFileProvider>();
second.Setup(s => s.GetFileInfo("hero.gif")).Returns(new TestFileInfo() { Name = "hero.gif", Exists = true });
writer.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
var manifest = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.Parse(memoryStream);
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var provider = new ManifestStaticWebAssetFileProvider(
manifest,
contentRoot => contentRoot switch
{
"D:\\path\\" => first.Object,
"D:\\other\\" => second.Object,
_ => throw new InvalidOperationException("Unknown provider")
});
// Act
var file = provider.GetFileInfo(path);
// Assert
Assert.Equal(exists, file.Exists);
Assert.Equal(firstLevelCount, manifest.Root.Children.Count);
Assert.All(manifest.Root.Children.Values, c => Assert.Single(c.Children));
}
[Theory]
[InlineData("/img/Subdir", true)]
[InlineData("/Img/subdir/hero.gif", true)]
// Note that we've changed the casing of the second segment
[InlineData("/img/subdir", false)]
[InlineData("/Img/Subdir/hero.gif", false)]
public void ParseWorksFolderAndFileWithDiferentCasing(string path, bool exists)
{
// Arrange
exists = exists | OperatingSystem.IsWindows();
var firstLevelCount = OperatingSystem.IsWindows() ? 1 : 2;
using var memoryStream = new MemoryStream();
using var writer = new StreamWriter(memoryStream);
// img/Subdir is a file without extension
writer.Write(@"{
""ContentRoots"": [
""D:\\path\\"",
""D:\\other\\""
],
""Root"": {
""Children"": {
""img"": {
""Children"": {
""Subdir"": {
""Asset"": {
""ContentRootIndex"": 0,
""SubPath"": ""Subdir""
}
}
}
},
""Img"": {
""Children"": {
""subdir"": {
""Children"": {
""hero.gif"": {
""Asset"": {
""ContentRootIndex"": 1,
""SubPath"": ""hero.gif""
}
}
}
}
}
}
}
}
}");
var first = new Mock<IFileProvider>();
first.Setup(s => s.GetFileInfo("Subdir")).Returns(new TestFileInfo() { Name = "Subdir", Exists = true });
var second = new Mock<IFileProvider>();
second.Setup(s => s.GetFileInfo("hero.gif")).Returns(new TestFileInfo() { Name = "hero.gif", Exists = true });
writer.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
var manifest = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.Parse(memoryStream);
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var provider = new ManifestStaticWebAssetFileProvider(
manifest,
contentRoot => contentRoot switch
{
"D:\\path\\" => first.Object,
"D:\\other\\" => second.Object,
_ => throw new InvalidOperationException("Unknown provider")
});
// Act
var file = provider.GetFileInfo(path);
// Assert
Assert.Equal(exists, file.Exists);
Assert.Equal(firstLevelCount, manifest.Root.Children.Count);
Assert.All(manifest.Root.Children.Values, c => Assert.Single(c.Children));
}
[Fact]
public void CanFindFileListedOnTheManifest()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var file = fileProvider.GetFileInfo("_content/RazorClassLibrary/file.version.js");
// Assert
Assert.NotNull(file);
Assert.True(file.Exists);
Assert.Equal("file.version.js", file.Name);
}
[Fact]
public void GetFileInfoHandlesRootCorrectly()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var file = fileProvider.GetFileInfo("");
// Assert
Assert.NotNull(file);
Assert.False(file.Exists);
Assert.False(file.IsDirectory);
Assert.Equal("", file.Name);
}
[Fact]
public void GetFileInfoHandlesRootPatternCorrectly()
{
var (manifest, factory) = CreateTestManifestWithPattern();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var file = fileProvider.GetFileInfo("/other.html");
// Assert
Assert.NotNull(file);
Assert.True(file.Exists);
Assert.False(file.IsDirectory);
Assert.Equal("other.html", file.Name);
}
[Fact]
public void GetDirectoryContentsHandlesRootPatternCorrectly()
{
var (manifest, factory) = CreateTestManifestWithPattern();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var contents = fileProvider.GetDirectoryContents("");
// Assert
Assert.NotNull(contents);
Assert.True(contents.Exists);
var file = contents.Single();
Assert.True(file.Exists);
Assert.False(file.IsDirectory);
Assert.Equal("other.html", file.Name);
}
[Fact]
public void CanFindFileMatchingPattern()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var file = fileProvider.GetFileInfo("_content/RazorClassLibrary/js/project-transitive-dep.js");
// Assert
Assert.NotNull(file);
Assert.True(file.Exists);
Assert.Equal("project-transitive-dep.js", file.Name);
}
[Fact]
public void CanFindFileWithSpaces()
{
// Arrange
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var expectedResult = OperatingSystem.IsWindows();
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new[] { Path.Combine(AppContext.BaseDirectory, "testroot", "wwwroot") };
manifest.Root = new()
{
Children = new(comparer)
{
["_content"] = new()
{
Children = new(comparer)
{
["Static Web Assets.txt"] = new()
{
Match = new()
{
ContentRoot = 0,
Path = "Static Web Assets.txt"
}
}
}
}
}
};
var provider = new ManifestStaticWebAssetFileProvider(manifest, root => new PhysicalFileProvider(root));
// Assert
Assert.True(provider.GetFileInfo("/_content/Static Web Assets.txt").Exists);
}
[Fact]
public void IgnoresFilesThatDontMatchThePattern()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var file = fileProvider.GetFileInfo("_content/RazorClassLibrary/styles.css");
// Assert
Assert.NotNull(file);
Assert.False(file.Exists);
}
[Fact]
public void ReturnsNotFoundFileWhenNoPatternAndNoEntryMatchPatch()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var file = fileProvider.GetFileInfo("_content/RazorClassLibrary/different");
// Assert
Assert.NotNull(file);
Assert.False(file.IsDirectory);
Assert.False(file.Exists);
}
[Fact]
public void GetDirectoryContentsHandlesRootCorrectly()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var contents = fileProvider.GetDirectoryContents("");
// Assert
Assert.NotNull(contents);
Assert.Equal(new[] { (true, "_content") }, contents.Select(e => (e.IsDirectory, e.Name)).OrderBy(e => e.Name).ToArray());
}
[Fact]
public void GetDirectoryContentsReturnsNonExistingDirectoryWhenDirectoryDoesNotExist()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var contents = fileProvider.GetDirectoryContents("_content/NonExisting");
// Assert
Assert.NotNull(contents);
Assert.False(contents.Exists);
}
[Fact]
public void GetDirectoryContentsListsEntriesBasedOnManifest()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var contents = fileProvider.GetDirectoryContents("_content");
// Assert
Assert.NotNull(contents);
Assert.Equal(new[]{
(true, "AnotherClassLibrary"),
(true, "RazorClassLibrary") },
contents.Select(e => (e.IsDirectory, e.Name)).OrderBy(e => e.Name).ToArray());
}
[Fact]
public void GetDirectoryContentsListsEntriesBasedOnPatterns()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var contents = fileProvider.GetDirectoryContents("_content/RazorClassLibrary/js");
// Assert
Assert.NotNull(contents);
Assert.Equal(new[]{
(false, "project-transitive-dep.js"),
(false, "project-transitive-dep.v4.js") },
contents.Select(e => (e.IsDirectory, e.Name)).OrderBy(e => e.Name).ToArray());
}
[Theory]
[InlineData("\\", "_content")]
[InlineData("\\_content\\RazorClassLib\\Dir", "Castle.Core.dll")]
[InlineData("", "_content")]
[InlineData("/", "_content")]
[InlineData("/_content", "RazorClassLib")]
[InlineData("/_content/RazorClassLib", "Dir")]
[InlineData("/_content/RazorClassLib/Dir", "Microsoft.AspNetCore.Hosting.Tests.dll")]
[InlineData("/_content/RazorClassLib/Dir/testroot/", "TextFile.txt")]
[InlineData("/_content/RazorClassLib/Dir/testroot/wwwroot/", "README")]
public void GetDirectoryContentsWalksUpContentRoot(string searchDir, string expected)
{
// Arrange
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var expectedResult = OperatingSystem.IsWindows();
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new[] { AppContext.BaseDirectory };
manifest.Root = new()
{
Children = new(comparer)
{
["_content"] = new()
{
Children = new(comparer)
{
["RazorClassLib"] = new()
{
Children = new(comparer)
{
["Dir"] = new()
{
Patterns = new ManifestStaticWebAssetFileProvider.StaticWebAssetPattern[]
{
new()
{
Pattern = "**",
ContentRoot = 0,
Depth = 3,
}
}
}
}
}
}
}
}
};
var provider = new ManifestStaticWebAssetFileProvider(manifest, root => new PhysicalFileProvider(root));
// Act
var directory = provider.GetDirectoryContents(searchDir);
// Assert
Assert.NotEmpty(directory);
Assert.Contains(directory, file => string.Equals(file.Name, expected));
}
[Theory]
[InlineData("/_content/RazorClass")]
public void GetDirectoryContents_PartialMatchFails(string requestedUrl)
{
// Arrange
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var expectedResult = OperatingSystem.IsWindows();
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new[] { AppContext.BaseDirectory };
manifest.Root = new()
{
Children = new(comparer)
{
["_content"] = new()
{
Children = new(comparer)
{
["RazorClassLib"] = new()
{
Children = new(comparer)
{
["Dir"] = new()
{
}
}
}
}
}
}
};
var provider = new ManifestStaticWebAssetFileProvider(manifest, root => new PhysicalFileProvider(root));
// Act
var directory = provider.GetDirectoryContents(requestedUrl);
// Assert
Assert.Empty(directory);
}
[Fact]
public void CombinesContentsFromManifestAndPatterns()
{
var (manifest, factory) = CreateTestManifest();
var fileProvider = new ManifestStaticWebAssetFileProvider(manifest, factory);
// Act
var contents = fileProvider.GetDirectoryContents("_content/RazorClassLibrary");
// Assert
Assert.NotNull(contents);
Assert.Equal(new[]{
(false, "file.version.js"),
(true, "js") },
contents.Select(e => (e.IsDirectory, e.Name)).OrderBy(e => e.Name).ToArray());
}
[Fact]
public void GetDirectoryContentsPrefixRespectsOsCaseSensitivity()
{
// Arrange
var comparer = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.PathComparer;
var expectedResult = OperatingSystem.IsWindows();
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new[] { Path.GetDirectoryName(typeof(ManifestStaticWebAssetsFileProviderTest).Assembly.Location) };
manifest.Root = new()
{
Children = new(comparer)
{
["_content"] = new()
{
Children = new(comparer)
{
["Microsoft.AspNetCore.Hosting.StaticWebAssets.xml"] = new()
{
Match = new()
{
ContentRoot = 0,
Path = "Microsoft.AspNetCore.Hosting.StaticWebAssets.xml"
}
}
}
}
}
};
var provider = new ManifestStaticWebAssetFileProvider(
manifest,
contentRoot => new PhysicalFileProvider(contentRoot));
// Act
var directory = provider.GetDirectoryContents("/_CONTENT/");
// Assert
Assert.Equal(expectedResult, directory.Exists);
}
private static (ManifestStaticWebAssetFileProvider.StaticWebAssetManifest manifest, Func<string, IFileProvider> factory) CreateTestManifest()
{
// Arrange
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new string[2] {
"Cero",
"Uno"
};
Func<string, IFileProvider> factory = (string contentRoot) =>
{
if (contentRoot == "Cero")
{
var styles = new TestFileInfo { Exists = true, IsDirectory = false, Name = "styles.css" };
var js = new TestFileInfo { Exists = true, IsDirectory = true, Name = "js" };
var file = new TestFileInfo { Exists = true, Name = "file.js", IsDirectory = false };
var transitiveDep = new TestFileInfo { Exists = true, IsDirectory = false, Name = "project-transitive-dep.js" };
var transitiveDepV4 = new TestFileInfo { Exists = true, IsDirectory = false, Name = "project-transitive-dep.v4.js" };
var providerMock = new Mock<IFileProvider>();
providerMock.Setup(p => p.GetDirectoryContents("")).Returns(new TestDirectoryContents(new[] { styles, js }));
providerMock.Setup(p => p.GetDirectoryContents("js")).Returns(new TestDirectoryContents(new[]
{
transitiveDep,
transitiveDepV4
}));
providerMock.Setup(p => p.GetFileInfo("different")).Returns(new NotFoundFileInfo("different"));
providerMock.Setup(p => p.GetFileInfo("file.js")).Returns(file);
providerMock.Setup(p => p.GetFileInfo("js")).Returns(js);
providerMock.Setup(p => p.GetFileInfo("styles.css")).Returns(styles);
providerMock.Setup(p => p.GetFileInfo("js/project-transitive-dep.js")).Returns(transitiveDep);
providerMock.Setup(p => p.GetFileInfo("js/project-transitive-dep.v4.js")).Returns(transitiveDepV4);
return providerMock.Object;
}
if (contentRoot == "Uno")
{
var css = new TestFileInfo { Exists = true, IsDirectory = true, Name = "css" };
var site = new TestFileInfo { Exists = true, IsDirectory = false, Name = "site.css" };
var js = new TestFileInfo { Exists = true, IsDirectory = true, Name = "js" };
var projectDirectDep = new TestFileInfo { Exists = true, IsDirectory = false, Name = "project-direct-dep.js" };
var providerMock = new Mock<IFileProvider>();
providerMock.Setup(p => p.GetDirectoryContents("")).Returns(new TestDirectoryContents(new[] { css, js }));
providerMock.Setup(p => p.GetDirectoryContents("js")).Returns(new TestDirectoryContents(new[]
{
projectDirectDep
}));
providerMock.Setup(p => p.GetDirectoryContents("css")).Returns(new TestDirectoryContents(new[]
{
site
}));
providerMock.Setup(p => p.GetFileInfo("js")).Returns(js);
providerMock.Setup(p => p.GetFileInfo("css")).Returns(css);
providerMock.Setup(p => p.GetFileInfo("css/site.css")).Returns(site);
providerMock.Setup(p => p.GetFileInfo("js/project-direct-dep.js")).Returns(projectDirectDep);
return providerMock.Object;
}
throw new InvalidOperationException("Invalid content root");
};
manifest.Root = new()
{
Children = new()
{
["_content"] = new()
{
Children = new()
{
["RazorClassLibrary"] = new()
{
Children = new() { ["file.version.js"] = new() { Match = new() { ContentRoot = 0, Path = "file.js" } } },
Patterns = new ManifestStaticWebAssetFileProvider.StaticWebAssetPattern[] { new() { ContentRoot = 0, Depth = 2, Pattern = "**/*.js" } },
},
["AnotherClassLibrary"] = new()
{
Patterns = new ManifestStaticWebAssetFileProvider.StaticWebAssetPattern[] { new() { ContentRoot = 1, Depth = 2, Pattern = "**" } }
}
}
}
}
};
return (manifest, factory);
}
private static (ManifestStaticWebAssetFileProvider.StaticWebAssetManifest manifest, Func<string, IFileProvider> factory) CreateTestManifestWithPattern()
{
// Arrange
var otherHtml = new TestFileInfo { Exists = true, IsDirectory = false, Name = "other.html" };
var manifest = new ManifestStaticWebAssetFileProvider.StaticWebAssetManifest();
manifest.ContentRoots = new [] { "Cero" };
Func<string, IFileProvider> factory = (string contentRoot) =>
{
if (contentRoot == "Cero")
{
var providerMock = new Mock<IFileProvider>();
providerMock.Setup(p => p.GetFileInfo("other.html")).Returns(otherHtml);
providerMock.Setup(p => p.GetDirectoryContents("")).Returns(new TestDirectoryContents(new[] { otherHtml })
{
Exists = true
});
return providerMock.Object;
}
throw new InvalidOperationException("Invalid content root");
};
manifest.Root = new()
{
Children = new Dictionary<string, ManifestStaticWebAssetFileProvider.StaticWebAssetNode>(),
Patterns = new[]
{
new ManifestStaticWebAssetFileProvider.StaticWebAssetPattern
{
ContentRoot = 0,
Depth = 0,
Pattern = "**"
}
}
};
return (manifest, factory);
}
}
internal class TestFileInfo : IFileInfo
{
public bool Exists { get; set; }
public long Length { get; set; }
public string PhysicalPath { get; set; }
public string Name { get; set; }
public DateTimeOffset LastModified { get; set; }
public bool IsDirectory { get; set; }
public Stream CreateReadStream() => Stream.Null;
}
internal class TestDirectoryContents : IDirectoryContents
{
private readonly IEnumerable<IFileInfo> _contents;
public TestDirectoryContents(IEnumerable<IFileInfo> contents)
{
_contents = contents;
}
public bool Exists { get; set; }
public IEnumerator<IFileInfo> GetEnumerator() => _contents.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
namespace Chatbase
{
public class Client
{
private HttpClient client;
public string api_key;
public string user_id;
public string platform;
public string version;
private static String ContentType
{
get { return "application/json"; }
}
private static String SingluarMessageEndpoint
{
get { return "https://chatbase.com/api/message"; }
}
private static String BatchMessageEndpoint
{
get { return "https://chatbase.com/api/messages?api_key={0}"; }
}
private static String SingularFBUserMessageEndpoint
{
get { return "https://chatbase.com/api/facebook/message_received?api_key={0}&intent={1}¬_handled={2}&feedback={3}&version={4}"; }
}
private static String BatchFBUserMessageEndpoint
{
get { return "https://chatbase.com/api/facebook/message_received_batch?api_key={0}"; }
}
private static String SingularFBAgentMessageEndpoint
{
get { return "https://chatbase.com/api/facebook/send_message?api_key={0}&version={1}"; }
}
private static String BatchFBAgentMessageEndpoint
{
get { return "https://chatbase.com/api/facebook/send_message_batch?api_key={0}"; }
}
public async Task<HttpResponseMessage> Send(Message msg)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(
typeof(Message));
ser.WriteObject(stream, msg);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string json = sr.ReadToEnd();
StringContent content = new StringContent(json, Encoding.UTF8, Client.ContentType);
return await client.PostAsync(Client.SingluarMessageEndpoint, content);
}
public async Task<HttpResponseMessage> Send(FBUserMessage msg)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(
typeof(FBUserMessage),
new Type[]
{
typeof(SenderID),
typeof(RecipientID),
typeof(FBMessageContent),
typeof(FBChatbaseFields)
}
);
ser.WriteObject(stream, msg);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string json = sr.ReadToEnd();
string url = String.Format(Client.SingularFBUserMessageEndpoint,
msg.api_key, msg.intent, msg.not_handled, msg.feedback, msg.version);
StringContent content = new StringContent(json, Encoding.UTF8, Client.ContentType);
return await client.PostAsync(url, content);
}
public async Task<HttpResponseMessage> Send(FBAgentMessage msg)
{
msg.SetChatbaseFields();
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(
typeof(FBAgentMessage),
new Type[]
{
typeof(SenderID),
typeof(RecipientID),
typeof(FBMessageContent),
typeof(FBChatbaseFields),
typeof(FBAgentMessageRequestBody),
typeof(FBAgentMessageResponseBody)
}
);
ser.WriteObject(stream, msg);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string json = sr.ReadToEnd();
string url = String.Format(Client.SingularFBAgentMessageEndpoint,
msg.api_key, msg.version);
StringContent content = new StringContent(json, Encoding.UTF8, Client.ContentType);
return await client.PostAsync(url, content);
}
public async Task<HttpResponseMessage> Send(MessageSet set)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(
typeof(MessageSet),
new Type[]{typeof(MessageCollection), typeof(Message)});
ser.WriteObject(stream, set);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string json = sr.ReadToEnd();
string url = String.Format(Client.BatchMessageEndpoint, set.api_key);
StringContent content = new StringContent(json, Encoding.UTF8, Client.ContentType);
return await client.PostAsync(url, content);
}
public async Task<HttpResponseMessage> Send(FBUserMessageSet set)
{
set.SetChatbaseFields();
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(
typeof(FBUserMessageSet),
new Type[]
{
typeof(FBUserMessageCollection),
typeof(FBUserMessage),
typeof(FBChatbaseFields),
typeof(SenderID),
typeof(RecipientID),
typeof(FBMessageContent)
}
);
ser.WriteObject(stream, set);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string json = sr.ReadToEnd();
string url = String.Format(Client.BatchFBUserMessageEndpoint, set.api_key);
StringContent content = new StringContent(json, Encoding.UTF8, Client.ContentType);
return await client.PostAsync(url, content);
}
public async Task<HttpResponseMessage> Send(FBAgentMessageSet set)
{
set.SetChatbaseFields();
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(
typeof(FBAgentMessageSet),
new Type[]
{
typeof(FBAgentMessageCollection),
typeof(FBAgentMessage),
typeof(FBChatbaseFields),
typeof(SenderID),
typeof(RecipientID),
typeof(FBMessageContent),
typeof(FBAgentMessageRequestBody),
typeof(FBAgentMessageResponseBody)
}
);
ser.WriteObject(stream, set);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string json = sr.ReadToEnd();
string url = String.Format(Client.BatchFBAgentMessageEndpoint, set.api_key);
StringContent content = new StringContent(json, Encoding.UTF8, Client.ContentType);
return await client.PostAsync(url, content);
}
private Message setMessageWithClientProperties(Message msg)
{
if (!String.IsNullOrEmpty(api_key)) {
msg.api_key = api_key;
}
if (!String.IsNullOrEmpty(user_id)) {
msg.user_id = user_id;
}
if (!String.IsNullOrEmpty(platform)) {
msg.platform = platform;
}
if (!String.IsNullOrEmpty(version)) {
msg.version = version;
}
return msg;
}
public Message NewMessageFromClientParams()
{
return setMessageWithClientProperties(new Message());
}
public Message NewMessage()
{
return new Message();
}
public Client()
{
client = new HttpClient();
}
public Client(string key)
{
client = new HttpClient();
api_key = key;
}
public Client(string key, string uid)
{
client = new HttpClient();
api_key = key;
user_id = uid;
}
public Client(string key, string uid, string plt)
{
client = new HttpClient();
api_key = key;
user_id = uid;
platform = plt;
}
public Client(string key, string uid, string plt, string ver)
{
client = new HttpClient();
api_key = key;
user_id = uid;
platform = plt;
version = ver;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class GetItemStrStringDictionaryTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
StringDictionary sd;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"one",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
string itm; // returned Item
// initialize IntStrings
intl = new IntlStrings();
// [] StringDictionary is constructed as expected
//-----------------------------------------------------------------
sd = new StringDictionary();
// [] get Item() on empty dictionary
//
if (sd.Count > 0)
sd.Clear();
for (int i = 0; i < keys.Length; i++)
{
itm = sd[keys[i]];
if (itm != null)
{
Assert.False(true, string.Format("Error, returned non-null for {0} key", i));
}
}
// [] get Item() on filled dictionary
//
int len = values.Length;
sd.Clear();
for (int i = 0; i < len; i++)
{
sd.Add(keys[i], values[i]);
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
for (int i = 0; i < len; i++)
{
if (String.Compare(sd[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[keys[i]], values[i]));
}
}
//
// [] get Item on dictionary with identical values
//
sd.Clear();
string intlStr = intl.GetRandomString(MAX_LEN);
sd.Add("keykey1", intlStr); // 1st duplicate
for (int i = 0; i < len; i++)
{
sd.Add(keys[i], values[i]);
}
sd.Add("keykey2", intlStr); // 2nd duplicate
if (sd.Count != len + 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len + 2));
}
// get Item
//
if (String.Compare(sd["keykey1"], intlStr) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", sd["keykey1"], intlStr));
}
if (String.Compare(sd["keykey2"], intlStr) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", sd["keykey2"], intlStr));
}
//
// Intl strings
// [] get Item() on dictionary filled with Intl strings
//
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
//
// will use first half of array as values and second half as keys
//
sd.Clear();
for (int i = 0; i < len; i++)
{
sd.Add(intlValues[i + len], intlValues[i]);
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
// get item
for (int i = 0; i < len; i++)
{
if (String.Compare(sd[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[intlValues[i + len]], intlValues[i]));
}
}
//
// [] Case sensitivity: keys are always lowercased
//
sd.Clear();
string[] intlValuesUpper = new string[len];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToLowerInvariant();
}
// array of uppercase keys
for (int i = 0; i < len; i++)
{
intlValuesUpper[i] = intlValues[i + len].ToUpperInvariant();
}
sd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
sd.Add(intlValues[i + len], intlValues[i]); // adding lowercase strings
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
// get Item
for (int i = 0; i < len; i++)
{
if (String.Compare(sd[intlValuesUpper[i]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[intlValuesUpper[i]], intlValues[i]));
}
}
//
// [] Invalid parameter
//
Assert.Throws<ArgumentNullException>(() => { itm = sd[null]; });
}
}
}
| |
/*=======================================================================
Simple Event Example. Copyright (c) Firelight Technologies 2004-2011.
This example plays an event created with the FMOD Designer sound
designer tool. It simply plays an event, retrieves the parameters
and allows the user to adjust them.
=========================================================================*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace simple_event
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TrackBar trackBarRPM;
private System.Windows.Forms.Label label;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Button exit_button;
private System.Windows.Forms.StatusBar statusBar;
private System.ComponentModel.IContainer components;
private bool initialised = false;
private bool trackbarscroll = false;
private bool exit = false;
/*
ALL FMOD CALLS MUST HAPPEN WITHIN THE SAME THREAD.
WE WILL DO EVERYTHING IN THE TIMER THREAD
*/
FMOD.EventSystem eventsystem = null;
FMOD.EventGroup eventgroup = null;
FMOD.EventCategory mastercategory = null;
FMOD.Event car = null;
FMOD.EventParameter rpm = null;
FMOD.EventParameter load = null;
FMOD.RESULT result;
float rpm_min, rpm_max, load_min, load_max;
private Label label2;
private TrackBar trackBarLoad;
private System.Windows.Forms.Label label1;
private void timer1_Tick(object sender, System.EventArgs e)
{
if (!initialised)
{
ERRCHECK(result = FMOD.Event_Factory.EventSystem_Create(ref eventsystem));
ERRCHECK(result = eventsystem.init(64, FMOD.INITFLAGS.NORMAL, (IntPtr)null, FMOD.EVENT_INITFLAGS.NORMAL));
ERRCHECK(result = eventsystem.setMediaPath("../../../../examples/media/"));
ERRCHECK(result = eventsystem.load("examples.fev"));
ERRCHECK(result = eventsystem.getGroup("examples/AdvancedTechniques", false, ref eventgroup));
ERRCHECK(result = eventgroup.getEvent("car", FMOD.EVENT_MODE.DEFAULT, ref car));
ERRCHECK(result = eventsystem.getCategory("master", ref mastercategory));
ERRCHECK(result = car.getParameter("load", ref load));
ERRCHECK(result = load.getRange(ref load_min, ref load_max));
ERRCHECK(result = load.setValue(load_max));
ERRCHECK(result = car.getParameterByIndex(0, ref rpm));
ERRCHECK(result = rpm.getRange(ref rpm_min, ref rpm_max));
ERRCHECK(result = rpm.setValue(1000.0f));
trackBarRPM.Minimum = (int)rpm_min;
trackBarRPM.Maximum = (int)rpm_max;
trackBarLoad.Minimum = (int)load_min;
trackBarLoad.Maximum = (int)load_max;
trackBarRPM.Value = 1000;
trackBarLoad.Value = (int)load_max;
ERRCHECK(result = car.start());
initialised = true;
}
/*
"Main Loop"
*/
if (trackbarscroll)
{
ERRCHECK(result = rpm.setValue((float)trackBarRPM.Value));
ERRCHECK(result = load.setValue((float)trackBarLoad.Value));
trackbarscroll = false;
}
float rpmvalue = 0.0f;
ERRCHECK(result = rpm.getValue(ref rpmvalue));
statusBar.Text = "RPM Value = " + rpmvalue;
ERRCHECK(result = eventsystem.update());
/*
Clean up and exit
*/
if (exit)
{
ERRCHECK(result = eventgroup.freeEventData());
ERRCHECK(result = eventsystem.release());
Application.Exit();
}
}
public Form1()
{
InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.trackBarRPM = new System.Windows.Forms.TrackBar();
this.label = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.exit_button = new System.Windows.Forms.Button();
this.statusBar = new System.Windows.Forms.StatusBar();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.trackBarLoad = new System.Windows.Forms.TrackBar();
((System.ComponentModel.ISupportInitialize)(this.trackBarRPM)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBarLoad)).BeginInit();
this.SuspendLayout();
//
// trackBarRPM
//
this.trackBarRPM.Location = new System.Drawing.Point(64, 64);
this.trackBarRPM.Maximum = 1000;
this.trackBarRPM.Name = "trackBarRPM";
this.trackBarRPM.Size = new System.Drawing.Size(216, 42);
this.trackBarRPM.TabIndex = 1;
this.trackBarRPM.TickStyle = System.Windows.Forms.TickStyle.None;
this.trackBarRPM.Scroll += new System.EventHandler(this.trackBarRPM_Scroll);
//
// trackBarLoad
//
this.trackBarLoad.Location = new System.Drawing.Point(64, 96);
this.trackBarLoad.Maximum = 1000;
this.trackBarLoad.Name = "trackBarLoad";
this.trackBarLoad.Size = new System.Drawing.Size(216, 42);
this.trackBarLoad.TabIndex = 21;
this.trackBarLoad.TickStyle = System.Windows.Forms.TickStyle.None;
this.trackBarLoad.Scroll += new System.EventHandler(this.trackBarLoad_Scroll);
//
// label
//
this.label.Location = new System.Drawing.Point(16, 16);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(264, 32);
this.label.TabIndex = 17;
this.label.Text = "Copyright (c) Firelight Technologies 2004-2011";
this.label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 10;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// exit_button
//
this.exit_button.Location = new System.Drawing.Point(105, 144);
this.exit_button.Name = "exit_button";
this.exit_button.Size = new System.Drawing.Size(72, 24);
this.exit_button.TabIndex = 18;
this.exit_button.Text = "Exit";
this.exit_button.Click += new System.EventHandler(this.exit_button_Click);
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 168);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(292, 24);
this.statusBar.TabIndex = 19;
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 64);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(34, 32);
this.label1.TabIndex = 20;
this.label1.Text = "RPM:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label2
//
this.label2.Location = new System.Drawing.Point(12, 96);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(46, 32);
this.label2.TabIndex = 22;
this.label2.Text = "LOAD:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 192);
this.Controls.Add(this.label2);
this.Controls.Add(this.trackBarLoad);
this.Controls.Add(this.label1);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.exit_button);
this.Controls.Add(this.label);
this.Controls.Add(this.trackBarRPM);
this.Name = "Form1";
this.Text = "Simple Event Example";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.trackBarRPM)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBarLoad)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
private void trackBarRPM_Scroll(object sender, System.EventArgs e)
{
trackbarscroll = true;
}
private void trackBarLoad_Scroll(object sender, System.EventArgs e)
{
trackbarscroll = true;
}
private void exit_button_Click(object sender, System.EventArgs e)
{
exit = true;
}
private void ERRCHECK(FMOD.RESULT result)
{
if (result != FMOD.RESULT.OK)
{
timer1.Stop();
MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result));
Environment.Exit(-1);
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Rithmic.Rithmic
File: RithmicMessageAdapter.cs
Created: 2015, 12, 2, 8:18 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Rithmic
{
using System;
using System.Linq;
using com.omnesys.omne.om;
using com.omnesys.rapi;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// The message adapter for Rithmic.
/// </summary>
public partial class RithmicMessageAdapter : MessageAdapter
{
private readonly SynchronizedDictionary<ConnectionId, bool?> _connStates = new SynchronizedDictionary<ConnectionId, bool?>();
private RithmicClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="RithmicMessageAdapter"/>.
/// </summary>
/// <param name="transactionIdGenerator">Transaction id generator.</param>
public RithmicMessageAdapter(IdGenerator transactionIdGenerator)
: base(transactionIdGenerator)
{
this.AddMarketDataSupport();
this.AddTransactionalSupport();
this.AddSupportedMessage(MessageTypes.ChangePassword);
}
/// <summary>
/// Create condition for order type <see cref="OrderTypes.Conditional"/>, that supports the adapter.
/// </summary>
/// <returns>Order condition. If the connection does not support the order type <see cref="OrderTypes.Conditional"/>, it will be returned <see langword="null" />.</returns>
public override OrderCondition CreateOrderCondition()
{
return new RithmicOrderCondition();
}
/// <summary>
/// <see cref="SecurityLookupMessage"/> required to get securities.
/// </summary>
public override bool SecurityLookupRequired => false;
/// <summary>
/// Gets a value indicating whether the connector supports security lookup.
/// </summary>
protected override bool IsSupportNativeSecurityLookup => true;
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
protected override void OnSendInMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.Reset:
{
_accounts.Clear();
_quotes.Clear();
if (_client != null)
{
try
{
_client.Session.logout();
}
catch (Exception ex)
{
SendOutError(ex);
}
_client = null;
}
SendOutMessage(new ResetMessage());
break;
}
case MessageTypes.Connect:
{
if (_client != null)
throw new InvalidOperationException(LocalizedStrings.Str1619);
Connect();
break;
}
case MessageTypes.Disconnect:
{
if (_client == null)
throw new InvalidOperationException(LocalizedStrings.Str1856);
_client.Session.logout();
break;
}
case MessageTypes.OrderRegister:
ProcessRegisterMessage((OrderRegisterMessage)message);
break;
case MessageTypes.OrderReplace:
ProcessReplaceMessage((OrderReplaceMessage)message);
break;
case MessageTypes.OrderCancel:
ProcessCancelMessage((OrderCancelMessage)message);
break;
case MessageTypes.OrderGroupCancel:
ProcessGroupCancelMessage((OrderGroupCancelMessage)message);
break;
case MessageTypes.OrderStatus:
ProcessOrderStatusMessage();
break;
case MessageTypes.SecurityLookup:
ProcessSecurityLookupMessage((SecurityLookupMessage)message);
break;
case MessageTypes.PortfolioLookup:
_client.Session.getAccounts();
break;
case MessageTypes.Portfolio:
ProcessPortfolioMessage((PortfolioMessage)message);
break;
case MessageTypes.MarketData:
ProcessMarketDataMessage((MarketDataMessage)message);
break;
case MessageTypes.ChangePassword:
var newPassword = ((ChangePasswordMessage)message).NewPassword;
_client.Session.changePassword(Password.To<string>(), newPassword.To<string>());
break;
}
}
private void Connect()
{
if (UserName.IsEmpty() || Password.IsEmpty())
throw new InvalidOperationException(LocalizedStrings.Str3456);
_client = new RithmicClient(this, AdminConnectionPoint, CertFile, DomainServerAddress, DomainName,
LicenseServerAddress, LocalBrokerAddress, LoggerAddress, LogFileName);
_client.OrderInfo += SessionHolderOnOrderInfo;
_client.OrderBust += SessionHolderOnOrderBust;
_client.OrderCancel += SessionHolderOnOrderCancel;
_client.OrderCancelFailure += SessionHolderOnOrderCancelFailure;
_client.OrderFailure += SessionHolderOnOrderFailure;
_client.OrderFill += SessionHolderOnOrderFill;
_client.OrderLineUpdate += SessionHolderOnOrderLineUpdate;
_client.OrderModify += SessionHolderOnOrderModify;
_client.OrderModifyFailure += SessionHolderOnOrderModifyFailure;
_client.OrderReject += SessionHolderOnOrderReject;
_client.OrderReport += SessionHolderOnOrderReport;
_client.OrderStatus += SessionHolderOnOrderStatus;
_client.OrderReplay += SessionHolderOnOrderReplay;
_client.Execution += SessionHolderOnExecution;
_client.AccountPnL += SessionHolderOnAccountPnL;
_client.AccountPnLUpdate += SessionHolderOnAccountPnLUpdate;
_client.AccountRms += SessionHolderOnAccountRms;
_client.Accounts += SessionHolderOnAccounts;
_client.AccountSodUpdate += SessionHolderOnAccountSodUpdate;
_client.TransactionError += SendOutError;
_client.SecurityBinaryContracts += SessionHolderOnSecurityBinaryContracts;
_client.SecurityInstrumentByUnderlying += SessionHolderOnSecurityInstrumentByUnderlying;
_client.SecurityOptions += SessionHolderOnSecurityOptions;
_client.SecurityRefData += SessionHolderOnSecurityRefData;
_client.Exchanges += SessionHolderOnExchanges;
_client.BidQuote += SessionHolderOnBidQuote;
_client.BestBidQuote += SessionHolderOnBestBidQuote;
_client.AskQuote += SessionHolderOnAskQuote;
_client.BestAskQuote += SessionHolderOnBestAskQuote;
_client.EndQuote += SessionHolderOnEndQuote;
_client.Level1 += SessionHolderOnLevel1;
_client.OrderBook += SessionHolderOnOrderBook;
_client.SettlementPrice += SessionHolderOnSettlementPrice;
_client.TradeCondition += SessionHolderOnTradeCondition;
_client.TradePrint += SessionHolderOnTradePrint;
_client.TradeVolume += SessionHolderOnTradeVolume;
_client.TradeReplay += SessionHolderOnTradeReplay;
_client.TimeBar += SessionHolderOnTimeBar;
_client.TimeBarReplay += SessionHolderOnTimeBarReplay;
_client.MarketDataError += SendOutError;
_client.Alert += SessionHolderOnAlert;
_client.PasswordChange += SessionHolderOnPasswordChange;
_connStates[ConnectionId.TradingSystem] = TransactionConnectionPoint.IsEmpty() ? (bool?)null : false;
_connStates[ConnectionId.MarketData] = MarketDataConnectionPoint.IsEmpty() ? (bool?)null : false;
_connStates[ConnectionId.PnL] = PositionConnectionPoint.IsEmpty() ? (bool?)null : false;
_connStates[ConnectionId.History] = HistoricalConnectionPoint.IsEmpty() ? (bool?)null : false;
_client.Session.login(_client.Callbacks,
UserName, Password.To<string>(),
MarketDataConnectionPoint,
TransactionalUserName.IsEmpty() ? UserName : TransactionalUserName,
(TransactionalPassword.IsEmpty() ? Password : TransactionalPassword).To<string>(),
TransactionConnectionPoint,
PositionConnectionPoint,
HistoricalConnectionPoint);
}
private void SessionHolderOnPasswordChange(PasswordChangeInfo info)
{
try
{
SendOutMessage(new ChangePasswordMessage
{
Error = info.RpCode == 0 ? null : new InvalidOperationException(OMErrors.OMgetErrorDesc(info.RpCode))
});
}
catch (Exception ex)
{
SendOutError(ex);
}
}
private void SessionHolderOnAlert(AlertInfo info)
{
try
{
if (!_connStates.ContainsKey(info.ConnectionId))
{
this.AddErrorLog("Received alert for unexpected connection id ({0}):\n{1}",
info.ConnectionId, info.DumpableToString());
return;
}
this.AddInfoLog("{0}: {1} - '{2}'", info.AlertType, info.ConnectionId, info.Message);
switch (info.AlertType)
{
case AlertType.ConnectionOpened:
case AlertType.TradingEnabled:
break;
case AlertType.LoginComplete:
{
var dict = _connStates;
bool canProcess;
lock (dict.SyncRoot)
{
dict[info.ConnectionId] = true;
canProcess = dict.Values.All(connected => connected == null || connected == true);
}
if (canProcess)
SendOutMessage(new ConnectMessage());
break;
}
case AlertType.ConnectionClosed:
{
var dict = _connStates;
bool canProcess;
lock (dict.SyncRoot)
{
dict[info.ConnectionId] = false;
canProcess = dict.Values.All(connected => connected == null || connected == false);
}
if (canProcess)
{
SendOutMessage(new DisconnectMessage());
_client.Session.shutdown();
}
break;
}
case AlertType.LoginFailed:
case AlertType.ServiceError:
case AlertType.ForcedLogout:
{
this.AddErrorLog(info.AlertType.ToString());
var dict = _connStates;
bool canProcess;
lock (dict.SyncRoot)
{
dict[info.ConnectionId] = false;
canProcess = dict.Values.All(connected => connected == null || connected == false);
}
if (canProcess)
SendOutMessage(new ConnectMessage { Error = new InvalidOperationException(LocalizedStrings.Str3458Params.Put(info.Message)) });
break;
}
case AlertType.ShutdownSignal:
{
_client.OrderInfo -= SessionHolderOnOrderInfo;
_client.OrderBust -= SessionHolderOnOrderBust;
_client.OrderCancel -= SessionHolderOnOrderCancel;
_client.OrderCancelFailure -= SessionHolderOnOrderCancelFailure;
_client.OrderFailure -= SessionHolderOnOrderFailure;
_client.OrderFill -= SessionHolderOnOrderFill;
_client.OrderLineUpdate -= SessionHolderOnOrderLineUpdate;
_client.OrderModify -= SessionHolderOnOrderModify;
_client.OrderModifyFailure -= SessionHolderOnOrderModifyFailure;
_client.OrderReject -= SessionHolderOnOrderReject;
_client.OrderReport -= SessionHolderOnOrderReport;
_client.OrderStatus -= SessionHolderOnOrderStatus;
_client.OrderReplay -= SessionHolderOnOrderReplay;
_client.Execution -= SessionHolderOnExecution;
_client.AccountPnL -= SessionHolderOnAccountPnL;
_client.AccountPnLUpdate -= SessionHolderOnAccountPnLUpdate;
_client.AccountRms -= SessionHolderOnAccountRms;
_client.Accounts -= SessionHolderOnAccounts;
_client.AccountSodUpdate -= SessionHolderOnAccountSodUpdate;
_client.TransactionError -= SendOutError;
_client.SecurityBinaryContracts -= SessionHolderOnSecurityBinaryContracts;
_client.SecurityInstrumentByUnderlying -= SessionHolderOnSecurityInstrumentByUnderlying;
_client.SecurityOptions -= SessionHolderOnSecurityOptions;
_client.SecurityRefData -= SessionHolderOnSecurityRefData;
_client.Exchanges -= SessionHolderOnExchanges;
_client.BidQuote -= SessionHolderOnBidQuote;
_client.BestBidQuote -= SessionHolderOnBestBidQuote;
_client.AskQuote -= SessionHolderOnAskQuote;
_client.BestAskQuote -= SessionHolderOnBestAskQuote;
_client.EndQuote -= SessionHolderOnEndQuote;
_client.Level1 -= SessionHolderOnLevel1;
_client.OrderBook -= SessionHolderOnOrderBook;
_client.SettlementPrice -= SessionHolderOnSettlementPrice;
_client.TradeCondition -= SessionHolderOnTradeCondition;
_client.TradePrint -= SessionHolderOnTradePrint;
_client.TradeVolume -= SessionHolderOnTradeVolume;
_client.TradeReplay -= SessionHolderOnTradeReplay;
_client.TimeBar -= SessionHolderOnTimeBar;
_client.TimeBarReplay -= SessionHolderOnTimeBarReplay;
_client.MarketDataError -= SendOutError;
_client.Alert -= SessionHolderOnAlert;
_client.PasswordChange -= SessionHolderOnPasswordChange;
_client = null;
break;
}
case AlertType.ConnectionBroken:
case AlertType.TradingDisabled:
case AlertType.QuietHeartbeat:
{
this.AddErrorLog(info.AlertType.ToString());
break;
}
default:
this.AddWarningLog("Unhandled alert: {0}:{1}:{2}", info.ConnectionId, info.AlertType, info.Message);
break;
}
}
catch (Exception ex)
{
SendOutError(ex);
}
}
private bool ProcessErrorCode(int code)
{
if (code == 0)
return true;
SendOutError(OMErrors.OMgetErrorDesc(code));
return false;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function initializeConvexEditor()
{
echo(" % - Initializing Sketch Tool");
exec( "./convexEditor.cs" );
exec( "./convexEditorGui.gui" );
exec( "./convexEditorToolbar.ed.gui" );
exec( "./convexEditorGui.cs" );
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
EditorGui.add( ConvexEditorGui );
EditorGui.add( ConvexEditorOptionsWindow );
EditorGui.add( ConvexEditorTreeWindow );
EditorGui.add( ConvexEditorToolbar );
new ScriptObject( ConvexEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = ConvexEditorGui;
};
// Note that we use the WorldEditor's Toolbar.
%map = new ActionMap();
%map.bindCmd( keyboard, "1", "ConvexEditorNoneModeBtn.performClick();", "" ); // Select
%map.bindCmd( keyboard, "2", "ConvexEditorMoveModeBtn.performClick();", "" ); // Move
%map.bindCmd( keyboard, "3", "ConvexEditorRotateModeBtn.performClick();", "" );// Rotate
%map.bindCmd( keyboard, "4", "ConvexEditorScaleModeBtn.performClick();", "" ); // Scale
ConvexEditorPlugin.map = %map;
ConvexEditorPlugin.initSettings();
}
function ConvexEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Sketch Tool", "", ConvexEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Sketch Tool (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "ConvexEditorPlugin", "ConvexEditorPalette", expandFilename("tools/convexEditor/images/convex-editor-btn"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( ConvexEditorOptionsWindow, ConvexEditorTreeWindow);
// Allocate our special menu.
// It will be added/removed when this editor is activated/deactivated.
if ( !isObject( ConvexActionsMenu ) )
{
singleton PopupMenu( ConvexActionsMenu )
{
superClass = "MenuBuilder";
barTitle = "Sketch";
Item[0] = "Hollow Selected Shape" TAB "" TAB "ConvexEditorGui.hollowSelection();";
item[1] = "Recenter Selected Shape" TAB "" TAB "ConvexEditorGui.recenterSelection();";
};
}
%this.popupMenu = ConvexActionsMenu;
exec( "./convexEditorSettingsTab.ed.gui" );
ESettingsWindow.addTabPage( EConvexEditorSettingsPage );
}
function ConvexEditorPlugin::onActivated( %this )
{
%this.readSettings();
EditorGui.bringToFront( ConvexEditorGui );
ConvexEditorGui.setVisible( true );
ConvexEditorToolbar.setVisible( true );
ConvexEditorGui.makeFirstResponder( true );
%this.map.push();
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo( "Sketch Tool." );
EditorGuiStatusBar.setSelection( "" );
// Add our menu.
EditorGui.menuBar.insert( ConvexActionsMenu, EditorGui.menuBar.dynamicItemInsertPos );
// Sync the pallete button state with the gizmo mode.
%mode = GlobalGizmoProfile.mode;
switch$ (%mode)
{
case "None":
ConvexEditorNoneModeBtn.performClick();
case "Move":
ConvexEditorMoveModeBtn.performClick();
case "Rotate":
ConvexEditorRotateModeBtn.performClick();
case "Scale":
ConvexEditorScaleModeBtn.performClick();
}
Parent::onActivated( %this );
}
function ConvexEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
%this.map.pop();
// Remove our menu.
EditorGui.menuBar.remove( ConvexActionsMenu );
Parent::onDeactivated( %this );
}
function ConvexEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if ( ConvexEditorGui.hasSelection() )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, %hasSelection ); // Deselect
}
function ConvexEditorPlugin::handleDelete( %this )
{
ConvexEditorGui.handleDelete();
}
function ConvexEditorPlugin::handleDeselect( %this )
{
ConvexEditorGui.handleDeselect();
}
function ConvexEditorPlugin::handleCut( %this )
{
//WorldEditorInspectorPlugin.handleCut();
}
function ConvexEditorPlugin::handleCopy( %this )
{
//WorldEditorInspectorPlugin.handleCopy();
}
function ConvexEditorPlugin::handlePaste( %this )
{
//WorldEditorInspectorPlugin.handlePaste();
}
function ConvexEditorPlugin::isDirty( %this )
{
return ConvexEditorGui.isDirty;
}
function ConvexEditorPlugin::onSaveMission( %this, %missionFile )
{
if( ConvexEditorGui.isDirty )
{
getScene(0).save( %missionFile );
ConvexEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function ConvexEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setDefaultValue( "MaterialName", "Grid_512_Orange" );
EditorSettings.endGroup();
}
function ConvexEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
ConvexEditorGui.materialName = EditorSettings.value("MaterialName");
EditorSettings.endGroup();
}
function ConvexEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setValue( "MaterialName", ConvexEditorGui.materialName );
EditorSettings.endGroup();
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PrimitiveOperations operations.
/// </summary>
public partial interface IPrimitiveOperations
{
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IntWrapperInner>> GetIntWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutIntWithHttpMessagesAsync(IntWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<LongWrapperInner>> GetLongWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutLongWithHttpMessagesAsync(LongWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<FloatWrapperInner>> GetFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutFloatWithHttpMessagesAsync(FloatWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<DoubleWrapperInner>> GetDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutDoubleWithHttpMessagesAsync(DoubleWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<BooleanWrapperInner>> GetBoolWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutBoolWithHttpMessagesAsync(BooleanWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<StringWrapperInner>> GetStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutStringWithHttpMessagesAsync(StringWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<DateWrapperInner>> GetDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutDateWithHttpMessagesAsync(DateWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<DatetimeWrapperInner>> GetDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and
/// '2015-05-18T11:38:00-08:00'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutDateTimeWithHttpMessagesAsync(DatetimeWrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<Datetimerfc1123WrapperInner>> GetDateTimeRfc1123WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015
/// 11:38:00 GMT'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PutDateTimeRfc1123WithHttpMessagesAsync(Datetimerfc1123WrapperInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<DurationWrapperInner>> GetDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='field'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<AzureOperationResponse> PutDurationWithHttpMessagesAsync(System.TimeSpan? field = default(System.TimeSpan?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<ByteWrapperInner>> GetByteWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='field'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<AzureOperationResponse> PutByteWithHttpMessagesAsync(byte[] field = default(byte[]), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace bGApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
public sealed class BuildJobExtension : JobExtension
{
public override Type ExtensionType => typeof(IJobExtension);
public override HostTypes HostType => HostTypes.Build;
private ServiceEndpoint SourceEndpoint { set; get; }
private ISourceProvider SourceProvider { set; get; }
public override IStep GetExtensionPreJobStep(IExecutionContext jobContext)
{
return new JobExtensionRunner(
context: jobContext.CreateChild(Guid.NewGuid(), StringUtil.Loc("GetSources"), nameof(BuildJobExtension)),
runAsync: GetSourceAsync,
condition: ExpressionManager.Succeeded,
displayName: StringUtil.Loc("GetSources"));
}
public override IStep GetExtensionPostJobStep(IExecutionContext jobContext)
{
return new JobExtensionRunner(
context: jobContext.CreateChild(Guid.NewGuid(), StringUtil.Loc("Cleanup"), nameof(BuildJobExtension)),
runAsync: PostJobCleanupAsync,
condition: ExpressionManager.Always,
displayName: StringUtil.Loc("Cleanup"));
}
// 1. use source provide to solve path, if solved result is rooted, return full path.
// 2. prefix default path root (build.sourcesDirectory), if result is rooted, return full path.
public override string GetRootedPath(IExecutionContext context, string path)
{
string rootedPath = null;
if (SourceProvider != null && SourceEndpoint != null)
{
path = SourceProvider.GetLocalPath(context, SourceEndpoint, path) ?? string.Empty;
Trace.Info($"Build JobExtension resolving path use source provide: {path}");
if (!string.IsNullOrEmpty(path) &&
path.IndexOfAny(Path.GetInvalidPathChars()) < 0 &&
Path.IsPathRooted(path))
{
try
{
rootedPath = Path.GetFullPath(path);
Trace.Info($"Path resolved by source provider is a rooted path, return absolute path: {rootedPath}");
return rootedPath;
}
catch (Exception ex)
{
Trace.Info($"Path resolved by source provider is a rooted path, but it is not a full qualified path: {path}");
Trace.Error(ex);
}
}
}
string defaultPathRoot = context.Variables.Get(Constants.Variables.Build.SourcesDirectory) ?? string.Empty;
Trace.Info($"The Default Path Root of Build JobExtension is build.sourcesDirectory: {defaultPathRoot}");
if (defaultPathRoot != null && defaultPathRoot.IndexOfAny(Path.GetInvalidPathChars()) < 0 &&
path != null && path.IndexOfAny(Path.GetInvalidPathChars()) < 0)
{
path = Path.Combine(defaultPathRoot, path);
Trace.Info($"After prefix Default Path Root provide by JobExtension: {path}");
if (Path.IsPathRooted(path))
{
try
{
rootedPath = Path.GetFullPath(path);
Trace.Info($"Return absolute path after prefix DefaultPathRoot: {rootedPath}");
return rootedPath;
}
catch (Exception ex)
{
Trace.Error(ex);
Trace.Info($"After prefix Default Path Root provide by JobExtension, the Path is a rooted path, but it is not full qualified, return the path: {path}.");
return path;
}
}
}
return rootedPath;
}
public override void ConvertLocalPath(IExecutionContext context, string localPath, out string repoName, out string sourcePath)
{
repoName = "";
// If no repo was found, send back an empty repo with original path.
sourcePath = localPath;
if (!string.IsNullOrEmpty(localPath) &&
File.Exists(localPath) &&
SourceEndpoint != null &&
SourceProvider != null)
{
// If we found a repo, calculate the relative path to the file
repoName = SourceEndpoint.Name;
sourcePath = IOUtil.MakeRelative(localPath, context.Variables.Get(Constants.Variables.Build.SourcesDirectory));
}
}
// Prepare build directory
// Set all build related variables
public override void InitializeJobExtension(IExecutionContext executionContext)
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
// This flag can be false for jobs like cleanup artifacts.
// If syncSources = false, we will not set source related build variable, not create build folder, not sync source.
bool syncSources = executionContext.Variables.Build_SyncSources ?? true;
if (!syncSources)
{
Trace.Info($"{Constants.Variables.Build.SyncSources} = false, we will not set source related build variable, not create build folder and not sync source");
return;
}
// Get the repo endpoint and source provider.
if (!TrySetPrimaryEndpointAndProviderInfo(executionContext))
{
throw new Exception(StringUtil.Loc("SupportedRepositoryEndpointNotFound"));
}
executionContext.Debug($"Primary repository: {SourceEndpoint.Name}. repository type: {SourceProvider.RepositoryType}");
// Set the repo variables.
string repositoryId;
if (SourceEndpoint.Data.TryGetValue("repositoryId", out repositoryId)) // TODO: Move to const after source artifacts PR is merged.
{
executionContext.Variables.Set(Constants.Variables.Build.RepoId, repositoryId);
}
executionContext.Variables.Set(Constants.Variables.Build.RepoName, SourceEndpoint.Name);
executionContext.Variables.Set(Constants.Variables.Build.RepoProvider, SourceEndpoint.Type);
executionContext.Variables.Set(Constants.Variables.Build.RepoUri, SourceEndpoint.Url?.AbsoluteUri);
string checkoutSubmoduleText;
if (SourceEndpoint.Data.TryGetValue(WellKnownEndpointData.CheckoutSubmodules, out checkoutSubmoduleText))
{
executionContext.Variables.Set(Constants.Variables.Build.RepoGitSubmoduleCheckout, checkoutSubmoduleText);
}
// overwrite primary repository's clean value if build.repository.clean is sent from server. this is used by tfvc gated check-in
bool? repoClean = executionContext.Variables.GetBoolean(Constants.Variables.Build.RepoClean);
if (repoClean != null)
{
SourceEndpoint.Data[WellKnownEndpointData.Clean] = repoClean.Value.ToString();
}
else
{
string cleanRepoText;
if (SourceEndpoint.Data.TryGetValue(WellKnownEndpointData.Clean, out cleanRepoText))
{
executionContext.Variables.Set(Constants.Variables.Build.RepoClean, cleanRepoText);
}
}
// Prepare the build directory.
executionContext.Output(StringUtil.Loc("PrepareBuildDir"));
var directoryManager = HostContext.GetService<IBuildDirectoryManager>();
TrackingConfig trackingConfig = directoryManager.PrepareDirectory(
executionContext,
SourceEndpoint,
SourceProvider);
// Set the directory variables.
executionContext.Output(StringUtil.Loc("SetBuildVars"));
string _workDirectory = IOUtil.GetWorkPath(HostContext);
executionContext.Variables.Set(Constants.Variables.Agent.BuildDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory));
executionContext.Variables.Set(Constants.Variables.System.ArtifactsDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory));
executionContext.Variables.Set(Constants.Variables.System.DefaultWorkingDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory));
executionContext.Variables.Set(Constants.Variables.Common.TestResultsDirectory, Path.Combine(_workDirectory, trackingConfig.TestResultsDirectory));
executionContext.Variables.Set(Constants.Variables.Build.BinariesDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory, Constants.Build.Path.BinariesDirectory));
executionContext.Variables.Set(Constants.Variables.Build.SourcesDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory));
executionContext.Variables.Set(Constants.Variables.Build.StagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory));
executionContext.Variables.Set(Constants.Variables.Build.ArtifactStagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory));
executionContext.Variables.Set(Constants.Variables.Build.RepoLocalPath, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory));
SourceProvider.SetVariablesInEndpoint(executionContext, SourceEndpoint);
}
private async Task GetSourceAsync(IExecutionContext executionContext)
{
// Validate args.
Trace.Entering();
// This flag can be false for jobs like cleanup artifacts.
// If syncSources = false, we will not set source related build variable, not create build folder, not sync source.
bool syncSources = executionContext.Variables.Build_SyncSources ?? true;
if (!syncSources)
{
Trace.Info($"{Constants.Variables.Build.SyncSources} = false, we will not set source related build variable, not create build folder and not sync source");
return;
}
ArgUtil.NotNull(SourceEndpoint, nameof(SourceEndpoint));
ArgUtil.NotNull(SourceProvider, nameof(SourceProvider));
// Read skipSyncSource property fron endpoint data
string skipSyncSourceText;
bool skipSyncSource = false;
if (SourceEndpoint.Data.TryGetValue("skipSyncSource", out skipSyncSourceText))
{
skipSyncSource = StringUtil.ConvertToBoolean(skipSyncSourceText, false);
}
// Prefer feature variable over endpoint data
skipSyncSource = executionContext.Variables.GetBoolean(Constants.Variables.Features.SkipSyncSource) ?? skipSyncSource;
if (skipSyncSource)
{
executionContext.Output($"Skip sync source for endpoint: {SourceEndpoint.Name}");
}
else
{
executionContext.Debug($"Sync source for endpoint: {SourceEndpoint.Name}");
await SourceProvider.GetSourceAsync(executionContext, SourceEndpoint, executionContext.CancellationToken);
}
}
private async Task PostJobCleanupAsync(IExecutionContext executionContext)
{
// Validate args.
Trace.Entering();
// If syncSources = false, we will not reset repository.
bool syncSources = executionContext.Variables.Build_SyncSources ?? true;
if (!syncSources)
{
Trace.Verbose($"{Constants.Variables.Build.SyncSources} = false, we will not run post job cleanup for this repository");
return;
}
ArgUtil.NotNull(SourceEndpoint, nameof(SourceEndpoint));
ArgUtil.NotNull(SourceProvider, nameof(SourceProvider));
// Read skipSyncSource property fron endpoint data
string skipSyncSourceText;
bool skipSyncSource = false;
if (SourceEndpoint != null && SourceEndpoint.Data.TryGetValue("skipSyncSource", out skipSyncSourceText))
{
skipSyncSource = StringUtil.ConvertToBoolean(skipSyncSourceText, false);
}
// Prefer feature variable over endpoint data
skipSyncSource = executionContext.Variables.GetBoolean(Constants.Variables.Features.SkipSyncSource) ?? skipSyncSource;
if (skipSyncSource)
{
Trace.Verbose($"{Constants.Variables.Build.SyncSources} = false, we will not run post job cleanup for this repository");
return;
}
await SourceProvider.PostJobCleanupAsync(executionContext, SourceEndpoint);
}
private bool TrySetPrimaryEndpointAndProviderInfo(IExecutionContext executionContext)
{
// Return the first service endpoint that contains a supported source provider.
Trace.Entering();
var extensionManager = HostContext.GetService<IExtensionManager>();
List<ISourceProvider> sourceProviders = extensionManager.GetExtensions<ISourceProvider>();
foreach (ServiceEndpoint ep in executionContext.Endpoints.Where(e => e.Data.ContainsKey("repositoryId")))
{
SourceProvider = sourceProviders
.FirstOrDefault(x => string.Equals(x.RepositoryType, ep.Type, StringComparison.OrdinalIgnoreCase));
if (SourceProvider != null)
{
SourceEndpoint = ep.Clone();
return true;
}
}
return false;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type PostExtensionsCollectionRequest.
/// </summary>
public partial class PostExtensionsCollectionRequest : BaseRequest, IPostExtensionsCollectionRequest
{
/// <summary>
/// Constructs a new PostExtensionsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public PostExtensionsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension)
{
return this.AddAsync(extension, CancellationToken.None);
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
extension.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(extension.GetType().FullName));
return this.SendAsync<Extension>(extension, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IPostExtensionsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IPostExtensionsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<PostExtensionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Expand(Expression<Func<Extension, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Select(Expression<Func<Extension, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IPostExtensionsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Stef.Validation;
using WireMock.Admin.Mappings;
using WireMock.Admin.Scenarios;
using WireMock.Admin.Settings;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Proxy;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.ResponseProviders;
using WireMock.Serialization;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Server
{
/// <summary>
/// The fluent mock server.
/// </summary>
public partial class WireMockServer
{
private const int EnhancedFileSystemWatcherTimeoutMs = 1000;
private const int AdminPriority = int.MinValue;
private const int ProxyPriority = 1000;
private const string ContentTypeJson = "application/json";
private const string AdminFiles = "/__admin/files";
private const string AdminMappings = "/__admin/mappings";
private const string AdminMappingsWireMockOrg = "/__admin/mappings/wiremock.org";
private const string AdminRequests = "/__admin/requests";
private const string AdminSettings = "/__admin/settings";
private const string AdminScenarios = "/__admin/scenarios";
private const string QueryParamReloadStaticMappings = "reloadStaticMappings";
private readonly RegexMatcher _adminRequestContentTypeJson = new ContentTypeMatcher(ContentTypeJson, true);
private readonly RegexMatcher _adminMappingsGuidPathMatcher = new RegexMatcher(@"^\/__admin\/mappings\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$");
private readonly RegexMatcher _adminRequestsGuidPathMatcher = new RegexMatcher(@"^\/__admin\/requests\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$");
#region InitAdmin
private void InitAdmin()
{
// __admin/settings
Given(Request.Create().WithPath(AdminSettings).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(SettingsGet));
Given(Request.Create().WithPath(AdminSettings).UsingMethod("PUT", "POST").WithHeader(HttpKnownHeaderNames.ContentType, _adminRequestContentTypeJson)).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(SettingsUpdate));
// __admin/mappings
Given(Request.Create().WithPath(AdminMappings).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingsGet));
Given(Request.Create().WithPath(AdminMappings).UsingPost().WithHeader(HttpKnownHeaderNames.ContentType, _adminRequestContentTypeJson)).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingsPost));
Given(Request.Create().WithPath(AdminMappingsWireMockOrg).UsingPost().WithHeader(HttpKnownHeaderNames.ContentType, _adminRequestContentTypeJson)).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingsPostWireMockOrg));
Given(Request.Create().WithPath(AdminMappings).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingsDelete));
// __admin/mappings/reset
Given(Request.Create().WithPath(AdminMappings + "/reset").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingsReset));
// __admin/mappings/{guid}
Given(Request.Create().WithPath(_adminMappingsGuidPathMatcher).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingGet));
Given(Request.Create().WithPath(_adminMappingsGuidPathMatcher).UsingPut().WithHeader(HttpKnownHeaderNames.ContentType, _adminRequestContentTypeJson)).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingPut));
Given(Request.Create().WithPath(_adminMappingsGuidPathMatcher).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingDelete));
// __admin/mappings/save
Given(Request.Create().WithPath(AdminMappings + "/save").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(MappingsSave));
// __admin/requests
Given(Request.Create().WithPath(AdminRequests).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(RequestsGet));
Given(Request.Create().WithPath(AdminRequests).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(RequestsDelete));
// __admin/requests/reset
Given(Request.Create().WithPath(AdminRequests + "/reset").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(RequestsDelete));
// __admin/request/{guid}
Given(Request.Create().WithPath(_adminRequestsGuidPathMatcher).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(RequestGet));
Given(Request.Create().WithPath(_adminRequestsGuidPathMatcher).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(RequestDelete));
// __admin/requests/find
Given(Request.Create().WithPath(AdminRequests + "/find").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(RequestsFind));
// __admin/scenarios
Given(Request.Create().WithPath(AdminScenarios).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(ScenariosGet));
Given(Request.Create().WithPath(AdminScenarios).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(ScenariosReset));
// __admin/scenarios/reset
Given(Request.Create().WithPath(AdminScenarios + "/reset").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(ScenariosReset));
// __admin/files/{filename}
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FilePost));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingPut()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FilePut));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileGet));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingHead()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileHead));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileDelete));
}
#endregion
#region StaticMappings
/// <inheritdoc cref="IWireMockServer.SaveStaticMappings" />
[PublicAPI]
public void SaveStaticMappings([CanBeNull] string folder = null)
{
foreach (var mapping in Mappings.Where(m => !m.IsAdminInterface))
{
_mappingToFileSaver.SaveMappingToFile(mapping, folder);
}
}
/// <inheritdoc cref="IWireMockServer.ReadStaticMappings" />
[PublicAPI]
public void ReadStaticMappings([CanBeNull] string folder = null)
{
if (folder == null)
{
folder = _settings.FileSystemHandler.GetMappingFolder();
}
if (!_settings.FileSystemHandler.FolderExists(folder))
{
_settings.Logger.Info("The Static Mapping folder '{0}' does not exist, reading Static MappingFiles will be skipped.", folder);
return;
}
foreach (string filename in _settings.FileSystemHandler.EnumerateFiles(folder, _settings.WatchStaticMappingsInSubdirectories == true).OrderBy(f => f))
{
_settings.Logger.Info("Reading Static MappingFile : '{0}'", filename);
try
{
ReadStaticMappingAndAddOrUpdate(filename);
}
catch
{
_settings.Logger.Error("Static MappingFile : '{0}' could not be read. This file will be skipped.", filename);
}
}
}
/// <inheritdoc cref="IWireMockServer.WatchStaticMappings" />
[PublicAPI]
public void WatchStaticMappings([CanBeNull] string folder = null)
{
if (folder == null)
{
folder = _settings.FileSystemHandler.GetMappingFolder();
}
if (!_settings.FileSystemHandler.FolderExists(folder))
{
return;
}
bool includeSubdirectories = _settings.WatchStaticMappingsInSubdirectories == true;
string includeSubdirectoriesText = includeSubdirectories ? " and Subdirectories" : string.Empty;
_settings.Logger.Info($"Watching folder '{folder}'{includeSubdirectoriesText} for new, updated and deleted MappingFiles.");
var watcher = new EnhancedFileSystemWatcher(folder, "*.json", EnhancedFileSystemWatcherTimeoutMs)
{
IncludeSubdirectories = includeSubdirectories
};
watcher.Created += (sender, args) =>
{
_settings.Logger.Info("MappingFile created : '{0}', reading file.", args.FullPath);
if (!ReadStaticMappingAndAddOrUpdate(args.FullPath))
{
_settings.Logger.Error("Unable to read MappingFile '{0}'.", args.FullPath);
}
};
watcher.Changed += (sender, args) =>
{
_settings.Logger.Info("MappingFile updated : '{0}', reading file.", args.FullPath);
if (!ReadStaticMappingAndAddOrUpdate(args.FullPath))
{
_settings.Logger.Error("Unable to read MappingFile '{0}'.", args.FullPath);
}
};
watcher.Deleted += (sender, args) =>
{
_settings.Logger.Info("MappingFile deleted : '{0}'", args.FullPath);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(args.FullPath);
if (Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
{
DeleteMapping(guidFromFilename);
}
else
{
DeleteMapping(args.FullPath);
}
};
watcher.EnableRaisingEvents = true;
}
/// <inheritdoc cref="IWireMockServer.WatchStaticMappings" />
[PublicAPI]
public bool ReadStaticMappingAndAddOrUpdate([NotNull] string path)
{
Guard.NotNull(path, nameof(path));
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(path);
if (FileHelper.TryReadMappingFileWithRetryAndDelay(_settings.FileSystemHandler, path, out string value))
{
var mappingModels = DeserializeJsonToArray<MappingModel>(value);
foreach (var mappingModel in mappingModels)
{
if (mappingModels.Length == 1 && Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
{
ConvertMappingAndRegisterAsRespondProvider(mappingModel, guidFromFilename, path);
}
else
{
ConvertMappingAndRegisterAsRespondProvider(mappingModel, null, path);
}
}
return true;
}
return false;
}
#endregion
#region Proxy and Record
private HttpClient _httpClientForProxy;
private void InitProxyAndRecord(IWireMockServerSettings settings)
{
_httpClientForProxy = HttpClientBuilder.Build(settings.ProxyAndRecordSettings);
var respondProvider = Given(Request.Create().WithPath("/*").UsingAnyMethod());
if (settings.StartAdminInterface == true)
{
respondProvider.AtPriority(ProxyPriority);
}
respondProvider.RespondWith(new ProxyAsyncResponseProvider(ProxyAndRecordAsync, settings));
}
private async Task<ResponseMessage> ProxyAndRecordAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
{
var requestUri = new Uri(requestMessage.Url);
var proxyUri = new Uri(settings.ProxyAndRecordSettings.Url);
var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery);
var proxyHelper = new ProxyHelper(settings);
var (responseMessage, mapping) = await proxyHelper.SendAsync(
_settings.ProxyAndRecordSettings,
_httpClientForProxy,
requestMessage,
proxyUriWithRequestPathAndQuery.AbsoluteUri
).ConfigureAwait(false);
if (mapping != null)
{
if (settings.ProxyAndRecordSettings.SaveMapping)
{
_options.Mappings.TryAdd(mapping.Guid, mapping);
}
if (settings.ProxyAndRecordSettings.SaveMappingToFile)
{
_mappingToFileSaver.SaveMappingToFile(mapping);
}
}
return responseMessage;
}
#endregion
#region Settings
private ResponseMessage SettingsGet(RequestMessage requestMessage)
{
var model = new SettingsModel
{
AllowPartialMapping = _settings.AllowPartialMapping,
MaxRequestLogCount = _settings.MaxRequestLogCount,
RequestLogExpirationDuration = _settings.RequestLogExpirationDuration,
GlobalProcessingDelay = (int?)_options.RequestProcessingDelay?.TotalMilliseconds,
AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods,
HandleRequestsSynchronously = _settings.HandleRequestsSynchronously,
ThrowExceptionWhenMatcherFails = _settings.ThrowExceptionWhenMatcherFails,
UseRegexExtended = _settings.UseRegexExtended,
SaveUnmatchedRequests = _settings.SaveUnmatchedRequests,
#if USE_ASPNETCORE
CorsPolicyOptions = _settings.CorsPolicyOptions?.ToString()
#endif
};
return ToJson(model);
}
private ResponseMessage SettingsUpdate(RequestMessage requestMessage)
{
var settings = DeserializeObject<SettingsModel>(requestMessage);
_options.MaxRequestLogCount = settings.MaxRequestLogCount;
_options.RequestLogExpirationDuration = settings.RequestLogExpirationDuration;
_options.AllowPartialMapping = settings.AllowPartialMapping;
if (settings.GlobalProcessingDelay != null)
{
_options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
}
_options.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods;
_options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously;
_settings.ThrowExceptionWhenMatcherFails = settings.ThrowExceptionWhenMatcherFails;
_settings.UseRegexExtended = settings.UseRegexExtended;
_settings.SaveUnmatchedRequests = settings.SaveUnmatchedRequests;
#if USE_ASPNETCORE
if (Enum.TryParse<CorsPolicyOptions>(settings.CorsPolicyOptions, true, out var corsPolicyOptions))
{
_settings.CorsPolicyOptions = corsPolicyOptions;
}
#endif
return ResponseMessageBuilder.Create("Settings updated");
}
#endregion Settings
#region Mapping/{guid}
private ResponseMessage MappingGet(RequestMessage requestMessage)
{
Guid guid = ParseGuidFromRequestMessage(requestMessage);
var mapping = Mappings.FirstOrDefault(m => !m.IsAdminInterface && m.Guid == guid);
if (mapping == null)
{
_settings.Logger.Warn("HttpStatusCode set to 404 : Mapping not found");
return ResponseMessageBuilder.Create("Mapping not found", 404);
}
var model = _mappingConverter.ToMappingModel(mapping);
return ToJson(model);
}
private ResponseMessage MappingPut(RequestMessage requestMessage)
{
Guid guid = ParseGuidFromRequestMessage(requestMessage);
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
Guid? guidFromPut = ConvertMappingAndRegisterAsRespondProvider(mappingModel, guid);
return ResponseMessageBuilder.Create("Mapping added or updated", 200, guidFromPut);
}
private ResponseMessage MappingDelete(RequestMessage requestMessage)
{
Guid guid = ParseGuidFromRequestMessage(requestMessage);
if (DeleteMapping(guid))
{
return ResponseMessageBuilder.Create("Mapping removed", 200, guid);
}
return ResponseMessageBuilder.Create("Mapping not found", 404);
}
private Guid ParseGuidFromRequestMessage(RequestMessage requestMessage)
{
return Guid.Parse(requestMessage.Path.Substring(AdminMappings.Length + 1));
}
#endregion Mapping/{guid}
#region Mappings
private ResponseMessage MappingsSave(RequestMessage requestMessage)
{
SaveStaticMappings();
return ResponseMessageBuilder.Create("Mappings saved to disk");
}
private IEnumerable<MappingModel> ToMappingModels()
{
return Mappings.Where(m => !m.IsAdminInterface).Select(_mappingConverter.ToMappingModel);
}
private ResponseMessage MappingsGet(RequestMessage requestMessage)
{
return ToJson(ToMappingModels());
}
private ResponseMessage MappingsPost(RequestMessage requestMessage)
{
try
{
var mappingModels = DeserializeRequestMessageToArray<MappingModel>(requestMessage);
if (mappingModels.Length == 1)
{
Guid? guid = ConvertMappingAndRegisterAsRespondProvider(mappingModels[0]);
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
}
foreach (var mappingModel in mappingModels)
{
ConvertMappingAndRegisterAsRespondProvider(mappingModel);
}
return ResponseMessageBuilder.Create("Mappings added", 201);
}
catch (ArgumentException a)
{
_settings.Logger.Error("HttpStatusCode set to 400 {0}", a);
return ResponseMessageBuilder.Create(a.Message, 400);
}
catch (Exception e)
{
_settings.Logger.Error("HttpStatusCode set to 500 {0}", e);
return ResponseMessageBuilder.Create(e.ToString(), 500);
}
}
private Guid? ConvertMappingAndRegisterAsRespondProvider(MappingModel mappingModel, Guid? guid = null, string path = null)
{
Guard.NotNull(mappingModel, nameof(mappingModel));
Guard.NotNull(mappingModel.Request, nameof(mappingModel.Request));
Guard.NotNull(mappingModel.Response, nameof(mappingModel.Response));
var requestBuilder = InitRequestBuilder(mappingModel.Request, true);
if (requestBuilder == null)
{
return null;
}
var responseBuilder = InitResponseBuilder(mappingModel.Response);
var respondProvider = Given(requestBuilder, mappingModel.SaveToFile == true);
if (guid != null)
{
respondProvider = respondProvider.WithGuid(guid.Value);
}
else if (mappingModel.Guid != null && mappingModel.Guid != Guid.Empty)
{
respondProvider = respondProvider.WithGuid(mappingModel.Guid.Value);
}
if (mappingModel.TimeSettings != null)
{
respondProvider = respondProvider.WithTimeSettings(TimeSettingsMapper.Map(mappingModel.TimeSettings));
}
if (path != null)
{
respondProvider = respondProvider.WithPath(path);
}
if (!string.IsNullOrEmpty(mappingModel.Title))
{
respondProvider = respondProvider.WithTitle(mappingModel.Title);
}
if (mappingModel.Priority != null)
{
respondProvider = respondProvider.AtPriority(mappingModel.Priority.Value);
}
if (mappingModel.Scenario != null)
{
respondProvider = respondProvider.InScenario(mappingModel.Scenario);
respondProvider = respondProvider.WhenStateIs(mappingModel.WhenStateIs);
respondProvider = respondProvider.WillSetStateTo(mappingModel.SetStateTo);
}
if (mappingModel.Webhook != null)
{
respondProvider = respondProvider.WithWebhook(WebhookMapper.Map(mappingModel.Webhook));
}
else if (mappingModel.Webhooks?.Length > 1)
{
var webhooks = mappingModel.Webhooks.Select(WebhookMapper.Map).ToArray();
respondProvider = respondProvider.WithWebhook(webhooks);
}
respondProvider.RespondWith(responseBuilder);
return respondProvider.Guid;
}
private ResponseMessage MappingsDelete(RequestMessage requestMessage)
{
if (!string.IsNullOrEmpty(requestMessage.Body))
{
var deletedGuids = MappingsDeleteMappingFromBody(requestMessage);
if (deletedGuids != null)
{
return ResponseMessageBuilder.Create($"Mappings deleted. Affected GUIDs: [{string.Join(", ", deletedGuids.ToArray())}]");
}
else
{
// return bad request
return ResponseMessageBuilder.Create("Poorly formed mapping JSON.", 400);
}
}
else
{
ResetMappings();
ResetScenarios();
return ResponseMessageBuilder.Create("Mappings deleted");
}
}
private IEnumerable<Guid> MappingsDeleteMappingFromBody(RequestMessage requestMessage)
{
var deletedGuids = new List<Guid>();
try
{
var mappingModels = DeserializeRequestMessageToArray<MappingModel>(requestMessage);
foreach (var mappingModel in mappingModels)
{
if (mappingModel.Guid.HasValue)
{
if (DeleteMapping(mappingModel.Guid.Value))
{
deletedGuids.Add(mappingModel.Guid.Value);
}
else
{
_settings.Logger.Debug($"Did not find/delete mapping with GUID: {mappingModel.Guid.Value}.");
}
}
}
}
catch (ArgumentException a)
{
_settings.Logger.Error("ArgumentException: {0}", a);
return null;
}
catch (Exception e)
{
_settings.Logger.Error("Exception: {0}", e);
return null;
}
return deletedGuids;
}
private ResponseMessage MappingsReset(RequestMessage requestMessage)
{
ResetMappings();
ResetScenarios();
string message = "Mappings reset";
if (requestMessage.Query.ContainsKey(QueryParamReloadStaticMappings) &&
bool.TryParse(requestMessage.Query[QueryParamReloadStaticMappings].ToString(), out bool reloadStaticMappings)
&& reloadStaticMappings)
{
ReadStaticMappings();
message = $"{message} and static mappings reloaded";
}
return ResponseMessageBuilder.Create(message);
}
#endregion Mappings
#region Request/{guid}
private ResponseMessage RequestGet(RequestMessage requestMessage)
{
Guid guid = ParseGuidFromRequestMessage(requestMessage);
var entry = LogEntries.FirstOrDefault(r => !r.RequestMessage.Path.StartsWith("/__admin/") && r.Guid == guid);
if (entry == null)
{
_settings.Logger.Warn("HttpStatusCode set to 404 : Request not found");
return ResponseMessageBuilder.Create("Request not found", 404);
}
var model = LogEntryMapper.Map(entry);
return ToJson(model);
}
private ResponseMessage RequestDelete(RequestMessage requestMessage)
{
Guid guid = ParseGuidFromRequestMessage(requestMessage);
if (DeleteLogEntry(guid))
{
return ResponseMessageBuilder.Create("Request removed");
}
return ResponseMessageBuilder.Create("Request not found", 404);
}
#endregion Request/{guid}
#region Requests
private ResponseMessage RequestsGet(RequestMessage requestMessage)
{
var result = LogEntries
.Where(r => !r.RequestMessage.Path.StartsWith("/__admin/"))
.Select(LogEntryMapper.Map);
return ToJson(result);
}
private ResponseMessage RequestsDelete(RequestMessage requestMessage)
{
ResetLogEntries();
return ResponseMessageBuilder.Create("Requests deleted");
}
#endregion Requests
#region Requests/find
private ResponseMessage RequestsFind(RequestMessage requestMessage)
{
var requestModel = DeserializeObject<RequestModel>(requestMessage);
var request = (Request)InitRequestBuilder(requestModel, false);
var dict = new Dictionary<ILogEntry, RequestMatchResult>();
foreach (var logEntry in LogEntries.Where(le => !le.RequestMessage.Path.StartsWith("/__admin/")))
{
var requestMatchResult = new RequestMatchResult();
if (request.GetMatchingScore(logEntry.RequestMessage, requestMatchResult) > MatchScores.AlmostPerfect)
{
dict.Add(logEntry, requestMatchResult);
}
}
var result = dict.OrderBy(x => x.Value.AverageTotalScore).Select(x => x.Key).Select(LogEntryMapper.Map);
return ToJson(result);
}
#endregion Requests/find
#region Scenarios
private ResponseMessage ScenariosGet(RequestMessage requestMessage)
{
var scenariosStates = Scenarios.Values.Select(s => new ScenarioStateModel
{
Name = s.Name,
NextState = s.NextState,
Started = s.Started,
Finished = s.Finished,
Counter = s.Counter
});
return ToJson(scenariosStates, true);
}
private ResponseMessage ScenariosReset(RequestMessage requestMessage)
{
ResetScenarios();
return ResponseMessageBuilder.Create("Scenarios reset");
}
#endregion
private IRequestBuilder InitRequestBuilder(RequestModel requestModel, bool pathOrUrlRequired)
{
IRequestBuilder requestBuilder = Request.Create();
if (requestModel.ClientIP != null)
{
if (requestModel.ClientIP is string clientIP)
{
requestBuilder = requestBuilder.WithClientIP(clientIP);
}
else
{
var clientIPModel = JsonUtils.ParseJTokenToObject<ClientIPModel>(requestModel.ClientIP);
if (clientIPModel?.Matchers != null)
{
requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
}
}
}
bool pathOrUrlMatchersValid = false;
if (requestModel.Path != null)
{
if (requestModel.Path is string path)
{
requestBuilder = requestBuilder.WithPath(path);
pathOrUrlMatchersValid = true;
}
else
{
var pathModel = JsonUtils.ParseJTokenToObject<PathModel>(requestModel.Path);
if (pathModel?.Matchers != null)
{
requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
pathOrUrlMatchersValid = true;
}
}
}
else if (requestModel.Url != null)
{
if (requestModel.Url is string url)
{
requestBuilder = requestBuilder.WithUrl(url);
pathOrUrlMatchersValid = true;
}
else
{
var urlModel = JsonUtils.ParseJTokenToObject<UrlModel>(requestModel.Url);
if (urlModel?.Matchers != null)
{
requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
pathOrUrlMatchersValid = true;
}
}
}
if (pathOrUrlRequired && !pathOrUrlMatchersValid)
{
_settings.Logger.Error("Path or Url matcher is missing for this mapping, this mapping will not be added.");
return null;
}
if (requestModel.Methods != null)
{
requestBuilder = requestBuilder.UsingMethod(requestModel.Methods);
}
if (requestModel.Headers != null)
{
foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null))
{
requestBuilder = requestBuilder.WithHeader(
headerModel.Name,
headerModel.IgnoreCase == true,
headerModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
headerModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray()
);
}
}
if (requestModel.Cookies != null)
{
foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null))
{
requestBuilder = requestBuilder.WithCookie(
cookieModel.Name,
cookieModel.IgnoreCase == true,
cookieModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
cookieModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
}
}
if (requestModel.Params != null)
{
foreach (var paramModel in requestModel.Params.Where(p => p != null && p.Matchers != null))
{
bool ignoreCase = paramModel.IgnoreCase == true;
requestBuilder = requestBuilder.WithParam(paramModel.Name, ignoreCase, paramModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
}
}
if (requestModel.Body?.Matcher != null)
{
requestBuilder = requestBuilder.WithBody(_matcherMapper.Map(requestModel.Body.Matcher));
}
else if (requestModel.Body?.Matchers != null)
{
requestBuilder = requestBuilder.WithBody(_matcherMapper.Map(requestModel.Body.Matchers));
}
return requestBuilder;
}
private IResponseBuilder InitResponseBuilder(ResponseModel responseModel)
{
IResponseBuilder responseBuilder = Response.Create();
if (responseModel.Delay > 0)
{
responseBuilder = responseBuilder.WithDelay(responseModel.Delay.Value);
}
else if (responseModel.MinimumRandomDelay >= 0 || responseModel.MaximumRandomDelay > 0)
{
responseBuilder = responseBuilder.WithRandomDelay(responseModel.MinimumRandomDelay ?? 0, responseModel.MaximumRandomDelay ?? 60_000);
}
if (responseModel.UseTransformer == true)
{
if (!Enum.TryParse<TransformerType>(responseModel.TransformerType, out var transformerType))
{
transformerType = TransformerType.Handlebars;
}
if (!Enum.TryParse<ReplaceNodeOptions>(responseModel.TransformerReplaceNodeOptions, out var option))
{
option = ReplaceNodeOptions.None;
}
responseBuilder = responseBuilder.WithTransformer(
transformerType,
responseModel.UseTransformerForBodyAsFile == true,
option);
}
if (!string.IsNullOrEmpty(responseModel.ProxyUrl))
{
var proxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = responseModel.ProxyUrl,
ClientX509Certificate2ThumbprintOrSubjectName = responseModel.X509Certificate2ThumbprintOrSubjectName,
WebProxySettings = responseModel.WebProxy != null ? new WebProxySettings
{
Address = responseModel.WebProxy.Address,
UserName = responseModel.WebProxy.UserName,
Password = responseModel.WebProxy.Password
} : null
};
return responseBuilder.WithProxy(proxyAndRecordSettings);
}
if (responseModel.StatusCode is string statusCodeAsString)
{
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsString);
}
else if (responseModel.StatusCode != null)
{
// Convert to Int32 because Newtonsoft deserializes an 'object' with a number value to a long.
responseBuilder = responseBuilder.WithStatusCode(Convert.ToInt32(responseModel.StatusCode));
}
if (responseModel.Headers != null)
{
foreach (var entry in responseModel.Headers)
{
responseBuilder = entry.Value is string value ?
responseBuilder.WithHeader(entry.Key, value) :
responseBuilder.WithHeader(entry.Key, JsonUtils.ParseJTokenToObject<string[]>(entry.Value));
}
}
else if (responseModel.HeadersRaw != null)
{
foreach (string headerLine in responseModel.HeadersRaw.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
{
int indexColon = headerLine.IndexOf(":", StringComparison.Ordinal);
string key = headerLine.Substring(0, indexColon).TrimStart(' ', '\t');
string value = headerLine.Substring(indexColon + 1).TrimStart(' ', '\t');
responseBuilder = responseBuilder.WithHeader(key, value);
}
}
if (responseModel.BodyAsBytes != null)
{
responseBuilder = responseBuilder.WithBody(responseModel.BodyAsBytes, responseModel.BodyDestination, ToEncoding(responseModel.BodyEncoding));
}
else if (responseModel.Body != null)
{
responseBuilder = responseBuilder.WithBody(responseModel.Body, responseModel.BodyDestination, ToEncoding(responseModel.BodyEncoding));
}
else if (responseModel.BodyAsJson != null)
{
responseBuilder = responseBuilder.WithBodyAsJson(responseModel.BodyAsJson, ToEncoding(responseModel.BodyEncoding), responseModel.BodyAsJsonIndented == true);
}
else if (responseModel.BodyAsFile != null)
{
responseBuilder = responseBuilder.WithBodyFromFile(responseModel.BodyAsFile);
}
if (responseModel.Fault != null && Enum.TryParse(responseModel.Fault.Type, out FaultType faultType))
{
responseBuilder.WithFault(faultType, responseModel.Fault.Percentage);
}
return responseBuilder;
}
private ResponseMessage ToJson<T>(T result, bool keepNullValues = false)
{
return new ResponseMessage
{
BodyData = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = JsonConvert.SerializeObject(result, keepNullValues ? JsonSerializationConstants.JsonSerializerSettingsIncludeNullValues : JsonSerializationConstants.JsonSerializerSettingsDefault)
},
StatusCode = (int)HttpStatusCode.OK,
Headers = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string>(ContentTypeJson) } }
};
}
private Encoding ToEncoding(EncodingModel encodingModel)
{
return encodingModel != null ? Encoding.GetEncoding(encodingModel.CodePage) : null;
}
private T DeserializeObject<T>(RequestMessage requestMessage)
{
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.String)
{
return JsonUtils.DeserializeObject<T>(requestMessage.BodyData.BodyAsString);
}
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{
return ((JObject)requestMessage.BodyData.BodyAsJson).ToObject<T>();
}
return default(T);
}
private T[] DeserializeRequestMessageToArray<T>(RequestMessage requestMessage)
{
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{
var bodyAsJson = requestMessage.BodyData.BodyAsJson;
return DeserializeObjectToArray<T>(bodyAsJson);
}
return default(T[]);
}
private T[] DeserializeObjectToArray<T>(object value)
{
if (value is JArray jArray)
{
return jArray.ToObject<T[]>();
}
var singleResult = ((JObject)value).ToObject<T>();
return new[] { singleResult };
}
private T[] DeserializeJsonToArray<T>(string value)
{
return DeserializeObjectToArray<T>(JsonUtils.DeserializeObject(value));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Internal.Host
{
internal
class InternalHostRawUserInterface : PSHostRawUserInterface
{
internal
InternalHostRawUserInterface(PSHostRawUserInterface externalRawUI, InternalHost parentHost)
{
// externalRawUI may be null
_externalRawUI = externalRawUI;
_parentHost = parentHost;
}
internal
void
ThrowNotInteractive()
{
// It might be interesting to do something like
// GetCallingMethodAndParameters here and display the name,
// but I don't want to put that in mainline non-trace code.
string message = HostInterfaceExceptionsStrings.HostFunctionNotImplemented;
HostException e = new HostException(
message,
null,
"HostFunctionNotImplemented",
ErrorCategory.NotImplemented);
throw e;
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
ConsoleColor
ForegroundColor
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
ConsoleColor result = _externalRawUI.ForegroundColor;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.ForegroundColor = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
ConsoleColor
BackgroundColor
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
ConsoleColor result = _externalRawUI.BackgroundColor;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.BackgroundColor = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
Coordinates
CursorPosition
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
Coordinates result = _externalRawUI.CursorPosition;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.CursorPosition = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
Coordinates
WindowPosition
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
Coordinates result = _externalRawUI.WindowPosition;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.WindowPosition = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
int
CursorSize
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
int result = _externalRawUI.CursorSize;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.CursorSize = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
Size
BufferSize
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
Size result = _externalRawUI.BufferSize;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.BufferSize = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
Size
WindowSize
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
Size result = _externalRawUI.WindowSize;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.WindowSize = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
Size
MaxWindowSize
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
Size result = _externalRawUI.MaxWindowSize;
return result;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
Size
MaxPhysicalWindowSize
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
Size result = _externalRawUI.MaxPhysicalWindowSize;
return result;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <param name="options">
/// </param>
/// <returns></returns>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
KeyInfo
ReadKey(ReadKeyOptions options)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
KeyInfo result = new KeyInfo();
try
{
result = _externalRawUI.ReadKey(options);
}
catch (PipelineStoppedException)
{
// PipelineStoppedException is thrown by host when it wants
// to stop the pipeline.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parentHost.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
{
throw;
}
lpl.Stopper.Stop();
}
return result;
}
/// <summary>
/// See base class.
/// </summary>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
void
FlushInputBuffer()
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.FlushInputBuffer();
}
/// <summary>
/// See base class.
/// </summary>
/// <returns></returns>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
bool
KeyAvailable
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
bool result = _externalRawUI.KeyAvailable;
return result;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
string
WindowTitle
{
get
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
string result = _externalRawUI.WindowTitle;
return result;
}
set
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.WindowTitle = value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <param name="origin"></param>
/// <param name="contents"></param>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
void
SetBufferContents(Coordinates origin, BufferCell[,] contents)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.SetBufferContents(origin, contents);
}
/// <summary>
/// See base class.
/// </summary>
/// <param name="r">
/// </param>
/// <param name="fill">
/// </param>
/// <remarks>
/// </remarks>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
void
SetBufferContents(Rectangle r, BufferCell fill)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.SetBufferContents(r, fill);
}
/// <summary>
/// See base class.
/// </summary>
/// <param name="r"></param>
/// <returns></returns>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
BufferCell[,]
GetBufferContents(Rectangle r)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
return _externalRawUI.GetBufferContents(r);
}
/// <summary>
/// See base class.
/// </summary>
/// <param name="source">
/// </param>
/// <param name="destination">
/// </param>
/// <param name="clip">
/// </param>
/// <param name="fill">
/// </param>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
void
ScrollBufferContents
(
Rectangle source,
Coordinates destination,
Rectangle clip,
BufferCell fill
)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
_externalRawUI.ScrollBufferContents(source, destination, clip, fill);
}
/// <summary>
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override int LengthInBufferCells(string str)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
return _externalRawUI.LengthInBufferCells(str);
}
/// <summary>
/// </summary>
/// <param name="str"></param>
/// <param name="offset"></param>
/// <returns></returns>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override int LengthInBufferCells(string str, int offset)
{
Dbg.Assert(offset >= 0, "offset >= 0");
Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length");
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
return _externalRawUI.LengthInBufferCells(str, offset);
}
/// <summary>
/// </summary>
/// <param name="character"></param>
/// <returns></returns>
/// <exception cref="HostException">
/// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not
/// implemented by the external host
/// </exception>
public override
int
LengthInBufferCells(char character)
{
if (_externalRawUI == null)
{
ThrowNotInteractive();
}
return _externalRawUI.LengthInBufferCells(character);
}
private PSHostRawUserInterface _externalRawUI;
private InternalHost _parentHost;
}
}
| |
// 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 Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using NuGet.ContentModel;
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class HarvestPackage : PackagingTask
{
/// <summary>
/// Package ID to harvest
/// </summary>
[Required]
public string PackageId { get; set; }
/// <summary>
/// Current package version.
/// </summary>
[Required]
public string PackageVersion { get; set; }
/// <summary>
/// Folder where packages have been restored
/// </summary>
[Required]
public string PackagesFolder { get; set; }
/// <summary>
/// Path to runtime.json that contains the runtime graph.
/// </summary>
[Required]
public string RuntimeFile { get; set; }
/// <summary>
/// Additional packages to consider for evaluating support but not harvesting assets.
/// Identity: Package ID
/// Version: Package version.
/// </summary>
public ITaskItem[] RuntimePackages { get; set; }
/// <summary>
/// Set to false to suppress harvesting of files and only harvest supported framework information.
/// </summary>
public bool HarvestAssets { get; set; }
/// <summary>
/// Set to true to harvest all files by default.
/// </summary>
public bool IncludeAllPaths { get; set; }
/// <summary>
/// Set to partial paths to exclude from file harvesting.
/// </summary>
public string[] PathsToExclude { get; set; }
/// <summary>
/// Set to partial paths to include from file harvesting.
/// </summary>
public ITaskItem[] PathsToInclude { get; set; }
/// <summary>
/// Set to partial paths to suppress from both file and support harvesting.
/// </summary>
public string[] PathsToSuppress { get; set; }
/// <summary>
/// Frameworks to consider for support evaluation.
/// Identity: Framework
/// RuntimeIDs: Semi-colon seperated list of runtime IDs
/// </summary>
public ITaskItem[] Frameworks { get; set; }
/// <summary>
/// Files already in the package.
/// Identity: path to file
/// AssemblyVersion: version of assembly
/// TargetFramework: target framework moniker to use for harvesting file's dependencies
/// TargetPath: path of file in package
/// IsReferenceAsset: true for files in Ref.
/// </summary>
public ITaskItem[] Files { get; set; }
/// <summary>
/// Frameworks that were supported by previous package version.
/// Identity: Framework
/// Version: Assembly version if supported
/// </summary>
[Output]
public ITaskItem[] SupportedFrameworks { get; set; }
/// <summary>
/// Files harvested from previous package version.
/// Identity: path to file
/// AssemblyVersion: version of assembly
/// TargetFramework: target framework moniker to use for harvesting file's dependencies
/// TargetPath: path of file in package
/// IsReferenceAsset: true for files in Ref.
/// </summary>
[Output]
public ITaskItem[] HarvestedFiles { get; set; }
/// <summary>
/// When Files are specified, contains the updated set of files, with removals.
/// </summary>
[Output]
public ITaskItem[] UpdatedFiles { get; set; }
/// <summary>
/// Generates a table in markdown that lists the API version supported by
/// various packages at all levels of NETStandard.
/// </summary>
/// <returns></returns>
public override bool Execute()
{
if (!Directory.Exists(PackagesFolder))
{
Log.LogError($"PackagesFolder {PackagesFolder} does not exist.");
}
if (HasPackagesToHarvest())
{
if (HarvestAssets)
{
HarvestFilesFromPackage();
}
if (Frameworks != null && Frameworks.Length > 0)
{
HarvestSupportedFrameworks();
}
}
return !Log.HasLoggedErrors;
}
private bool HasPackagesToHarvest()
{
bool result = true;
IEnumerable<string> packageDirs = new[] { Path.Combine(PackageId, PackageVersion) };
if (RuntimePackages != null)
{
packageDirs = packageDirs.Concat(
RuntimePackages.Select(p => Path.Combine(p.ItemSpec, p.GetMetadata("Version"))));
}
foreach (var packageDir in packageDirs)
{
var pathToPackage = Path.Combine(PackagesFolder, packageDir);
if (!Directory.Exists(pathToPackage))
{
Log.LogError($"Cannot harvest package '{PackageId}' version '{PackageVersion}' because {pathToPackage} does not exist. Harvesting is needed to redistribute assets and ensure compatiblity with the previous release. You can disable this by setting HarvestStablePackage=false.");
result = false;
}
}
return result;
}
private void HarvestSupportedFrameworks()
{
List<ITaskItem> supportedFrameworks = new List<ITaskItem>();
AggregateNuGetAssetResolver resolver = new AggregateNuGetAssetResolver(RuntimeFile);
string packagePath = Path.Combine(PackagesFolder, PackageId, PackageVersion);
// add the primary package
resolver.AddPackageItems(PackageId, GetPackageItems(packagePath));
if (RuntimePackages != null)
{
// add any split runtime packages
foreach (var runtimePackage in RuntimePackages)
{
var runtimePackageId = runtimePackage.ItemSpec;
var runtimePackageVersion = runtimePackage.GetMetadata("Version");
resolver.AddPackageItems(runtimePackageId, GetPackageItems(PackagesFolder, runtimePackageId, runtimePackageVersion));
}
}
// create a resolver that can be used to determine the API version for inbox assemblies
// since inbox assemblies are represented with placeholders we can remove the placeholders
// and use the netstandard reference assembly to determine the API version
var filesWithoutPlaceholders = GetPackageItems(packagePath)
.Where(f => !NuGetAssetResolver.IsPlaceholder(f));
NuGetAssetResolver resolverWithoutPlaceholders = new NuGetAssetResolver(RuntimeFile, filesWithoutPlaceholders);
string package = $"{PackageId}/{PackageVersion}";
foreach (var framework in Frameworks)
{
var runtimeIds = framework.GetMetadata("RuntimeIDs")?.Split(';');
NuGetFramework fx;
try
{
fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework.");
continue;
}
var compileAssets = resolver.ResolveCompileAssets(fx, PackageId);
bool hasCompileAsset, hasCompilePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Compile", package, fx.ToString(), compileAssets, out hasCompileAsset, out hasCompilePlaceHolder);
// start by making sure it has some asset available for compile
var isSupported = hasCompileAsset || hasCompilePlaceHolder;
if (!isSupported)
{
Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported.");
continue;
}
foreach (var runtimeId in runtimeIds)
{
string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}";
var runtimeAssets = resolver.ResolveRuntimeAssets(fx, runtimeId);
bool hasRuntimeAsset, hasRuntimePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Runtime", package, target, runtimeAssets, out hasRuntimeAsset, out hasRuntimePlaceHolder);
isSupported &= hasCompileAsset == hasRuntimeAsset;
isSupported &= hasCompilePlaceHolder == hasRuntimePlaceHolder;
if (!isSupported)
{
Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported on {target}.");
break;
}
}
if (isSupported)
{
var supportedFramework = new TaskItem(framework.ItemSpec);
supportedFramework.SetMetadata("HarvestedFromPackage", package);
// set version
// first try the resolved compile asset for this package
var refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r))?.Substring(PackageId.Length + 1);
if (refAssm == null)
{
// if we didn't have a compile asset it means this framework is supported inbox with a placeholder
// resolve the assets without placeholders to pick up the netstandard reference assembly.
compileAssets = resolverWithoutPlaceholders.ResolveCompileAssets(fx);
refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r));
}
string version = "unknown";
if (refAssm != null)
{
version = VersionUtility.GetAssemblyVersion(Path.Combine(packagePath, refAssm))?.ToString() ?? version;
}
supportedFramework.SetMetadata("Version", version);
Log.LogMessage(LogImportance.Low, $"Validating version {version} for {supportedFramework.ItemSpec} because it was supported by {PackageId}/{PackageVersion}.");
supportedFrameworks.Add(supportedFramework);
}
}
SupportedFrameworks = supportedFrameworks.ToArray();
}
public void HarvestFilesFromPackage()
{
string pathToPackage = Path.Combine(PackagesFolder, PackageId, PackageVersion);
if (!Directory.Exists(pathToPackage))
{
Log.LogError($"Cannot harvest from package {PackageId}/{PackageVersion} because {pathToPackage} does not exist.");
return;
}
var livePackageItems = Files.NullAsEmpty()
.Where(f => IsIncludedExtension(f.GetMetadata("Extension")))
.Select(f => new PackageItem(f));
var livePackageFiles = new Dictionary<string, PackageItem>(StringComparer.OrdinalIgnoreCase);
foreach (var livePackageItem in livePackageItems)
{
PackageItem existingitem;
if (livePackageFiles.TryGetValue(livePackageItem.TargetPath, out existingitem))
{
Log.LogError($"Package contains two files with same targetpath: {livePackageItem.TargetPath}, items:{livePackageItem.SourcePath}, {existingitem.SourcePath}.");
}
else
{
livePackageFiles.Add(livePackageItem.TargetPath, livePackageItem);
}
}
var harvestedFiles = new List<ITaskItem>();
var removeFiles = new List<ITaskItem>();
// make sure we preserve refs that match desktop assemblies
var liveDesktopDlls = livePackageFiles.Values.Where(pi => pi.IsDll && pi.TargetFramework?.Framework == FrameworkConstants.FrameworkIdentifiers.Net);
var desktopRefVersions = liveDesktopDlls.Where(d => d.IsRef && d.Version != null).Select(d => d.Version);
var desktopLibVersions = liveDesktopDlls.Where(d => !d.IsRef && d.Version != null).Select(d => d.Version);
// find destkop assemblies with no matching lib.
var preserveRefVersion = new HashSet<Version>(desktopLibVersions);
preserveRefVersion.ExceptWith(desktopRefVersions);
foreach (var extension in s_includedExtensions)
{
foreach (var packageFile in Directory.EnumerateFiles(pathToPackage, $"*{extension}", SearchOption.AllDirectories))
{
string packagePath = packageFile.Substring(pathToPackage.Length + 1).Replace('\\', '/');
// determine if we should include this file from the harvested package
// exclude if its specifically set for exclusion
if (ShouldExclude(packagePath))
{
Log.LogMessage(LogImportance.Low, $"Excluding package path {packagePath} because it is specifically excluded.");
continue;
}
ITaskItem includeItem = null;
if (!IncludeAllPaths && !ShouldInclude(packagePath, out includeItem))
{
Log.LogMessage(LogImportance.Low, $"Excluding package path {packagePath} because it is not included in {nameof(PathsToInclude)}.");
continue;
}
// allow for the harvested item to be moved
var remappedTargetPath = includeItem?.GetMetadata("TargetPath");
if (!String.IsNullOrEmpty(remappedTargetPath))
{
packagePath = remappedTargetPath + '/' + Path.GetFileName(packageFile);
}
var assemblyVersion = extension == s_dll ? VersionUtility.GetAssemblyVersion(packageFile) : null;
PackageItem liveFile = null;
// determine if the harvested file clashes with a live built file
// we'll prefer the harvested reference assembly so long as it's the same API
// version and not required to match implementation 1:1 as is the case for desktop
if (livePackageFiles.TryGetValue(packagePath, out liveFile))
{
// Not a dll, or not a versioned assembly: prefer live built file.
if (extension != s_dll || assemblyVersion == null || liveFile.Version == null)
{
// we don't consider this an error even for explicitly included files
Log.LogMessage(LogImportance.Low, $"Preferring live build of package path {packagePath} over the asset from last stable package because the file is not versioned.");
continue;
}
// not a ref
if (!liveFile.IsRef )
{
LogSkipIncludedFile(packagePath, " because it is a newer implementation.");
continue;
}
// preserve desktop references to ensure bindingRedirects will work.
if (liveFile.TargetFramework.Framework == FrameworkConstants.FrameworkIdentifiers.Net)
{
LogSkipIncludedFile(packagePath, " because it is desktop reference.");
continue;
}
// as above but handle the case where a netstandard ref may be used for a desktop impl.
if (preserveRefVersion.Contains(liveFile.Version))
{
LogSkipIncludedFile(packagePath, " because it will be applicable for desktop projects.");
continue;
}
// preserve references with a different major.minor version
if (assemblyVersion.Major != liveFile.Version.Major ||
assemblyVersion.Minor != liveFile.Version.Minor)
{
LogSkipIncludedFile(packagePath, $" because it is a different API version ( {liveFile.Version.Major}.{liveFile.Version.Minor} vs {assemblyVersion.Major}.{assemblyVersion.Minor}.");
continue;
}
// preserve references that specifically set the preserve metadata.
bool preserve = false;
bool.TryParse(liveFile.OriginalItem.GetMetadata("Preserve"), out preserve);
if (preserve)
{
LogSkipIncludedFile(packagePath, " because it set metadata Preserve=true.");
continue;
}
// replace the live file with the harvested one, removing both the live file and PDB from the
// file list.
Log.LogMessage($"Using reference {packagePath} from last stable package {PackageId}/{PackageVersion} rather than the built reference {liveFile.SourcePath} since it is the same API version. Set <Preserve>true</Preserve> on {liveFile.SourceProject} if you'd like to avoid this..");
removeFiles.Add(liveFile.OriginalItem);
PackageItem livePdbFile;
if (livePackageFiles.TryGetValue(Path.ChangeExtension(packagePath, ".pdb"), out livePdbFile))
{
removeFiles.Add(livePdbFile.OriginalItem);
}
}
else
{
Log.LogMessage(LogImportance.Low, $"Including {packagePath} from last stable package {PackageId}/{PackageVersion}.");
}
var item = new TaskItem(packageFile);
if (liveFile?.OriginalItem != null)
{
// preserve all the meta-data from the live file that was replaced.
liveFile.OriginalItem.CopyMetadataTo(item);
}
else
{
if (includeItem != null)
{
includeItem.CopyMetadataTo(item);
}
var targetPath = Path.GetDirectoryName(packagePath).Replace('\\', '/');
item.SetMetadata("TargetPath", targetPath);
string targetFramework = GetTargetFrameworkFromPackagePath(targetPath);
item.SetMetadata("TargetFramework", targetFramework);
// only harvest for non-portable frameworks, matches logic in packaging.targets.
bool harvestDependencies = !targetFramework.StartsWith("portable-");
item.SetMetadata("HarvestDependencies", harvestDependencies.ToString());
item.SetMetadata("IsReferenceAsset", IsReferencePackagePath(targetPath).ToString());
}
if (assemblyVersion != null)
{
// overwrite whatever metadata may have been copied from the live file.
item.SetMetadata("AssemblyVersion", assemblyVersion.ToString());
}
item.SetMetadata("HarvestedFrom", $"{PackageId}/{PackageVersion}/{packagePath}");
harvestedFiles.Add(item);
}
}
HarvestedFiles = harvestedFiles.ToArray();
if (_pathsNotIncluded != null)
{
foreach (var pathNotIncluded in _pathsNotIncluded)
{
Log.LogError($"Path '{pathNotIncluded}' was specified in {nameof(PathsToInclude)} but was not found in the package {PackageId}/{PackageVersion}.");
}
}
if (Files != null)
{
UpdatedFiles = Files.Except(removeFiles).ToArray();
}
}
private void LogSkipIncludedFile(string packagePath, string reason)
{
if (IncludeAllPaths)
{
Log.LogMessage(LogImportance.Low, $"Preferring live build of package path {packagePath} over the asset from last stable package{reason}.");
}
else
{
Log.LogError($"Package path {packagePath} was specified to be harvested but it conflicts with live build{reason}.");
}
}
private HashSet<string> _pathsToExclude = null;
private bool ShouldExclude(string packagePath)
{
if (_pathsToExclude == null)
{
_pathsToExclude = new HashSet<string>(PathsToExclude.NullAsEmpty().Select(NormalizePath), StringComparer.OrdinalIgnoreCase);
}
return ShouldSuppress(packagePath) || ProbePath(packagePath, _pathsToExclude);
}
private Dictionary<string, ITaskItem> _pathsToInclude = null;
private HashSet<string> _pathsNotIncluded = null;
private bool ShouldInclude(string packagePath, out ITaskItem includeItem)
{
if (_pathsToInclude == null)
{
_pathsToInclude = PathsToInclude.NullAsEmpty().ToDictionary(i => NormalizePath(i.ItemSpec), i=> i, StringComparer.OrdinalIgnoreCase);
_pathsNotIncluded = new HashSet<string>(_pathsToInclude.Keys);
}
return ProbePath(packagePath, _pathsToInclude, _pathsNotIncluded, out includeItem);
}
private HashSet<string> _pathsToSuppress = null;
private bool ShouldSuppress(string packagePath)
{
if (_pathsToSuppress == null)
{
_pathsToSuppress = new HashSet<string>(PathsToSuppress.NullAsEmpty().Select(NormalizePath));
}
return ProbePath(packagePath, _pathsToSuppress);
}
private static bool ProbePath(string path, ICollection<string> pathsIncluded)
{
for (var probePath = NormalizePath(path);
!String.IsNullOrEmpty(probePath);
probePath = NormalizePath(Path.GetDirectoryName(probePath)))
{
if (pathsIncluded.Contains(probePath))
{
return true;
}
}
return false;
}
private static bool ProbePath<T>(string path, IDictionary<string, T> pathsIncluded, ICollection<string> pathsNotIncluded, out T result)
{
result = default(T);
for (var probePath = NormalizePath(path);
!String.IsNullOrEmpty(probePath);
probePath = NormalizePath(Path.GetDirectoryName(probePath)))
{
if (pathsIncluded.TryGetValue(probePath, out result))
{
pathsNotIncluded.Remove(probePath);
return true;
}
}
return false;
}
private static string NormalizePath(string path)
{
return path?.Replace('\\', '/')?.Trim();
}
private static string GetTargetFrameworkFromPackagePath(string path)
{
var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (parts.Length >= 2)
{
if (parts[0].Equals("lib", StringComparison.OrdinalIgnoreCase) ||
parts[0].Equals("ref", StringComparison.OrdinalIgnoreCase))
{
return parts[1];
}
if (parts.Length >= 4 &&
parts[0].Equals("runtimes", StringComparison.OrdinalIgnoreCase) &&
parts[2].Equals("lib", StringComparison.OrdinalIgnoreCase))
{
return parts[3];
}
}
return null;
}
private static string s_dll = ".dll";
private static string[] s_includedExtensions = new[] { s_dll, ".pdb", ".xml", "._" };
private static bool IsIncludedExtension(string extension)
{
return extension != null && extension.Length > 0 && s_includedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);
}
private static bool IsReferencePackagePath(string path)
{
return path.StartsWith("ref", StringComparison.OrdinalIgnoreCase);
}
private IEnumerable<string> GetPackageItems(string packagesFolder, string packageId, string packageVersion)
{
string packageFolder = Path.Combine(packagesFolder, packageId, packageVersion);
return GetPackageItems(packageFolder);
}
private IEnumerable<string> GetPackageItems(string packageFolder)
{
return Directory.EnumerateFiles(packageFolder, "*", SearchOption.AllDirectories)
.Select(f => f.Substring(packageFolder.Length + 1).Replace('\\', '/'))
.Where(f => !ShouldSuppress(f));
}
}
}
| |
using System;
using System.Reflection;
using System.IO;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
namespace Lesson07
{
public class Game : GameWindow
{
private bool light; // Lighting ON/OFF
private bool lp; // L Pressed?
private bool fp; // F Pressed?
private float xrot; // X Rotation
private float yrot; // Y Rotation
private float xspeed; // X Rotation Speed
private float yspeed; // Y Rotation Speed
private float z=-5.0f; // Depth Into The Screen
private float[] lightAmbient = { 0.5f, 0.5f, 0.5f, 1.0f };
private float[] lightDiffuse = { 1.0f, 1.0f, 1.0f, 1.0f };
private float[] lightPosition= { 0.0f, 0.0f, 2.0f, 1.0f };
private uint filter; // Which Filter To Use
private uint[] texture = new uint[3]; // Storage for 3 textures
public Game()
: base(800, 600, GraphicsMode.Default, Program.APPLICATION_TITLE)
{
VSync = VSyncMode.On;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.InitGL(this.Width, this.Height);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.ReSizeGLScene(this.Width, this.Height);
}
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
if (Keyboard[Key.Escape])
{
Exit();
}
if (Keyboard[Key.L])
{
if (!lp)
{
lp = true;
light = !light;
if (!light)
{
GL.Disable(EnableCap.Lighting);
}
else
{
GL.Enable(EnableCap.Lighting);
}
}
}
else
{
lp = false;
}
if (Keyboard[Key.F])
{
if (!fp)
{
fp = true;
filter += 1;
if (filter > 2)
{
filter = 0;
}
}
}
else
{
fp = false;
}
if (Keyboard[Key.PageDown])
{
z -= 0.02f;
}
if (Keyboard[Key.PageUp])
{
z += 0.02f;
}
if (Keyboard[Key.Up])
{
xspeed -= 0.01f;
}
if (Keyboard[Key.Down])
{
xspeed += 0.01f;
}
if (Keyboard[Key.Right])
{
yspeed += 0.01f;
}
if (Keyboard[Key.Left])
{
yspeed -= 0.01f;
}
}
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
this.DrawGLScene();
SwapBuffers();
}
private void LoadGLTextures()
{
string fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "lola.bmp");
using (var bitmap = new System.Drawing.Bitmap(fileName, false))
{
var bitmapRect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
var lockData = bitmap.LockBits(bitmapRect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// Create Nearest Filtered Texture
GL.GenTextures(3, texture);
GL.BindTexture(TextureTarget.Texture2D, texture[0]);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Nearest);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmapRect.Width, bitmapRect.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, lockData.Scan0);
// Create Linear Filtered Texture
GL.BindTexture(TextureTarget.Texture2D, texture[1]);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmapRect.Width, bitmapRect.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, lockData.Scan0);
// Create MipMapped Texture
GL.BindTexture(TextureTarget.Texture2D, texture[2]);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.LinearMipmapNearest);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmapRect.Width, bitmapRect.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, lockData.Scan0);
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
bitmap.UnlockBits(lockData);
}
}
private void InitGL(int width, int height)
{
this.LoadGLTextures(); // Load The Texture(s)
GL.Enable(EnableCap.Texture2D); // Enable Texture Mapping
GL.ClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This Will Clear The Background Color To Black
GL.ClearDepth(1.0); // Enables Clearing Of The Depth Buffer
GL.DepthFunc(DepthFunction.Less); // The Type Of Depth Test To Do
GL.Enable(EnableCap.DepthTest); // Enables Depth Testing
GL.ShadeModel(ShadingModel.Smooth); // Enables Smooth Color Shading
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity(); // Reset The Projection Matrix
PerspectiveGL(45.0f, width / height, 0.1f, 100.0f);
GL.MatrixMode(MatrixMode.Modelview);
GL.Light(LightName.Light1, LightParameter.Ambient, lightAmbient);
GL.Light(LightName.Light1, LightParameter.Diffuse, lightDiffuse);
GL.Light(LightName.Light1, LightParameter.Position, lightPosition);
GL.Enable(EnableCap.Light1);
}
private void ReSizeGLScene(int width, int height)
{
if (height == 0) // Prevent A Divide By Zero If The Window Is Too Small
height = 1;
GL.Viewport(0, 0, width, height); // Reset The Current Viewport And Perspective Transformation
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
PerspectiveGL(45.0f, width / height, 0.1f, 100.0f); // Calculate The Aspect Ratio Of The Window
GL.MatrixMode(MatrixMode.Modelview);
}
private void DrawGLScene()
{
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // Clear The Screen And The Depth Buffer
GL.LoadIdentity(); // Reset The View
GL.Translate(0.0f,0.0f,z);
GL.Rotate(xrot,1.0f,0.0f,0.0f);
GL.Rotate(yrot,0.0f,1.0f,0.0f);
GL.BindTexture(TextureTarget.Texture2D, texture[filter]);
GL.Begin(PrimitiveType.Quads);
// Front Face
GL.Normal3( 0.0f, 0.0f, 1.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 1.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3( 1.0f, -1.0f, 1.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3( 1.0f, 1.0f, 1.0f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, 1.0f);
// Back Face
GL.Normal3( 0.0f, 0.0f,-1.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, -1.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, -1.0f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3( 1.0f, 1.0f, -1.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3( 1.0f, -1.0f, -1.0f);
// Top Face
GL.Normal3( 0.0f, 1.0f, 0.0f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, -1.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1.0f, 1.0f, 1.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3( 1.0f, 1.0f, 1.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3( 1.0f, 1.0f, -1.0f);
// Bottom Face
GL.Normal3( 0.0f,-1.0f, 0.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(-1.0f, -1.0f, -1.0f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3( 1.0f, -1.0f, -1.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3( 1.0f, -1.0f, 1.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 1.0f);
// Right face
GL.Normal3( 1.0f, 0.0f, 0.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3( 1.0f, -1.0f, -1.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3( 1.0f, 1.0f, -1.0f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3( 1.0f, 1.0f, 1.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3( 1.0f, -1.0f, 1.0f);
// Left Face
GL.Normal3(-1.0f, 0.0f, 0.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, -1.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 1.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, 1.0f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1.0f, 1.0f, -1.0f);
GL.End();
xrot += xspeed;
yrot += yspeed;
}
/// <remarks>
/// http://nehe.gamedev.net/article/replacement_for_gluperspective/21002/
/// </remarks>
private void PerspectiveGL(double fovY, double aspect, double zNear, double zFar)
{
const double pi = 3.1415926535897932384626433832795;
double fW, fH;
fH = Math.Tan(fovY / 360 * pi) * zNear;
fW = fH * aspect;
GL.Frustum(-fW, fW, -fH, fH, zNear, zFar);
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class RelateDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RelateDialog));
this.btnHelp = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnEllipse = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.cmbDataFormats = new System.Windows.Forms.ComboBox();
this.txtDataSource = new System.Windows.Forms.TextBox();
this.lblDataSource = new System.Windows.Forms.Label();
this.lblDataFormats = new System.Windows.Forms.Label();
this.lblKey = new System.Windows.Forms.Label();
this.cbxUnmatched = new System.Windows.Forms.CheckBox();
this.txtKey = new System.Windows.Forms.TextBox();
this.btnBuildKey = new System.Windows.Forms.Button();
this.gbxShow = new System.Windows.Forms.GroupBox();
this.rbAll = new System.Windows.Forms.RadioButton();
this.rbView = new System.Windows.Forms.RadioButton();
this.lbxDataSourceObjects = new System.Windows.Forms.ListBox();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.gbxShow.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnEllipse
//
resources.ApplyResources(this.btnEllipse, "btnEllipse");
this.btnEllipse.Name = "btnEllipse";
this.btnEllipse.Click += new System.EventHandler(this.btnEllipse_Click);
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// cmbDataFormats
//
resources.ApplyResources(this.cmbDataFormats, "cmbDataFormats");
this.cmbDataFormats.Name = "cmbDataFormats";
this.cmbDataFormats.SelectedIndexChanged += new System.EventHandler(this.cmbDataFormats_SelectedIndexChanged);
//
// txtDataSource
//
resources.ApplyResources(this.txtDataSource, "txtDataSource");
this.txtDataSource.Name = "txtDataSource";
//
// lblDataSource
//
resources.ApplyResources(this.lblDataSource, "lblDataSource");
this.lblDataSource.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblDataSource.Name = "lblDataSource";
//
// lblDataFormats
//
resources.ApplyResources(this.lblDataFormats, "lblDataFormats");
this.lblDataFormats.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblDataFormats.Name = "lblDataFormats";
//
// lblKey
//
this.lblKey.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblKey, "lblKey");
this.lblKey.Name = "lblKey";
//
// cbxUnmatched
//
resources.ApplyResources(this.cbxUnmatched, "cbxUnmatched");
this.cbxUnmatched.Name = "cbxUnmatched";
//
// txtKey
//
resources.ApplyResources(this.txtKey, "txtKey");
this.txtKey.Name = "txtKey";
//
// btnBuildKey
//
resources.ApplyResources(this.btnBuildKey, "btnBuildKey");
this.btnBuildKey.Name = "btnBuildKey";
this.btnBuildKey.Click += new System.EventHandler(this.btnBuildKey_Click);
//
// gbxShow
//
resources.ApplyResources(this.gbxShow, "gbxShow");
this.gbxShow.Controls.Add(this.rbAll);
this.gbxShow.Controls.Add(this.rbView);
this.gbxShow.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.gbxShow.Name = "gbxShow";
this.gbxShow.TabStop = false;
//
// rbAll
//
resources.ApplyResources(this.rbAll, "rbAll");
this.rbAll.Name = "rbAll";
this.rbAll.CheckedChanged += new System.EventHandler(this.View_CheckedChanged);
//
// rbView
//
this.rbView.Checked = true;
resources.ApplyResources(this.rbView, "rbView");
this.rbView.Name = "rbView";
this.rbView.TabStop = true;
this.rbView.CheckedChanged += new System.EventHandler(this.View_CheckedChanged);
//
// lbxDataSourceObjects
//
resources.ApplyResources(this.lbxDataSourceObjects, "lbxDataSourceObjects");
this.lbxDataSourceObjects.Name = "lbxDataSourceObjects";
this.lbxDataSourceObjects.Sorted = true;
this.lbxDataSourceObjects.SelectedIndexChanged += new System.EventHandler(this.lbxDataSourceObjects_SelectedIndexChanged);
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
this.btnSaveOnly.UseVisualStyleBackColor = true;
//
// RelateDialog
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.gbxShow);
this.Controls.Add(this.lbxDataSourceObjects);
this.Controls.Add(this.btnBuildKey);
this.Controls.Add(this.txtKey);
this.Controls.Add(this.txtDataSource);
this.Controls.Add(this.cbxUnmatched);
this.Controls.Add(this.lblKey);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnEllipse);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.cmbDataFormats);
this.Controls.Add(this.lblDataSource);
this.Controls.Add(this.lblDataFormats);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "RelateDialog";
this.ShowIcon = false;
this.Load += new System.EventHandler(this.RelateDialog_Load);
this.gbxShow.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnEllipse;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.ComboBox cmbDataFormats;
private System.Windows.Forms.TextBox txtDataSource;
private System.Windows.Forms.Label lblDataSource;
private System.Windows.Forms.Label lblDataFormats;
private System.Windows.Forms.Label lblKey;
private System.Windows.Forms.CheckBox cbxUnmatched;
private System.Windows.Forms.TextBox txtKey;
private System.Windows.Forms.Button btnBuildKey;
private System.Windows.Forms.GroupBox gbxShow;
private System.Windows.Forms.RadioButton rbAll;
private System.Windows.Forms.RadioButton rbView;
private System.Windows.Forms.ListBox lbxDataSourceObjects;
private System.Windows.Forms.Button btnSaveOnly;
}
}
| |
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.VersioningAndUnification.AppConfig
{
public sealed class StronglyNamedDependencyAppConfig : ResolveAssemblyReferenceTestFixture
{
public StronglyNamedDependencyAppConfig(ITestOutputHelper output) : base(output)
{
}
/// <summary>
/// Return the default search paths.
/// </summary>
/// <value></value>
new internal string[] DefaultPaths
{
get { return new string[] { s_myApp_V05Path, s_myApp_V10Path, s_myComponentsV05Path, s_myComponentsV10Path, s_myComponentsV20Path, s_myComponentsV30Path }; }
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 1.0.0.0 of UnifyMe.
/// - An app.config was passed in that promotes UnifyMe version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of UnifyMe exists.
/// - Version 2.0.0.0 of UnifyMe exists.
/// Expected:
/// - The resulting UnifyMe returned should be 2.0.0.0.
/// Rationale:
/// Strongly named dependencies should unify according to the bindingRedirects in the app.config.
/// </summary>
[Fact]
public void Exists()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedDependencyFiles);
t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 1.0.0.0 of UnifyMe.
/// - An app.config was passed in that promotes UnifyMe version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of UnifyMe exists.
/// - Version 2.0.0.0 of UnifyMe exists.
/// -Version 2.0.0.0 of UnifyMe is in the Black List
/// Expected:
/// - There should be a warning indicating that DependsOnUnified has a dependency UnifyMe 2.0.0.0 which is not in a TargetFrameworkSubset.
/// - There will be no unified message.
/// Rationale:
/// Strongly named dependencies should unify according to the bindingRedirects in the app.config, if the unified version is in the black list it should be removed and warned.
/// </summary>
[Fact]
public void ExistsPromotedDependencyInTheBlackList()
{
string engineOnlySubset =
"<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
"<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
"</FileList >";
string implicitRedistListContents =
"<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
"<File AssemblyName='UniFYme' Version='2.0.0.0' Culture='neutral' PublicKeyToken='b77a5c561934e089' InGAC='false' />" +
"</FileList >";
string redistListPath = FileUtilities.GetTemporaryFile();
string subsetListPath = FileUtilities.GetTemporaryFile();
string appConfigFile = null;
try
{
File.WriteAllText(redistListPath, implicitRedistListContents);
File.WriteAllText(subsetListPath, engineOnlySubset);
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistListPath) };
t.InstalledAssemblySubsetTables = new TaskItem[] { new TaskItem(subsetListPath) };
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t, false);
Assert.True(succeeded);
Assert.Empty(t.ResolvedDependencyFiles);
engine.AssertLogDoesntContain
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
);
}
finally
{
File.Delete(redistListPath);
File.Delete(subsetListPath);
// Cleanup.
File.Delete(appConfigFile);
}
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 1.0.0.0 of UnifyMe.
/// - An app.config was passed in that promotes a *different* assembly version name from
// 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// An unrelated bindingRedirect in the app.config should have no bearing on unification
/// of another file.
/// </summary>
[Fact]
public void ExistsDifferentName()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='DontUnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedDependencyFiles);
t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 1.0.0.0 of UnifyMe.
/// - An app.config was passed in that promotes assembly version from range 0.0.0.0-1.5.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 2.0.0.0.
/// Rationale:
/// Strongly named dependencies should unify according to the bindingRedirects in the app.config, even
/// if a range is involved.
/// </summary>
[Fact]
public void ExistsOldVersionRange()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-1.5.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedDependencyFiles);
t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 1.0.0.0 of UnifyMe.
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 4.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 4.0.0.0 of the file *does not* exist.
/// Expected:
/// - The dependent assembly should be unresolved.
/// Rationale:
/// The fusion loader is going to want to respect the app.config file. There's no point in
/// feeding it the wrong version.
/// </summary>
[Fact]
public void HighVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='4.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Empty(t.ResolvedDependencyFiles);
string shouldContain;
string code = t.Log.ExtractMessageCode
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.FailedToResolveReference"),
String.Format(AssemblyResources.GetString("General.CouldNotLocateAssembly"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")),
out shouldContain
);
engine.AssertLogContains
(
shouldContain
);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))
);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 0.5.0.0 of UnifyMe.
/// - An app.config was passed in that promotes assembly version from 0.0.0.0-2.0.0.0 to 2.0.0.0
/// - Version 0.5.0.0 of the file *does not* exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The resulting assembly returned should be 2.0.0.0.
/// Rationale:
/// The lower (unified-from) version need not exist on disk (in fact we shouldn't even try to
/// resolve it) in order to arrive at the correct answer.
/// </summary>
[Fact]
public void LowVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=0.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedDependencyFiles);
t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "0.5.0.0", appConfigFile, Path.Combine(s_myApp_V05Path, "DependsOnUnified.dll"))
);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - An app.config is passed in that has some garbage in the version number.
/// Expected:
/// - An error and task failure.
/// Rationale:
/// Can't proceed with a bad app.config.
/// </summary>
[Fact]
public void GarbageVersionInAppConfigFile()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='GarbledOldVersion' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='Garbled' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.False(succeeded);
Assert.Equal(1, engine.Errors);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - An app.config is passed in that has a missing oldVersion in a bindingRedirect.
/// Expected:
/// - An error and task failure.
/// Rationale:
/// Can't proceed with a bad app.config.
/// </summary>
[Fact]
public void GarbageAppConfigMissingOldVersion()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='MissingOldVersion' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.False(succeeded);
Assert.Equal(1, engine.Errors);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("AppConfig.BindingRedirectMissingOldVersion"))
);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - An app.config is passed in that has a missing newVersion in a bindingRedirect.
/// Expected:
/// - An error and task failure.
/// Rationale:
/// Can't proceed with a bad app.config.
/// </summary>
[Fact]
public void GarbageAppConfigMissingNewVersion()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='MissingNewVersion' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.False(succeeded);
Assert.Equal(1, engine.Errors);
engine.AssertLogContains
(
String.Format(AssemblyResources.GetString("AppConfig.BindingRedirectMissingNewVersion"))
);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - An app.config is passed in that has some missing information in <assemblyIdentity> element.
/// Expected:
/// - An error and task failure.
/// Rationale:
/// Can't proceed with a bad app.config.
/// </summary>
[Fact]
public void GarbageAppConfigAssemblyNameMissingPKTAndCulture()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='GarbledOldVersion' />\n" +
" <bindingRedirect oldVersion='Garbled' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.False(succeeded);
Assert.Equal(1, engine.Errors);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - An app.config is specified
/// *and*
/// - AutoUnify=true.
/// Expected:
/// - Success.
/// Rationale:
/// With the introduction of the GenerateBindingRedirects task, RAR now accepts AutoUnify and App.Config at the same time.
/// </summary>
[Fact]
public void AppConfigSpecifiedWhenAutoUnifyEqualsTrue()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
t.AutoUnify = true;
bool succeeded = Execute(t);
// With the introduction of GenerateBindingRedirects task, RAR now accepts AutoUnify and App.Config at the same time.
Assert.True(succeeded);
Assert.Equal(0, engine.Errors);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - An app.config is specified, but the file doesn't exist.
/// Expected:
/// - An error and task failure.
/// Rationale:
/// App.config must exist if specified.
/// </summary>
[Fact]
public void AppConfigDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = @"C:\MyNonexistentFolder\MyNonExistentApp.config";
bool succeeded = Execute(t);
Assert.False(succeeded);
Assert.Equal(1, engine.Errors);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ASYNC
using System;
using System.Globalization;
using System.Threading;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public partial class JsonTextReader
{
// It's not safe to perform the async methods here in a derived class as if the synchronous equivalent
// has been overriden then the asychronous method will no longer be doing the same operation
#if HAVE_ASYNC // Double-check this isn't included inappropriately.
private readonly bool _safeAsync;
#endif
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken);
}
internal Task<bool> DoReadAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValueAsync(cancellationToken);
case State.Object:
case State.ObjectStart:
return ParseObjectAsync(cancellationToken);
case State.PostValue:
return LoopReadAsync(cancellationToken);
case State.Finished:
return ReadFromFinishedAsync(cancellationToken);
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<bool> LoopReadAsync(CancellationToken cancellationToken)
{
while (_currentState == State.PostValue)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_currentState = State.Finished;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
return await DoReadAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return false;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
SetToken(JsonToken.None);
return false;
}
private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken)
{
return ReadDataAsync(append, 0, cancellationToken);
}
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
if (_isEndOfFile)
{
return 0;
}
PrepareBufferForReadData(append, charsRequired);
int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false);
_charsUsed += charsRead;
if (charsRead == 0)
{
_isEndOfFile = true;
}
_chars[_charsUsed] = '\0';
return charsRead;
}
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 't':
await ParseTrueAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'f':
await ParseFalseAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'n':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
switch (_chars[_charPos + 1])
{
case 'u':
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
break;
case 'e':
await ParseConstructorAsync(cancellationToken).ConfigureAwait(false);
break;
default:
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
}
else
{
_charPos++;
throw CreateUnexpectedEndException();
}
return true;
case 'N':
await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 'I':
await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case 'u':
await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false);
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber(ReadType.Read);
return true;
}
throw CreateUnexpectedCharacterException(currentChar);
}
}
}
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
_stringBuffer.Position = 0;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
charPos++;
char writeChar;
switch (currentChar)
{
case 'b':
writeChar = '\b';
break;
case 't':
writeChar = '\t';
break;
case 'n':
writeChar = '\n';
break;
case 'f':
writeChar = '\f';
break;
case 'r':
writeChar = '\r';
break;
case '\\':
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
break;
case 'u':
_charPos = charPos;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
EnsureBufferNotEmpty();
WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
EnsureBufferNotEmpty();
WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition);
return;
}
break;
}
}
}
private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken)
{
_charPos++;
Task<bool> task = EnsureCharsAsync(1, append, cancellationToken);
switch (task.Status)
{
case TaskStatus.RanToCompletion:
SetNewLine(task.Result);
return AsyncUtils.CompletedTask;
case TaskStatus.Canceled:
case TaskStatus.Faulted:
return task;
}
return ProcessCarriageReturnAsync(task);
}
private async Task ProcessCarriageReturnAsync(Task<bool> task)
{
SetNewLine(await task.ConfigureAwait(false));
}
private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken)
{
return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false));
}
private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
if (_charPos + relativePosition < _charsUsed)
{
return AsyncUtils.True;
}
if (_isEndOfFile)
{
return AsyncUtils.False;
}
return ReadCharsAsync(relativePosition, append, cancellationToken);
}
private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false);
// no more content
if (charsRead == 0)
{
return false;
}
charsRequired -= charsRead;
} while (charsRequired > 0);
return true;
}
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
// should have already parsed / character before reaching this method
_charPos++;
if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
bool singlelineComment;
if (_chars[_charPos] == '*')
{
singlelineComment = false;
}
else if (_chars[_charPos] == '/')
{
singlelineComment = true;
}
else
{
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
int initialPosition = _charPos;
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
if (!singlelineComment)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
EndComment(setToken, initialPosition, _charPos);
return;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos] == '/')
{
EndComment(setToken, initialPosition, _charPos - 1);
_charPos++;
return;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
}
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
_charPos++;
}
else
{
return;
}
break;
}
}
}
private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_charPos++;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false);
ParseReadString(quote, readType);
}
private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken)
{
return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value);
}
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
return false;
}
if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
return true;
}
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
SetToken(newToken, tokenValue);
}
else
{
throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value.");
}
}
private Task ParseTrueAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken);
}
private Task ParseFalseAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken);
}
private Task ParseNullAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken);
}
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != '(')
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false);
ParseReadNumber(readType, firstChar, initialPosition);
}
private Task ParseUndefinedAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken);
}
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
if (NameTable != null)
{
propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length)
// no match in name table
?? _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != ':')
{
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
int charPos = _charPos;
while (true)
{
char currentChar = _chars[charPos];
if (currentChar == '\0')
{
_charPos = charPos;
if (_charsUsed == charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
return;
}
}
else if (ReadNumberCharIntoBuffer(currentChar, charPos))
{
return;
}
else
{
charPos++;
}
}
}
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
}
continue;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition))
{
return;
}
}
}
private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken)
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_isEndOfFile = true;
return true;
}
}
else
{
_charPos++;
}
return false;
}
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
{
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
return;
}
_charPos += 2;
throw CreateUnexpectedCharacterException(_chars[_charPos - 1]);
}
_charPos = _charsUsed;
throw CreateUnexpectedEndException();
}
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedStringValue(readType);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return ParseNumberNegativeInfinity(readType);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return Value;
case 't':
case 'f':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False;
if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.String, expected);
return expected;
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedNumber(readType);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken);
}
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return ReadBooleanString(_stringReference.ToString());
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case 't':
case 'f':
bool isTrue = currentChar == 't';
if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.Boolean, isTrue);
return isTrue;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
bool isWrapped = false;
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
}
return data;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false);
isWrapped = true;
break;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken);
}
internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken)
{
return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken);
}
internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken)
{
return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken);
}
internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken)
{
return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken);
}
internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken)
{
return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken);
}
internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken)
{
return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
#endif
| |
// Copyright (c) 2010-2013 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;
using System.IO;
using System.Runtime.InteropServices;
using SharpDX.Direct3D11;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A Texture 1D front end to <see cref="SharpDX.Direct3D11.Texture1D"/>.
/// </summary>
public class Texture1D : Texture1DBase
{
internal Texture1D(GraphicsDevice device, Texture1DDescription description1D, params DataBox[] dataBox) : base(device, description1D, dataBox)
{
}
internal Texture1D(GraphicsDevice device, Direct3D11.Texture1D texture) : base(device, texture)
{
}
internal override RenderTargetView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice)
{
throw new System.NotSupportedException();
}
/// <summary>
/// Makes a copy of this texture.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public override Texture Clone()
{
return new Texture1D(GraphicsDevice, this.Description);
}
/// <summary>
/// Creates a new texture from a <see cref="Texture1DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, Texture1DDescription description)
{
return new Texture1D(device, description);
}
/// <summary>
/// Creates a new texture from a <see cref="Direct3D11.Texture1D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture1D"/>.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, Direct3D11.Texture1D texture)
{
return new Texture1D(device, texture);
}
/// <summary>
/// Creates a new <see cref="Texture1D"/> with a single mipmap.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, int width, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return New(device, width, false, format, flags, arraySize, usage);
}
/// <summary>
/// Creates a new <see cref="Texture1D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, int width, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return new Texture1D(device, NewDescription(width, format, flags | TextureFlags.ShaderResource, mipCount, arraySize, usage));
}
/// <summary>
/// Creates a new <see cref="Texture1D" /> with a single level of mipmap.
/// </summary>
/// <typeparam name="T">Type of the initial data to upload to the texture</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="textureData">Texture data. Size of must be equal to sizeof(Format) * width </param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>A new instance of <see cref="Texture1D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_Texture1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
/// <remarks>
/// The first dimension of mipMapTextures describes the number of array (Texture1D Array), second dimension is the mipmap, the third is the texture data for a particular mipmap.
/// </remarks>
public unsafe static Texture1D New<T>(GraphicsDevice device, int width, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct
{
return new Texture1D(device, NewDescription(width, format, flags | TextureFlags.ShaderResource, 1, 1, usage), GetDataBox(format, width, 1, 1, textureData, (IntPtr)Interop.Fixed(textureData)));
}
/// <summary>
/// Creates a new <see cref="Texture1D" /> directly from an <see cref="Image"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="image">An image in CPU memory.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture1D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
if (image == null) throw new ArgumentNullException("image");
if (image.Description.Dimension != TextureDimension.Texture1D)
throw new ArgumentException("Invalid image. Must be 1D", "image");
return new Texture1D(device, CreateTextureDescriptionFromImage(image, flags | TextureFlags.ShaderResource, usage), image.ToDataBox());
}
/// <summary>
/// Loads a 1D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="stream">The stream to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 1D</exception>
/// <returns>A texture</returns>
public static new Texture1D Load(GraphicsDevice device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
var texture = Texture.Load(device, stream, flags | TextureFlags.ShaderResource, usage);
if (!(texture is Texture1D))
throw new ArgumentException(string.Format("Texture is not type of [Texture1D] but [{0}]", texture.GetType().Name));
return (Texture1D)texture;
}
/// <summary>
/// Loads a 1D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="filePath">The file to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 1D</exception>
/// <returns>A texture</returns>
public static new Texture1D Load(GraphicsDevice device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
return Load(device, stream, flags, usage);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// Code in this file was copied from https://github.com/dotnet/roslyn
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
#if !CORECLR // Only enable/port what is needed by CORE CLR.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache.
/// </summary>
internal static class GlobalAssemblyCache
{
/// <summary>
/// Represents the current Processor architecture.
/// </summary>
public static readonly ProcessorArchitecture[] CurrentArchitectures = (IntPtr.Size == 4)
? new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86 }
: new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64 };
#region Interop
private const int MAX_PATH = 260;
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")]
private interface IAssemblyEnum
{
[PreserveSig]
int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone(out IAssemblyEnum ppEnum);
}
[ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAssemblyCache
{
void UninstallAssembly();
void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo);
void CreateAssemblyCacheItem();
void CreateAssemblyScavenger();
void InstallAssembly();
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct ASSEMBLY_INFO
{
public uint cbAssemblyInfo;
public uint dwAssemblyFlags;
public ulong uliAssemblySizeInKB;
public char* pszCurrentAssemblyPathBuf;
public uint cchBuf;
}
private enum ASM_CACHE
{
ZAP = 0x1,
GAC = 0x2, // C:\Windows\Assembly\GAC
DOWNLOAD = 0x4,
ROOT = 0x8, // C:\Windows\Assembly
GAC_MSIL = 0x10,
GAC_32 = 0x20, // C:\Windows\Assembly\GAC_32
GAC_64 = 0x40, // C:\Windows\Assembly\GAC_64
ROOT_EX = 0x80, // C:\Windows\Microsoft.NET\assembly
}
[DllImport("clr", CharSet = CharSet.Auto, PreserveSig = true)]
private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved);
[DllImport("clr", CharSet = CharSet.Auto, PreserveSig = false)]
private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved);
#endregion
private const int S_OK = 0;
private const int S_FALSE = 1;
// Internal for testing.
internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects(
FusionAssemblyIdentity.IAssemblyName partialNameFilter,
ProcessorArchitecture[] architectureFilter)
{
IAssemblyEnum enumerator;
int hr = CreateAssemblyEnum(out enumerator, null, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero);
if (hr == S_FALSE)
{
// no assembly found
yield break;
}
if (hr != S_OK)
{
Exception e = Marshal.GetExceptionForHR(hr);
if (e is FileNotFoundException)
{
// invalid assembly name:
yield break;
}
if (e != null)
{
throw e;
}
// for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception:
throw new ArgumentException("Invalid assembly name");
}
while (true)
{
FusionAssemblyIdentity.IAssemblyName nameObject;
FusionAssemblyIdentity.IApplicationContext applicationContext;
hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0);
if (hr != 0)
{
if (hr < 0)
{
Marshal.ThrowExceptionForHR(hr);
}
break;
}
if (architectureFilter != null)
{
var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject);
if (!architectureFilter.Contains(assemblyArchitecture))
{
continue;
}
}
yield return nameObject;
}
}
/// <summary>
/// Looks up specified partial assembly name in the GAC and returns the best matching full assembly name/>.
/// </summary>
/// <param name="displayName">The display name of an assembly.</param>
/// <param name="location">Full path name of the resolved assembly.</param>
/// <param name="architectureFilter">The optional processor architecture.</param>
/// <param name="preferredCulture">The optional preferred culture information.</param>
/// <returns>An assembly identity or null, if <paramref name="displayName"/> can't be resolved.</returns>
/// <exception cref="ArgumentNullException"><paramref name="displayName"/> is null.</exception>
public static unsafe string ResolvePartialName(
string displayName,
out string location,
ProcessorArchitecture[] architectureFilter = null,
CultureInfo preferredCulture = null)
{
if (displayName == null)
{
throw new ArgumentNullException("displayName");
}
location = null;
FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName);
if (nameObject == null)
{
return null;
}
var candidates = GetAssemblyObjects(nameObject, architectureFilter);
string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null;
var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName);
if (bestMatch == null)
{
return null;
}
string fullName = FusionAssemblyIdentity.GetDisplayName(bestMatch, FusionAssemblyIdentity.ASM_DISPLAYF.FULL);
fixed (char* p = new char[MAX_PATH])
{
ASSEMBLY_INFO info = new ASSEMBLY_INFO
{
cbAssemblyInfo = (uint)Marshal.SizeOf(typeof(ASSEMBLY_INFO)),
pszCurrentAssemblyPathBuf = p,
cchBuf = (uint)MAX_PATH
};
IAssemblyCache assemblyCacheObject;
CreateAssemblyCache(out assemblyCacheObject, 0);
assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info);
Debug.Assert(info.pszCurrentAssemblyPathBuf != null);
Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0');
var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1);
Debug.Assert(result.IndexOf('\0') == -1);
location = result;
}
return fullName;
}
}
}
#endif // !CORECLR
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Infrastructure.Common;
using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using Xunit;
using System.Collections.Generic;
using System.Text;
public class Tcp_ClientCredentialTypeCertificateCanonicalNameTests : ConditionalWcfTest
{
// We set up three endpoints on the WCF service (server) side, each with a different certificate:
// Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address - is bound to a cert where CN=localhost
// Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address - is bound to a cert where CN=domainname
// Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address - is bound to a cert with a fqdn, e.g., CN=domainname.example.com
//
// When tests are run, a /p:ServiceHost=<name> is specified; if none is specified, then "localhost" is used
// Hence, we are only able to determine at runtime whether a particular endpoint presented by the WCF Service is going
// to pass a variation or fail a variation.
[WcfFact]
[Condition(nameof(Root_Certificate_Installed))]
[OuterLoop]
public static void Certificate_With_CanonicalName_Localhost_Address_EchoString()
{
var localhostEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address);
var endpointAddress = new EndpointAddress(localhostEndpointUri);
bool shouldCallSucceed = string.Compare(localhostEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0;
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
var errorBuilder = new StringBuilder();
errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", localhostEndpointUri.Host);
errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. ");
errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", localhostEndpointUri);
errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic.");
Assert.True(shouldCallSucceed, errorBuilder.ToString());
}
catch (Exception exception) when (exception is CommunicationException || exception is MessageSecurityException)
{
if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException"))
{
// If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the
// message is really brittle and we can't account for loc and how .NET Native will display the exceptions
// The exception message should look like:
//
// System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected
// DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this
// is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as
// the Identity property of EndpointAddress when creating channel proxy.
var errorBuilder = new StringBuilder();
errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", localhostEndpointUri.Host);
errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. ");
errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", localhostEndpointUri.Host);
errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message);
Assert.True(!shouldCallSucceed, errorBuilder.ToString());
}
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Root_Certificate_Installed))]
[OuterLoop]
public static void Certificate_With_CanonicalName_DomainName_Address_EchoString()
{
var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address);
var endpointAddress = new EndpointAddress(domainNameEndpointUri);
// We check that:
// 1. The WCF service's reported hostname does not contain a '.' (which means we're hitting the FQDN)
// 2. The WCF service's reported hostname is not "localhost" (which means we're hitting localhost)
// If both these conditions are true, expect the test to pass. Otherwise, it should fail
bool shouldCallSucceed = domainNameEndpointUri.Host.IndexOf('.') == -1 && string.Compare(domainNameEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) != 0;
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
var errorBuilder = new StringBuilder();
errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", domainNameEndpointUri.Host);
errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. ");
errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", domainNameEndpointUri);
errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic.");
Assert.True(shouldCallSucceed, errorBuilder.ToString());
}
catch (Exception exception) when (exception is CommunicationException || exception is MessageSecurityException)
{
if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException"))
{
// If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the
// message is really brittle and we can't account for loc and how .NET Native will display the exceptions
// The exception message should look like:
//
// System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected
// DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this
// is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as
// the Identity property of EndpointAddress when creating channel proxy.
var errorBuilder = new StringBuilder();
errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", domainNameEndpointUri.Host);
errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. ");
errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", domainNameEndpointUri.Host);
errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message);
Assert.True(!shouldCallSucceed, errorBuilder.ToString());
}
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Root_Certificate_Installed))]
[OuterLoop]
public static void Certificate_With_CanonicalName_Fqdn_Address_EchoString()
{
bool shouldCallSucceed = false;
var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address);
// Get just the hostname part of the domainName Uri
var domainNameHost = domainNameEndpointUri.Host.Split('.')[0];
var fqdnEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address);
var endpointAddress = new EndpointAddress(fqdnEndpointUri);
// If the WCF service's reported FQDN is the same as the services's reported hostname,
// it means that there the WCF service is set up on a network where FQDNs aren't used, only hostnames.
// Since our pass/fail detection logic on whether or not this is an FQDN depends on whether the host name has a '.', we don't test this case
if (string.Compare(domainNameHost, fqdnEndpointUri.Host, StringComparison.OrdinalIgnoreCase) != 0)
{
shouldCallSucceed = fqdnEndpointUri.Host.IndexOf('.') > -1;
}
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
var errorBuilder = new StringBuilder();
errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", fqdnEndpointUri.Host);
errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. ");
errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", fqdnEndpointUri);
errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic.");
Assert.True(shouldCallSucceed, errorBuilder.ToString());
}
catch (MessageSecurityException exception)
{
// If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the
// message is really brittle and we can't account for loc and how .NET Native will display the exceptions
// The exception message should look like:
//
// System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected
// DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this
// is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as
// the Identity property of EndpointAddress when creating channel proxy.
var errorBuilder = new StringBuilder();
errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", fqdnEndpointUri.Host);
errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. ");
errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", fqdnEndpointUri.Host);
errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message);
Assert.True(!shouldCallSucceed, errorBuilder.ToString());
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\EnSightRectGridBin.tcl
// output file is AVEnSightRectGridBin.cs
/// <summary>
/// The testing class derived from AVEnSightRectGridBin
/// </summary>
public class AVEnSightRectGridBinClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVEnSightRectGridBin(String [] argv)
{
//Prefix Content is: ""
VTK_VARY_RADIUS_BY_VECTOR = 2;
// create pipeline[]
//[]
reader = new vtkGenericEnSightReader();
// Make sure all algorithms use the composite data pipeline[]
cdp = new vtkCompositeDataPipeline();
vtkGenericEnSightReader.SetDefaultExecutivePrototype((vtkExecutive)cdp);
reader.SetCaseFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/EnSight/RectGrid_bin.case");
reader.Update();
toRectilinearGrid = new vtkCastToConcrete();
// toRectilinearGrid SetInputConnection [reader GetOutputPort] []
toRectilinearGrid.SetInputData((vtkDataObject)reader.GetOutput().GetBlock((uint)0));
toRectilinearGrid.Update();
plane = new vtkRectilinearGridGeometryFilter();
plane.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
plane.SetExtent((int)0,(int)100,(int)0,(int)100,(int)15,(int)15);
tri = new vtkTriangleFilter();
tri.SetInputConnection((vtkAlgorithmOutput)plane.GetOutputPort());
warper = new vtkWarpVector();
warper.SetInputConnection((vtkAlgorithmOutput)tri.GetOutputPort());
warper.SetScaleFactor((double)0.05);
planeMapper = new vtkDataSetMapper();
planeMapper.SetInputConnection((vtkAlgorithmOutput)warper.GetOutputPort());
planeMapper.SetScalarRange((double)0.197813,(double)0.710419);
planeActor = new vtkActor();
planeActor.SetMapper((vtkMapper)planeMapper);
cutPlane = new vtkPlane();
// eval cutPlane SetOrigin [[reader GetOutput] GetCenter][]
cutPlane.SetOrigin(
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetCenter()[0],
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetCenter()[1],
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetCenter()[2]);
cutPlane.SetNormal((double)1,(double)0,(double)0);
planeCut = new vtkCutter();
planeCut.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
planeCut.SetCutFunction((vtkImplicitFunction)cutPlane);
cutMapper = new vtkDataSetMapper();
cutMapper.SetInputConnection((vtkAlgorithmOutput)planeCut.GetOutputPort());
cutMapper.SetScalarRange(
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetPointData().GetScalars().GetRange()[0],
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetPointData().GetScalars().GetRange()[1]);
cutActor = new vtkActor();
cutActor.SetMapper((vtkMapper)cutMapper);
iso = new vtkContourFilter();
iso.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
iso.SetValue((int)0,(double)0.7);
normals = new vtkPolyDataNormals();
normals.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
normals.SetFeatureAngle((double)45);
isoMapper = vtkPolyDataMapper.New();
isoMapper.SetInputConnection((vtkAlgorithmOutput)normals.GetOutputPort());
isoMapper.ScalarVisibilityOff();
isoActor = new vtkActor();
isoActor.SetMapper((vtkMapper)isoMapper);
isoActor.GetProperty().SetColor((double) 1.0000, 0.8941, 0.7686 );
isoActor.GetProperty().SetRepresentationToWireframe();
streamer = new vtkStreamLine();
// streamer SetInputConnection [reader GetOutputPort][]
streamer.SetInputData((vtkDataObject)reader.GetOutput().GetBlock((uint)0));
streamer.SetStartPosition((double)-1.2,(double)-0.1,(double)1.3);
streamer.SetMaximumPropagationTime((double)500);
streamer.SetStepLength((double)0.05);
streamer.SetIntegrationStepLength((double)0.05);
streamer.SetIntegrationDirectionToIntegrateBothDirections();
streamTube = new vtkTubeFilter();
streamTube.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort());
streamTube.SetRadius((double)0.025);
streamTube.SetNumberOfSides((int)6);
streamTube.SetVaryRadius((int)VTK_VARY_RADIUS_BY_VECTOR);
mapStreamTube = vtkPolyDataMapper.New();
mapStreamTube.SetInputConnection((vtkAlgorithmOutput)streamTube.GetOutputPort());
mapStreamTube.SetScalarRange(
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetPointData().GetScalars().GetRange()[0],
(double)((vtkDataSet)((vtkMultiBlockDataSet)reader.GetOutput()).GetBlock((uint)0)).GetPointData().GetScalars().GetRange()[1]);
// [[[[reader GetOutput] GetPointData] GetScalars] GetRange][]
streamTubeActor = new vtkActor();
streamTubeActor.SetMapper((vtkMapper)mapStreamTube);
streamTubeActor.GetProperty().BackfaceCullingOn();
outline = new vtkOutlineFilter();
outline.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineActor.GetProperty().SetColor((double) 0.0000, 0.0000, 0.0000 );
// Graphics stuff[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.SetMultiSamples(0);
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)planeActor);
ren1.AddActor((vtkProp)cutActor);
ren1.AddActor((vtkProp)isoActor);
ren1.AddActor((vtkProp)streamTubeActor);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)400,(int)400);
cam1 = ren1.GetActiveCamera();
cam1.SetClippingRange((double)3.76213,(double)10.712);
cam1.SetFocalPoint((double)-0.0842503,(double)-0.136905,(double)0.610234);
cam1.SetPosition((double)2.53813,(double)2.2678,(double)-5.22172);
cam1.SetViewUp((double)-0.241047,(double)0.930635,(double)0.275343);
iren.Initialize();
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
vtkGenericEnSightReader.SetDefaultExecutivePrototype(null);
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static int VTK_VARY_RADIUS_BY_VECTOR;
static vtkGenericEnSightReader reader;
static vtkCompositeDataPipeline cdp;
static vtkCastToConcrete toRectilinearGrid;
static vtkRectilinearGridGeometryFilter plane;
static vtkTriangleFilter tri;
static vtkWarpVector warper;
static vtkDataSetMapper planeMapper;
static vtkActor planeActor;
static vtkPlane cutPlane;
static vtkCutter planeCut;
static vtkDataSetMapper cutMapper;
static vtkActor cutActor;
static vtkContourFilter iso;
static vtkPolyDataNormals normals;
static vtkPolyDataMapper isoMapper;
static vtkActor isoActor;
static vtkStreamLine streamer;
static vtkTubeFilter streamTube;
static vtkPolyDataMapper mapStreamTube;
static vtkActor streamTubeActor;
static vtkOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int GetVTK_VARY_RADIUS_BY_VECTOR()
{
return VTK_VARY_RADIUS_BY_VECTOR;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_VARY_RADIUS_BY_VECTOR(int toSet)
{
VTK_VARY_RADIUS_BY_VECTOR = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkGenericEnSightReader Getreader()
{
return reader;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setreader(vtkGenericEnSightReader toSet)
{
reader = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCompositeDataPipeline Getcdp()
{
return cdp;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcdp(vtkCompositeDataPipeline toSet)
{
cdp = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCastToConcrete GettoRectilinearGrid()
{
return toRectilinearGrid;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettoRectilinearGrid(vtkCastToConcrete toSet)
{
toRectilinearGrid = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRectilinearGridGeometryFilter Getplane()
{
return plane;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane(vtkRectilinearGridGeometryFilter toSet)
{
plane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTriangleFilter Gettri()
{
return tri;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settri(vtkTriangleFilter toSet)
{
tri = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkWarpVector Getwarper()
{
return warper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setwarper(vtkWarpVector toSet)
{
warper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetMapper GetplaneMapper()
{
return planeMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneMapper(vtkDataSetMapper toSet)
{
planeMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetplaneActor()
{
return planeActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneActor(vtkActor toSet)
{
planeActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPlane GetcutPlane()
{
return cutPlane;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutPlane(vtkPlane toSet)
{
cutPlane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCutter GetplaneCut()
{
return planeCut;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneCut(vtkCutter toSet)
{
planeCut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetMapper GetcutMapper()
{
return cutMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutMapper(vtkDataSetMapper toSet)
{
cutMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetcutActor()
{
return cutActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutActor(vtkActor toSet)
{
cutActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkContourFilter Getiso()
{
return iso;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiso(vtkContourFilter toSet)
{
iso = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataNormals Getnormals()
{
return normals;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setnormals(vtkPolyDataNormals toSet)
{
normals = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetisoMapper()
{
return isoMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoMapper(vtkPolyDataMapper toSet)
{
isoMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetisoActor()
{
return isoActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoActor(vtkActor toSet)
{
isoActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStreamLine Getstreamer()
{
return streamer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamer(vtkStreamLine toSet)
{
streamer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTubeFilter GetstreamTube()
{
return streamTube;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamTube(vtkTubeFilter toSet)
{
streamTube = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetmapStreamTube()
{
return mapStreamTube;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetmapStreamTube(vtkPolyDataMapper toSet)
{
mapStreamTube = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetstreamTubeActor()
{
return streamTubeActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamTubeActor(vtkActor toSet)
{
streamTubeActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(reader!= null){reader.Dispose();}
if(cdp!= null){cdp.Dispose();}
if(toRectilinearGrid!= null){toRectilinearGrid.Dispose();}
if(plane!= null){plane.Dispose();}
if(tri!= null){tri.Dispose();}
if(warper!= null){warper.Dispose();}
if(planeMapper!= null){planeMapper.Dispose();}
if(planeActor!= null){planeActor.Dispose();}
if(cutPlane!= null){cutPlane.Dispose();}
if(planeCut!= null){planeCut.Dispose();}
if(cutMapper!= null){cutMapper.Dispose();}
if(cutActor!= null){cutActor.Dispose();}
if(iso!= null){iso.Dispose();}
if(normals!= null){normals.Dispose();}
if(isoMapper!= null){isoMapper.Dispose();}
if(isoActor!= null){isoActor.Dispose();}
if(streamer!= null){streamer.Dispose();}
if(streamTube!= null){streamTube.Dispose();}
if(mapStreamTube!= null){mapStreamTube.Dispose();}
if(streamTubeActor!= null){streamTubeActor.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
using System;
using System.Text;
/// <summary>
/// StringBuilder.Length Property
/// Gets or sets the length of this instance.
/// </summary>
public class StringBuilderLength
{
private const int c_MIN_STR_LEN = 1;
private const int c_MAX_STR_LEN = 260;
private const int c_MAX_CAPACITY = Int16.MaxValue;
public static int Main()
{
StringBuilderLength testObj = new StringBuilderLength();
TestLibrary.TestFramework.BeginTestCase("for property: StringBuilder.Length");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
const string c_TEST_DESC = "PosTest1: Get the Length property";
string errorDesc;
StringBuilder sb;
int actualLength, expectedLength;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
expectedLength = str.Length;
actualLength = sb.Length;
if (actualLength != expectedLength)
{
errorDesc = "Length of current StringBuilder " + sb + " is not the value ";
errorDesc += string.Format("{0} as expected: actual({1})", expectedLength, actualLength);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
const string c_TEST_DESC = "PosTest2: Set the Length property";
string errorDesc;
StringBuilder sb;
int actualLength, expectedLength;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
expectedLength = TestLibrary.Generator.GetInt32(-55) % c_MAX_STR_LEN + 1;
sb.Length = expectedLength;
actualLength = sb.Length;
if (actualLength != expectedLength)
{
errorDesc = "Length of current StringBuilder " + sb + " is not the value ";
errorDesc += string.Format("{0} as expected: actual({1})", expectedLength, actualLength);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentOutOfRangeException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: The value specified for a set operation is less than zero.";
string errorDesc;
StringBuilder sb;
int length;
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
length = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Length = length;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: The value specified for a set operation is greater than MaxCapacity.";
string errorDesc;
StringBuilder sb;
int length;
sb = new StringBuilder(0, c_MAX_CAPACITY);
length = c_MAX_CAPACITY + 1 +
TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - c_MAX_CAPACITY);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Length = length;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Stroke math
//
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg.VertexSource
{
public enum LineCap
{
Butt,
Square,
Round
}
public enum LineJoin
{
Miter,
MiterRevert,
Round,
Bevel,
MiterRound
}
public enum InnerJoin
{
Bevel,
Miter,
Jag,
Round
}
public class StrokeMath
{
public enum status_e
{
initial,
ready,
cap1,
cap2,
outline1,
close_first,
outline2,
out_vertices,
end_poly1,
end_poly2,
stop
};
private double m_width;
private double m_width_abs;
private double m_width_eps;
private int m_width_sign;
private double m_miter_limit;
private double m_inner_miter_limit;
private double m_approx_scale;
private LineCap m_line_cap;
private LineJoin m_line_join;
private InnerJoin m_inner_join;
public StrokeMath()
{
m_width = 0.5;
m_width_abs = 0.5;
m_width_eps = 0.5 / 1024.0;
m_width_sign = 1;
m_miter_limit = 4.0;
m_inner_miter_limit = 1.01;
m_approx_scale = 1.0;
m_line_cap = LineCap.Butt;
m_line_join = LineJoin.Miter;
m_inner_join = InnerJoin.Miter;
}
public void line_cap(LineCap lc)
{
m_line_cap = lc;
}
public void line_join(LineJoin lj)
{
m_line_join = lj;
}
public void inner_join(InnerJoin ij)
{
m_inner_join = ij;
}
public LineCap line_cap()
{
return m_line_cap;
}
public LineJoin line_join()
{
return m_line_join;
}
public InnerJoin inner_join()
{
return m_inner_join;
}
public void width(double w)
{
m_width = w * 0.5;
if (m_width < 0)
{
m_width_abs = -m_width;
m_width_sign = -1;
}
else
{
m_width_abs = m_width;
m_width_sign = 1;
}
m_width_eps = m_width / 1024.0;
}
public void miter_limit(double ml)
{
m_miter_limit = ml;
}
public void miter_limit_theta(double t)
{
m_miter_limit = 1.0 / Math.Sin(t * 0.5);
}
public void inner_miter_limit(double ml)
{
m_inner_miter_limit = ml;
}
public void approximation_scale(double aproxScale)
{
m_approx_scale = aproxScale;
}
public double width()
{
return m_width * 2.0;
}
public double miter_limit()
{
return m_miter_limit;
}
public double inner_miter_limit()
{
return m_inner_miter_limit;
}
public double approximation_scale()
{
return m_approx_scale;
}
public void calc_cap(IVertexDest vc, VertexDistance v0, VertexDistance v1, double len)
{
vc.remove_all();
double dx1 = (v1.y - v0.y) / len;
double dy1 = (v1.x - v0.x) / len;
double dx2 = 0;
double dy2 = 0;
dx1 *= m_width;
dy1 *= m_width;
if (m_line_cap != LineCap.Round)
{
if (m_line_cap == LineCap.Square)
{
dx2 = dy1 * m_width_sign;
dy2 = dx1 * m_width_sign;
}
add_vertex(vc, v0.x - dx1 - dx2, v0.y + dy1 - dy2);
add_vertex(vc, v0.x + dx1 - dx2, v0.y - dy1 - dy2);
}
else
{
double da = Math.Acos(m_width_abs / (m_width_abs + 0.125 / m_approx_scale)) * 2;
double a1;
int i;
int n = (int)(Math.PI / da);
da = Math.PI / (n + 1);
add_vertex(vc, v0.x - dx1, v0.y + dy1);
if (m_width_sign > 0)
{
a1 = Math.Atan2(dy1, -dx1);
a1 += da;
for (i = 0; i < n; i++)
{
add_vertex(vc, v0.x + Math.Cos(a1) * m_width,
v0.y + Math.Sin(a1) * m_width);
a1 += da;
}
}
else
{
a1 = Math.Atan2(-dy1, dx1);
a1 -= da;
for (i = 0; i < n; i++)
{
add_vertex(vc, v0.x + Math.Cos(a1) * m_width,
v0.y + Math.Sin(a1) * m_width);
a1 -= da;
}
}
add_vertex(vc, v0.x + dx1, v0.y - dy1);
}
}
public void calc_join(IVertexDest vc, VertexDistance v0,
VertexDistance v1,
VertexDistance v2,
double len1,
double len2)
{
double dx1 = m_width * (v1.y - v0.y) / len1;
double dy1 = m_width * (v1.x - v0.x) / len1;
double dx2 = m_width * (v2.y - v1.y) / len2;
double dy2 = m_width * (v2.x - v1.x) / len2;
vc.remove_all();
double cp = agg_math.cross_product(v0.x, v0.y, v1.x, v1.y, v2.x, v2.y);
if (cp != 0 && (cp > 0) == (m_width > 0))
{
// Inner join
//---------------
double limit = ((len1 < len2) ? len1 : len2) / m_width_abs;
if (limit < m_inner_miter_limit)
{
limit = m_inner_miter_limit;
}
switch (m_inner_join)
{
default: // inner_bevel
add_vertex(vc, v1.x + dx1, v1.y - dy1);
add_vertex(vc, v1.x + dx2, v1.y - dy2);
break;
case InnerJoin.Miter:
calc_miter(vc,
v0, v1, v2, dx1, dy1, dx2, dy2,
LineJoin.MiterRevert,
limit, 0);
break;
case InnerJoin.Jag:
case InnerJoin.Round:
cp = (dx1 - dx2) * (dx1 - dx2) + (dy1 - dy2) * (dy1 - dy2);
if (cp < len1 * len1 && cp < len2 * len2)
{
calc_miter(vc,
v0, v1, v2, dx1, dy1, dx2, dy2,
LineJoin.MiterRevert,
limit, 0);
}
else
{
if (m_inner_join == InnerJoin.Jag)
{
add_vertex(vc, v1.x + dx1, v1.y - dy1);
add_vertex(vc, v1.x, v1.y);
add_vertex(vc, v1.x + dx2, v1.y - dy2);
}
else
{
add_vertex(vc, v1.x + dx1, v1.y - dy1);
add_vertex(vc, v1.x, v1.y);
calc_arc(vc, v1.x, v1.y, dx2, -dy2, dx1, -dy1);
add_vertex(vc, v1.x, v1.y);
add_vertex(vc, v1.x + dx2, v1.y - dy2);
}
}
break;
}
}
else
{
// Outer join
//---------------
// Calculate the distance between v1 and
// the central point of the bevel line segment
//---------------
double dx = (dx1 + dx2) / 2;
double dy = (dy1 + dy2) / 2;
double dbevel = Math.Sqrt(dx * dx + dy * dy);
if (m_line_join == LineJoin.Round || m_line_join == LineJoin.Bevel)
{
// This is an optimization that reduces the number of points
// in cases of almost collinear segments. If there's no
// visible difference between bevel and miter joins we'd rather
// use miter join because it adds only one point instead of two.
//
// Here we calculate the middle point between the bevel points
// and then, the distance between v1 and this middle point.
// At outer joins this distance always less than stroke width,
// because it's actually the height of an isosceles triangle of
// v1 and its two bevel points. If the difference between this
// width and this value is small (no visible bevel) we can
// add just one point.
//
// The constant in the expression makes the result approximately
// the same as in round joins and caps. You can safely comment
// out this entire "if".
//-------------------
if (m_approx_scale * (m_width_abs - dbevel) < m_width_eps)
{
if (agg_math.calc_intersection(v0.x + dx1, v0.y - dy1,
v1.x + dx1, v1.y - dy1,
v1.x + dx2, v1.y - dy2,
v2.x + dx2, v2.y - dy2,
out dx, out dy))
{
add_vertex(vc, dx, dy);
}
else
{
add_vertex(vc, v1.x + dx1, v1.y - dy1);
}
return;
}
}
switch (m_line_join)
{
case LineJoin.Miter:
case LineJoin.MiterRevert:
case LineJoin.MiterRound:
calc_miter(vc,
v0, v1, v2, dx1, dy1, dx2, dy2,
m_line_join,
m_miter_limit,
dbevel);
break;
case LineJoin.Round:
calc_arc(vc, v1.x, v1.y, dx1, -dy1, dx2, -dy2);
break;
default: // Bevel join
add_vertex(vc, v1.x + dx1, v1.y - dy1);
add_vertex(vc, v1.x + dx2, v1.y - dy2);
break;
}
}
}
private void add_vertex(IVertexDest vc, double x, double y)
{
vc.add(new Vector2(x, y));
}
private void calc_arc(IVertexDest vc,
double x, double y,
double dx1, double dy1,
double dx2, double dy2)
{
double a1 = Math.Atan2(dy1 * m_width_sign, dx1 * m_width_sign);
double a2 = Math.Atan2(dy2 * m_width_sign, dx2 * m_width_sign);
double da = a1 - a2;
int i, n;
da = Math.Acos(m_width_abs / (m_width_abs + 0.125 / m_approx_scale)) * 2;
add_vertex(vc, x + dx1, y + dy1);
if (m_width_sign > 0)
{
if (a1 > a2) a2 += 2 * Math.PI;
n = (int)((a2 - a1) / da);
da = (a2 - a1) / (n + 1);
a1 += da;
for (i = 0; i < n; i++)
{
add_vertex(vc, x + Math.Cos(a1) * m_width, y + Math.Sin(a1) * m_width);
a1 += da;
}
}
else
{
if (a1 < a2) a2 -= 2 * Math.PI;
n = (int)((a1 - a2) / da);
da = (a1 - a2) / (n + 1);
a1 -= da;
for (i = 0; i < n; i++)
{
add_vertex(vc, x + Math.Cos(a1) * m_width, y + Math.Sin(a1) * m_width);
a1 -= da;
}
}
add_vertex(vc, x + dx2, y + dy2);
}
private void calc_miter(IVertexDest vc,
VertexDistance v0,
VertexDistance v1,
VertexDistance v2,
double dx1, double dy1,
double dx2, double dy2,
LineJoin lj,
double mlimit,
double dbevel)
{
double xi = v1.x;
double yi = v1.y;
double di = 1;
double lim = m_width_abs * mlimit;
bool miter_limit_exceeded = true; // Assume the worst
bool intersection_failed = true; // Assume the worst
if (agg_math.calc_intersection(v0.x + dx1, v0.y - dy1,
v1.x + dx1, v1.y - dy1,
v1.x + dx2, v1.y - dy2,
v2.x + dx2, v2.y - dy2,
out xi, out yi))
{
// Calculation of the intersection succeeded
//---------------------
di = agg_math.calc_distance(v1.x, v1.y, xi, yi);
if (di <= lim)
{
// Inside the miter limit
//---------------------
add_vertex(vc, xi, yi);
miter_limit_exceeded = false;
}
intersection_failed = false;
}
else
{
// Calculation of the intersection failed, most probably
// the three points lie one straight line.
// First check if v0 and v2 lie on the opposite sides of vector:
// (v1.x, v1.y) -> (v1.x+dx1, v1.y-dy1), that is, the perpendicular
// to the line determined by vertices v0 and v1.
// This condition determines whether the next line segments continues
// the previous one or goes back.
//----------------
double x2 = v1.x + dx1;
double y2 = v1.y - dy1;
if ((agg_math.cross_product(v0.x, v0.y, v1.x, v1.y, x2, y2) < 0.0) ==
(agg_math.cross_product(v1.x, v1.y, v2.x, v2.y, x2, y2) < 0.0))
{
// This case means that the next segment continues
// the previous one (straight line)
//-----------------
add_vertex(vc, v1.x + dx1, v1.y - dy1);
miter_limit_exceeded = false;
}
}
if (miter_limit_exceeded)
{
// Miter limit exceeded
//------------------------
switch (lj)
{
case LineJoin.MiterRevert:
// For the compatibility with SVG, PDF, etc,
// we use a simple bevel join instead of
// "smart" bevel
//-------------------
add_vertex(vc, v1.x + dx1, v1.y - dy1);
add_vertex(vc, v1.x + dx2, v1.y - dy2);
break;
case LineJoin.MiterRound:
calc_arc(vc, v1.x, v1.y, dx1, -dy1, dx2, -dy2);
break;
default:
// If no miter-revert, calculate new dx1, dy1, dx2, dy2
//----------------
if (intersection_failed)
{
mlimit *= m_width_sign;
add_vertex(vc, v1.x + dx1 + dy1 * mlimit,
v1.y - dy1 + dx1 * mlimit);
add_vertex(vc, v1.x + dx2 - dy2 * mlimit,
v1.y - dy2 - dx2 * mlimit);
}
else
{
double x1 = v1.x + dx1;
double y1 = v1.y - dy1;
double x2 = v1.x + dx2;
double y2 = v1.y - dy2;
di = (lim - dbevel) / (di - dbevel);
add_vertex(vc, x1 + (xi - x1) * di,
y1 + (yi - y1) * di);
add_vertex(vc, x2 + (xi - x2) * di,
y2 + (yi - y2) * di);
}
break;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
[Export(typeof(IPreviewFactoryService)), Shared]
internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService
{
private const double DefaultZoomLevel = 0.75;
private readonly ITextViewRoleSet _previewRoleSet;
private readonly ITextBufferFactoryService _textBufferFactoryService;
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IProjectionBufferFactoryService _projectionBufferFactoryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly ITextDifferencingSelectorService _differenceSelectorService;
private readonly IDifferenceBufferFactoryService _differenceBufferService;
private readonly IWpfDifferenceViewerFactoryService _differenceViewerService;
[ImportingConstructor]
public PreviewFactoryService(
ITextBufferFactoryService textBufferFactoryService,
IContentTypeRegistryService contentTypeRegistryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
ITextEditorFactoryService textEditorFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
ITextDifferencingSelectorService differenceSelectorService,
IDifferenceBufferFactoryService differenceBufferService,
IWpfDifferenceViewerFactoryService differenceViewerService)
{
Contract.ThrowIfTrue(this.ForegroundKind == ForegroundThreadDataKind.Unknown);
_textBufferFactoryService = textBufferFactoryService;
_contentTypeRegistryService = contentTypeRegistryService;
_projectionBufferFactoryService = projectionBufferFactoryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_differenceSelectorService = differenceSelectorService;
_differenceBufferService = differenceBufferService;
_differenceViewerService = differenceViewerService;
_previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet(
TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable);
}
public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
{
return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken);
}
public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: The order in which previews are added to the below list is significant.
// Preview for a changed document is preferred over preview for changed references and so on.
var previewItems = new List<SolutionPreviewItem>();
SolutionChangeSummary changeSummary = null;
if (newSolution != null)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
cancellationToken.ThrowIfCancellationRequested();
var projectId = projectChanges.ProjectId;
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
foreach (var documentId in projectChanges.GetChangedDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetAddedDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetRemovedDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c =>
CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetChangedAdditionalDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetAddedAdditionalDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c =>
CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c)));
}
foreach (var metadataReference in projectChanges.GetAddedMetadataReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.Adding_reference_0_to_1, metadataReference.Display, oldProject.Name)));
}
foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.Removing_reference_0_from_1, metadataReference.Display, oldProject.Name)));
}
foreach (var projectReference in projectChanges.GetAddedProjectReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.Adding_reference_0_to_1, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)));
}
foreach (var projectReference in projectChanges.GetRemovedProjectReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.Removing_reference_0_from_1, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)));
}
foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.Adding_analyzer_reference_0_to_1, analyzer.Display, oldProject.Name)));
}
foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.Removing_analyzer_reference_0_from_1, analyzer.Display, oldProject.Name)));
}
}
foreach (var project in solutionChanges.GetAddedProjects())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(project.Id, null,
string.Format(EditorFeaturesResources.Adding_project_0, project.Name)));
}
foreach (var project in solutionChanges.GetRemovedProjects())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(project.Id, null,
string.Format(EditorFeaturesResources.Removing_project_0, project.Name)));
}
foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(ProjectReferencesChanged))
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null,
string.Format(EditorFeaturesResources.Changing_project_references_for_0, projectChanges.OldProject.Name)));
}
changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges);
}
return new SolutionPreviewResult(previewItems, changeSummary);
}
private bool ProjectReferencesChanged(ProjectChanges projectChanges)
{
var oldProjectReferences = projectChanges.OldProject.ProjectReferences.ToDictionary(r => r.ProjectId);
var newProjectReferences = projectChanges.NewProject.ProjectReferences.ToDictionary(r => r.ProjectId);
// These are the set of project reference that remained in the project. We don't care
// about project references that were added or removed. Those will already be reported.
var preservedProjectIds = oldProjectReferences.Keys.Intersect(newProjectReferences.Keys);
foreach (var projectId in preservedProjectIds)
{
var oldProjectReference = oldProjectReferences[projectId];
var newProjectReference = newProjectReferences[projectId];
if (!oldProjectReference.Equals(newProjectReference))
{
return true;
}
}
return false;
}
public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken)
{
return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken);
}
private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var firstLine = string.Format(EditorFeaturesResources.Adding_0_to_1_with_content_colon,
document.Name, document.Project.Name);
var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService);
var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length))
.CreateTrackingSpan(SpanTrackingMode.EdgeExclusive);
var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService);
return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken);
}
public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var newBuffer = CreateNewBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var rightWorkspace = new PreviewWorkspace(
document.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution);
rightWorkspace.OpenDocument(document.Id);
return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken);
}
public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var newBuffer = CreateNewPlainTextBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var rightWorkspace = new PreviewWorkspace(
document.Project.Solution.WithAdditionalDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText));
rightWorkspace.OpenAdditionalDocument(document.Id);
return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken);
}
public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken)
{
return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken);
}
private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var firstLine = string.Format(EditorFeaturesResources.Removing_0_from_1_with_content_colon,
document.Name, document.Project.Name);
var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length))
.CreateTrackingSpan(SpanTrackingMode.EdgeExclusive);
var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService);
var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService);
return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken);
}
public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and possibly open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var leftDocument = document.Project
.RemoveDocument(document.Id)
.AddDocument(document.Name, oldBuffer.AsTextContainer().CurrentText);
var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution);
leftWorkspace.OpenDocument(leftDocument.Id);
return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken);
}
public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and possibly open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewPlainTextBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var leftDocumentId = DocumentId.CreateNewId(document.Project.Id);
var leftSolution = document.Project.Solution
.RemoveAdditionalDocument(document.Id)
.AddAdditionalDocument(leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText);
var leftDocument = leftSolution.GetAdditionalDocument(leftDocumentId);
var leftWorkspace = new PreviewWorkspace(leftSolution);
leftWorkspace.OpenAdditionalDocument(leftDocumentId);
return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken);
}
public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken)
{
return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken);
}
public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and currently open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken);
var newBuffer = CreateNewBuffer(newDocument, cancellationToken);
// Convert the diffs to be line based.
// Compute the diffs between the old text and the new.
var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken);
// Need to show the spans in the right that are different.
// We also need to show the spans that are in conflict.
var originalSpans = GetOriginalSpans(diffResult, cancellationToken);
var changedSpans = GetChangedSpans(diffResult, cancellationToken);
var description = default(string);
var allSpans = default(NormalizedSpanCollection);
if (newDocument.SupportsSyntaxTree)
{
var newRoot = newDocument.GetSyntaxRootSynchronously(cancellationToken);
var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList();
var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind))
.Select(a => ConflictAnnotation.GetDescription(a))
.Distinct();
var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind);
var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList();
var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind))
.Select(a => WarningAnnotation.GetDescription(a))
.Distinct();
var suppressDiagnosticsNodes = newRoot.GetAnnotatedNodesAndTokens(SuppressDiagnosticsAnnotation.Kind);
var suppressDiagnosticsSpans = suppressDiagnosticsNodes.Select(n => n.Span.ToSpan()).ToList();
AttachAnnotationsToBuffer(newBuffer, conflictSpans, warningSpans, suppressDiagnosticsSpans);
description = conflictSpans.Count == 0 && warningSpans.Count == 0
? null
: string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions));
allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans));
}
else
{
allSpans = new NormalizedSpanCollection(changedSpans);
}
var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken);
var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken);
if (!originalLineSpans.Any())
{
// This means that we have no differences (likely because of conflicts).
// In such cases, use the same spans for the left (old) buffer as the right (new) buffer.
originalLineSpans = changedLineSpans;
}
// Create PreviewWorkspaces around the buffers to be displayed on the left and right
// so that all IDE services (colorizer, squiggles etc.) light up in these buffers.
var leftDocument = oldDocument.Project
.RemoveDocument(oldDocument.Id)
.AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath);
var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution);
leftWorkspace.OpenDocument(leftDocument.Id);
var rightWorkspace = new PreviewWorkspace(
newDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution);
rightWorkspace.OpenDocument(newDocument.Id);
return CreateChangedDocumentViewAsync(
oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans,
leftWorkspace, rightWorkspace, zoomLevel, cancellationToken);
}
public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and currently open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken);
var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken);
// Convert the diffs to be line based.
// Compute the diffs between the old text and the new.
var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken);
// Need to show the spans in the right that are different.
var originalSpans = GetOriginalSpans(diffResult, cancellationToken);
var changedSpans = GetChangedSpans(diffResult, cancellationToken);
string description = null;
var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken);
var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken);
// TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above?
// Create PreviewWorkspaces around the buffers to be displayed on the left and right
// so that all IDE services (colorizer, squiggles etc.) light up in these buffers.
var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id);
var leftSolution = oldDocument.Project.Solution
.RemoveAdditionalDocument(oldDocument.Id)
.AddAdditionalDocument(leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText);
var leftWorkspace = new PreviewWorkspace(leftSolution);
leftWorkspace.OpenAdditionalDocument(leftDocumentId);
var rightWorkSpace = new PreviewWorkspace(
oldDocument.Project.Solution.WithAdditionalDocumentText(oldDocument.Id, newBuffer.AsTextContainer().CurrentText));
rightWorkSpace.OpenAdditionalDocument(newDocument.Id);
return CreateChangedDocumentViewAsync(
oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans,
leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken);
}
private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description,
List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace,
double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!(originalSpans.Any() && changedSpans.Any()))
{
// Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw.
// So if either is empty (signaling that there are no changes to preview in the document), then we bail out.
// This can happen in cases where the user has already applied the fix and light bulb has already been dismissed,
// but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at
// this point, the preview that we return will never be displayed to the user. So returning null here is harmless.
return SpecializedTasks.Default<object>();
}
var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
_contentTypeRegistryService,
_editorOptionsFactoryService.GlobalOptions,
oldBuffer.CurrentSnapshot,
"...",
description,
originalSpans.ToArray());
var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
_contentTypeRegistryService,
_editorOptionsFactoryService.GlobalOptions,
newBuffer.CurrentSnapshot,
"...",
description,
changedSpans.ToArray());
return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken);
}
private static void AttachAnnotationsToBuffer(
ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans, IEnumerable<Span> suppressDiagnosticsSpans)
{
// Attach the spans to the buffer.
newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans));
newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans));
newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.SuppressDiagnosticsSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, suppressDiagnosticsSpans));
}
private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// is it okay to create buffer from threads other than UI thread?
var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>();
var contentType = contentTypeService.GetDefaultContentType();
return _textBufferFactoryService.CreateTextBuffer(
document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType);
}
private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var contentType = _textBufferFactoryService.TextContentType;
return _textBufferFactoryService.CreateTextBuffer(
document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType);
}
private async Task<object> CreateNewDifferenceViewerAsync(
PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace,
IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer,
double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// leftWorkspace can be null if the change is adding a document.
// rightWorkspace can be null if the change is removing a document.
// However both leftWorkspace and rightWorkspace can't be null at the same time.
Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null));
var diffBuffer = _differenceBufferService.CreateDifferenceBuffer(
originalBuffer, changedBuffer,
new StringDifferenceOptions(), disableEditing: true);
var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet);
diffViewer.Closed += (s, e) =>
{
// Workaround Editor bug. The editor has an issue where they sometimes crash when
// trying to apply changes to projection buffer. So, when the user actually invokes
// a SuggestedAction we may then edit a text buffer, which the editor will then
// try to propagate through the projections we have here over that buffer. To ensure
// that that doesn't happen, we clear out the projections first so that this crash
// won't happen.
originalBuffer.DeleteSpans(0, originalBuffer.CurrentSnapshot.SpanCount);
changedBuffer.DeleteSpans(0, changedBuffer.CurrentSnapshot.SpanCount);
leftWorkspace?.Dispose();
leftWorkspace = null;
rightWorkspace?.Dispose();
rightWorkspace = null;
};
const string DiffOverviewMarginName = "deltadifferenceViewerOverview";
if (leftWorkspace == null)
{
diffViewer.ViewMode = DifferenceViewMode.RightViewOnly;
diffViewer.RightView.ZoomLevel *= zoomLevel;
diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else if (rightWorkspace == null)
{
diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly;
diffViewer.LeftView.ZoomLevel *= zoomLevel;
diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else
{
diffViewer.ViewMode = DifferenceViewMode.Inline;
diffViewer.InlineView.ZoomLevel *= zoomLevel;
diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
// Disable focus / tab stop for the diff viewer.
diffViewer.RightView.VisualElement.Focusable = false;
diffViewer.LeftView.VisualElement.Focusable = false;
diffViewer.InlineView.VisualElement.Focusable = false;
// This code path must be invoked on UI thread.
AssertIsForeground();
// We use ConfigureAwait(true) to stay on the UI thread.
await diffViewer.SizeToFitAsync().ConfigureAwait(true);
leftWorkspace?.EnableDiagnostic();
rightWorkspace?.EnableDiagnostic();
return new DifferenceViewerPreview(diffViewer);
}
private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var result = new List<LineSpan>();
foreach (var span in allSpans)
{
cancellationToken.ThrowIfCancellationRequested();
var lineSpan = GetLineSpan(textSnapshot, span);
MergeLineSpans(result, lineSpan);
}
return result;
}
// Find the lines that surround the span of the difference. Try to expand the span to
// include both the previous and next lines so that we can show more context to the
// user.
private LineSpan GetLineSpan(
ITextSnapshot snapshot,
Span span)
{
var startLine = snapshot.GetLineNumberFromPosition(span.Start);
var endLine = snapshot.GetLineNumberFromPosition(span.End);
if (startLine > 0)
{
startLine--;
}
if (endLine < snapshot.LineCount)
{
endLine++;
}
return LineSpan.FromBounds(startLine, endLine);
}
// Adds a line span to the spans we've been collecting. If the line span overlaps or
// abuts a previous span then the two are merged.
private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan)
{
if (lineSpans.Count > 0)
{
var lastLineSpan = lineSpans.Last();
// We merge them if there's no more than one line between the two. Otherwise
// we'd show "..." between two spans where we could just show the actual code.
if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1))
{
nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End);
lineSpans.RemoveAt(lineSpans.Count - 1);
}
}
lineSpans.Add(nextLineSpan);
}
private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Get the text that's actually in the editor.
var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
// Defer to the editor to figure out what changes the client made.
var diffService = _differenceSelectorService.GetTextDifferencingService(
oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType());
diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService;
return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions()
{
DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line,
});
}
private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var lineSpans = new List<Span>();
foreach (var difference in diffResult)
{
cancellationToken.ThrowIfCancellationRequested();
var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left);
lineSpans.Add(mappedSpan);
}
return new NormalizedSpanCollection(lineSpans);
}
private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var lineSpans = new List<Span>();
foreach (var difference in diffResult)
{
cancellationToken.ThrowIfCancellationRequested();
var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right);
lineSpans.Add(mappedSpan);
}
return new NormalizedSpanCollection(lineSpans);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace DotNetRevolution.EventSourcing.Auditor.WebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLiteLegacy
{
public class SQLiteGenericTableHandler<T> : SQLiteFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected static SqliteConnection m_Connection;
private static bool m_initialized;
public SQLiteGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
if (!m_initialized)
{
m_Connection = new SqliteConnection(connectionString);
m_Connection.Open();
if (storeName != String.Empty)
{
Assembly assem = GetType().Assembly;
SqliteConnection newConnection =
(SqliteConnection)((ICloneable)m_Connection).Clone();
newConnection.Open();
Migration m = new Migration(newConnection, assem, storeName);
m.Update();
newConnection.Close();
newConnection.Dispose();
}
m_initialized = true;
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
public T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
SqliteCommand cmd = new SqliteCommand();
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
terms.Add("`" + fields[i] + "` = :" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
protected T[] DoQuery(SqliteCommand cmd)
{
IDataReader reader = ExecuteReader(cmd, m_Connection);
if (reader == null)
return new T[0];
CheckColumnNames(reader);
List<T> result = new List<T>();
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
CloseCommand(cmd);
return result.ToArray();
}
public T[] Get(string where)
{
SqliteCommand cmd = new SqliteCommand();
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
public bool Store(T row)
{
SqliteCommand cmd = new SqliteCommand();
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
public bool Delete(string field, string val)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field);
cmd.Parameters.Add(new SqliteParameter(field, val));
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
}
}
| |
namespace Newtonsoft.Json.Converters
{
using System;
using System.Collections.Generic;
using System.Xml;
using Utilities;
public class XmlNodeConverter : JsonConverter
{
private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
private const string TextName = "#text";
private const string CommentName = "#comment";
private const string CDataName = "#cdata-section";
private const string WhitespaceName = "#whitespace";
private const string SignificantWhitespaceName = "#significant-whitespace";
private const string DeclarationName = "?xml";
#region Writing
public override void WriteJson(JsonWriter writer, object value)
{
XmlNode node = value as XmlNode;
if (node == null)
throw new ArgumentException("Value must be an XmlNode", "value");
writer.WriteStartObject();
SerializeNode(writer, node, true);
writer.WriteEndObject();
}
private string GetPropertyName(XmlNode node)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
return "@" + node.Name;
case XmlNodeType.CDATA:
return CDataName;
case XmlNodeType.Comment:
return CommentName;
case XmlNodeType.Element:
return node.Name;
case XmlNodeType.ProcessingInstruction:
return "?" + node.Name;
case XmlNodeType.XmlDeclaration:
return DeclarationName;
case XmlNodeType.SignificantWhitespace:
return SignificantWhitespaceName;
case XmlNodeType.Text:
return TextName;
case XmlNodeType.Whitespace:
return WhitespaceName;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType);
}
}
private void SerializeGroupedNodes(JsonWriter writer, XmlNode node)
{
// group nodes together by name
var nodesGroupedByName = new Dictionary<string, List<XmlNode>>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
var childNode = node.ChildNodes[i];
var nodeName = GetPropertyName(childNode);
List<XmlNode> nodes;
if (!nodesGroupedByName.TryGetValue(nodeName, out nodes))
{
nodes = new List<XmlNode>();
nodesGroupedByName.Add(nodeName, nodes);
}
nodes.Add(childNode);
}
// loop through grouped nodes. write single name instances as normal,
// write multiple names together in an array
foreach (var nodeNameGroup in nodesGroupedByName)
{
var groupedNodes = nodeNameGroup.Value;
if (groupedNodes.Count == 1)
{
SerializeNode(writer, groupedNodes[0], true);
}
else
{
writer.WritePropertyName(nodeNameGroup.Key);
writer.WriteStartArray();
foreach (var xnode in groupedNodes)
{
this.SerializeNode(writer, xnode, false);
}
writer.WriteEndArray();
}
}
}
private void SerializeNode(JsonWriter writer, XmlNode node, bool writePropertyName)
{
switch (node.NodeType)
{
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
SerializeGroupedNodes(writer, node);
break;
case XmlNodeType.Element:
if (writePropertyName)
writer.WritePropertyName(node.Name);
if (CollectionUtils.IsNullOrEmpty(node.Attributes) && node.ChildNodes.Count == 1
&& node.ChildNodes[0].NodeType == XmlNodeType.Text)
{
// write elements with a single text child as a name value pair
writer.WriteValue(node.ChildNodes[0].Value);
}
else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
{
// empty element
writer.WriteNull();
}
else
{
writer.WriteStartObject();
if (node.Attributes != null)
{
for (int i = 0; i < node.Attributes.Count; i++)
{
SerializeNode(writer, node.Attributes[i], true);
}
}
SerializeGroupedNodes(writer, node);
writer.WriteEndObject();
}
break;
case XmlNodeType.Comment:
if (writePropertyName)
writer.WriteComment(node.Value);
break;
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node));
writer.WriteValue(node.Value);
break;
case XmlNodeType.XmlDeclaration:
var declaration = (XmlDeclaration)node;
writer.WritePropertyName(GetPropertyName(node));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(declaration.Version))
{
writer.WritePropertyName("@version");
writer.WriteValue(declaration.Version);
}
if (!string.IsNullOrEmpty(declaration.Encoding))
{
writer.WritePropertyName("@encoding");
writer.WriteValue(declaration.Encoding);
}
if (!string.IsNullOrEmpty(declaration.Standalone))
{
writer.WritePropertyName("@standalone");
writer.WriteValue(declaration.Standalone);
}
writer.WriteEndObject();
break;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
}
}
#endregion
#region Reading
public override object ReadJson(JsonReader reader, Type objectType)
{
// maybe have CanReader and a CanWrite methods so this sort of test wouldn't be necessary
if (objectType != typeof(XmlDocument))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments");
var document = new XmlDocument();
var manager = new XmlNamespaceManager(document.NameTable);
reader.Read();
DeserializeNode(reader, document, manager, document);
return document;
}
private void DeserializeValue(
JsonReader reader,
XmlDocument document,
XmlNamespaceManager manager,
string propertyName,
XmlNode currentNode)
{
switch (propertyName)
{
case TextName:
currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
break;
case CDataName:
currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
break;
case WhitespaceName:
currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
break;
case SignificantWhitespaceName:
currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
break;
default:
// processing instructions and the xml declaration start with ?
if (propertyName[0] == '?')
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@version":
reader.Read();
version = reader.Value.ToString();
break;
case "@encoding":
reader.Read();
encoding = reader.Value.ToString();
break;
case "@standalone":
reader.Read();
standalone = reader.Value.ToString();
break;
default:
throw new JsonSerializationException(
"Unexpected property name encountered while deserializing XmlDeclaration: "
+ reader.Value);
}
}
XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, standalone);
currentNode.AppendChild(declaration);
}
else
{
XmlProcessingInstruction instruction =
document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
currentNode.AppendChild(instruction);
}
}
else
{
// deserialize xml element
bool finishedAttributes = false;
bool finishedElement = false;
string elementPrefix = GetPrefix(propertyName);
var attributeNameValues = new Dictionary<string, string>();
// a string token means the element only has a single text child
if (reader.TokenType != JsonToken.String
&& reader.TokenType != JsonToken.Null
&& reader.TokenType != JsonToken.Boolean
&& reader.TokenType != JsonToken.Integer
&& reader.TokenType != JsonToken.Float
&& reader.TokenType != JsonToken.Date)
{
// read properties until first non-attribute is encountered
while (!finishedAttributes && !finishedElement && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
if (attributeName[0] == '@')
{
attributeName = attributeName.Substring(1);
reader.Read();
string attributeValue = reader.Value.ToString();
attributeNameValues.Add(attributeName, attributeValue);
string namespacePrefix;
if (IsNamespaceAttribute(attributeName, out namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
}
else
{
finishedAttributes = true;
}
break;
case JsonToken.EndObject:
finishedElement = true;
break;
default:
throw new JsonSerializationException(
"Unexpected JsonToken: " + reader.TokenType);
}
}
}
// have to wait until attributes have been parsed before creating element
// attributes may contain namespace info used by the element
XmlElement element = (!string.IsNullOrEmpty(elementPrefix))
? document.CreateElement(propertyName, manager.LookupNamespace(elementPrefix))
: document.CreateElement(propertyName);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = GetPrefix(nameValue.Key);
XmlAttribute attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix))
: document.CreateAttribute(nameValue.Key);
attribute.Value = nameValue.Value;
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String)
{
element.AppendChild(document.CreateTextNode(reader.Value.ToString()));
}
else if (reader.TokenType == JsonToken.Integer)
{
element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value)));
}
else if (reader.TokenType == JsonToken.Float)
{
element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value)));
}
else if (reader.TokenType == JsonToken.Boolean)
{
element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value)));
}
else if (reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(XmlConvert.ToString((DateTime)reader.Value, DefaultDateTimeFormat)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (!finishedElement)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
}
}
break;
}
}
private void DeserializeNode(
JsonReader reader,
XmlDocument document,
XmlNamespaceManager manager,
XmlNode currentNode)
{
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
reader.Read();
if (reader.TokenType == JsonToken.StartArray)
{
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
}
else
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
//case JsonToken.String:
// DeserializeValue(reader, document, manager, TextName, currentNode);
// break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
default:
throw new JsonSerializationException(
"Unexpected JsonToken when deserializing node: " + reader.TokenType);
}
}
while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes
}
/// <summary>
/// Checks if the attributeName is a namespace attribute.
/// </summary>
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
if (attributeName.Length == 5)
{
prefix = string.Empty;
return true;
}
else if (attributeName[5] == ':')
{
prefix = attributeName.Substring(6, attributeName.Length - 6);
return true;
}
}
prefix = null;
return false;
}
private string GetPrefix(string qualifiedName)
{
int colonPosition = qualifiedName.IndexOf(':');
if ((colonPosition == -1 || colonPosition == 0) || (qualifiedName.Length - 1) == colonPosition)
return string.Empty;
else
return qualifiedName.Substring(0, colonPosition);
}
#endregion
public override bool CanConvert(Type valueType)
{
return typeof(XmlNode).IsAssignableFrom(valueType);
}
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Creating
{
public sealed class CreateResourceWithClientGeneratedIdTests
: IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public CreateResourceWithClientGeneratedIdTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemGroupsController>();
testContext.UseController<RgbColorsController>();
testContext.ConfigureServicesAfterStartup(services =>
{
services.AddResourceDefinition<ImplicitlyChangingWorkItemGroupDefinition>();
});
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.AllowClientGeneratedIds = true;
}
[Fact]
public async Task Can_create_resource_with_client_generated_guid_ID_having_side_effects()
{
// Arrange
WorkItemGroup newGroup = _fakers.WorkItemGroup.Generate();
newGroup.Id = Guid.NewGuid();
var requestBody = new
{
data = new
{
type = "workItemGroups",
id = newGroup.StringId,
attributes = new
{
name = newGroup.Name
}
}
};
const string route = "/workItemGroups";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Type.Should().Be("workItemGroups");
responseDocument.Data.SingleValue.Id.Should().Be(newGroup.StringId);
responseDocument.Data.SingleValue.Attributes["name"].Should().Be($"{newGroup.Name}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}");
responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(newGroup.Id);
groupInDatabase.Name.Should().Be($"{newGroup.Name}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}");
});
PropertyInfo property = typeof(WorkItemGroup).GetProperty(nameof(Identifiable.Id));
property.Should().NotBeNull().And.Subject.PropertyType.Should().Be(typeof(Guid));
}
[Fact]
public async Task Can_create_resource_with_client_generated_guid_ID_having_side_effects_with_fieldset()
{
// Arrange
WorkItemGroup newGroup = _fakers.WorkItemGroup.Generate();
newGroup.Id = Guid.NewGuid();
var requestBody = new
{
data = new
{
type = "workItemGroups",
id = newGroup.StringId,
attributes = new
{
name = newGroup.Name
}
}
};
const string route = "/workItemGroups?fields[workItemGroups]=name";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Type.Should().Be("workItemGroups");
responseDocument.Data.SingleValue.Id.Should().Be(newGroup.StringId);
responseDocument.Data.SingleValue.Attributes.Should().HaveCount(1);
responseDocument.Data.SingleValue.Attributes["name"].Should().Be($"{newGroup.Name}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}");
responseDocument.Data.SingleValue.Relationships.Should().BeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(newGroup.Id);
groupInDatabase.Name.Should().Be($"{newGroup.Name}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}");
});
PropertyInfo property = typeof(WorkItemGroup).GetProperty(nameof(Identifiable.Id));
property.Should().NotBeNull().And.Subject.PropertyType.Should().Be(typeof(Guid));
}
[Fact]
public async Task Can_create_resource_with_client_generated_string_ID_having_no_side_effects()
{
// Arrange
RgbColor newColor = _fakers.RgbColor.Generate();
var requestBody = new
{
data = new
{
type = "rgbColors",
id = newColor.StringId,
attributes = new
{
displayName = newColor.DisplayName
}
}
};
const string route = "/rgbColors";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
RgbColor colorInDatabase = await dbContext.RgbColors.FirstWithIdAsync(newColor.Id);
colorInDatabase.DisplayName.Should().Be(newColor.DisplayName);
});
PropertyInfo property = typeof(RgbColor).GetProperty(nameof(Identifiable.Id));
property.Should().NotBeNull().And.Subject.PropertyType.Should().Be(typeof(string));
}
[Fact]
public async Task Can_create_resource_with_client_generated_string_ID_having_no_side_effects_with_fieldset()
{
// Arrange
RgbColor newColor = _fakers.RgbColor.Generate();
var requestBody = new
{
data = new
{
type = "rgbColors",
id = newColor.StringId,
attributes = new
{
displayName = newColor.DisplayName
}
}
};
const string route = "/rgbColors?fields[rgbColors]=id";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
RgbColor colorInDatabase = await dbContext.RgbColors.FirstWithIdAsync(newColor.Id);
colorInDatabase.DisplayName.Should().Be(newColor.DisplayName);
});
PropertyInfo property = typeof(RgbColor).GetProperty(nameof(Identifiable.Id));
property.Should().NotBeNull().And.Subject.PropertyType.Should().Be(typeof(string));
}
[Fact]
public async Task Cannot_create_resource_for_existing_client_generated_ID()
{
// Arrange
RgbColor existingColor = _fakers.RgbColor.Generate();
RgbColor colorToCreate = _fakers.RgbColor.Generate();
colorToCreate.Id = existingColor.Id;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RgbColors.Add(existingColor);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "rgbColors",
id = colorToCreate.StringId,
attributes = new
{
displayName = colorToCreate.DisplayName
}
}
};
const string route = "/rgbColors";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Conflict);
error.Title.Should().Be("Another resource with the specified ID already exists.");
error.Detail.Should().Be($"Another resource of type 'rgbColors' with ID '{existingColor.StringId}' already exists.");
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Globalization;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
internal abstract class FieldGeneratorBase : SourceGeneratorBase<FieldDescriptor>
{
private readonly int _fieldOrdinal;
protected FieldGeneratorBase(FieldDescriptor descriptor, int fieldOrdinal)
: base(descriptor)
{
_fieldOrdinal = fieldOrdinal;
}
public abstract void WriteHash(TextGenerator writer);
public abstract void WriteEquals(TextGenerator writer);
public abstract void WriteToString(TextGenerator writer);
public int FieldOrdinal
{
get { return _fieldOrdinal; }
}
private static bool AllPrintableAscii(string text)
{
foreach (char c in text)
{
if (c < 0x20 || c > 0x7e)
{
return false;
}
}
return true;
}
/// <summary>
/// This returns true if the field has a non-default default value. For instance this returns
/// false for numerics with a default of zero '0', or booleans with a default of false.
/// </summary>
protected bool HasDefaultValue
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.Float:
case FieldType.Double:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
{
IConvertible value = (IConvertible) Descriptor.DefaultValue;
return value.ToString(CultureInfo.InvariantCulture) != "0";
}
case FieldType.Bool:
return ((bool) Descriptor.DefaultValue) == true;
default:
return true;
}
}
}
/// <remarks>Copy exists in ExtensionGenerator.cs</remarks>
protected string DefaultValue
{
get
{
string suffix = "";
switch (Descriptor.FieldType)
{
case FieldType.Float:
suffix = "F";
break;
case FieldType.Double:
suffix = "D";
break;
case FieldType.Int64:
suffix = "L";
break;
case FieldType.UInt64:
suffix = "UL";
break;
}
switch (Descriptor.FieldType)
{
case FieldType.Float:
case FieldType.Double:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
{
// The simple Object.ToString converts using the current culture.
// We want to always use the invariant culture so it's predictable.
IConvertible value = (IConvertible) Descriptor.DefaultValue;
//a few things that must be handled explicitly
if (Descriptor.FieldType == FieldType.Double && value is double)
{
if (double.IsNaN((double) value))
{
return "double.NaN";
}
if (double.IsPositiveInfinity((double) value))
{
return "double.PositiveInfinity";
}
if (double.IsNegativeInfinity((double) value))
{
return "double.NegativeInfinity";
}
}
else if (Descriptor.FieldType == FieldType.Float && value is float)
{
if (float.IsNaN((float) value))
{
return "float.NaN";
}
if (float.IsPositiveInfinity((float) value))
{
return "float.PositiveInfinity";
}
if (float.IsNegativeInfinity((float) value))
{
return "float.NegativeInfinity";
}
}
return value.ToString(CultureInfo.InvariantCulture) + suffix;
}
case FieldType.Bool:
return (bool) Descriptor.DefaultValue ? "true" : "false";
case FieldType.Bytes:
if (!Descriptor.HasDefaultValue)
{
return "pb::ByteString.Empty";
}
if (UseLiteRuntime && Descriptor.DefaultValue is ByteString)
{
string temp = (((ByteString) Descriptor.DefaultValue).ToBase64());
return String.Format("pb::ByteString.FromBase64(\"{0}\")", temp);
}
return string.Format("(pb::ByteString) {0}.Descriptor.Fields[{1}].DefaultValue",
GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.String:
if (AllPrintableAscii(Descriptor.Proto.DefaultValue))
{
// All chars are ASCII and printable. In this case we only
// need to escape quotes and backslashes.
return "\"" + Descriptor.Proto.DefaultValue
.Replace("\\", "\\\\")
.Replace("'", "\\'")
.Replace("\"", "\\\"")
+ "\"";
}
if (UseLiteRuntime && Descriptor.DefaultValue is String)
{
string temp = Convert.ToBase64String(
Encoding.UTF8.GetBytes((String) Descriptor.DefaultValue));
return String.Format("pb::ByteString.FromBase64(\"{0}\").ToStringUtf8()", temp);
}
return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue",
GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.Enum:
return TypeName + "." + ((EnumValueDescriptor) Descriptor.DefaultValue).Name;
case FieldType.Message:
case FieldType.Group:
return TypeName + ".DefaultInstance";
default:
throw new InvalidOperationException("Invalid field descriptor type");
}
}
}
protected string PropertyName
{
get { return Descriptor.CSharpOptions.PropertyName; }
}
protected string Name
{
get { return NameHelpers.UnderscoresToCamelCase(GetFieldName(Descriptor)); }
}
protected int Number
{
get { return Descriptor.FieldNumber; }
}
protected void AddNullCheck(TextGenerator writer)
{
AddNullCheck(writer, "value");
}
protected void AddNullCheck(TextGenerator writer, string name)
{
if (IsNullableType)
{
writer.WriteLine(" pb::ThrowHelper.ThrowIfNull({0}, \"{0}\");", name);
}
}
protected void AddPublicMemberAttributes(TextGenerator writer)
{
AddDeprecatedFlag(writer);
AddClsComplianceCheck(writer);
}
protected void AddClsComplianceCheck(TextGenerator writer)
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
}
protected bool IsObsolete { get { return Descriptor.Options.Deprecated; } }
/// <summary>
/// Writes [global::System.ObsoleteAttribute()] if the member is obsolete
/// </summary>
protected void AddDeprecatedFlag(TextGenerator writer)
{
if (IsObsolete)
{
writer.WriteLine("[global::System.ObsoleteAttribute()]");
}
}
/// <summary>
/// For encodings with fixed sizes, returns that size in bytes. Otherwise
/// returns -1. TODO(jonskeet): Make this less ugly.
/// </summary>
protected int FixedSize
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.Enum:
case FieldType.Bytes:
case FieldType.String:
case FieldType.Message:
case FieldType.Group:
return -1;
case FieldType.Float:
return WireFormat.FloatSize;
case FieldType.SFixed32:
return WireFormat.SFixed32Size;
case FieldType.Fixed32:
return WireFormat.Fixed32Size;
case FieldType.Double:
return WireFormat.DoubleSize;
case FieldType.SFixed64:
return WireFormat.SFixed64Size;
case FieldType.Fixed64:
return WireFormat.Fixed64Size;
case FieldType.Bool:
return WireFormat.BoolSize;
default:
throw new InvalidOperationException("Invalid field descriptor type");
}
}
}
protected bool IsNullableType
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.Float:
case FieldType.Double:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
case FieldType.Bool:
case FieldType.Enum:
return false;
case FieldType.Bytes:
case FieldType.String:
case FieldType.Message:
case FieldType.Group:
return true;
default:
throw new InvalidOperationException("Invalid field descriptor type");
}
}
}
protected string TypeName
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.Enum:
return GetClassName(Descriptor.EnumType);
case FieldType.Message:
case FieldType.Group:
return GetClassName(Descriptor.MessageType);
default:
return DescriptorUtil.GetMappedTypeName(Descriptor.MappedType);
}
}
}
protected string MessageOrGroup
{
get { return Descriptor.FieldType == FieldType.Group ? "Group" : "Message"; }
}
/// <summary>
/// Returns the type name as used in CodedInputStream method names: SFixed32, UInt32 etc.
/// </summary>
protected string CapitalizedTypeName
{
get
{
// Our enum names match perfectly. How serendipitous.
return Descriptor.FieldType.ToString();
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="IndexEnumerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------
// <summary>
// </summary>
// ---------------------------------------------------------------------
namespace Microsoft.Database.Isam
{
using System;
using System.Collections;
using Microsoft.Isam.Esent.Interop;
/// <summary>
/// Enumerates the indices on a given table.
/// </summary>
public class IndexEnumerator : IEnumerator
{
/// <summary>
/// The database
/// </summary>
private readonly IsamDatabase database;
/// <summary>
/// The table name
/// </summary>
private readonly string tableName;
/// <summary>
/// The enumerator
/// </summary>
private readonly IDictionaryEnumerator enumerator;
/// <summary>
/// The index list
/// </summary>
private JET_INDEXLIST indexList;
/// <summary>
/// The cleanup
/// </summary>
private bool cleanup = false;
/// <summary>
/// The moved
/// </summary>
private bool moved = false;
/// <summary>
/// The current
/// </summary>
private bool current = false;
/// <summary>
/// The index definition
/// </summary>
private IndexDefinition indexDefinition = null;
/// <summary>
/// The index update identifier
/// </summary>
private long indexUpdateID = 0;
/// <summary>
/// Initializes a new instance of the <see cref="IndexEnumerator" /> class.
/// </summary>
/// <param name="database">The database.</param>
/// <param name="tableName">Name of the table.</param>
internal IndexEnumerator(IsamDatabase database, string tableName)
{
this.database = database;
this.tableName = tableName;
this.enumerator = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="IndexEnumerator"/> class.
/// </summary>
/// <param name="enumerator">The enumerator.</param>
internal IndexEnumerator(IDictionaryEnumerator enumerator)
{
this.database = null;
this.enumerator = enumerator;
}
/// <summary>
/// Finalizes an instance of the IndexEnumerator class
/// </summary>
~IndexEnumerator()
{
this.Reset();
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>The current element in the collection.</returns>
/// <exception cref="System.InvalidOperationException">
/// after last index on table
/// or
/// before first index on table
/// </exception>
/// <remarks>
/// This is the type safe version that may not work in other CLR
/// languages.
/// </remarks>
public IndexDefinition Current
{
get
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
if (!this.current)
{
if (this.moved)
{
throw new InvalidOperationException("after last index on table");
}
else
{
throw new InvalidOperationException("before first index on table");
}
}
if (this.indexDefinition == null || this.indexUpdateID != DatabaseCommon.SchemaUpdateID)
{
this.indexDefinition = IndexDefinition.Load(this.database, this.tableName, this.indexList);
this.indexUpdateID = DatabaseCommon.SchemaUpdateID;
}
return this.indexDefinition;
}
}
else
{
return (IndexDefinition)this.enumerator.Value;
}
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>The current element in the collection.</returns>
/// <remarks>
/// This is the standard version that will work with other CLR
/// languages.
/// </remarks>
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
public void Reset()
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
if (this.cleanup)
{
if (!this.database.IsamSession.Disposed)
{
// BUGBUG: we will try to close an already closed tableid
// if it was already closed due to a rollback. this could
// cause us to crash in ESENT due to lack of full validation
// in small config. we should use cursor LS to detect when
// our cursor gets closed and thus avoid closing it again
Api.JetCloseTable(this.database.IsamSession.Sesid, this.indexList.tableid);
}
}
this.cleanup = false;
this.moved = false;
this.current = false;
this.indexDefinition = null;
}
}
else
{
this.enumerator.Reset();
}
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
if (!this.moved)
{
Api.JetGetIndexInfo(
this.database.IsamSession.Sesid,
this.database.Dbid,
this.tableName,
null,
out this.indexList,
JET_IdxInfo.List);
this.cleanup = true;
this.current = Api.TryMoveFirst(this.database.IsamSession.Sesid, this.indexList.tableid);
}
else if (this.current)
{
this.current = Api.TryMoveNext(this.database.IsamSession.Sesid, this.indexList.tableid);
if (!this.current)
{
Api.JetCloseTable(this.database.IsamSession.Sesid, this.indexList.tableid);
this.cleanup = false;
}
}
this.moved = true;
this.indexDefinition = null;
return this.current;
}
}
else
{
return this.enumerator.MoveNext();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
$Pref::WorldEditor::FileSpec = "Torque Mission Files (*.mis)|*.mis|All Files (*.*)|*.*|";
//////////////////////////////////////////////////////////////////////////
// File Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorFileMenu::onMenuSelect(%this)
{
%this.enableItem(2, EditorIsDirty());
}
//////////////////////////////////////////////////////////////////////////
// Package that gets temporarily activated to toggle editor after mission loading.
// Deactivates itself.
package BootEditor {
function GameConnection::initialControlSet( %this )
{
Parent::initialControlSet( %this );
toggleEditor( true );
deactivatePackage( "BootEditor" );
}
};
//////////////////////////////////////////////////////////////////////////
/// Checks the various dirty flags and returns true if the
/// mission or other related resources need to be saved.
function EditorIsDirty()
{
// We kept a hard coded test here, but we could break these
// into the registered tools if we wanted to.
%isDirty = ( isObject( "ETerrainEditor" ) && ( ETerrainEditor.isMissionDirty || ETerrainEditor.isDirty ) )
|| ( isObject( "EWorldEditor" ) && EWorldEditor.isDirty )
|| ( isObject( "ETerrainPersistMan" ) && ETerrainPersistMan.hasDirty() );
// Give the editor plugins a chance to set the dirty flag.
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
%isDirty |= %obj.isDirty();
}
return %isDirty;
}
/// Clears all the dirty state without saving.
function EditorClearDirty()
{
EWorldEditor.isDirty = false;
ETerrainEditor.isDirty = false;
ETerrainEditor.isMissionDirty = false;
ETerrainPersistMan.clearAll();
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
%obj.clearDirty();
}
}
function EditorQuitGame()
{
if( EditorIsDirty())
{
MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before quitting?", "EditorSaveMissionMenu(); quit();", "quit();", "" );
}
else
quit();
}
function EditorExitMission()
{
if( EditorIsDirty())
{
MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before exiting?", "EditorDoExitMission(true);", "EditorDoExitMission(false);", "");
}
else
EditorDoExitMission(false);
}
function EditorDoExitMission(%saveFirst)
{
if(%saveFirst)
{
EditorSaveMissionMenu();
}
else
{
EditorClearDirty();
}
if (isObject( MainMenuGui ))
Editor.close("MainMenuGui");
disconnect();
}
function EditorOpenTorsionProject( %projectFile )
{
// Make sure we have a valid path to the Torsion installation.
%torsionPath = EditorSettings.value( "WorldEditor/torsionPath" );
if( !isFile( %torsionPath ) )
{
MessageBoxOK(
"Torsion Not Found",
"Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences."
);
return;
}
// Determine the path to the .torsion file.
if( %projectFile $= "" )
{
%projectName = fileBase( getExecutableName() );
%projectFile = makeFullPath( %projectName @ ".torsion" );
if( !isFile( %projectFile ) )
{
%projectFile = findFirstFile( "*.torsion", false );
if( !isFile( %projectFile ) )
{
MessageBoxOK(
"Project File Not Found",
"Cannot find .torsion project file in '" @ getMainDotCsDir() @ "'."
);
return;
}
}
}
// Open the project in Torsion.
shellExecute( %torsionPath, "\"" @ %projectFile @ "\"" );
}
function EditorOpenFileInTorsion( %file, %line )
{
// Make sure we have a valid path to the Torsion installation.
%torsionPath = EditorSettings.value( "WorldEditor/torsionPath" );
if( !isFile( %torsionPath ) )
{
MessageBoxOK(
"Torsion Not Found",
"Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences."
);
return;
}
// If no file was specified, take the current mission file.
if( %file $= "" )
%file = makeFullPath( $Server::MissionFile );
// Open the file in Torsion.
%args = "\"" @ %file;
if( %line !$= "" )
%args = %args @ ":" @ %line;
%args = %args @ "\"";
shellExecute( %torsionPath, %args );
}
function EditorOpenDeclarationInTorsion( %object )
{
%fileName = %object.getFileName();
if( %fileName $= "" )
return;
EditorOpenFileInTorsion( makeFullPath( %fileName ), %object.getDeclarationLine() );
}
function EditorNewLevel( %file )
{
%saveFirst = false;
if ( EditorIsDirty() )
{
error(knob);
%saveFirst = MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @
$Server::MissionFile @ "\" before creating a new mission?", "SaveDontSave", "Question") == $MROk;
}
if(%saveFirst)
EditorSaveMission();
// Clear dirty flags first to avoid duplicate dialog box from EditorOpenMission()
if( isObject( Editor ) )
{
EditorClearDirty();
Editor.getUndoManager().clearAll();
}
if( %file $= "" )
%file = EditorSettings.value( "WorldEditor/newLevelFile" );
if( !$missionRunning )
{
activatePackage( "BootEditor" );
StartLevel( %file );
}
else
EditorOpenMission(%file);
//EWorldEditor.isDirty = true;
//ETerrainEditor.isDirty = true;
EditorGui.saveAs = true;
}
function EditorSaveMissionMenu()
{
if(EditorGui.saveAs)
EditorSaveMissionAs();
else
EditorSaveMission();
}
function EditorSaveMission()
{
// just save the mission without renaming it
// first check for dirty and read-only files:
if((EWorldEditor.isDirty || ETerrainEditor.isMissionDirty) && !isWriteableFileName($Server::MissionFile))
{
MessageBox("Error", "Mission file \""@ $Server::MissionFile @ "\" is read-only. Continue?", "Ok", "Stop");
return false;
}
if(ETerrainEditor.isDirty)
{
// Find all of the terrain files
initContainerTypeSearch($TypeMasks::TerrainObjectType);
while ((%terrainObject = containerSearchNext()) != 0)
{
if (!isWriteableFileName(%terrainObject.terrainFile))
{
if (MessageBox("Error", "Terrain file \""@ %terrainObject.terrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk)
continue;
else
return false;
}
}
}
// now write the terrain and mission files out:
if(EWorldEditor.isDirty || ETerrainEditor.isMissionDirty)
getRootScene().save($Server::MissionFile);
if(ETerrainEditor.isDirty)
{
// Find all of the terrain files
initContainerTypeSearch($TypeMasks::TerrainObjectType);
while ((%terrainObject = containerSearchNext()) != 0)
%terrainObject.save(%terrainObject.terrainFile);
}
ETerrainPersistMan.saveDirty();
// Give EditorPlugins a chance to save.
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
if ( %obj.isDirty() )
%obj.onSaveMission( $Server::MissionFile );
}
EditorClearDirty();
EditorGui.saveAs = false;
return true;
}
function EditorSaveMissionAs( %missionName )
{
// If we didn't get passed a new mission name then
// prompt the user for one.
if ( %missionName $= "" )
{
%dlg = new SaveFileDialog()
{
Filters = $Pref::WorldEditor::FileSpec;
DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory");
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if(%ret)
{
// Immediately override/set the levelsDirectory
EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) );
%missionName = %dlg.FileName;
}
%dlg.delete();
if(! %ret)
return;
}
if( fileExt( %missionName ) !$= ".mis" )
%missionName = %missionName @ ".mis";
EWorldEditor.isDirty = true;
%saveMissionFile = $Server::MissionFile;
$Server::MissionFile = %missionName;
%copyTerrainsFailed = false;
// Rename all the terrain files. Save all previous names so we can
// reset them if saving fails.
%newMissionName = fileBase(%missionName);
%oldMissionName = fileBase(%saveMissionFile);
initContainerTypeSearch( $TypeMasks::TerrainObjectType );
%savedTerrNames = new ScriptObject();
for( %i = 0;; %i ++ )
{
%terrainObject = containerSearchNext();
if( !%terrainObject )
break;
%savedTerrNames.array[ %i ] = %terrainObject.terrainFile;
%terrainFilePath = makeRelativePath( filePath( %terrainObject.terrainFile ), getMainDotCsDir() );
%terrainFileName = fileName( %terrainObject.terrainFile );
// Workaround to have terrains created in an unsaved "New Level..." mission
// moved to the correct place.
if( EditorGui.saveAs && %terrainFilePath $= "tools/art/terrains" )
%terrainFilePath = "art/terrains";
// Try and follow the existing naming convention.
// If we can't, use systematic terrain file names.
if( strstr( %terrainFileName, %oldMissionName ) >= 0 )
%terrainFileName = strreplace( %terrainFileName, %oldMissionName, %newMissionName );
else
%terrainFileName = %newMissionName @ "_" @ %i @ ".ter";
%newTerrainFile = %terrainFilePath @ "/" @ %terrainFileName;
if (!isWriteableFileName(%newTerrainFile))
{
if (MessageBox("Error", "Terrain file \""@ %newTerrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk)
continue;
else
{
%copyTerrainsFailed = true;
break;
}
}
if( !%terrainObject.save( %newTerrainFile ) )
{
error( "Failed to save '" @ %newTerrainFile @ "'" );
%copyTerrainsFailed = true;
break;
}
%terrainObject.terrainFile = %newTerrainFile;
}
ETerrainEditor.isDirty = false;
// Save the mission.
if(%copyTerrainsFailed || !EditorSaveMission())
{
// It failed, so restore the mission and terrain filenames.
$Server::MissionFile = %saveMissionFile;
initContainerTypeSearch( $TypeMasks::TerrainObjectType );
for( %i = 0;; %i ++ )
{
%terrainObject = containerSearchNext();
if( !%terrainObject )
break;
%terrainObject.terrainFile = %savedTerrNames.array[ %i ];
}
}
%savedTerrNames.delete();
}
function EditorOpenMission(%filename)
{
if( EditorIsDirty())
{
// "EditorSaveBeforeLoad();", "getLoadFilename(\"*.mis\", \"EditorDoLoadMission\");"
if(MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @
$Server::MissionFile @ "\" before opening a new mission?", SaveDontSave, Question) == $MROk)
{
if(! EditorSaveMission())
return;
}
}
if(%filename $= "")
{
%dlg = new OpenFileDialog()
{
Filters = $Pref::WorldEditor::FileSpec;
DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory");
ChangePath = false;
MustExist = true;
};
%ret = %dlg.Execute();
if(%ret)
{
// Immediately override/set the levelsDirectory
EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) );
%filename = %dlg.FileName;
}
%dlg.delete();
if(! %ret)
return;
}
// close the current editor, it will get cleaned up by MissionCleanup
if( isObject( "Editor" ) )
Editor.close( LoadingGui );
EditorClearDirty();
// If we haven't yet connnected, create a server now.
// Otherwise just load the mission.
if( !$missionRunning )
{
activatePackage( "BootEditor" );
StartLevel( %filename );
}
else
{
loadMission( %filename, true ) ;
pushInstantGroup();
// recreate and open the editor
Editor::create();
MissionCleanup.add( Editor );
MissionCleanup.add( Editor.getUndoManager() );
EditorGui.loadingMission = true;
Editor.open();
popInstantGroup();
}
}
function EditorOpenSceneAppend(%levelAsset)
{
//Load the asset's level file
exec(%levelAsset.levelFile);
//We'll assume the scene name and assetname are the same for now
%sceneName = %levelAsset.AssetName;
%scene = nameToID(%sceneName);
if(isObject(%scene))
{
//Append it to our scene heirarchy
$scenesRootGroup.add(%scene);
}
}
function EditorExportToCollada()
{
%dlg = new SaveFileDialog()
{
Filters = "COLLADA Files (*.dae)|*.dae|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%exportFile = %dlg.FileName;
}
if( fileExt( %exportFile ) !$= ".dae" )
%exportFile = %exportFile @ ".dae";
%dlg.delete();
if ( !%ret )
return;
if ( EditorGui.currentEditor.getId() == ShapeEditorPlugin.getId() )
ShapeEdShapeView.exportToCollada( %exportFile );
else
EWorldEditor.colladaExportSelection( %exportFile );
}
function EditorMakePrefab()
{
%dlg = new SaveFileDialog()
{
Filters = "Prefab Files (*.prefab)|*.prefab|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%saveFile = %dlg.FileName;
}
if( fileExt( %saveFile ) !$= ".prefab" )
%saveFile = %saveFile @ ".prefab";
%dlg.delete();
if ( !%ret )
return;
EWorldEditor.makeSelectionPrefab( %saveFile );
EditorTree.buildVisibleTree( true );
}
function EditorExplodePrefab()
{
//echo( "EditorExplodePrefab()" );
EWorldEditor.explodeSelectedPrefab();
EditorTree.buildVisibleTree( true );
}
function makeSelectedAMesh()
{
%dlg = new SaveFileDialog()
{
Filters = "Collada file (*.dae)|*.dae|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%saveFile = %dlg.FileName;
}
if( fileExt( %saveFile ) !$= ".dae" )
%saveFile = %saveFile @ ".dae";
%dlg.delete();
if ( !%ret )
return;
EWorldEditor.makeSelectionAMesh( %saveFile );
EditorTree.buildVisibleTree( true );
}
function EditorMount()
{
echo( "EditorMount" );
%size = EWorldEditor.getSelectionSize();
if ( %size != 2 )
return;
%a = EWorldEditor.getSelectedObject(0);
%b = EWorldEditor.getSelectedObject(1);
//%a.mountObject( %b, 0 );
EWorldEditor.mountRelative( %a, %b );
}
function EditorUnmount()
{
echo( "EditorUnmount" );
%obj = EWorldEditor.getSelectedObject(0);
%obj.unmount();
}
//////////////////////////////////////////////////////////////////////////
// View Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorViewMenu::onMenuSelect( %this )
{
%this.checkItem( 1, EWorldEditor.renderOrthoGrid );
}
//////////////////////////////////////////////////////////////////////////
// Edit Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorEditMenu::onMenuSelect( %this )
{
// UndoManager is in charge of enabling or disabling the undo/redo items.
Editor.getUndoManager().updateUndoMenu( %this );
// SICKHEAD: It a perfect world we would abstract
// cut/copy/paste with a generic selection object
// which would know how to process itself.
// Give the active editor a chance at fixing up
// the state of the edit menu.
// Do we really need this check here?
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.onEditMenuSelect( %this );
}
//////////////////////////////////////////////////////////////////////////
function EditorMenuEditDelete()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleDelete();
}
function EditorMenuEditDeselect()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleDeselect();
}
function EditorMenuEditCut()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleCut();
}
function EditorMenuEditCopy()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleCopy();
}
function EditorMenuEditPaste()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handlePaste();
}
//////////////////////////////////////////////////////////////////////////
// Window Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorToolsMenu::onSelectItem(%this, %id)
{
%toolName = getField( %this.item[%id], 2 );
EditorGui.setEditor(%toolName, %paletteName );
%this.checkRadioItem(0, %this.getItemCount(), %id);
return true;
}
function EditorToolsMenu::setupDefaultState(%this)
{
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
// Camera Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorCameraMenu::onSelectItem(%this, %id, %text)
{
if(%id == 0 || %id == 1)
{
// Handle the Free Camera/Orbit Camera toggle
%this.checkRadioItem(0, 1, %id);
}
return Parent::onSelectItem(%this, %id, %text);
}
function EditorCameraMenu::setupDefaultState(%this)
{
// Set the Free Camera/Orbit Camera check marks
%this.checkRadioItem(0, 1, 0);
Parent::setupDefaultState(%this);
}
function EditorFreeCameraTypeMenu::onSelectItem(%this, %id, %text)
{
// Handle the camera type radio
%this.checkRadioItem(0, 2, %id);
return Parent::onSelectItem(%this, %id, %text);
}
function EditorFreeCameraTypeMenu::setupDefaultState(%this)
{
// Set the camera type check marks
%this.checkRadioItem(0, 2, 0);
Parent::setupDefaultState(%this);
}
function EditorCameraSpeedMenu::onSelectItem(%this, %id, %text)
{
// Grab and set speed
%speed = getField( %this.item[%id], 2 );
$Camera::movementSpeed = %speed;
// Update Editor
%this.checkRadioItem(0, 6, %id);
// Update Toolbar TextEdit
EWorldEditorCameraSpeed.setText( $Camera::movementSpeed );
// Update Toolbar Slider
CameraSpeedDropdownCtrlContainer-->Slider.setValue( $Camera::movementSpeed );
return true;
}
function EditorCameraSpeedMenu::setupDefaultState(%this)
{
// Setup camera speed gui's. Both menu and editorgui
%this.setupGuiControls();
//Grab and set speed
%defaultSpeed = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeed");
if( %defaultSpeed $= "" )
{
// Update Editor with default speed
%defaultSpeed = 25;
}
$Camera::movementSpeed = %defaultSpeed;
// Update Toolbar TextEdit
EWorldEditorCameraSpeed.setText( %defaultSpeed );
// Update Toolbar Slider
CameraSpeedDropdownCtrlContainer-->Slider.setValue( %defaultSpeed );
Parent::setupDefaultState(%this);
}
function EditorCameraSpeedMenu::setupGuiControls(%this)
{
// Default levelInfo params
%minSpeed = 5;
%maxSpeed = 200;
%speedA = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMin");
%speedB = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMax");
if( %speedA < %speedB )
{
if( %speedA == 0 )
{
if( %speedB > 1 )
%minSpeed = 1;
else
%minSpeed = 0.1;
}
else
{
%minSpeed = %speedA;
}
%maxSpeed = %speedB;
}
// Set up the camera speed items
%inc = ( (%maxSpeed - %minSpeed) / (%this.getItemCount() - 1) );
for( %i = 0; %i < %this.getItemCount(); %i++)
%this.item[%i] = setField( %this.item[%i], 2, (%minSpeed + (%inc * %i)));
// Set up min/max camera slider range
eval("CameraSpeedDropdownCtrlContainer-->Slider.range = \"" @ %minSpeed @ " " @ %maxSpeed @ "\";");
}
//////////////////////////////////////////////////////////////////////////
// Tools Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorUtilitiesMenu::onSelectItem(%this, %id, %text)
{
return Parent::onSelectItem(%this, %id, %text);
}
//////////////////////////////////////////////////////////////////////////
// World Menu Handler Object Menu
//////////////////////////////////////////////////////////////////////////
function EditorWorldMenu::onMenuSelect(%this)
{
%selSize = EWorldEditor.getSelectionSize();
%lockCount = EWorldEditor.getSelectionLockCount();
%hideCount = EWorldEditor.getSelectionHiddenCount();
%this.enableItem(0, %lockCount < %selSize); // Lock Selection
%this.enableItem(1, %lockCount > 0); // Unlock Selection
%this.enableItem(3, %hideCount < %selSize); // Hide Selection
%this.enableItem(4, %hideCount > 0); // Show Selection
%this.enableItem(6, %selSize > 1 && %lockCount == 0); // Align bounds
%this.enableItem(7, %selSize > 1 && %lockCount == 0); // Align center
%this.enableItem(9, %selSize > 0 && %lockCount == 0); // Reset Transforms
%this.enableItem(10, %selSize > 0 && %lockCount == 0); // Reset Selected Rotation
%this.enableItem(11, %selSize > 0 && %lockCount == 0); // Reset Selected Scale
%this.enableItem(12, %selSize > 0 && %lockCount == 0); // Transform Selection
%this.enableItem(14, %selSize > 0 && %lockCount == 0); // Drop Selection
%this.enableItem(17, %selSize > 0); // Make Prefab
%this.enableItem(18, %selSize > 0); // Explode Prefab
%this.enableItem(20, %selSize > 1); // Mount
%this.enableItem(21, %selSize > 0); // Unmount
}
//////////////////////////////////////////////////////////////////////////
function EditorDropTypeMenu::onSelectItem(%this, %id, %text)
{
// This sets up which drop script function to use when
// a drop type is selected in the menu.
EWorldEditor.dropType = getField(%this.item[%id], 2);
%this.checkRadioItem(0, (%this.getItemCount() - 1), %id);
return true;
}
function EditorDropTypeMenu::setupDefaultState(%this)
{
// Check the radio item for the currently set drop type.
%numItems = %this.getItemCount();
%dropTypeIndex = 0;
for( ; %dropTypeIndex < %numItems; %dropTypeIndex ++ )
if( getField( %this.item[ %dropTypeIndex ], 2 ) $= EWorldEditor.dropType )
break;
// Default to screenCenter if we didn't match anything.
if( %dropTypeIndex > (%numItems - 1) )
%dropTypeIndex = 4;
%this.checkRadioItem( 0, (%numItems - 1), %dropTypeIndex );
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
function EditorAlignBoundsMenu::onSelectItem(%this, %id, %text)
{
// Have the editor align all selected objects by the selected bounds.
EWorldEditor.alignByBounds(getField(%this.item[%id], 2));
return true;
}
function EditorAlignBoundsMenu::setupDefaultState(%this)
{
// Allow the parent to set the menu's default state
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
function EditorAlignCenterMenu::onSelectItem(%this, %id, %text)
{
// Have the editor align all selected objects by the selected axis.
EWorldEditor.alignByAxis(getField(%this.item[%id], 2));
return true;
}
function EditorAlignCenterMenu::setupDefaultState(%this)
{
// Allow the parent to set the menu's default state
Parent::setupDefaultState(%this);
}
| |
//#define TRACE_SERIALIZATION
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Runtime;
namespace Orleans.Serialization
{
/// <summary>
/// Reader for Orleans binary token streams
/// </summary>
public class BinaryTokenStreamReader
{
private readonly IList<ArraySegment<byte>> buffers;
private readonly int buffersCount;
private int currentSegmentIndex;
private ArraySegment<byte> currentSegment;
private byte[] currentBuffer;
private int currentOffset;
private int currentSegmentOffset;
private int currentSegmentCount;
private int totalProcessedBytes;
private int currentSegmentOffsetPlusCount;
private readonly int totalLength;
private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]);
private static readonly byte[] emptyByteArray = new byte[0];
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input byte array.
/// </summary>
/// <param name="input">Input binary data to be tokenized.</param>
public BinaryTokenStreamReader(byte[] input)
: this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) })
{
}
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input buffers.
/// </summary>
/// <param name="buffs">The list of ArraySegments to use for the data.</param>
public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs)
{
buffers = buffs;
totalProcessedBytes = 0;
currentSegmentIndex = 0;
InitializeCurrentSegment(0);
totalLength = buffs.Sum(b => b.Count);
buffersCount = buffs.Count;
Trace("Starting new stream reader");
}
private void InitializeCurrentSegment(int segmentIndex)
{
currentSegment = buffers[segmentIndex];
currentBuffer = currentSegment.Array;
currentOffset = currentSegment.Offset;
currentSegmentOffset = currentOffset;
currentSegmentCount = currentSegment.Count;
currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount;
}
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input buffer.
/// </summary>
/// <param name="buff">ArraySegment to use for the data.</param>
public BinaryTokenStreamReader(ArraySegment<byte> buff)
: this(new[] { buff })
{
}
/// <summary> Current read position in the stream. </summary>
public int CurrentPosition => currentOffset + totalProcessedBytes - currentSegmentOffset;
/// <summary>
/// Creates a copy of the current stream reader.
/// </summary>
/// <returns>The new copy</returns>
public BinaryTokenStreamReader Copy()
{
return new BinaryTokenStreamReader(this.buffers);
}
private void StartNextSegment()
{
totalProcessedBytes += currentSegment.Count;
currentSegmentIndex++;
if (currentSegmentIndex < buffersCount)
{
InitializeCurrentSegment(currentSegmentIndex);
}
else
{
currentSegment = emptySegment;
currentBuffer = null;
currentOffset = 0;
currentSegmentOffset = 0;
currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount;
}
}
private byte[] CheckLength(int n, out int offset)
{
bool ignore;
byte[] res;
if (TryCheckLengthFast(n, out res, out offset, out ignore))
{
return res;
}
return CheckLength(n, out offset, out ignore);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool TryCheckLengthFast(int n, out byte[] res, out int offset, out bool safeToUse)
{
safeToUse = false;
res = null;
offset = 0;
var nextOffset = currentOffset + n;
if (nextOffset <= currentSegmentOffsetPlusCount)
{
offset = currentOffset;
currentOffset = nextOffset;
res = currentBuffer;
return true;
}
return false;
}
private byte[] CheckLength(int n, out int offset, out bool safeToUse)
{
safeToUse = false;
offset = 0;
if (currentOffset == currentSegmentOffsetPlusCount)
{
StartNextSegment();
}
byte[] res;
if (TryCheckLengthFast(n, out res, out offset, out safeToUse))
{
return res;
}
if ((CurrentPosition + n > totalLength))
{
throw new SerializationException(
String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}",
CurrentPosition, n, totalLength));
}
var temp = new byte[n];
var i = 0;
while (i < n)
{
var segmentOffsetPlusCount = currentSegmentOffsetPlusCount;
var bytesFromThisBuffer = Math.Min(segmentOffsetPlusCount - currentOffset, n - i);
Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer);
i += bytesFromThisBuffer;
currentOffset += bytesFromThisBuffer;
if (currentOffset >= segmentOffsetPlusCount)
{
if (currentSegmentIndex >= buffersCount)
{
throw new SerializationException(
String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count));
}
StartNextSegment();
}
}
safeToUse = true;
offset = 0;
return temp;
}
/// <summary> Read an <c>Int32</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public int ReadInt()
{
int offset;
var buff = CheckLength(sizeof(int), out offset);
var val = BitConverter.ToInt32(buff, offset);
Trace("--Read int {0}", val);
return val;
}
/// <summary> Read an <c>UInt32</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public uint ReadUInt()
{
int offset;
var buff = CheckLength(sizeof(uint), out offset);
var val = BitConverter.ToUInt32(buff, offset);
Trace("--Read uint {0}", val);
return val;
}
/// <summary> Read an <c>Int16</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public short ReadShort()
{
int offset;
var buff = CheckLength(sizeof(short), out offset);
var val = BitConverter.ToInt16(buff, offset);
Trace("--Read short {0}", val);
return val;
}
/// <summary> Read an <c>UInt16</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public ushort ReadUShort()
{
int offset;
var buff = CheckLength(sizeof(ushort), out offset);
var val = BitConverter.ToUInt16(buff, offset);
Trace("--Read ushort {0}", val);
return val;
}
/// <summary> Read an <c>Int64</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public long ReadLong()
{
int offset;
var buff = CheckLength(sizeof(long), out offset);
var val = BitConverter.ToInt64(buff, offset);
Trace("--Read long {0}", val);
return val;
}
/// <summary> Read an <c>UInt64</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public ulong ReadULong()
{
int offset;
var buff = CheckLength(sizeof(ulong), out offset);
var val = BitConverter.ToUInt64(buff, offset);
Trace("--Read ulong {0}", val);
return val;
}
/// <summary> Read an <c>float</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public float ReadFloat()
{
int offset;
var buff = CheckLength(sizeof(float), out offset);
var val = BitConverter.ToSingle(buff, offset);
Trace("--Read float {0}", val);
return val;
}
/// <summary> Read an <c>double</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public double ReadDouble()
{
int offset;
var buff = CheckLength(sizeof(double), out offset);
var val = BitConverter.ToDouble(buff, offset);
Trace("--Read double {0}", val);
return val;
}
/// <summary> Read an <c>decimal</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public decimal ReadDecimal()
{
int offset;
var buff = CheckLength(4 * sizeof(int), out offset);
var raw = new int[4];
Trace("--Read decimal");
var n = offset;
for (var i = 0; i < 4; i++)
{
raw[i] = BitConverter.ToInt32(buff, n);
n += sizeof(int);
}
return new decimal(raw);
}
public DateTime ReadDateTime()
{
var n = ReadLong();
return n == 0 ? default(DateTime) : DateTime.FromBinary(n);
}
/// <summary> Read an <c>string</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public string ReadString()
{
var n = ReadInt();
if (n == 0)
{
Trace("--Read empty string");
return String.Empty;
}
string s = null;
// a length of -1 indicates that the string is null.
if (-1 != n)
{
int offset;
var buff = CheckLength(n, out offset);
s = Encoding.UTF8.GetString(buff, offset, n);
}
Trace("--Read string '{0}'", s);
return s;
}
/// <summary> Read the next bytes from the stream. </summary>
/// <param name="count">Number of bytes to read.</param>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public byte[] ReadBytes(int count)
{
if (count == 0)
{
return emptyByteArray;
}
bool safeToUse;
int offset;
byte[] buff;
if (!TryCheckLengthFast(count, out buff, out offset, out safeToUse))
{
buff = CheckLength(count, out offset, out safeToUse);
}
Trace("--Read byte array of length {0}", count);
if (!safeToUse)
{
var result = new byte[count];
Array.Copy(buff, offset, result, 0, count);
return result;
}
else
{
return buff;
}
}
/// <summary> Read the next bytes from the stream. </summary>
/// <param name="destination">Output array to store the returned data in.</param>
/// <param name="offset">Offset into the destination array to write to.</param>
/// <param name="count">Number of bytes to read.</param>
public void ReadByteArray(byte[] destination, int offset, int count)
{
if (offset + count > destination.Length)
{
throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small");
}
var buffOffset = 0;
var buff = count == 0 ? emptyByteArray : CheckLength(count, out buffOffset);
Buffer.BlockCopy(buff, buffOffset, destination, offset, count);
}
/// <summary> Read an <c>char</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public char ReadChar()
{
Trace("--Read char");
return Convert.ToChar(ReadShort());
}
/// <summary> Read an <c>byte</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public byte ReadByte()
{
int offset;
var buff = CheckLength(1, out offset);
Trace("--Read byte");
return buff[offset];
}
/// <summary> Read an <c>sbyte</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public sbyte ReadSByte()
{
int offset;
var buff = CheckLength(1, out offset);
Trace("--Read sbyte");
return unchecked((sbyte)(buff[offset]));
}
/// <summary> Read an <c>IPAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public IPAddress ReadIPAddress()
{
int offset;
var buff = CheckLength(16, out offset);
bool v4 = true;
for (var i = 0; i < 12; i++)
{
if (buff[offset + i] != 0)
{
v4 = false;
break;
}
}
if (v4)
{
var v4Bytes = new byte[4];
for (var i = 0; i < 4; i++)
{
v4Bytes[i] = buff[offset + 12 + i];
}
return new IPAddress(v4Bytes);
}
else
{
var v6Bytes = new byte[16];
for (var i = 0; i < 16; i++)
{
v6Bytes[i] = buff[offset + i];
}
return new IPAddress(v6Bytes);
}
}
/// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public IPEndPoint ReadIPEndPoint()
{
var addr = ReadIPAddress();
var port = ReadInt();
return new IPEndPoint(addr, port);
}
/// <summary> Read an <c>SiloAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public SiloAddress ReadSiloAddress()
{
var ep = ReadIPEndPoint();
var gen = ReadInt();
return SiloAddress.New(ep, gen);
}
/// <summary> Read an <c>GrainId</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal GrainId ReadGrainId()
{
UniqueKey key = ReadUniqueKey();
return GrainId.GetGrainId(key);
}
/// <summary> Read an <c>ActivationId</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal ActivationId ReadActivationId()
{
UniqueKey key = ReadUniqueKey();
return ActivationId.GetActivationId(key);
}
internal UniqueKey ReadUniqueKey()
{
ulong n0 = ReadULong();
ulong n1 = ReadULong();
ulong typeCodeData = ReadULong();
string keyExt = ReadString();
return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt);
}
internal Guid ReadGuid()
{
byte[] bytes = ReadBytes(16);
return new Guid(bytes);
}
internal GrainDirectoryEntryStatus ReadMultiClusterStatus()
{
byte val = ReadByte();
return (GrainDirectoryEntryStatus)val;
}
/// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal ActivationAddress ReadActivationAddress()
{
var silo = ReadSiloAddress();
var grain = ReadGrainId();
var act = ReadActivationId();
if (silo.Equals(SiloAddress.Zero))
silo = null;
if (act.Equals(ActivationId.Zero))
act = null;
return ActivationAddress.GetAddress(silo, grain, act);
}
/// <summary>
/// Read a block of data into the specified output <c>Array</c>.
/// </summary>
/// <param name="array">Array to output the data to.</param>
/// <param name="n">Number of bytes to read.</param>
public void ReadBlockInto(Array array, int n)
{
int offset;
var buff = CheckLength(n, out offset);
Buffer.BlockCopy(buff, offset, array, 0, n);
Trace("--Read block of {0} bytes", n);
}
/// <summary>
/// Peek at the next token in this input stream.
/// </summary>
/// <returns>Next token thatr will be read from the stream.</returns>
internal SerializationTokenType PeekToken()
{
if (currentOffset == currentSegment.Count + currentSegment.Offset)
StartNextSegment();
return (SerializationTokenType)currentBuffer[currentOffset];
}
/// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal SerializationTokenType ReadToken()
{
int offset;
var buff = CheckLength(1, out offset);
Trace("--Read token {0}", (SerializationTokenType)buff[offset]);
return (SerializationTokenType)buff[offset];
}
internal bool TryReadSimpleType(out object result, out SerializationTokenType token)
{
token = ReadToken();
byte[] bytes;
switch (token)
{
case SerializationTokenType.True:
result = true;
break;
case SerializationTokenType.False:
result = false;
break;
case SerializationTokenType.Null:
result = null;
break;
case SerializationTokenType.Object:
result = new object();
break;
case SerializationTokenType.Int:
result = ReadInt();
break;
case SerializationTokenType.Uint:
result = ReadUInt();
break;
case SerializationTokenType.Short:
result = ReadShort();
break;
case SerializationTokenType.Ushort:
result = ReadUShort();
break;
case SerializationTokenType.Long:
result = ReadLong();
break;
case SerializationTokenType.Ulong:
result = ReadULong();
break;
case SerializationTokenType.Byte:
result = ReadByte();
break;
case SerializationTokenType.Sbyte:
result = ReadSByte();
break;
case SerializationTokenType.Float:
result = ReadFloat();
break;
case SerializationTokenType.Double:
result = ReadDouble();
break;
case SerializationTokenType.Decimal:
result = ReadDecimal();
break;
case SerializationTokenType.String:
result = ReadString();
break;
case SerializationTokenType.Character:
result = ReadChar();
break;
case SerializationTokenType.Guid:
bytes = ReadBytes(16);
result = new Guid(bytes);
break;
case SerializationTokenType.Date:
result = DateTime.FromBinary(ReadLong());
break;
case SerializationTokenType.TimeSpan:
result = new TimeSpan(ReadLong());
break;
case SerializationTokenType.GrainId:
result = ReadGrainId();
break;
case SerializationTokenType.ActivationId:
result = ReadActivationId();
break;
case SerializationTokenType.SiloAddress:
result = ReadSiloAddress();
break;
case SerializationTokenType.ActivationAddress:
result = ReadActivationAddress();
break;
case SerializationTokenType.IpAddress:
result = ReadIPAddress();
break;
case SerializationTokenType.IpEndPoint:
result = ReadIPEndPoint();
break;
case SerializationTokenType.CorrelationId:
result = new CorrelationId(ReadBytes(CorrelationId.SIZE_BYTES));
break;
default:
result = null;
return false;
}
return true;
}
/// <summary> Read a <c>Type</c> value from the stream. </summary>
/// <param name="expected">Expected Type, if known.</param>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public Type ReadFullTypeHeader(Type expected = null)
{
var token = ReadToken();
if (token == SerializationTokenType.ExpectedType)
{
return expected;
}
var t = CheckSpecialTypeCode(token);
if (t != null)
{
return t;
}
if (token == SerializationTokenType.SpecifiedType)
{
#if TRACE_SERIALIZATION
var tt = ReadSpecifiedTypeHeader();
Trace("--Read specified type header for type {0}", tt);
return tt;
#else
return ReadSpecifiedTypeHeader();
#endif
}
throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected");
}
internal static Type CheckSpecialTypeCode(SerializationTokenType token)
{
switch (token)
{
case SerializationTokenType.Boolean:
return typeof(bool);
case SerializationTokenType.Int:
return typeof(int);
case SerializationTokenType.Short:
return typeof(short);
case SerializationTokenType.Long:
return typeof(long);
case SerializationTokenType.Sbyte:
return typeof(sbyte);
case SerializationTokenType.Uint:
return typeof(uint);
case SerializationTokenType.Ushort:
return typeof(ushort);
case SerializationTokenType.Ulong:
return typeof(ulong);
case SerializationTokenType.Byte:
return typeof(byte);
case SerializationTokenType.Float:
return typeof(float);
case SerializationTokenType.Double:
return typeof(double);
case SerializationTokenType.Decimal:
return typeof(decimal);
case SerializationTokenType.String:
return typeof(string);
case SerializationTokenType.Character:
return typeof(char);
case SerializationTokenType.Guid:
return typeof(Guid);
case SerializationTokenType.Date:
return typeof(DateTime);
case SerializationTokenType.TimeSpan:
return typeof(TimeSpan);
case SerializationTokenType.IpAddress:
return typeof(IPAddress);
case SerializationTokenType.IpEndPoint:
return typeof(IPEndPoint);
case SerializationTokenType.GrainId:
return typeof(GrainId);
case SerializationTokenType.ActivationId:
return typeof(ActivationId);
case SerializationTokenType.SiloAddress:
return typeof(SiloAddress);
case SerializationTokenType.ActivationAddress:
return typeof(ActivationAddress);
case SerializationTokenType.CorrelationId:
return typeof(CorrelationId);
#if false // Note: not yet implemented as simple types on the Writer side
case SerializationTokenType.Object:
return typeof(Object);
case SerializationTokenType.ByteArray:
return typeof(byte[]);
case SerializationTokenType.ShortArray:
return typeof(short[]);
case SerializationTokenType.IntArray:
return typeof(int[]);
case SerializationTokenType.LongArray:
return typeof(long[]);
case SerializationTokenType.UShortArray:
return typeof(ushort[]);
case SerializationTokenType.UIntArray:
return typeof(uint[]);
case SerializationTokenType.ULongArray:
return typeof(ulong[]);
case SerializationTokenType.FloatArray:
return typeof(float[]);
case SerializationTokenType.DoubleArray:
return typeof(double[]);
case SerializationTokenType.CharArray:
return typeof(char[]);
case SerializationTokenType.BoolArray:
return typeof(bool[]);
#endif
default:
break;
}
return null;
}
/// <summary> Read a <c>Type</c> value from the stream. </summary>
internal Type ReadSpecifiedTypeHeader()
{
// Assumes that the SpecifiedType token has already been read
var token = ReadToken();
switch (token)
{
case SerializationTokenType.Boolean:
return typeof(bool);
case SerializationTokenType.Int:
return typeof(int);
case SerializationTokenType.Short:
return typeof(short);
case SerializationTokenType.Long:
return typeof(long);
case SerializationTokenType.Sbyte:
return typeof(sbyte);
case SerializationTokenType.Uint:
return typeof(uint);
case SerializationTokenType.Ushort:
return typeof(ushort);
case SerializationTokenType.Ulong:
return typeof(ulong);
case SerializationTokenType.Byte:
return typeof(byte);
case SerializationTokenType.Float:
return typeof(float);
case SerializationTokenType.Double:
return typeof(double);
case SerializationTokenType.Decimal:
return typeof(decimal);
case SerializationTokenType.String:
return typeof(string);
case SerializationTokenType.Character:
return typeof(char);
case SerializationTokenType.Guid:
return typeof(Guid);
case SerializationTokenType.Date:
return typeof(DateTime);
case SerializationTokenType.TimeSpan:
return typeof(TimeSpan);
case SerializationTokenType.IpAddress:
return typeof(IPAddress);
case SerializationTokenType.IpEndPoint:
return typeof(IPEndPoint);
case SerializationTokenType.GrainId:
return typeof(GrainId);
case SerializationTokenType.ActivationId:
return typeof(ActivationId);
case SerializationTokenType.SiloAddress:
return typeof(SiloAddress);
case SerializationTokenType.ActivationAddress:
return typeof(ActivationAddress);
case SerializationTokenType.CorrelationId:
return typeof(CorrelationId);
case SerializationTokenType.Request:
return typeof(InvokeMethodRequest);
case SerializationTokenType.Response:
return typeof(Response);
case SerializationTokenType.StringObjDict:
return typeof(Dictionary<string, object>);
case SerializationTokenType.Object:
return typeof(Object);
case SerializationTokenType.Tuple + 1:
Trace("----Reading type info for a Tuple'1");
return typeof(Tuple<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Tuple + 2:
Trace("----Reading type info for a Tuple'2");
return typeof(Tuple<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.Tuple + 3:
Trace("----Reading type info for a Tuple'3");
return typeof(Tuple<,,>).MakeGenericType(ReadGenericArguments(3));
case SerializationTokenType.Tuple + 4:
Trace("----Reading type info for a Tuple'4");
return typeof(Tuple<,,,>).MakeGenericType(ReadGenericArguments(4));
case SerializationTokenType.Tuple + 5:
Trace("----Reading type info for a Tuple'5");
return typeof(Tuple<,,,,>).MakeGenericType(ReadGenericArguments(5));
case SerializationTokenType.Tuple + 6:
Trace("----Reading type info for a Tuple'6");
return typeof(Tuple<,,,,,>).MakeGenericType(ReadGenericArguments(6));
case SerializationTokenType.Tuple + 7:
Trace("----Reading type info for a Tuple'7");
return typeof(Tuple<,,,,,,>).MakeGenericType(ReadGenericArguments(7));
case SerializationTokenType.Array + 1:
var et1 = ReadFullTypeHeader();
return et1.MakeArrayType();
case SerializationTokenType.Array + 2:
var et2 = ReadFullTypeHeader();
return et2.MakeArrayType(2);
case SerializationTokenType.Array + 3:
var et3 = ReadFullTypeHeader();
return et3.MakeArrayType(3);
case SerializationTokenType.Array + 4:
var et4 = ReadFullTypeHeader();
return et4.MakeArrayType(4);
case SerializationTokenType.Array + 5:
var et5 = ReadFullTypeHeader();
return et5.MakeArrayType(5);
case SerializationTokenType.Array + 6:
var et6 = ReadFullTypeHeader();
return et6.MakeArrayType(6);
case SerializationTokenType.Array + 7:
var et7 = ReadFullTypeHeader();
return et7.MakeArrayType(7);
case SerializationTokenType.Array + 8:
var et8 = ReadFullTypeHeader();
return et8.MakeArrayType(8);
case SerializationTokenType.List:
return typeof(List<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Dictionary:
return typeof(Dictionary<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.KeyValuePair:
return typeof(KeyValuePair<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.Set:
return typeof(HashSet<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.SortedList:
return typeof(SortedList<,>).MakeGenericType(ReadGenericArguments(2));
case SerializationTokenType.SortedSet:
return typeof(SortedSet<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Stack:
return typeof(Stack<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Queue:
return typeof(Queue<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.LinkedList:
return typeof(LinkedList<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.Nullable:
return typeof(Nullable<>).MakeGenericType(ReadGenericArguments(1));
case SerializationTokenType.ByteArray:
return typeof(byte[]);
case SerializationTokenType.ShortArray:
return typeof(short[]);
case SerializationTokenType.IntArray:
return typeof(int[]);
case SerializationTokenType.LongArray:
return typeof(long[]);
case SerializationTokenType.UShortArray:
return typeof(ushort[]);
case SerializationTokenType.UIntArray:
return typeof(uint[]);
case SerializationTokenType.ULongArray:
return typeof(ulong[]);
case SerializationTokenType.FloatArray:
return typeof(float[]);
case SerializationTokenType.DoubleArray:
return typeof(double[]);
case SerializationTokenType.CharArray:
return typeof(char[]);
case SerializationTokenType.BoolArray:
return typeof(bool[]);
case SerializationTokenType.SByteArray:
return typeof(sbyte[]);
case SerializationTokenType.NamedType:
var typeName = ReadString();
try
{
return SerializationManager.ResolveTypeName(typeName);
}
catch (TypeAccessException ex)
{
throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message);
}
default:
break;
}
throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference");
}
private Type[] ReadGenericArguments(int n)
{
Trace("About to read {0} generic arguments", n);
var args = new Type[n];
for (var i = 0; i < n; i++)
{
args[i] = ReadFullTypeHeader();
}
Trace("Finished reading {0} generic arguments", n);
return args;
}
private StreamWriter trace;
[Conditional("TRACE_SERIALIZATION")]
private void Trace(string format, params object[] args)
{
if (trace == null)
{
var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks);
Console.WriteLine("Opening trace file at '{0}'", path);
trace = File.CreateText(path);
}
trace.Write(format, args);
trace.WriteLine(" at offset {0}", CurrentPosition);
trace.Flush();
}
}
}
| |
//
// PlayerEngine.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2005-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Runtime.InteropServices;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Preferences;
namespace Banshee.GStreamer
{
internal enum GstState
{
VoidPending = 0,
Null = 1,
Ready = 2,
Paused = 3,
Playing = 4
}
internal delegate void BansheePlayerEosCallback (IntPtr player);
internal delegate void BansheePlayerErrorCallback (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug);
internal delegate void BansheePlayerStateChangedCallback (IntPtr player, GstState old_state, GstState new_state, GstState pending_state);
internal delegate void BansheePlayerIterateCallback (IntPtr player);
internal delegate void BansheePlayerBufferingCallback (IntPtr player, int buffering_progress);
internal delegate void BansheePlayerVisDataCallback (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum);
internal delegate IntPtr VideoPipelineSetupHandler (IntPtr player, IntPtr bus);
internal delegate void GstTaggerTagFoundCallback (IntPtr player, string tagName, ref GLib.Value value);
public class PlayerEngine : Banshee.MediaEngine.PlayerEngine,
IEqualizer, IVisualizationDataSource, ISupportClutter
{
private uint GST_CORE_ERROR = 0;
private uint GST_LIBRARY_ERROR = 0;
private uint GST_RESOURCE_ERROR = 0;
private uint GST_STREAM_ERROR = 0;
private HandleRef handle;
private BansheePlayerEosCallback eos_callback;
private BansheePlayerErrorCallback error_callback;
private BansheePlayerStateChangedCallback state_changed_callback;
private BansheePlayerIterateCallback iterate_callback;
private BansheePlayerBufferingCallback buffering_callback;
private BansheePlayerVisDataCallback vis_data_callback;
private VideoPipelineSetupHandler video_pipeline_setup_callback;
private GstTaggerTagFoundCallback tag_found_callback;
private bool buffering_finished;
private int pending_volume = -1;
private bool xid_is_set = false;
private event VisualizationDataHandler data_available = null;
public event VisualizationDataHandler DataAvailable {
add {
if (value == null) {
return;
} else if (data_available == null) {
bp_set_vis_data_callback (handle, vis_data_callback);
}
data_available += value;
}
remove {
if (value == null) {
return;
}
data_available -= value;
if (data_available == null) {
bp_set_vis_data_callback (handle, null);
}
}
}
protected override bool DelayedInitialize {
get { return true; }
}
public PlayerEngine ()
{
IntPtr ptr = bp_new ();
if (ptr == IntPtr.Zero) {
throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library"));
}
handle = new HandleRef (this, ptr);
bp_get_error_quarks (out GST_CORE_ERROR, out GST_LIBRARY_ERROR,
out GST_RESOURCE_ERROR, out GST_STREAM_ERROR);
eos_callback = new BansheePlayerEosCallback (OnEos);
error_callback = new BansheePlayerErrorCallback (OnError);
state_changed_callback = new BansheePlayerStateChangedCallback (OnStateChange);
iterate_callback = new BansheePlayerIterateCallback (OnIterate);
buffering_callback = new BansheePlayerBufferingCallback (OnBuffering);
vis_data_callback = new BansheePlayerVisDataCallback (OnVisualizationData);
video_pipeline_setup_callback = new VideoPipelineSetupHandler (OnVideoPipelineSetup);
tag_found_callback = new GstTaggerTagFoundCallback (OnTagFound);
bp_set_eos_callback (handle, eos_callback);
bp_set_iterate_callback (handle, iterate_callback);
bp_set_error_callback (handle, error_callback);
bp_set_state_changed_callback (handle, state_changed_callback);
bp_set_buffering_callback (handle, buffering_callback);
bp_set_tag_found_callback (handle, tag_found_callback);
bp_set_video_pipeline_setup_callback (handle, video_pipeline_setup_callback);
}
protected override void Initialize ()
{
if (!bp_initialize_pipeline (handle)) {
bp_destroy (handle);
handle = new HandleRef (this, IntPtr.Zero);
throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library"));
}
OnStateChanged (PlayerState.Ready);
if (pending_volume >= 0) {
Volume = (ushort)pending_volume;
}
InstallPreferences ();
ReplayGainEnabled = ReplayGainEnabledSchema.Get ();
}
public override void Dispose ()
{
UninstallPreferences ();
base.Dispose ();
bp_destroy (handle);
handle = new HandleRef (this, IntPtr.Zero);
}
public override void Close (bool fullShutdown)
{
bp_stop (handle, fullShutdown);
base.Close (fullShutdown);
}
protected override void OpenUri (SafeUri uri)
{
// The GStreamer engine can use the XID of the main window if it ever
// needs to bring up the plugin installer so it can be transient to
// the main window.
if (!xid_is_set) {
IPropertyStoreExpose service = ServiceManager.Get<IService> ("GtkElementsService") as IPropertyStoreExpose;
if (service != null) {
bp_set_application_gdk_window (handle, service.PropertyStore.Get<IntPtr> ("PrimaryWindow.RawHandle"));
}
xid_is_set = true;
}
IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri);
try {
if (!bp_open (handle, uri_ptr)) {
throw new ApplicationException ("Could not open resource");
}
} finally {
GLib.Marshaller.Free (uri_ptr);
}
}
public override void Play ()
{
bp_play (handle);
}
public override void Pause ()
{
bp_pause (handle);
}
public override void VideoExpose (IntPtr window, bool direct)
{
bp_video_window_expose (handle, window, direct);
}
public override IntPtr [] GetBaseElements ()
{
IntPtr [] elements = new IntPtr[3];
if (bp_get_pipeline_elements (handle, out elements[0], out elements[1], out elements[2])) {
return elements;
}
return null;
}
private void OnEos (IntPtr player)
{
Close (false);
OnEventChanged (PlayerEvent.EndOfStream);
}
private void OnIterate (IntPtr player)
{
OnEventChanged (PlayerEvent.Iterate);
}
private void OnStateChange (IntPtr player, GstState old_state, GstState new_state, GstState pending_state)
{
if (old_state == GstState.Ready && new_state == GstState.Paused && pending_state == GstState.Playing) {
OnStateChanged (PlayerState.Loaded);
return;
} else if (old_state == GstState.Paused && new_state == GstState.Playing && pending_state == GstState.VoidPending) {
if (CurrentState == PlayerState.Loaded) {
OnEventChanged (PlayerEvent.StartOfStream);
}
OnStateChanged (PlayerState.Playing);
return;
} else if (CurrentState == PlayerState.Playing && old_state == GstState.Playing && new_state == GstState.Paused) {
OnStateChanged (PlayerState.Paused);
return;
}
}
private void OnError (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug)
{
Close (true);
string error_message = error == IntPtr.Zero
? Catalog.GetString ("Unknown Error")
: GLib.Marshaller.Utf8PtrToString (error);
if (domain == GST_RESOURCE_ERROR) {
GstResourceError domain_code = (GstResourceError) code;
if (CurrentTrack != null) {
switch (domain_code) {
case GstResourceError.NotFound:
CurrentTrack.SavePlaybackError (StreamPlaybackError.ResourceNotFound);
break;
default:
break;
}
}
Log.Error (String.Format ("GStreamer resource error: {0}", domain_code), false);
} else if (domain == GST_STREAM_ERROR) {
GstStreamError domain_code = (GstStreamError) code;
if (CurrentTrack != null) {
switch (domain_code) {
case GstStreamError.CodecNotFound:
CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound);
break;
default:
break;
}
}
Log.Error (String.Format("GStreamer stream error: {0}", domain_code), false);
} else if (domain == GST_CORE_ERROR) {
GstCoreError domain_code = (GstCoreError) code;
if (CurrentTrack != null) {
switch (domain_code) {
case GstCoreError.MissingPlugin:
CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound);
break;
default:
break;
}
}
if (domain_code != GstCoreError.MissingPlugin) {
Log.Error (String.Format("GStreamer core error: {0}", (GstCoreError) code), false);
}
} else if (domain == GST_LIBRARY_ERROR) {
Log.Error (String.Format("GStreamer library error: {0}", (GstLibraryError) code), false);
}
OnEventChanged (new PlayerEventErrorArgs (error_message));
}
private void OnBuffering (IntPtr player, int progress)
{
if (buffering_finished && progress >= 100) {
return;
}
buffering_finished = progress >= 100;
OnEventChanged (new PlayerEventBufferingArgs ((double) progress / 100.0));
}
private void OnTagFound (IntPtr player, string tagName, ref GLib.Value value)
{
OnTagFound (ProcessNativeTagResult (tagName, ref value));
}
private void OnVisualizationData (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum)
{
VisualizationDataHandler handler = data_available;
if (handler == null) {
return;
}
float [] flat = new float[channels * samples];
Marshal.Copy (data, flat, 0, flat.Length);
float [][] cbd = new float[channels][];
for (int i = 0; i < channels; i++) {
float [] channel = new float[samples];
Array.Copy (flat, i * samples, channel, 0, samples);
cbd[i] = channel;
}
float [] spec = new float[bands];
Marshal.Copy (spectrum, spec, 0, bands);
try {
handler (cbd, new float[][] { spec });
} catch (Exception e) {
Log.Exception ("Uncaught exception during visualization data post.", e);
}
}
private static StreamTag ProcessNativeTagResult (string tagName, ref GLib.Value valueRaw)
{
if (tagName == String.Empty || tagName == null) {
return StreamTag.Zero;
}
object value = null;
try {
value = valueRaw.Val;
} catch {
return StreamTag.Zero;
}
if (value == null) {
return StreamTag.Zero;
}
StreamTag item;
item.Name = tagName;
item.Value = value;
return item;
}
public override ushort Volume {
get { return (ushort)Math.Round (bp_get_volume (handle) * 100.0); }
set {
if ((IntPtr)handle == IntPtr.Zero) {
pending_volume = value;
return;
}
bp_set_volume (handle, value / 100.0);
OnEventChanged (PlayerEvent.Volume);
}
}
public override uint Position {
get { return (uint)bp_get_position(handle); }
set {
bp_set_position (handle, (ulong)value);
OnEventChanged (PlayerEvent.Seek);
}
}
public override bool CanSeek {
get { return bp_can_seek (handle); }
}
public override uint Length {
get { return (uint)bp_get_duration (handle); }
}
public override string Id {
get { return "gstreamer"; }
}
public override string Name {
get { return "GStreamer 0.10"; }
}
private bool? supports_equalizer = null;
public override bool SupportsEqualizer {
get {
if (supports_equalizer == null) {
supports_equalizer = bp_equalizer_is_supported (handle);
}
return supports_equalizer.Value;
}
}
public override VideoDisplayContextType VideoDisplayContextType {
get { return bp_video_get_display_context_type (handle); }
}
public override IntPtr VideoDisplayContext {
set { bp_video_set_display_context (handle, value); }
get { return bp_video_get_display_context (handle); }
}
public double AmplifierLevel {
set {
double scale = Math.Pow (10.0, value / 20.0);
bp_equalizer_set_preamp_level (handle, scale);
}
}
public int [] BandRange {
get {
int min = -1;
int max = -1;
bp_equalizer_get_bandrange (handle, out min, out max);
return new int [] { min, max };
}
}
public uint [] EqualizerFrequencies {
get {
uint count = bp_equalizer_get_nbands (handle);
double [] freq = new double[count];
bp_equalizer_get_frequencies (handle, out freq);
uint [] ret = new uint[count];
for (int i = 0; i < count; i++) {
ret[i] = (uint)freq[i];
}
return ret;
}
}
public void SetEqualizerGain (uint band, double gain)
{
bp_equalizer_set_gain (handle, band, gain);
}
private static string [] source_capabilities = { "file", "http", "cdda" };
public override IEnumerable SourceCapabilities {
get { return source_capabilities; }
}
private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac" };
public override IEnumerable ExplicitDecoderCapabilities {
get { return decoder_capabilities; }
}
private bool ReplayGainEnabled {
get { return bp_replaygain_get_enabled (handle); }
set { bp_replaygain_set_enabled (handle, value); }
}
#region ISupportClutter
private IntPtr clutter_video_sink;
private IntPtr clutter_video_texture;
private bool clutter_video_sink_enabled;
public void EnableClutterVideoSink (IntPtr videoTexture)
{
clutter_video_sink_enabled = true;
clutter_video_texture = videoTexture;
}
public void DisableClutterVideoSink ()
{
clutter_video_sink_enabled = false;
clutter_video_texture = IntPtr.Zero;
}
public bool IsClutterVideoSinkInitialized {
get { return
clutter_video_sink_enabled &&
clutter_video_texture != IntPtr.Zero &&
clutter_video_sink != IntPtr.Zero;
}
}
private IntPtr OnVideoPipelineSetup (IntPtr player, IntPtr bus)
{
try {
if (clutter_video_sink_enabled) {
if (clutter_video_sink != IntPtr.Zero) {
// FIXME: does this get unreffed by the pipeline?
}
clutter_video_sink = clutter_gst_video_sink_new (clutter_video_texture);
} else if (!clutter_video_sink_enabled && clutter_video_sink != IntPtr.Zero) {
clutter_video_sink = IntPtr.Zero;
clutter_video_texture = IntPtr.Zero;
}
} catch (Exception e) {
Log.Exception ("Clutter support could not be initialized", e);
clutter_video_sink = IntPtr.Zero;
clutter_video_texture = IntPtr.Zero;
clutter_video_sink_enabled = false;
}
return clutter_video_sink;
}
#endregion
#region Preferences
private PreferenceBase replaygain_preference;
private void InstallPreferences ()
{
PreferenceService service = ServiceManager.Get<PreferenceService> ();
if (service == null) {
return;
}
replaygain_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (ReplayGainEnabledSchema,
Catalog.GetString ("_Enable ReplayGain correction"),
Catalog.GetString ("For tracks that have ReplayGain data, automatically scale (normalize) playback volume"),
delegate { ReplayGainEnabled = ReplayGainEnabledSchema.Get (); }
));
}
private void UninstallPreferences ()
{
PreferenceService service = ServiceManager.Get<PreferenceService> ();
if (service == null) {
return;
}
service["general"]["misc"].Remove (replaygain_preference);
replaygain_preference = null;
}
public static readonly SchemaEntry<bool> ReplayGainEnabledSchema = new SchemaEntry<bool> (
"player_engine", "replay_gain_enabled",
false,
"Enable ReplayGain",
"If ReplayGain data is present on tracks when playing, allow volume scaling"
);
#endregion
[DllImport ("libbanshee.dll")]
private static extern IntPtr bp_new ();
[DllImport ("libbanshee.dll")]
private static extern bool bp_initialize_pipeline (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_destroy (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_eos_callback (HandleRef player, BansheePlayerEosCallback cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_error_callback (HandleRef player, BansheePlayerErrorCallback cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_vis_data_callback (HandleRef player, BansheePlayerVisDataCallback cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_state_changed_callback (HandleRef player,
BansheePlayerStateChangedCallback cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_iterate_callback (HandleRef player,
BansheePlayerIterateCallback cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_buffering_callback (HandleRef player,
BansheePlayerBufferingCallback cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_video_pipeline_setup_callback (HandleRef player,
VideoPipelineSetupHandler cb);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_tag_found_callback (HandleRef player,
GstTaggerTagFoundCallback cb);
[DllImport ("libbanshee.dll")]
private static extern bool bp_open (HandleRef player, IntPtr uri);
[DllImport ("libbanshee.dll")]
private static extern void bp_stop (HandleRef player, bool nullstate);
[DllImport ("libbanshee.dll")]
private static extern void bp_pause (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_play (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_volume (HandleRef player, double volume);
[DllImport("libbanshee.dll")]
private static extern double bp_get_volume (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern bool bp_can_seek (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern bool bp_set_position (HandleRef player, ulong time_ms);
[DllImport ("libbanshee.dll")]
private static extern ulong bp_get_position (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern ulong bp_get_duration (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern bool bp_get_pipeline_elements (HandleRef player, out IntPtr playbin,
out IntPtr audiobin, out IntPtr audiotee);
[DllImport ("libbanshee.dll")]
private static extern void bp_set_application_gdk_window (HandleRef player, IntPtr window);
[DllImport ("libbanshee.dll")]
private static extern VideoDisplayContextType bp_video_get_display_context_type (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_video_set_display_context (HandleRef player, IntPtr displayContext);
[DllImport ("libbanshee.dll")]
private static extern IntPtr bp_video_get_display_context (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_video_window_expose (HandleRef player, IntPtr displayContext, bool direct);
[DllImport ("libbanshee.dll")]
private static extern void bp_get_error_quarks (out uint core, out uint library,
out uint resource, out uint stream);
[DllImport ("libbanshee.dll")]
private static extern bool bp_equalizer_is_supported (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_equalizer_set_preamp_level (HandleRef player, double level);
[DllImport ("libbanshee.dll")]
private static extern void bp_equalizer_set_gain (HandleRef player, uint bandnum, double gain);
[DllImport ("libbanshee.dll")]
private static extern void bp_equalizer_get_bandrange (HandleRef player, out int min, out int max);
[DllImport ("libbanshee.dll")]
private static extern uint bp_equalizer_get_nbands (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern void bp_equalizer_get_frequencies (HandleRef player,
[MarshalAs (UnmanagedType.LPArray)] out double [] freq);
[DllImport ("libbanshee.dll")]
private static extern void bp_replaygain_set_enabled (HandleRef player, bool enabled);
[DllImport ("libbanshee.dll")]
private static extern bool bp_replaygain_get_enabled (HandleRef player);
[DllImport ("libbanshee.dll")]
private static extern IntPtr clutter_gst_video_sink_new (IntPtr texture);
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects
{
public unsafe class SimObject
{
public SimObject()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.SimObjectCreateInstance());
}
public SimObject(uint pId)
{
ObjectPtr = Sim.FindObjectWrapperById(pId);
}
public SimObject(string pName)
{
ObjectPtr = Sim.FindObjectWrapperByName(pName);
}
public SimObject(IntPtr pObjPtr)
{
ObjectPtr = Sim.WrapObject(pObjPtr);
}
public SimObject(Sim.SimObjectPtr* pObjPtr)
{
ObjectPtr = pObjPtr;
}
public SimObject(SimObject pObj)
{
ObjectPtr = pObj.ObjectPtr;
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectGetCanSaveDynamicFields(IntPtr obj);
private static _SimObjectGetCanSaveDynamicFields _SimObjectGetCanSaveDynamicFieldsFunc;
internal static bool SimObjectGetCanSaveDynamicFields(IntPtr obj)
{
if (_SimObjectGetCanSaveDynamicFieldsFunc == null)
{
_SimObjectGetCanSaveDynamicFieldsFunc =
(_SimObjectGetCanSaveDynamicFields)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetCanSaveDynamicFields"), typeof(_SimObjectGetCanSaveDynamicFields));
}
return _SimObjectGetCanSaveDynamicFieldsFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetCanSaveDynamicFields(IntPtr obj, bool val);
private static _SimObjectSetCanSaveDynamicFields _SimObjectSetCanSaveDynamicFieldsFunc;
internal static void SimObjectSetCanSaveDynamicFields(IntPtr obj, bool val)
{
if (_SimObjectSetCanSaveDynamicFieldsFunc == null)
{
_SimObjectSetCanSaveDynamicFieldsFunc =
(_SimObjectSetCanSaveDynamicFields)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetCanSaveDynamicFields"), typeof(_SimObjectSetCanSaveDynamicFields));
}
_SimObjectSetCanSaveDynamicFieldsFunc(obj, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetInternalName(IntPtr obj);
private static _SimObjectGetInternalName _SimObjectGetInternalNameFunc;
internal static IntPtr SimObjectGetInternalName(IntPtr obj)
{
if (_SimObjectGetInternalNameFunc == null)
{
_SimObjectGetInternalNameFunc =
(_SimObjectGetInternalName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetInternalName"), typeof(_SimObjectGetInternalName));
}
return _SimObjectGetInternalNameFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetInternalName(IntPtr obj, string val);
private static _SimObjectSetInternalName _SimObjectSetInternalNameFunc;
internal static void SimObjectSetInternalName(IntPtr obj, string val)
{
if (_SimObjectSetInternalNameFunc == null)
{
_SimObjectSetInternalNameFunc =
(_SimObjectSetInternalName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetInternalName"), typeof(_SimObjectSetInternalName));
}
_SimObjectSetInternalNameFunc(obj, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetParentGroup(IntPtr obj);
private static _SimObjectGetParentGroup _SimObjectGetParentGroupFunc;
internal static IntPtr SimObjectGetParentGroup(IntPtr obj)
{
if (_SimObjectGetParentGroupFunc == null)
{
_SimObjectGetParentGroupFunc =
(_SimObjectGetParentGroup)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetParentGroup"), typeof(_SimObjectGetParentGroup));
}
return _SimObjectGetParentGroupFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetParentGroup(IntPtr obj, IntPtr parent);
private static _SimObjectSetParentGroup _SimObjectSetParentGroupFunc;
internal static void SimObjectSetParentGroup(IntPtr obj, IntPtr parent)
{
if (_SimObjectSetParentGroupFunc == null)
{
_SimObjectSetParentGroupFunc =
(_SimObjectSetParentGroup)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetParentGroup"), typeof(_SimObjectSetParentGroup));
}
_SimObjectSetParentGroupFunc(obj, parent);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetSuperClass(IntPtr obj);
private static _SimObjectGetSuperClass _SimObjectGetSuperClassFunc;
internal static IntPtr SimObjectGetSuperClass(IntPtr obj)
{
if (_SimObjectGetSuperClassFunc == null)
{
_SimObjectGetSuperClassFunc =
(_SimObjectGetSuperClass)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetSuperClass"), typeof(_SimObjectGetSuperClass));
}
return _SimObjectGetSuperClassFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetSuperClass(IntPtr obj, string val);
private static _SimObjectSetSuperClass _SimObjectSetSuperClassFunc;
internal static void SimObjectSetSuperClass(IntPtr obj, string val)
{
if (_SimObjectSetSuperClassFunc == null)
{
_SimObjectSetSuperClassFunc =
(_SimObjectSetSuperClass)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetSuperClass"), typeof(_SimObjectSetSuperClass));
}
_SimObjectSetSuperClassFunc(obj, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetClass(IntPtr obj);
private static _SimObjectGetClass _SimObjectGetClassFunc;
internal static IntPtr SimObjectGetClass(IntPtr obj)
{
if (_SimObjectGetClassFunc == null)
{
_SimObjectGetClassFunc =
(_SimObjectGetClass)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetClass"), typeof(_SimObjectGetClass));
}
return _SimObjectGetClassFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetClass(IntPtr obj, string val);
private static _SimObjectSetClass _SimObjectSetClassFunc;
internal static void SimObjectSetClass(IntPtr obj, string val)
{
if (_SimObjectSetClassFunc == null)
{
_SimObjectSetClassFunc =
(_SimObjectSetClass)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetClass"), typeof(_SimObjectSetClass));
}
_SimObjectSetClassFunc(obj, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectCreateInstance();
private static _SimObjectCreateInstance _SimObjectCreateInstanceFunc;
internal static IntPtr SimObjectCreateInstance()
{
if (_SimObjectCreateInstanceFunc == null)
{
_SimObjectCreateInstanceFunc =
(_SimObjectCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectCreateInstance"), typeof(_SimObjectCreateInstance));
}
return _SimObjectCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectRegisterObject(IntPtr obj);
private static _SimObjectRegisterObject _SimObjectRegisterObjectFunc;
internal static bool SimObjectRegisterObject(IntPtr obj)
{
if (_SimObjectRegisterObjectFunc == null)
{
_SimObjectRegisterObjectFunc =
(_SimObjectRegisterObject)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectRegisterObject"), typeof(_SimObjectRegisterObject));
}
return _SimObjectRegisterObjectFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetName(IntPtr obj);
private static _SimObjectGetName _SimObjectGetNameFunc;
internal static IntPtr SimObjectGetName(IntPtr obj)
{
if (_SimObjectGetNameFunc == null)
{
_SimObjectGetNameFunc =
(_SimObjectGetName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetName"), typeof(_SimObjectGetName));
}
return _SimObjectGetNameFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetName(IntPtr obj, string val);
private static _SimObjectSetName _SimObjectSetNameFunc;
internal static void SimObjectSetName(IntPtr obj, string val)
{
if (_SimObjectSetNameFunc == null)
{
_SimObjectSetNameFunc =
(_SimObjectSetName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetName"), typeof(_SimObjectSetName));
}
_SimObjectSetNameFunc(obj, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate uint _SimObjectGetID(IntPtr obj);
private static _SimObjectGetID _SimObjectGetIDFunc;
internal static uint SimObjectGetID(IntPtr obj)
{
if (_SimObjectGetIDFunc == null)
{
_SimObjectGetIDFunc =
(_SimObjectGetID)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetID"), typeof(_SimObjectGetID));
}
return _SimObjectGetIDFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectIsMethod(IntPtr obj, string val);
private static _SimObjectIsMethod _SimObjectIsMethodFunc;
internal static bool SimObjectIsMethod(IntPtr obj, string val)
{
if (_SimObjectIsMethodFunc == null)
{
_SimObjectIsMethodFunc =
(_SimObjectIsMethod)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectIsMethod"), typeof(_SimObjectIsMethod));
}
return _SimObjectIsMethodFunc(obj, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectCall(IntPtr obj, int argc, string[] argv);
private static _SimObjectCall _SimObjectCallFunc;
internal static bool SimObjectCall(IntPtr obj, int argc, string[] argv)
{
if (_SimObjectCallFunc == null)
{
_SimObjectCallFunc =
(_SimObjectCall)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectCall"), typeof(_SimObjectCall));
}
return _SimObjectCallFunc(obj, argc, argv);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectDumpClassHierarchy(IntPtr obj);
private static _SimObjectDumpClassHierarchy _SimObjectDumpClassHierarchyFunc;
internal static void SimObjectDumpClassHierarchy(IntPtr obj)
{
if (_SimObjectDumpClassHierarchyFunc == null)
{
_SimObjectDumpClassHierarchyFunc =
(_SimObjectDumpClassHierarchy)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectDumpClassHierarchy"), typeof(_SimObjectDumpClassHierarchy));
}
_SimObjectDumpClassHierarchyFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectDump(IntPtr obj);
private static _SimObjectDump _SimObjectDumpFunc;
internal static void SimObjectDump(IntPtr obj)
{
if (_SimObjectDumpFunc == null)
{
_SimObjectDumpFunc =
(_SimObjectDump)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectDump"), typeof(_SimObjectDump));
}
_SimObjectDumpFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectIsMemberOfClass(IntPtr obj, string className);
private static _SimObjectIsMemberOfClass _SimObjectIsMemberOfClassFunc;
internal static bool SimObjectIsMemberOfClass(IntPtr obj, string className)
{
if (_SimObjectIsMemberOfClassFunc == null)
{
_SimObjectIsMemberOfClassFunc =
(_SimObjectIsMemberOfClass)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectIsMemberOfClass"), typeof(_SimObjectIsMemberOfClass));
}
return _SimObjectIsMemberOfClassFunc(obj, className);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetClassName(IntPtr obj);
private static _SimObjectGetClassName _SimObjectGetClassNameFunc;
internal static IntPtr SimObjectGetClassName(IntPtr obj)
{
if (_SimObjectGetClassNameFunc == null)
{
_SimObjectGetClassNameFunc =
(_SimObjectGetClassName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetClassName"), typeof(_SimObjectGetClassName));
}
return _SimObjectGetClassNameFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetFieldValue(IntPtr obj, string fieldName);
private static _SimObjectGetFieldValue _SimObjectGetFieldValueFunc;
internal static IntPtr SimObjectGetFieldValue(IntPtr obj, string fieldName)
{
if (_SimObjectGetFieldValueFunc == null)
{
_SimObjectGetFieldValueFunc =
(_SimObjectGetFieldValue)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetFieldValue"), typeof(_SimObjectGetFieldValue));
}
return _SimObjectGetFieldValueFunc(obj, fieldName);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetFieldValue(IntPtr obj, string fieldName, string value);
private static _SimObjectSetFieldValue _SimObjectSetFieldValueFunc;
internal static void SimObjectSetFieldValue(IntPtr obj, string fieldName, string value)
{
if (_SimObjectSetFieldValueFunc == null)
{
_SimObjectSetFieldValueFunc =
(_SimObjectSetFieldValue)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetFieldValue"), typeof(_SimObjectSetFieldValue));
}
_SimObjectSetFieldValueFunc(obj, fieldName, value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _SimObjectGetDynamicFieldCount(IntPtr obj);
private static _SimObjectGetDynamicFieldCount _SimObjectGetDynamicFieldCountFunc;
internal static int SimObjectGetDynamicFieldCount(IntPtr obj)
{
if (_SimObjectGetDynamicFieldCountFunc == null)
{
_SimObjectGetDynamicFieldCountFunc =
(_SimObjectGetDynamicFieldCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetDynamicFieldCount"), typeof(_SimObjectGetDynamicFieldCount));
}
return _SimObjectGetDynamicFieldCountFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetDynamicField(IntPtr obj, int index);
private static _SimObjectGetDynamicField _SimObjectGetDynamicFieldFunc;
internal static IntPtr SimObjectGetDynamicField(IntPtr obj, int index)
{
if (_SimObjectGetDynamicFieldFunc == null)
{
_SimObjectGetDynamicFieldFunc =
(_SimObjectGetDynamicField)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetDynamicField"), typeof(_SimObjectGetDynamicField));
}
return _SimObjectGetDynamicFieldFunc(obj, index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _SimObjectGetFieldCount(IntPtr obj);
private static _SimObjectGetFieldCount _SimObjectGetFieldCountFunc;
internal static int SimObjectGetFieldCount(IntPtr obj)
{
if (_SimObjectGetFieldCountFunc == null)
{
_SimObjectGetFieldCountFunc =
(_SimObjectGetFieldCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetFieldCount"), typeof(_SimObjectGetFieldCount));
}
return _SimObjectGetFieldCountFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetField(IntPtr obj, int index);
private static _SimObjectGetField _SimObjectGetFieldFunc;
internal static IntPtr SimObjectGetField(IntPtr obj, int index)
{
if (_SimObjectGetFieldFunc == null)
{
_SimObjectGetFieldFunc =
(_SimObjectGetField)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetField"), typeof(_SimObjectGetField));
}
return _SimObjectGetFieldFunc(obj, index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetProgenitorFile(IntPtr obj);
private static _SimObjectGetProgenitorFile _SimObjectGetProgenitorFileFunc;
internal static IntPtr SimObjectGetProgenitorFile(IntPtr obj)
{
if (_SimObjectGetProgenitorFileFunc == null)
{
_SimObjectGetProgenitorFileFunc =
(_SimObjectGetProgenitorFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetProgenitorFile"), typeof(_SimObjectGetProgenitorFile));
}
return _SimObjectGetProgenitorFileFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectSetProgenitorFile(IntPtr obj, string file);
private static _SimObjectSetProgenitorFile _SimObjectSetProgenitorFileFunc;
internal static void SimObjectSetProgenitorFile(IntPtr obj, string file)
{
if (_SimObjectSetProgenitorFileFunc == null)
{
_SimObjectSetProgenitorFileFunc =
(_SimObjectSetProgenitorFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSetProgenitorFile"), typeof(_SimObjectSetProgenitorFile));
}
_SimObjectSetProgenitorFileFunc(obj, file);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _SimObjectGetType(IntPtr obj);
private static _SimObjectGetType _SimObjectGetTypeFunc;
internal static int SimObjectGetType(IntPtr obj)
{
if (_SimObjectGetTypeFunc == null)
{
_SimObjectGetTypeFunc =
(_SimObjectGetType)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetType"), typeof(_SimObjectGetType));
}
return _SimObjectGetTypeFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetFieldType(IntPtr obj, string fieldName);
private static _SimObjectGetFieldType _SimObjectGetFieldTypeFunc;
internal static IntPtr SimObjectGetFieldType(IntPtr obj, string fieldName)
{
if (_SimObjectGetFieldTypeFunc == null)
{
_SimObjectGetFieldTypeFunc =
(_SimObjectGetFieldType)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetFieldType"), typeof(_SimObjectGetFieldType));
}
return _SimObjectGetFieldTypeFunc(obj, fieldName);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectIsChildOfGroup(IntPtr obj, IntPtr group);
private static _SimObjectIsChildOfGroup _SimObjectIsChildOfGroupFunc;
internal static bool SimObjectIsChildOfGroup(IntPtr obj, IntPtr group)
{
if (_SimObjectIsChildOfGroupFunc == null)
{
_SimObjectIsChildOfGroupFunc =
(_SimObjectIsChildOfGroup)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectIsChildOfGroup"), typeof(_SimObjectIsChildOfGroup));
}
return _SimObjectIsChildOfGroupFunc(obj, group);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectGetGroup(IntPtr obj);
private static _SimObjectGetGroup _SimObjectGetGroupFunc;
internal static IntPtr SimObjectGetGroup(IntPtr obj)
{
if (_SimObjectGetGroupFunc == null)
{
_SimObjectGetGroupFunc =
(_SimObjectGetGroup)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectGetGroup"), typeof(_SimObjectGetGroup));
}
return _SimObjectGetGroupFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectDelete(IntPtr obj);
private static _SimObjectDelete _SimObjectDeleteFunc;
internal static void SimObjectDelete(IntPtr obj)
{
if (_SimObjectDeleteFunc == null)
{
_SimObjectDeleteFunc =
(_SimObjectDelete)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectDelete"), typeof(_SimObjectDelete));
}
_SimObjectDeleteFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _SimObjectClone(IntPtr obj, bool copyDynamicFields);
private static _SimObjectClone _SimObjectCloneFunc;
internal static IntPtr SimObjectClone(IntPtr obj, bool copyDynamicFields)
{
if (_SimObjectCloneFunc == null)
{
_SimObjectCloneFunc =
(_SimObjectClone)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectClone"), typeof(_SimObjectClone));
}
return _SimObjectCloneFunc(obj, copyDynamicFields);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectStartTimer(IntPtr obj, string callbackFunction, float timePeriod, int repeat);
private static _SimObjectStartTimer _SimObjectStartTimerFunc;
internal static bool SimObjectStartTimer(IntPtr obj, string callbackFunction, float timePeriod, int repeat)
{
if (_SimObjectStartTimerFunc == null)
{
_SimObjectStartTimerFunc =
(_SimObjectStartTimer)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectStartTimer"), typeof(_SimObjectStartTimer));
}
return _SimObjectStartTimerFunc(obj, callbackFunction, timePeriod, repeat);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectStopTimer(IntPtr obj);
private static _SimObjectStopTimer _SimObjectStopTimerFunc;
internal static void SimObjectStopTimer(IntPtr obj)
{
if (_SimObjectStopTimerFunc == null)
{
_SimObjectStopTimerFunc =
(_SimObjectStopTimer)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectStopTimer"), typeof(_SimObjectStopTimer));
}
_SimObjectStopTimerFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectIsTimerActive(IntPtr obj);
private static _SimObjectIsTimerActive _SimObjectIsTimerActiveFunc;
internal static bool SimObjectIsTimerActive(IntPtr obj)
{
if (_SimObjectIsTimerActiveFunc == null)
{
_SimObjectIsTimerActiveFunc =
(_SimObjectIsTimerActive)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectIsTimerActive"), typeof(_SimObjectIsTimerActive));
}
return _SimObjectIsTimerActiveFunc(obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _SimObjectSchedule(IntPtr obj, int time, int argc, string[] argv);
private static _SimObjectSchedule _SimObjectScheduleFunc;
internal static int SimObjectSchedule(IntPtr obj, int time, int argc, string[] argv)
{
if (_SimObjectScheduleFunc == null)
{
_SimObjectScheduleFunc =
(_SimObjectSchedule)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSchedule"), typeof(_SimObjectSchedule));
}
return _SimObjectScheduleFunc(obj, time, argc, argv);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _SimObjectSave(IntPtr obj, string filename, bool selectedOnly);
private static _SimObjectSave _SimObjectSaveFunc;
internal static bool SimObjectSave(IntPtr obj, string filename, bool selectedOnly)
{
if (_SimObjectSaveFunc == null)
{
_SimObjectSaveFunc =
(_SimObjectSave)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectSave"), typeof(_SimObjectSave));
}
return _SimObjectSaveFunc(obj, filename, selectedOnly);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectAddFieldFilter(IntPtr obj, string fieldName);
private static _SimObjectAddFieldFilter _SimObjectAddFieldFilterFunc;
internal static void SimObjectAddFieldFilter(IntPtr obj, string fieldName)
{
if (_SimObjectAddFieldFilterFunc == null)
{
_SimObjectAddFieldFilterFunc =
(_SimObjectAddFieldFilter)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectAddFieldFilter"), typeof(_SimObjectAddFieldFilter));
}
_SimObjectAddFieldFilterFunc(obj, fieldName);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _SimObjectRemoveFieldFilter(IntPtr obj, string fieldName);
private static _SimObjectRemoveFieldFilter _SimObjectRemoveFieldFilterFunc;
internal static void SimObjectRemoveFieldFilter(IntPtr obj, string fieldName)
{
if (_SimObjectRemoveFieldFilterFunc == null)
{
_SimObjectRemoveFieldFilterFunc =
(_SimObjectRemoveFieldFilter)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"SimObjectRemoveFieldFilter"), typeof(_SimObjectRemoveFieldFilter));
}
_SimObjectRemoveFieldFilterFunc(obj, fieldName);
}
}
#endregion
#region Properties
public bool CanSaveDynamicFields
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectGetCanSaveDynamicFields(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetCanSaveDynamicFields(ObjectPtr->ObjPtr, value);
}
}
public string InternalName
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetInternalName(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetInternalName(ObjectPtr->ObjPtr, value);
}
}
public SimGroup ParentGroup
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return new SimGroup(InternalUnsafeMethods.SimObjectGetParentGroup(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetParentGroup(ObjectPtr->ObjPtr, value.ObjectPtr->ObjPtr);
}
}
public string Superclass
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetSuperClass(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetSuperClass(ObjectPtr->ObjPtr, value);
}
}
public string Class
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetClass(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetClass(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public bool RegisterObject()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectRegisterObject(ObjectPtr->ObjPtr);
}
public string GetName()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetName(ObjectPtr->ObjPtr));
}
public void SetName(string val)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetName(ObjectPtr->ObjPtr, val);
}
public uint GetID()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectGetID(ObjectPtr->ObjPtr);
}
public bool IsMethod(string val)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectIsMethod(ObjectPtr->ObjPtr, val);
}
public bool Call(int argc, string[] argv)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectCall(ObjectPtr->ObjPtr, argc, argv);
}
public void DumpClassHierarchy()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectDumpClassHierarchy(ObjectPtr->ObjPtr);
}
public void Dump()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectDump(ObjectPtr->ObjPtr);
}
public bool IsMemberOfClass(string className)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectIsMemberOfClass(ObjectPtr->ObjPtr, className);
}
public string GetClassName()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetClassName(ObjectPtr->ObjPtr));
}
public string GetFieldValue(string fieldName)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetFieldValue(ObjectPtr->ObjPtr, fieldName));
}
public void SetFieldValue(string fieldName, string value)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetFieldValue(ObjectPtr->ObjPtr, fieldName, value);
}
public int GetDynamicFieldCount()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectGetDynamicFieldCount(ObjectPtr->ObjPtr);
}
public string GetDynamicField(int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetDynamicField(ObjectPtr->ObjPtr, index));
}
public int GetFieldCount()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectGetFieldCount(ObjectPtr->ObjPtr);
}
public string GetField(int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetField(ObjectPtr->ObjPtr, index));
}
public string GetProgenitorFile()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetProgenitorFile(ObjectPtr->ObjPtr));
}
public void SetProgenitorFile(string file)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectSetProgenitorFile(ObjectPtr->ObjPtr, file);
}
public int GetType()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectGetType(ObjectPtr->ObjPtr);
}
public string GetFieldType(string fieldName)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.SimObjectGetFieldType(ObjectPtr->ObjPtr, fieldName));
}
public bool IsChildOfGroup(SimGroup group)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectIsChildOfGroup(ObjectPtr->ObjPtr, group.ObjectPtr->ObjPtr);
}
public SimGroup GetGroup()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return new SimGroup(InternalUnsafeMethods.SimObjectGetGroup(ObjectPtr->ObjPtr));
}
public void Delete()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectDelete(ObjectPtr->ObjPtr);
}
public SimObject Clone(bool copyDynamicFields = false)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return new SimObject(InternalUnsafeMethods.SimObjectClone(ObjectPtr->ObjPtr, copyDynamicFields));
}
public bool StartTimer(string callbackFunction, float timePeriod, int repeat = 0)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectStartTimer(ObjectPtr->ObjPtr, callbackFunction, timePeriod, repeat);
}
public void StopTimer()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectStopTimer(ObjectPtr->ObjPtr);
}
public bool IsTimerActive()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectIsTimerActive(ObjectPtr->ObjPtr);
}
public int Schedule(int time, int argc, string[] argv)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectSchedule(ObjectPtr->ObjPtr, time, argc, argv);
}
public bool Save(string filename, bool selectedOnly = false)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.SimObjectSave(ObjectPtr->ObjPtr, filename, selectedOnly);
}
public void AddFieldFilter(string fieldName)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectAddFieldFilter(ObjectPtr->ObjPtr, fieldName);
}
public void RemoveFieldFilter(string fieldName)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.SimObjectRemoveFieldFilter(ObjectPtr->ObjPtr, fieldName);
}
#endregion
#region SimObject specifics
public T As<T>() where T : new()
{
return (T)Activator.CreateInstance(typeof (T), this);
}
public Sim.SimObjectPtr* ObjectPtr { get; protected set; }
public void SetPointerFromObject(SimObject obj)
{
ObjectPtr = obj.ObjectPtr;
}
public bool IsDead()
{
return ObjectPtr->ObjPtr == IntPtr.Zero;
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool pDisposing)
{
if (ObjectPtr->ObjPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal((IntPtr) ObjectPtr);
}
}
~SimObject()
{
Dispose(false);
}
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Numerics;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("sys", typeof(IronPython.Modules.SysModule))]
namespace IronPython.Modules {
public static class SysModule {
public const string __doc__ = "Provides access to functions which query or manipulate the Python runtime.";
public const int api_version = 0;
// argv is set by PythonContext and only on the initial load
public static readonly string byteorder = BitConverter.IsLittleEndian ? "little" : "big";
// builtin_module_names is set by PythonContext and updated on reload
public const string copyright = "Copyright (c) IronPython Team";
private static string GetPrefix() {
string prefix;
#if FEATURE_ASSEMBLY_LOCATION
try {
prefix = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
} catch (SecurityException) {
prefix = String.Empty;
} catch (ArgumentException) {
prefix = String.Empty;
} catch (MethodAccessException) {
prefix = String.Empty;
}
#else
prefix = String.Empty;
#endif
return prefix;
}
/// <summary>
/// Returns detailed call statistics. Not implemented in IronPython and always returns None.
/// </summary>
public static object callstats() {
return null;
}
/// <summary>
/// Handles output of the expression statement.
/// Prints the value and sets the __builtin__._
/// </summary>
[PythonHidden]
[Documentation(@"displayhook(object) -> None
Print an object to sys.stdout and also save it in __builtin__._")]
public static void displayhookImpl(CodeContext/*!*/ context, object value) {
if (value != null) {
PythonOps.Print(context, PythonOps.Repr(context, value));
context.LanguageContext.BuiltinModuleDict["_"] = value;
}
}
public static BuiltinFunction displayhook = BuiltinFunction.MakeFunction(
"displayhook",
ArrayUtils.ConvertAll(typeof(SysModule).GetMember("displayhookImpl"), (x) => (MethodBase)x),
typeof(SysModule)
);
public static readonly BuiltinFunction __displayhook__ = displayhook;
public const int dllhandle = 0;
[PythonHidden]
[Documentation(@"excepthook(exctype, value, traceback) -> None
Handle an exception by displaying it with a traceback on sys.stderr._")]
public static void excepthookImpl(CodeContext/*!*/ context, object exctype, object value, object traceback) {
PythonContext pc = context.LanguageContext;
PythonOps.PrintWithDest(
context,
pc.SystemStandardError,
pc.FormatException(PythonExceptions.ToClr(value))
);
}
public static readonly BuiltinFunction excepthook = BuiltinFunction.MakeFunction(
"excepthook",
ArrayUtils.ConvertAll(typeof(SysModule).GetMember("excepthookImpl"), (x) => (MethodBase)x),
typeof(SysModule)
);
public static readonly BuiltinFunction __excepthook__ = excepthook;
public static int getcheckinterval() {
throw PythonOps.NotImplementedError("IronPython does not support sys.getcheckinterval");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
public static void setcheckinterval(int value) {
throw PythonOps.NotImplementedError("IronPython does not support sys.setcheckinterval");
}
public static int getrefcount(CodeContext/*!*/ context, object o) {
// getrefcount() is used at various places in the CPython test suite, usually to
// check that instances are not cloned. Under .NET, we cannot provide that functionality,
// but we can at least return a dummy result so that the tests can continue.
PythonOps.Warn(context, PythonExceptions.RuntimeWarning, "IronPython does not support sys.getrefcount. A dummy result is returned.");
return 1000000;
}
// warnoptions is set by PythonContext and updated on each reload
[Python3Warning("sys.exc_clear() not supported in 3.x; use except clauses")]
public static void exc_clear() {
PythonOps.ClearCurrentException();
}
public static PythonTuple exc_info(CodeContext/*!*/ context) {
return PythonOps.GetExceptionInfo(context);
}
// exec_prefix and executable are set by PythonContext and updated on each reload
public static void exit() {
exit(null);
}
public static void exit(object code) {
if (code == null) {
throw new PythonExceptions._SystemExit().InitAndGetClrException();
} else {
// throw as a python exception here to get the args set.
throw new PythonExceptions._SystemExit().InitAndGetClrException(code);
}
}
public static string getdefaultencoding(CodeContext/*!*/ context) {
return context.LanguageContext.GetDefaultEncodingName();
}
public static object getfilesystemencoding() {
if(Environment.OSVersion.Platform == PlatformID.Unix)
return "utf-8";
return "mbcs";
}
[PythonHidden]
public static TraceBackFrame/*!*/ _getframeImpl(CodeContext/*!*/ context) {
return _getframeImpl(context, 0);
}
[PythonHidden]
public static TraceBackFrame/*!*/ _getframeImpl(CodeContext/*!*/ context, int depth) {
return _getframeImpl(context, depth, PythonOps.GetFunctionStack());
}
internal static TraceBackFrame/*!*/ _getframeImpl(CodeContext/*!*/ context, int depth, List<FunctionStack> stack) {
if (depth < stack.Count) {
TraceBackFrame cur = null;
for (int i = 0; i < stack.Count - depth; i++) {
var elem = stack[i];
if (elem.Frame != null) {
// we previously handed out a frame here, hand out the same one now
cur = elem.Frame;
} else {
// create a new frame and save it for future calls
cur = new TraceBackFrame(
context,
Builtin.globals(elem.Context),
Builtin.locals(elem.Context),
elem.Code,
cur
);
stack[i] = new FunctionStack(elem.Context, elem.Code, cur);
}
}
return cur;
}
throw PythonOps.ValueError("call stack is not deep enough");
}
public static int getsizeof(object o) {
return ObjectOps.__sizeof__(o);
}
public static PythonTuple getwindowsversion() {
var osVer = Environment.OSVersion;
return new windows_version(
osVer.Version.Major,
osVer.Version.Minor,
osVer.Version.Build,
(int)osVer.Platform
#if FEATURE_OS_SERVICEPACK
, osVer.ServicePack
#else
, ""
#endif
);
}
[PythonType("sys.getwindowsversion"), PythonHidden]
public class windows_version : PythonTuple {
internal windows_version(int major, int minor, int build, int platform, string service_pack)
: base(new object[] { major, minor, build, platform, service_pack }) {
this.major = major;
this.minor = minor;
this.build = build;
this.platform = platform;
this.service_pack = service_pack;
}
public readonly int major;
public readonly int minor;
public readonly int build;
public readonly int platform;
public readonly string service_pack;
public const int n_fields = 5;
public const int n_sequence_fields = 5;
public const int n_unnamed_fields = 0;
public override string __repr__(CodeContext context) {
return string.Format("sys.getwindowsversion(major={0}, minor={1}, build={2}, platform={3}, service_pack='{4}')",
this.major, this.minor, this.build, this.platform, this.service_pack);
}
}
// hex_version is set by PythonContext
public const int maxint = Int32.MaxValue;
public const int maxsize = Int32.MaxValue;
public const int maxunicode = (int)ushort.MaxValue;
// modules is set by PythonContext and only on the initial load
// path is set by PythonContext and only on the initial load
public const string platform = "cli";
public static readonly string prefix = GetPrefix();
// ps1 and ps2 are set by PythonContext and only on the initial load
public static void setdefaultencoding(CodeContext context, object name) {
if (name == null) throw PythonOps.TypeError("name cannot be None");
if (!(name is string strName)) throw PythonOps.TypeError("name must be a string");
PythonContext pc = context.LanguageContext;
Encoding enc;
if (!StringOps.TryGetEncoding(strName, out enc)) {
throw PythonOps.LookupError("'{0}' does not match any available encodings", strName);
}
pc.DefaultEncoding = enc;
}
#if PROFILE_SUPPORT
// not enabled because we don't yet support tracing built-in functions. Doing so is a little
// difficult because it's hard to flip tracing on/off for them w/o a perf overhead in the
// non-profiling case.
public static void setprofile(CodeContext/*!*/ context, TracebackDelegate o) {
PythonContext pyContext = context.LanguageContext;
pyContext.EnsureDebugContext();
if (o == null) {
pyContext.UnregisterTracebackHandler();
} else {
pyContext.RegisterTracebackHandler();
}
// Register the trace func with the listener
pyContext.TracebackListener.SetProfile(o);
}
#endif
public static void settrace(CodeContext/*!*/ context, object o) {
context.LanguageContext.SetTrace(o);
}
public static object call_tracing(CodeContext/*!*/ context, object func, PythonTuple args) {
return context.LanguageContext.CallTracing(func, args);
}
public static object gettrace(CodeContext/*!*/ context) {
return context.LanguageContext.GetTrace();
}
public static void setrecursionlimit(CodeContext/*!*/ context, int limit) {
context.LanguageContext.RecursionLimit = limit;
}
public static int getrecursionlimit(CodeContext/*!*/ context) {
return context.LanguageContext.RecursionLimit;
}
// stdin, stdout, stderr, __stdin__, __stdout__, and __stderr__ added by PythonContext
// version and version_info are set by PythonContext
public static PythonTuple subversion = PythonTuple.MakeTuple("IronPython", "", "");
public static readonly string winver = CurrentVersion.Series;
#region Special types
[PythonHidden, PythonType("flags"), DontMapIEnumerableToIter]
public sealed class SysFlags : IList<object> {
private const string _className = "sys.flags";
internal SysFlags() { }
private const int INDEX_DEBUG = 0;
private const int INDEX_PY3K_WARNING = 1;
private const int INDEX_DIVISION_WARNING = 2;
private const int INDEX_DIVISION_NEW = 3;
private const int INDEX_INSPECT = 4;
private const int INDEX_INTERACTIVE = 5;
private const int INDEX_OPTIMIZE = 6;
private const int INDEX_DONT_WRITE_BYTECODE = 7;
private const int INDEX_NO_USER_SITE = 8;
private const int INDEX_NO_SITE = 9;
private const int INDEX_IGNORE_ENVIRONMENT = 10;
private const int INDEX_TABCHECK = 11;
private const int INDEX_VERBOSE = 12;
private const int INDEX_UNICODE = 13;
private const int INDEX_BYTES_WARNING = 14;
public const int n_fields = 15;
public const int n_sequence_fields = 15;
public const int n_unnamed_fields = 0;
private static readonly string[] _keys = new string[] {
"debug", "py3k_warning", "division_warning", "division_new", "inspect",
"interactive", "optimize", "dont_write_bytecode", "no_user_site", "no_site",
"ignore_environment", "tabcheck", "verbose", "unicode", "bytes_warning"
};
private object[] _values = new object[n_fields] {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
private PythonTuple __tuple = null;
private PythonTuple _tuple {
get {
_Refresh();
return __tuple;
}
}
private string __string = null;
private string _string {
get {
_Refresh();
return __string;
}
}
public override string ToString() {
return _string;
}
public string __repr__() {
return _string;
}
private bool _modified = true;
private void _Refresh() {
if (_modified) {
__tuple = PythonTuple.MakeTuple(_values);
StringBuilder sb = new StringBuilder("sys.flags(");
for (int i = 0; i < n_fields; i++) {
if (_keys[i] == null) {
sb.Append(_values[i]);
} else {
sb.AppendFormat("{0}={1}", _keys[i], _values[i]);
}
if (i < n_fields - 1) {
sb.Append(", ");
} else {
sb.Append(')');
}
}
__string = sb.ToString();
_modified = false;
}
}
private int _GetVal(int index) {
return (int)_values[index];
}
private void _SetVal(int index, int value) {
if ((int)_values[index] != value) {
_modified = true;
_values[index] = value;
}
}
#region ICollection<object> Members
void ICollection<object>.Add(object item) {
throw new InvalidOperationException(_className + " is readonly");
}
void ICollection<object>.Clear() {
throw new InvalidOperationException(_className + " is readonly");
}
[PythonHidden]
public bool Contains(object item) {
return _tuple.Contains(item);
}
[PythonHidden]
public void CopyTo(object[] array, int arrayIndex) {
_tuple.CopyTo(array, arrayIndex);
}
public int Count {
[PythonHidden]
get {
return n_fields;
}
}
bool ICollection<object>.IsReadOnly {
get { return true; }
}
bool ICollection<object>.Remove(object item) {
throw new InvalidOperationException(_className + " is readonly");
}
#endregion
#region IEnumerable Members
[PythonHidden]
public IEnumerator GetEnumerator() {
return _tuple.GetEnumerator();
}
#endregion
#region IEnumerable<object> Members
IEnumerator<object> IEnumerable<object>.GetEnumerator() {
return ((IEnumerable<object>)_tuple).GetEnumerator();
}
#endregion
#region ISequence Members
public int __len__() {
return n_fields;
}
public object this[int i] {
get {
return _tuple[i];
}
}
public object this[BigInteger i] {
get {
return this[(int)i];
}
}
public object __getslice__(int start, int end) {
return _tuple.__getslice__(start, end);
}
public object this[Slice s] {
get {
return _tuple[s];
}
}
public object this[object o] {
get {
return this[Converter.ConvertToIndex(o)];
}
}
#endregion
#region IList<object> Members
[PythonHidden]
public int IndexOf(object item) {
return _tuple.IndexOf(item);
}
void IList<object>.Insert(int index, object item) {
throw new InvalidOperationException(_className + " is readonly");
}
void IList<object>.RemoveAt(int index) {
throw new InvalidOperationException(_className + " is readonly");
}
object IList<object>.this[int index] {
get {
return _tuple[index];
}
set {
throw new InvalidOperationException(_className + " is readonly");
}
}
#endregion
#region binary ops
public static PythonTuple operator +([NotNull]SysFlags f, [NotNull]PythonTuple t) {
return f._tuple + t;
}
public static PythonTuple operator *([NotNull]SysFlags f, int n) {
return f._tuple * n;
}
public static PythonTuple operator *(int n, [NotNull]SysFlags f) {
return f._tuple * n;
}
public static object operator *([NotNull]SysFlags f, [NotNull]Runtime.Index n) {
return f._tuple * n;
}
public static object operator *([NotNull]Runtime.Index n, [NotNull]SysFlags f) {
return f._tuple * n;
}
public static object operator *([NotNull]SysFlags f, object n) {
return f._tuple * n;
}
public static object operator *(object n, [NotNull]SysFlags f) {
return f._tuple * n;
}
#endregion
# region comparison and hashing methods
public static bool operator >(SysFlags f, PythonTuple t) {
return f._tuple > t;
}
public static bool operator <(SysFlags f, PythonTuple t) {
return f._tuple < t;
}
public static bool operator >=(SysFlags f, PythonTuple t) {
return f._tuple >= t;
}
public static bool operator <=(SysFlags f, PythonTuple t) {
return f._tuple <= t;
}
public override bool Equals(object obj) {
if (obj is SysFlags) {
return _tuple.Equals(((SysFlags)obj)._tuple);
}
return _tuple.Equals(obj);
}
public override int GetHashCode() {
return _tuple.GetHashCode();
}
# endregion
#region sys.flags API
public int debug {
get { return _GetVal(INDEX_DEBUG); }
internal set { _SetVal(INDEX_DEBUG, value); }
}
public int py3k_warning {
get { return _GetVal(INDEX_PY3K_WARNING); }
internal set { _SetVal(INDEX_PY3K_WARNING, value); }
}
public int division_warning {
get { return _GetVal(INDEX_DIVISION_WARNING); }
internal set { _SetVal(INDEX_DIVISION_WARNING, value); }
}
public int division_new {
get { return _GetVal(INDEX_DIVISION_NEW); }
internal set { _SetVal(INDEX_DIVISION_NEW, value); }
}
public int inspect {
get { return _GetVal(INDEX_INSPECT); }
internal set { _SetVal(INDEX_INSPECT, value); }
}
public int interactive {
get { return _GetVal(INDEX_INTERACTIVE); }
internal set { _SetVal(INDEX_INTERACTIVE, value); }
}
public int optimize {
get { return _GetVal(INDEX_OPTIMIZE); }
internal set { _SetVal(INDEX_OPTIMIZE, value); }
}
public int dont_write_bytecode {
get { return _GetVal(INDEX_DONT_WRITE_BYTECODE); }
internal set { _SetVal(INDEX_DONT_WRITE_BYTECODE, value); }
}
public int no_user_site {
get { return _GetVal(INDEX_NO_USER_SITE); }
internal set { _SetVal(INDEX_NO_USER_SITE, value); }
}
public int no_site {
get { return _GetVal(INDEX_NO_SITE); }
internal set { _SetVal(INDEX_NO_SITE, value); }
}
public int ignore_environment {
get { return _GetVal(INDEX_IGNORE_ENVIRONMENT); }
internal set { _SetVal(INDEX_IGNORE_ENVIRONMENT, value); }
}
public int tabcheck {
get { return _GetVal(INDEX_TABCHECK); }
internal set { _SetVal(INDEX_TABCHECK, value); }
}
public int verbose {
get { return _GetVal(INDEX_VERBOSE); }
internal set { _SetVal(INDEX_VERBOSE, value); }
}
public int unicode {
get { return _GetVal(INDEX_UNICODE); }
internal set { _SetVal(INDEX_UNICODE, value); }
}
public int bytes_warning {
get { return _GetVal(INDEX_BYTES_WARNING); }
internal set { _SetVal(INDEX_BYTES_WARNING, value); }
}
#endregion
}
#endregion
// These values are based on the .NET 2 BigInteger in Microsoft.Scripting.Math
public static longinfo long_info = new longinfo(32, 4);
[PythonType("sys.long_info"), PythonHidden]
public class longinfo : PythonTuple {
internal longinfo(int bits_per_digit, int sizeof_digit)
: base(new object[] {bits_per_digit, sizeof_digit}) {
this.bits_per_digit = bits_per_digit;
this.sizeof_digit = sizeof_digit;
}
public readonly int bits_per_digit;
public readonly int sizeof_digit;
public const int n_fields = 2;
public const int n_sequence_fields = 2;
public const int n_unnamed_fields = 0;
public override string __repr__(CodeContext context) {
return string.Format("sys.long_info(bits_per_digit={0}, sizeof_digit={1})",
this.bits_per_digit, this.sizeof_digit);
}
}
public static string float_repr_style = "legacy";
public static floatinfo float_info = new floatinfo(
Double.MaxValue, // DBL_MAX
1024, // DBL_MAX_EXP
308, // DBL_MAX_10_EXP
// DBL_MIN
BitConverter.Int64BitsToDouble(BitConverter.IsLittleEndian ? 0x0010000000000000 : 0x0000000000001000),
-1021, // DBL_MIN_EXP
-307, // DBL_MIN_10_EXP
15, // DBL_DIG
53, // DBL_MANT_DIG
// DBL_EPSILON
BitConverter.Int64BitsToDouble(BitConverter.IsLittleEndian ? 0x3cb0000000000000 : 0x000000000000b03c),
2, // FLT_RADIX
1); // FLT_ROUNDS
[PythonType("sys.float_info"), PythonHidden]
public class floatinfo : PythonTuple {
internal floatinfo(double max, int max_exp, int max_10_exp,
double min, int min_exp, int min_10_exp,
int dig, int mant_dig, double epsilon, int radix, int rounds)
: base(new object[] { max, max_exp, max_10_exp,
min, min_exp, min_10_exp,
dig, mant_dig, epsilon, radix, rounds}) {
this.max = max;
this.max_exp = max_exp;
this.max_10_exp = max_10_exp;
this.min = min;
this.min_exp = min_exp;
this.min_10_exp = min_10_exp;
this.dig = dig;
this.mant_dig = mant_dig;
this.epsilon = epsilon;
this.radix = radix;
this.rounds = rounds;
}
public readonly double max;
public readonly int max_exp;
public readonly int max_10_exp;
public readonly double min;
public readonly int min_exp;
public readonly int min_10_exp;
public readonly int dig;
public readonly int mant_dig;
public readonly double epsilon;
public readonly int radix;
public readonly int rounds;
public const int n_fields = 11;
public const int n_sequence_fields = 11;
public const int n_unnamed_fields = 0;
public override string __repr__(CodeContext context) {
return string.Format("sys.float_info(max={0}, max_exp={1}, max_10_exp={2}, " +
"min={3}, min_exp={4}, min_10_exp={5}, " +
"dig={6}, mant_dig={7}, epsilon={8}, radix={9}, rounds={10})",
max, max_exp, max_10_exp,
min, min_exp, min_10_exp,
dig, mant_dig, epsilon, radix, rounds);
}
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
dict["stdin"] = dict["__stdin__"];
dict["stdout"] = dict["__stdout__"];
dict["stderr"] = dict["__stderr__"];
// !!! These fields do need to be reset on "reload(sys)". However, the initial value is specified by the
// engine elsewhere. For now, we initialize them just once to some default value
dict["warnoptions"] = new List(0);
PublishBuiltinModuleNames(context, dict);
context.SetHostVariables(dict);
dict["meta_path"] = new List(0);
dict["path_hooks"] = new List(0);
// add zipimport to the path hooks for importing from zip files.
try {
if (Importer.ImportModule(
context.SharedClsContext, context.SharedClsContext.GlobalDict,
"zipimport", false, -1) is PythonModule zipimport) {
object zipimporter = PythonOps.GetBoundAttr(
context.SharedClsContext, zipimport, "zipimporter");
if (dict["path_hooks"] is List path_hooks && zipimporter != null) {
path_hooks.Add(zipimporter);
}
}
} catch {
// this is not a fatal error, so we don't do anything.
}
dict["path_importer_cache"] = new PythonDictionary();
}
internal static void PublishBuiltinModuleNames(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
object[] keys = new object[context.BuiltinModules.Keys.Count];
int index = 0;
foreach (object key in context.BuiltinModules.Keys) {
keys[index++] = key;
}
dict["builtin_module_names"] = PythonTuple.MakeTuple(keys);
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Runtime.Caching;
using System.Collections.Generic;
using Alachisoft.NCache.Runtime.Events;
using Alachisoft.NCache.Common.Events;
using Alachisoft.NCache.Common.Locking;
using Alachisoft.NCache.Common.DataSource;
using Alachisoft.NCache.Client.Caching;
using Alachisoft.NCache.Caching.Events;
using Alachisoft.NCache.Common.Pooling;
namespace Alachisoft.NCache.Client
{
internal class CacheImplBase
{
private ClientInfo _clientInfo;
private string _clientID;
private SerializationFormat _serializationFormat;
internal CacheImplBase()
{
_clientInfo = new ClientInfo();
_clientInfo.ProcessID = AppUtil.CurrentProcess.Id;
_clientInfo.ClientID = System.Guid.NewGuid().ToString();
_clientInfo.MachineName = Environment.MachineName;
//Client version has following format :
//[2 digits for major version][1 digit for service paack][1 digit for private patch]
//e.g. 4122 means 4.1 major , 2 for service pack 2 and last 4 for private patch 4
_clientInfo.ClientVersion = 5000; //changed for 5.0
_clientID = ClientInfo.GetLegacyClientID(_clientInfo);
}
internal ClientInfo LocalClientInfo { get { return _clientInfo; } }
protected internal virtual bool SerializationEnabled { get { return true; } }
protected internal virtual TypeInfoMap TypeMap { get { return null; } set { } }
protected internal virtual EventManager EventManager
{
get { return null; }
}
/// <summary>
/// Occurs in response to a <see cref="Cache.RaiseCustomEvent"/> method call.
/// </summary>
/// <remarks>
/// You can use this event to handle custom application defined event notifications.
/// <para>Doing a lot of processing inside the handler might have an impact on the performance
/// of the cache and cluster. It is therefore advisable to do minimal processing inside the handler.
/// </para>
/// For more information on how to use this callback see the documentation
/// for <see cref="CustomEventCallback"/>.
/// </remarks>
public event CustomEventCallback CustomEvent;
public virtual long Count { get { return 0; } }
public string ClientID { get { return _clientID; } }
public virtual string Name { get { return null; } }
internal virtual PoolManager PoolManager { get; }
public virtual void Dispose(bool disposing) { }
public virtual void RegisterGeneralNotification(EventTypeInternal eventType, EventDataFilter datafilter, short sequenceNumber) { }
public virtual void UnRegisterGeneralNotification(EventTypeInternal unregister, short sequenceNumber) { }
public virtual void RegisterAddEvent() { }
public virtual void RegisterRemoveEvent() { }
public virtual void RegisterUpdateEvent() { }
public virtual void RegisterCustomEvent() { }
public virtual void RegisterNodeJoinedEvent() { }
public virtual void RegisterNodeLeftEvent() { }
public virtual void UnregisterAddEvent() { }
public virtual void UnregisterRemoveEvent() { }
public virtual void UnregisterUpdateEvent() { }
public virtual void UnregisterCustomEvent() { }
public virtual void UnregisterNodeJoinedEvent() { }
public virtual void UnregisterNodeLeftEvent() { }
public virtual void UnregisterHashmapChangedEvent() { }
public virtual void RegisterCacheStoppedEvent() { }
public virtual void UnregisterCacheStoppedEvent() { }
public virtual void RegisterClearEvent() { }
public virtual void UnregisterClearEvent() { }
internal virtual void MakeTargetCacheActivePassive(bool makeActive) { }
public virtual void Add(string key, object value, DateTime absoluteExpiration,
TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, short onDsItemAddedCallback, bool isResyncExpiredItems,
Hashtable queryInfo, BitSet flagMap, string providerName, string resyncProviderName, EventDataFilter updateCallbackFilter,
EventDataFilter removeCallabackFilter, long size, bool encryptionEnabled, string clientId, string typeName)
{
}
public virtual IDictionary<string, Exception> Add(string[] keys, CacheItem[] items,
short onDataSourceItemsAdded, string providerName, long[] sizes, bool encryptionEnabled,
string clientId, short updateCallbackId, short removeCallbackId,
EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter,
CallbackType callbackType = CallbackType.PushBasedNotification)
{
return null;
}
public virtual void Clear(BitSet flagMap, short onDsClearedCallback, string providerName)
{
}
public virtual void ClearAsync(BitSet flagMap, short onDsClearedCallback, string providerName)
{
}
public virtual void ClearAsync(BitSet flagMap, short onAsyncCacheClearCallback, short onDsClearedCallback, string providerName)
{
}
public virtual bool Contains(string key)
{
return false;
}
public virtual IDictionary<string, bool> ContainsBulk(string[] keys)
{
return null;
}
public virtual CompressedValueEntry Get<T>(string key, BitSet flagMap, string group, string subGroup, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType)
{
return null;
}
public virtual void RaiseCustomEvent(object notifId, object data) { }
public virtual IDictionary Get<T>(string[] keys, BitSet flagMap)
{
return null;
}
public virtual object GetCacheItem(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType)
{
return null;
}
public virtual IDictionary GetCacheItemBulk(string[] keys, BitSet flagMap)
{
return null;
}
public virtual void Insert(string key, object value, DateTime absoluteExpiration,
TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, short onDsItemUpdatedCallback, bool isResyncExpiredItems,
Hashtable queryInfo, BitSet flagMap, object lockId, LockAccessType accessType, string providerName,
string resyncProviderName, EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter, long size, bool encryptionEnabled, string clientId, string typeName, CallbackType callbackType = CallbackType.PushBasedNotification)
{
}
public virtual IDictionary<string, Exception> Insert(string[] keys,
CacheItem[] items, short onDsItemsUpdatedCallback, string providerName,
long[] sizes, bool encryptionEnabled, string clientId,
short updateCallbackId, short removeCallbackId,
EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter,
CallbackType callbackType = CallbackType.PushBasedNotification)
{
return null;
}
public virtual CompressedValueEntry Remove<T>(string key, BitSet flagMap, short dsItemRemovedCallbackId, object lockId, LockAccessType accessType, string ProviderName)
{
return null;
}
public virtual void Delete(string key, BitSet flagMap, short dsItemRemovedCallbackId, object lockId, LockAccessType accessType)
{
}
public virtual IDictionary Remove<T>(string[] keys, BitSet flagMap, string providerName, short onDsItemsRemovedCallback)
{
return null;
}
public virtual void Delete(string[] keys, BitSet flagMap, string providerName, short onDsItemsRemovedCallback)
{
}
//Delete that can be use to Delete nay item in cache by providing only key
public virtual void Delete(string key)
{
LockHandle lockHandle=null;
LockAccessType accessType= LockAccessType.IGNORE_LOCK;
object lockId = (lockHandle == null) ? null : lockHandle.LockId;
BitSet flagMap = new BitSet();
short dsItemRemovedCallbackId = -1;
this.Delete(key, flagMap, dsItemRemovedCallbackId, lockId, accessType);
}
public virtual void Remove(string group, string subGroup)
{
}
public virtual object SafeSerialize(object serializableObject, string serializationContext, ref BitSet flag, CacheImplBase cacheImpl, ref long size, UserObjectType userObjectType,bool isCustomAttributeBaseSerialzed=false)
{
return null;
}
public virtual T SafeDeserialize<T>(object serializedObject, string serializationContext, BitSet flag, CacheImplBase cacheImpl, UserObjectType userObjectType)
{
return default(T);
}
public virtual IEnumerator GetEnumerator()
{
return null;
}
public virtual EnumerationDataChunk GetNextChunk(EnumerationPointer pointer)
{
return null;
}
public virtual List<EnumerationDataChunk> GetNextChunk(List<EnumerationPointer> pointers)
{
return null;
}
public virtual Hashtable GetCompactTypes()
{
return null;
}
public virtual Hashtable GetEncryptionInfo()
{
return null;
}
public virtual Hashtable GetExpirationInfo()
{
return null;
}
public virtual void Unlock(string key)
{
}
public virtual void Unlock(string key, object lockId)
{
}
public virtual bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle)
{
lockHandle = null;
return false;
}
public virtual bool CheckCSecurityAuthorization(string cacheId, byte[] password, string userId)
{
return false;
}
internal virtual bool IsLocked(string key, ref LockHandle lockHandle)
{
return false;
}
public virtual void RegisterKeyNotificationCallback(string key, short updateCallbackid, short removeCallbackid, bool notifyOnItemExpiration) { }
public virtual void UnRegisterKeyNotificationCallback(string key, short updateCallbackid, short removeCallbackid) { }
public virtual void RegisterKeyNotificationCallback(string key, short update, short remove, EventDataFilter datafilter, bool notifyOnItemExpiration, CallbackType callbackType = CallbackType.PushBasedNotification) { }
public virtual void RegisterKeyNotificationCallback(string key, short update, short remove, EventDataFilter datafilter, bool notifyOnItemExpiration) { }
public virtual void UnRegisterKeyNotificationCallback(string key, short update, short remove, EventTypeInternal eventType) { }
public virtual void RegisterKeyNotificationCallback(string[] keys, short updateCallbackid, short removeCallbackid, string clientId, CallbackType callbackType = CallbackType.PullBasedCallback) { }
public virtual void UnRegisterKeyNotificationCallback(string[] keys, short updateCallbackid, short removeCallbackid) { }
public virtual void RegisterKeyNotificationCallback(string[] key, short update, short remove, EventDataFilter datafilter, bool notifyOnItemExpiration) { }
public virtual void UnRegisterKeyNotificationCallback(string[] key, short update, short remove, EventTypeInternal eventType) { }
public virtual void RegisterKeyNotificationCallback(string[] key, short update, short remove, EventDataFilter datafilter, bool notifyOnItemExpiration, CallbackType callbackType = CallbackType.PushBasedNotification) { }
public virtual void RegisterPollingNotification(short pollingCallbackId) { }
public virtual bool SetAttributes(string key, CacheItemAttributes attribute)
{
return false;
}
public virtual void Dispose(string serverAddress)
{ }
internal virtual PollingResult Poll()
{
return null;
}
public virtual void RegisterCacheClientConnectivityEvent() { }
public virtual void UnregisterCacheClientConnectivityEvent() { }
public virtual IList<ClientInfo> GetConnectedClientList()
{
return null;
}
#region / --- Touch --- /
internal virtual void Touch(List<string> key) { }
#endregion
#region ----- Messaging pub/sub------
internal virtual long GetMessageCount(string topicName)
{
return 0;
}
internal virtual bool GetOrCreate(string topicName, TopicOperationType type)
{
return false;
}
internal virtual bool Subscribe(string topicName, string subscriptionName, SubscriptionType pubSubType, long creationTime, long expiration, SubscriptionPolicyType subscriptionPolicy = SubscriptionPolicyType.NonDurableExclusiveSubscription)
{
return false;
}
internal virtual bool UnSubscribe(string topicName, string recepientId, SubscriptionPolicyType subscriptionPolicy, SubscriptionType pubSubType,bool dispose=false)
{
return false;
}
internal virtual void PublishMessage(string messageId, object payLoad, long creationTime, long expirationTime, Hashtable metadata, BitSet flagMap)
{
}
internal virtual object GetMessageData(BitSet flagMap)
{
return null;
}
internal virtual bool RemoveTopic(string topicName, bool forcefully)
{
return false;
}
internal virtual void AcknowledgeMessageReceipt(IDictionary<string, IList<string>> topicWiseMessageIds)
{
}
#endregion
}
}
| |
// Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace DBus
{
using Protocol;
using System.Threading.Tasks;
public class BusObject
{
static Dictionary<object, BusObject> boCache = new Dictionary<object, BusObject>();
protected Connection conn;
string bus_name;
ObjectPath object_path;
public BusObject()
{
}
public BusObject(Connection conn, string bus_name, ObjectPath object_path)
{
this.conn = conn;
this.bus_name = bus_name;
this.object_path = object_path;
}
public Connection Connection
{
get
{
return conn;
}
}
public string BusName
{
get
{
return bus_name;
}
}
public ObjectPath Path
{
get
{
return object_path;
}
}
public async Task ToggleSignalAsync(string iface, string member, Delegate dlg, bool adding)
{
MatchRule rule = new MatchRule();
rule.MessageType = MessageType.Signal;
rule.Fields.Add(FieldCode.Interface, new MatchTest(iface));
rule.Fields.Add(FieldCode.Member, new MatchTest(member));
rule.Fields.Add(FieldCode.Path, new MatchTest(object_path));
// FIXME: Cause a regression compared to 0.6 as name wasn't matched before
// the problem arises because busname is not used by DBus daemon and
// instead it uses the canonical name of the sender (i.e. similar to ':1.13')
// rule.Fields.Add (FieldCode.Sender, new MatchTest (bus_name));
if (adding)
{
if (conn.Handlers.ContainsKey(rule))
conn.Handlers[rule] = Delegate.Combine(conn.Handlers[rule], dlg);
else
{
conn.Handlers[rule] = dlg;
await conn.AddMatchAsync(rule.ToString()).ConfigureAwait(false);
}
}
else if (conn.Handlers.ContainsKey(rule))
{
conn.Handlers[rule] = Delegate.Remove(conn.Handlers[rule], dlg);
if (conn.Handlers[rule] == null)
{
await conn.RemoveMatchAsync(rule.ToString()).ConfigureAwait(false);
conn.Handlers.Remove(rule);
}
}
}
public void SendSignal(string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
exception = null;
Signature outSig = String.IsNullOrEmpty(inSigStr) ? Signature.Empty : new Signature(inSigStr);
MessageContainer signal = new MessageContainer
{
Type = MessageType.Signal,
Path = object_path,
Interface = iface,
Member = member,
Signature = outSig,
};
Message signalMsg = signal.Message;
signalMsg.AttachBodyTo(writer);
conn.Send(signalMsg);
}
public async Task<MessageReader> SendMethodCall(string iface, string member, string inSigStr, MessageWriter writer, Type retType)
{
if (string.IsNullOrEmpty(bus_name))
throw new ArgumentNullException("bus_name");
if (object_path == null)
throw new ArgumentNullException("object_path");
Signature inSig = String.IsNullOrEmpty(inSigStr) ? Signature.Empty : new Signature(inSigStr);
MessageContainer method_call = new MessageContainer
{
Path = object_path,
Interface = iface,
Member = member,
Destination = bus_name,
Signature = inSig
};
Message callMsg = method_call.Message;
callMsg.AttachBodyTo(writer);
bool needsReply = true;
callMsg.ReplyExpected = needsReply;
callMsg.Signature = inSig;
if (!needsReply)
{
conn.Send(callMsg);
return null;
}
#if PROTO_REPLY_SIGNATURE
if (needsReply) {
Signature outSig = Signature.GetSig (retType);
callMsg.Header[FieldCode.ReplySignature] = outSig;
}
#endif
Message retMsg = await conn.SendWithReply(callMsg).ConfigureAwait(false);
MessageReader retVal = null;
//handle the reply message
switch (retMsg.Header.MessageType)
{
case MessageType.MethodReturn:
retVal = new MessageReader(retMsg);
break;
case MessageType.Error:
MessageContainer error = MessageContainer.FromMessage(retMsg);
string errMsg = String.Empty;
if (retMsg.Signature.Value.StartsWith("s"))
{
MessageReader reader = new MessageReader(retMsg);
errMsg = reader.ReadString();
}
throw new Exception(error.ErrorName + ": " + errMsg);
default:
throw new Exception("Got unexpected message of type " + retMsg.Header.MessageType + " while waiting for a MethodReturn or Error");
}
return retVal;
}
// c.f. https://github.com/mono/dbus-sharp/pull/37
// for both property methods
public async Task<object> SendPropertyGet(string iface, string property)
{
var writer = new MessageWriter();
writer.Write(iface);
writer.Write(property);
var reader = await SendMethodCall("org.freedesktop.DBus.Properties", "Get", "ss", writer, typeof(object)).ConfigureAwait(false);
return reader.ReadValue(typeof(object));
}
public Task SendPropertySet(string iface, string property, object value)
{
var writer = new MessageWriter();
writer.Write(iface);
writer.Write(property);
writer.Write(typeof(object), value);
return SendMethodCall("org.freedesktop.DBus.Properties", "Set", "ssv", writer, typeof(void));
}
public Task InvokeAsync(MethodBase methodBase, string methodName, object[] inArgs, out object[] outArgs, out object retVal, out Exception exception)
{
outArgs = new object[0];
retVal = null;
exception = null;
MethodInfo mi = methodBase as MethodInfo;
if (mi != null && mi.IsSpecialName && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
{
string[] parts = methodName.Split(new char[] { '_' }, 2);
string ename = parts[1];
Delegate dlg = (Delegate)inArgs[0];
return ToggleSignalAsync(Mapper.GetInterfaceName(mi), ename, dlg, parts[0] == "add");
}
Type[] inTypes = Mapper.GetTypes(ArgDirection.In, mi.GetParameters());
Signature inSig = Signature.GetSig(inTypes);
string iface = null;
if (mi != null)
iface = Mapper.GetInterfaceName(mi);
if (mi != null && mi.IsSpecialName)
{
methodName = methodName.Replace("get_", "Get");
methodName = methodName.Replace("set_", "Set");
}
MessageWriter writer = new MessageWriter(conn);
if (inArgs != null && inArgs.Length != 0)
{
for (int i = 0; i != inTypes.Length; i++)
writer.Write(inTypes[i], inArgs[i]);
}
MessageReader reader = null;
try
{
reader = SendMethodCall(iface, methodName, inSig.Value, writer, mi.ReturnType).Result;
}
catch (Exception e)
{
exception = e;
}
if (reader != null)
retVal = reader.ReadValue(mi.ReturnType);
return Task.FromResult(0);
}
public static object GetObject(Connection conn, string bus_name, ObjectPath object_path, Type declType)
{
Type proxyType = TypeImplementer.Root.GetImplementation(declType);
object instObj = Activator.CreateInstance(proxyType);
BusObject inst = GetBusObject(instObj);
inst.conn = conn;
inst.bus_name = bus_name;
inst.object_path = object_path;
return instObj;
}
public static BusObject GetBusObject(object instObj)
{
if (instObj is BusObject)
return (BusObject)instObj;
BusObject inst;
if (boCache.TryGetValue(instObj, out inst))
return inst;
inst = new BusObject();
boCache[instObj] = inst;
return inst;
}
public Delegate GetHookupDelegate(EventInfo ei)
{
DynamicMethod hookupMethod = TypeImplementer.GetHookupMethod(ei);
Delegate d = hookupMethod.CreateDelegate(ei.EventHandlerType, this);
return d;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using System.Collections;
namespace Newtonsoft.Json.Utilities
{
internal static class CollectionUtils
{
public static List<T> CreateList<T>(params T[] values)
{
return new List<T>(values);
}
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty(ICollection collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(ICollection<T> collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Determines whether the collection is null, empty or its contents are uninitialized values.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty or its contents are uninitialized values; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmptyOrDefault<T>(IList<T> list)
{
if (IsNullOrEmpty<T>(list))
return true;
return ReflectionUtils.ItemsUnitializedValue<T>(list);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end)
{
return Slice<T>(list, start, end, null);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes,
/// getting every so many items based upon the step.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <param name="step">The step.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end, int? step)
{
if (list == null)
throw new ArgumentNullException("list");
if (step == 0)
throw new ArgumentException("Step cannot be zero.", "step");
List<T> slicedList = new List<T>();
// nothing to slice
if (list.Count == 0)
return slicedList;
// set defaults for null arguments
int s = step ?? 1;
int startIndex = start ?? 0;
int endIndex = end ?? list.Count;
// start from the end of the list if start is negitive
startIndex = (startIndex < 0) ? list.Count + startIndex : startIndex;
// end from the start of the list if end is negitive
endIndex = (endIndex < 0) ? list.Count + endIndex : endIndex;
// ensure indexes keep within collection bounds
startIndex = Math.Max(startIndex, 0);
endIndex = Math.Min(endIndex, list.Count - 1);
// loop between start and end indexes, incrementing by the step
for (int i = startIndex; i < endIndex; i += s)
{
slicedList.Add(list[i]);
}
return slicedList;
}
/// <summary>
/// Group the collection using a function which returns the key.
/// </summary>
/// <param name="source">The source collection to group.</param>
/// <param name="keySelector">The key selector.</param>
/// <returns>A Dictionary with each key relating to a list of objects in a list grouped under it.</returns>
public static Dictionary<K, List<V>> GroupBy<K, V>(ICollection<V> source, Func<V, K> keySelector)
{
if (keySelector == null)
throw new ArgumentNullException("keySelector");
Dictionary<K, List<V>> groupedValues = new Dictionary<K, List<V>>();
foreach (V value in source)
{
// using delegate to get the value's key
K key = keySelector(value);
List<V> groupedValueList;
// add a list for grouped values if the key is not already in Dictionary
if (!groupedValues.TryGetValue(key, out groupedValueList))
{
groupedValueList = new List<V>();
groupedValues.Add(key, groupedValueList);
}
groupedValueList.Add(value);
}
return groupedValues;
}
/// <summary>
/// Adds the elements of the specified collection to the specified generic IList.
/// </summary>
/// <param name="initial">The list to add to.</param>
/// <param name="collection">The collection of elements to add.</param>
public static void AddRange<T>(IList<T> initial, IEnumerable<T> collection)
{
if (initial == null)
throw new ArgumentNullException("initial");
if (collection == null)
return;
foreach (T value in collection)
{
initial.Add(value);
}
}
public static List<T> Distinct<T>(List<T> collection)
{
List<T> distinctList = new List<T>();
foreach (T value in collection)
{
if (!distinctList.Contains(value))
distinctList.Add(value);
}
return distinctList;
}
public static List<List<T>> Flatten<T>(params IList<T>[] lists)
{
List<List<T>> flattened = new List<List<T>>();
Dictionary<int, T> currentList = new Dictionary<int, T>();
Recurse<T>(new List<IList<T>>(lists), 0, currentList, flattened);
return flattened;
}
private static void Recurse<T>(IList<IList<T>> global, int current, Dictionary<int, T> currentSet, List<List<T>> flattenedResult)
{
IList<T> currentArray = global[current];
for (int i = 0; i < currentArray.Count; i++)
{
currentSet[current] = currentArray[i];
if (current == global.Count - 1)
{
List<T> items = new List<T>();
for (int k = 0; k < currentSet.Count; k++)
{
items.Add(currentSet[k]);
}
flattenedResult.Add(items);
}
else
{
Recurse(global, current + 1, currentSet, flattenedResult);
}
}
}
public static List<T> CreateList<T>(ICollection collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return new List<T>(array);
}
public static bool ListEquals<T>(IList<T> a, IList<T> b)
{
if (a == null || b == null)
return (a == null && b == null);
if (a.Count != b.Count)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a.Count; i++)
{
if (!comparer.Equals(a[i], b[i]))
return false;
}
return true;
}
#region GetSingleItem
public static bool TryGetSingleItem<T>(IList<T> list, out T value)
{
return TryGetSingleItem<T>(list, false, out value);
}
public static bool TryGetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty, out T value)
{
return MiscellaneousUtils.TryAction<T>(delegate { return GetSingleItem(list, returnDefaultIfEmpty); }, out value);
}
public static T GetSingleItem<T>(IList<T> list)
{
return GetSingleItem<T>(list, false);
}
public static T GetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty)
{
if (list.Count == 1)
return list[0];
else if (returnDefaultIfEmpty && list.Count == 0)
return default(T);
else
throw new Exception(string.Format("Expected single {0} in list but got {1}.", typeof(T), list.Count));
}
#endregion
public static IList<T> Minus<T>(IList<T> list, IList<T> minus)
{
ValidationUtils.ArgumentNotNull(list, "list");
List<T> result = new List<T>(list.Count);
foreach (T t in list)
{
if (minus == null || !minus.Contains(t))
result.Add(t);
}
return result;
}
public static T[] CreateArray<T>(IEnumerable<T> enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
if (enumerable is T[])
return (T[])enumerable;
List<T> tempList = new List<T>(enumerable);
return tempList.ToArray();
}
public static object CreateGenericList(Type listType)
{
ValidationUtils.ArgumentNotNull(listType, "listType");
return ReflectionUtils.CreateGeneric(typeof(List<>), listType);
}
public static bool IsListType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "listType");
if (type.IsArray)
return true;
else if (typeof(IList).IsAssignableFrom(type))
return true;
else if (ReflectionUtils.IsSubClass(type, typeof(IList<>)))
return true;
else
return false;
}
public static IList CreateAndPopulateList(Type listType, Action<IList> populateList)
{
ValidationUtils.ArgumentNotNull(listType, "listType");
ValidationUtils.ArgumentNotNull(populateList, "populateList");
IList list;
Type readOnlyCollectionType;
bool isReadOnlyOrFixedSize = false;
if (listType.IsArray)
{
// have to use an arraylist when creating array
// there is no way to know the size until it is finised
list = new ArrayList();
isReadOnlyOrFixedSize = true;
}
else if (ReflectionUtils.IsSubClass(listType, typeof(ReadOnlyCollection<>), out readOnlyCollectionType))
{
Type readOnlyCollectionContentsType = readOnlyCollectionType.GetGenericArguments()[0];
Type genericEnumerable = ReflectionUtils.MakeGenericType(typeof(IEnumerable<>), readOnlyCollectionContentsType);
bool suitableConstructor = false;
foreach (ConstructorInfo constructor in listType.GetConstructors())
{
IList<ParameterInfo> parameters = constructor.GetParameters();
if (parameters.Count == 1)
{
if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType))
{
suitableConstructor = true;
break;
}
}
}
if (!suitableConstructor)
throw new Exception(string.Format("Readonly type {0} does not have a public constructor that takes a type that implements {1}.", listType, genericEnumerable));
// can't add or modify a readonly list
// use List<T> and convert once populated
list = (IList)CreateGenericList(readOnlyCollectionContentsType);
isReadOnlyOrFixedSize = true;
}
else if (typeof(IList).IsAssignableFrom(listType) && ReflectionUtils.IsInstantiatableType(listType))
{
list = (IList)Activator.CreateInstance(listType);
}
else
{
throw new Exception(string.Format("Cannot create and populate list type {0}.", listType));
}
populateList(list);
// create readonly and fixed sized collections using the temporary list
if (isReadOnlyOrFixedSize)
{
if (listType.IsArray)
list = ((ArrayList)list).ToArray(ReflectionUtils.GetListItemType(listType));
else if (ReflectionUtils.IsSubClass(listType, typeof(ReadOnlyCollection<>)))
list = (IList)Activator.CreateInstance(listType, list);
}
return list;
}
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, 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.IO;
using System.Text;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Util
{
public class URIUtils
{
/// <summary>Index of a component which was not found.</summary>
/// <remarks>Index of a component which was not found.</remarks>
private const int NotFound = -1;
/// <summary>Default encoding.</summary>
/// <remarks>Default encoding.</remarks>
private const string Utf8Encoding = "UTF-8";
/// <summary>
/// Error message presented when a user tries to treat an opaque URI as
/// hierarchical.
/// </summary>
/// <remarks>
/// Error message presented when a user tries to treat an opaque URI as
/// hierarchical.
/// </remarks>
private const string NotHierarchical = "This isn't a hierarchical URI.";
// COPY: Partially copied from android.net.Uri
// COPY: Partially copied from libcore.net.UriCodec
public static string Decode(string s)
{
if (s == null)
{
return null;
}
try
{
return URLDecoder.Decode(s, Utf8Encoding);
}
catch (UnsupportedEncodingException e)
{
// This is highly unlikely since we always use UTF-8 encoding.
throw new RuntimeException(e);
}
}
/// <summary>Searches the query string for the first value with the given key.</summary>
/// <remarks>Searches the query string for the first value with the given key.</remarks>
/// <param name="key">which will be encoded</param>
/// <exception cref="System.NotSupportedException">if this isn't a hierarchical URI</exception>
/// <exception cref="System.ArgumentNullException">if key is null</exception>
/// <returns>the decoded value or null if no parameter is found</returns>
public static string GetQueryParameter(URI uri, string key)
{
if (uri.IsOpaque())
{
throw new NotSupportedException(NotHierarchical);
}
if (key == null)
{
throw new ArgumentNullException("key");
}
string query = uri.GetRawQuery();
if (query == null)
{
return null;
}
string encodedKey = Encode(key, null);
int length = query.Length;
int start = 0;
do
{
int nextAmpersand = query.IndexOf('&', start);
int end = nextAmpersand != -1 ? nextAmpersand : length;
int separator = query.IndexOf('=', start);
if (separator > end || separator == -1)
{
separator = end;
}
if (separator - start == encodedKey.Length && query.RegionMatches(start, encodedKey
, 0, encodedKey.Length))
{
if (separator == end)
{
return string.Empty;
}
else
{
string encodedValue = Sharpen.Runtime.Substring(query, separator + 1, end);
return Decode(encodedValue, true, Sharpen.Extensions.GetEncoding(Utf8Encoding));
}
}
// Move start to end of name.
if (nextAmpersand != -1)
{
start = nextAmpersand + 1;
}
else
{
break;
}
}
while (true);
return null;
}
private static readonly char[] HexDigits = "0123456789ABCDEF".ToCharArray();
/// <summary>
/// Encodes characters in the given string as '%'-escaped octets
/// using the UTF-8 scheme.
/// </summary>
/// <remarks>
/// Encodes characters in the given string as '%'-escaped octets
/// using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
/// ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
/// all other characters.
/// </remarks>
/// <param name="s">string to encode</param>
/// <returns>
/// an encoded version of s suitable for use as a URI component,
/// or null if s is null
/// </returns>
public static string Encode(string s)
{
return Encode(s, null);
}
/// <summary>
/// Encodes characters in the given string as '%'-escaped octets
/// using the UTF-8 scheme.
/// </summary>
/// <remarks>
/// Encodes characters in the given string as '%'-escaped octets
/// using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
/// ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
/// all other characters with the exception of those specified in the
/// allow argument.
/// </remarks>
/// <param name="s">string to encode</param>
/// <param name="allow">
/// set of additional characters to allow in the encoded form,
/// null if no characters should be skipped
/// </param>
/// <returns>
/// an encoded version of s suitable for use as a URI component,
/// or null if s is null
/// </returns>
public static string Encode(string s, string allow)
{
if (s == null)
{
return null;
}
// Lazily-initialized buffers.
StringBuilder encoded = null;
int oldLength = s.Length;
// This loop alternates between copying over allowed characters and
// encoding in chunks. This results in fewer method calls and
// allocations than encoding one character at a time.
int current = 0;
while (current < oldLength)
{
// Start in "copying" mode where we copy over allowed chars.
// Find the next character which needs to be encoded.
int nextToEncode = current;
while (nextToEncode < oldLength && IsAllowed(s[nextToEncode], allow))
{
nextToEncode++;
}
// If there's nothing more to encode...
if (nextToEncode == oldLength)
{
if (current == 0)
{
// We didn't need to encode anything!
return s;
}
else
{
// Presumably, we've already done some encoding.
encoded.AppendRange(s, current, oldLength);
return encoded.ToString();
}
}
if (encoded == null)
{
encoded = new StringBuilder();
}
if (nextToEncode > current)
{
// Append allowed characters leading up to this point.
encoded.AppendRange(s, current, nextToEncode);
}
// assert nextToEncode == current
// Switch to "encoding" mode.
// Find the next allowed character.
current = nextToEncode;
int nextAllowed = current + 1;
while (nextAllowed < oldLength && !IsAllowed(s[nextAllowed], allow))
{
nextAllowed++;
}
// Convert the substring to bytes and encode the bytes as
// '%'-escaped octets.
string toEncode = Sharpen.Runtime.Substring(s, current, nextAllowed);
try
{
byte[] bytes = Sharpen.Runtime.GetBytesForString(toEncode, Utf8Encoding);
int bytesLength = bytes.Length;
for (int i = 0; i < bytesLength; i++)
{
encoded.Append('%');
encoded.Append(HexDigits[(bytes[i] & unchecked((int)(0xf0))) >> 4]);
encoded.Append(HexDigits[bytes[i] & unchecked((int)(0xf))]);
}
}
catch (UnsupportedEncodingException e)
{
throw new Exception(e);
}
current = nextAllowed;
}
// Encoded could still be null at this point if s is empty.
return encoded == null ? s : encoded.ToString();
}
/// <summary>Returns true if the given character is allowed.</summary>
/// <remarks>Returns true if the given character is allowed.</remarks>
/// <param name="c">character to check</param>
/// <param name="allow">characters to allow</param>
/// <returns>
/// true if the character is allowed or false if it should be
/// encoded
/// </returns>
private static bool IsAllowed(char c, string allow)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| "_-!.~'()*".IndexOf(c) != NotFound || (allow != null && allow.IndexOf(c) !=
NotFound);
}
// COPY: Copied from libcore.net.UriCodec
/// <param name="convertPlus">true to convert '+' to ' '.</param>
public static string Decode(string s, bool convertPlus, Encoding charset)
{
if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1))
{
return s;
}
StringBuilder result = new StringBuilder(s.Length);
ByteArrayOutputStream @out = new ByteArrayOutputStream();
for (int i = 0; i < s.Length; )
{
char c = s[i];
if (c == '%')
{
do
{
if (i + 2 >= s.Length)
{
throw new ArgumentException("Incomplete % sequence at: " + i);
}
int d1 = HexToInt(s[i + 1]);
int d2 = HexToInt(s[i + 2]);
if (d1 == -1 || d2 == -1)
{
throw new ArgumentException("Invalid % sequence " + Sharpen.Runtime.Substring(s,
i, i + 3) + " at " + i);
}
@out.Write(unchecked((byte)((d1 << 4) + d2)));
i += 3;
}
while (i < s.Length && s[i] == '%');
result.Append(new string(@out.ToByteArray(), charset));
@out.Reset();
}
else
{
if (convertPlus && c == '+')
{
c = ' ';
}
result.Append(c);
i++;
}
}
return result.ToString();
}
// COPY: Copied from libcore.net.UriCodec
/// <summary>
/// Like
/// <see cref="char.Digit(char, int)">char.Digit(char, int)</see>
/// , but without support for non-ASCII
/// characters.
/// </summary>
private static int HexToInt(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
else
{
if ('a' <= c && c <= 'f')
{
return 10 + (c - 'a');
}
else
{
if ('A' <= c && c <= 'F')
{
return 10 + (c - 'A');
}
else
{
return -1;
}
}
}
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpImplementStandardExceptionConstructorsAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ImplementStandardExceptionConstructorsFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicImplementStandardExceptionConstructorsAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ImplementStandardExceptionConstructorsFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class ImplementStandardExceptionConstructorsFixerTests
{
#region CSharpUnitTests
//Note: In the test cases you won't see a missing all 3 constructors scenario, because that will never occur since default constructor is always generated by system in that case
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2292")]
public async Task TestCSFixMissingTwoCtors_Case1()
{
var code = @"
using System;
public class [|[|SomeException|]|] : Exception
{
public SomeException()
{
}
}
";
var fix = @"
using System;
public class SomeException : Exception
{
public SomeException()
{
}
public SomeException(string message) : base(message)
{
}
public SomeException(string message, Exception innerException) : base(message, innerException)
{
}
}
";
await new VerifyCS.Test
{
TestState = { Sources = { code } },
FixedState = { Sources = { fix } },
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2292")]
public async Task TestCSFixMissingTwoCtors_Case2()
{
var code = @"
using System;
public class [|[|SomeException|]|] : Exception
{
public SomeException(string message)
{
}
}
";
var fix = @"
using System;
public class SomeException : Exception
{
public SomeException(string message)
{
}
public SomeException()
{
}
public SomeException(string message, Exception innerException) : base(message, innerException)
{
}
}
";
await new VerifyCS.Test
{
TestState = { Sources = { code } },
FixedState = { Sources = { fix } },
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2292")]
public async Task TestCSFixMissingTwoCtors_Case3()
{
var code = @"
using System;
public class [|[|SomeException|]|] : Exception
{
public SomeException(string message, Exception innerException)
{
}
}
";
var fix = @"
using System;
public class SomeException : Exception
{
public SomeException(string message, Exception innerException)
{
}
public SomeException()
{
}
public SomeException(string message) : base(message)
{
}
}
";
await new VerifyCS.Test
{
TestState = { Sources = { code } },
FixedState = { Sources = { fix } },
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[Fact]
public async Task TestCSFixMissingOneCtor_Case1()
{
var code = @"
using System;
public class [|SomeException|] : Exception
{
public SomeException(string message): base(message)
{
}
public SomeException(string message, Exception innerException) : base(message, innerException)
{
}
}
";
var fix = @"
using System;
public class SomeException : Exception
{
public SomeException(string message): base(message)
{
}
public SomeException(string message, Exception innerException) : base(message, innerException)
{
}
public SomeException()
{
}
}
";
await VerifyCS.VerifyCodeFixAsync(code, fix);
}
[Fact]
public async Task TestCSFixMissingOneCtor_Case2()
{
var code = @"
using System;
public class [|SomeException|] : Exception
{
public SomeException()
{
}
public SomeException(string message)
{
}
}
";
var fix = @"
using System;
public class SomeException : Exception
{
public SomeException()
{
}
public SomeException(string message)
{
}
public SomeException(string message, Exception innerException) : base(message, innerException)
{
}
}
";
await VerifyCS.VerifyCodeFixAsync(code, fix);
}
[Fact]
public async Task TestCSFixMissingOneCtor_Case3()
{
var code = @"
using System;
public class [|SomeException|] : Exception
{
public SomeException()
{
}
public SomeException(string message, Exception innerException)
{
}
}
";
var fix = @"
using System;
public class SomeException : Exception
{
public SomeException()
{
}
public SomeException(string message, Exception innerException)
{
}
public SomeException(string message) : base(message)
{
}
}
";
await VerifyCS.VerifyCodeFixAsync(code, fix);
}
#endregion
#region BasicUnitTests
//Note: In the test cases you won't see a missing all 3 constructors scenario, because that will never occur since default constructor is always generated by system in that case
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2292")]
public async Task TestVBFixMissingTwoCtors_Case1()
{
var code = @"
Imports System
Public Class [|[|SomeException|]|] : Inherits Exception
Public Sub New()
End Sub
End Class
";
var fix = @"
Imports System
Public Class SomeException : Inherits Exception
Public Sub New()
End Sub
Public Sub New(message As String)
MyBase.New(message)
End Sub
Public Sub New(message As String, innerException As Exception)
MyBase.New(message, innerException)
End Sub
End Class
";
await new VerifyVB.Test
{
TestState = { Sources = { code } },
FixedState = { Sources = { fix } },
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2292")]
public async Task TestVBFixMissingTwoCtors_Case2()
{
var code = @"
Imports System
Public Class [|[|SomeException|]|] : Inherits Exception
Public Sub New(message As String)
End Sub
End Class
";
var fix = @"
Imports System
Public Class SomeException : Inherits Exception
Public Sub New(message As String)
End Sub
Public Sub New()
End Sub
Public Sub New(message As String, innerException As Exception)
MyBase.New(message, innerException)
End Sub
End Class
";
await new VerifyVB.Test
{
TestState = { Sources = { code } },
FixedState = { Sources = { fix } },
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/2292")]
public async Task TestVBFixMissingTwoCtors_Case3()
{
var code = @"
Imports System
Public Class [|[|SomeException|]|] : Inherits Exception
Public Sub New(message As String, innerException As Exception)
End Sub
End Class
";
var fix = @"
Imports System
Public Class SomeException : Inherits Exception
Public Sub New(message As String, innerException As Exception)
End Sub
Public Sub New()
End Sub
Public Sub New(message As String)
MyBase.New(message)
End Sub
End Class
";
await new VerifyVB.Test
{
TestState = { Sources = { code } },
FixedState = { Sources = { fix } },
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[Fact]
public async Task TestVBFixMissingOneCtor_Case1()
{
var code = @"
Imports System
Public Class [|SomeException|] : Inherits Exception
Public Sub New()
End Sub
Public Sub New(message As String)
End Sub
End Class
";
var fix = @"
Imports System
Public Class SomeException : Inherits Exception
Public Sub New()
End Sub
Public Sub New(message As String)
End Sub
Public Sub New(message As String, innerException As Exception)
MyBase.New(message, innerException)
End Sub
End Class
";
await VerifyVB.VerifyCodeFixAsync(code, fix);
}
[Fact]
public async Task TestVBFixMissingOneCtor_Case2()
{
var code = @"
Imports System
Public Class [|SomeException|] : Inherits Exception
Public Sub New()
End Sub
Public Sub New(message As String, innerException As Exception)
End Sub
End Class
";
var fix = @"
Imports System
Public Class SomeException : Inherits Exception
Public Sub New()
End Sub
Public Sub New(message As String, innerException As Exception)
End Sub
Public Sub New(message As String)
MyBase.New(message)
End Sub
End Class
";
await VerifyVB.VerifyCodeFixAsync(code, fix);
}
[Fact]
public async Task TestVBFixMissingOneCtor_Case3()
{
var code = @"
Imports System
Public Class [|SomeException|] : Inherits Exception
Public Sub New(message As String)
End Sub
Public Sub New(message As String, innerException As Exception)
End Sub
End Class
";
var fix = @"
Imports System
Public Class SomeException : Inherits Exception
Public Sub New(message As String)
End Sub
Public Sub New(message As String, innerException As Exception)
End Sub
Public Sub New()
End Sub
End Class
";
await VerifyVB.VerifyCodeFixAsync(code, fix);
}
#endregion
}
}
| |
// Copyright (C) 2004-2007 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation
//
// There are special exceptions to the terms and conditions of the GPL
// as it is applied to this software. View the full text of the
// exception in file EXCEPTIONS in the directory of this software
// distribution.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Collections;
using System.Text;
using MySql.Data.Common;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using MySql.Data.MySqlClient.Properties;
namespace MySql.Data.MySqlClient
{
/// <include file='docs/mysqlcommand.xml' path='docs/ClassSummary/*'/>
public sealed class MySqlCommand : DbCommand
{
MySqlConnection connection;
MySqlTransaction curTransaction;
string cmdText;
CommandType cmdType;
long updatedRowCount;
UpdateRowSource updatedRowSource;
MySqlParameterCollection parameters;
private int cursorPageSize;
private IAsyncResult asyncResult;
private bool designTimeVisible;
internal Int64 lastInsertedId;
private PreparableStatement statement;
private int commandTimeout;
private bool timedOut, canceled;
private bool resetSqlSelect;
List<MySqlCommand> batch;
private string batchableCommandText;
internal string parameterHash;
/// <include file='docs/mysqlcommand.xml' path='docs/ctor1/*'/>
public MySqlCommand()
{
designTimeVisible = true;
cmdType = CommandType.Text;
parameters = new MySqlParameterCollection(this);
updatedRowSource = UpdateRowSource.Both;
cursorPageSize = 0;
cmdText = String.Empty;
timedOut = false;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ctor2/*'/>
public MySqlCommand(string cmdText)
: this()
{
CommandText = cmdText;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ctor3/*'/>
public MySqlCommand(string cmdText, MySqlConnection connection)
: this(cmdText)
{
Connection = connection;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ctor4/*'/>
public MySqlCommand(string cmdText, MySqlConnection connection,
MySqlTransaction transaction)
:
this(cmdText, connection)
{
curTransaction = transaction;
}
#region Properties
/// <include file='docs/mysqlcommand.xml' path='docs/LastInseredId/*'/>
public Int64 LastInsertedId
{
get { return lastInsertedId; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/CommandText/*'/>
public override string CommandText
{
get { return cmdText; }
set
{
cmdText = value;
statement = null;
if (cmdText != null && cmdText.EndsWith("DEFAULT VALUES"))
{
cmdText = cmdText.Substring(0, cmdText.Length - 14);
cmdText = cmdText + "() VALUES ()";
}
}
}
internal int UpdateCount
{
get { return (int)updatedRowCount; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/CommandTimeout/*'/>
public override int CommandTimeout
{
get { return commandTimeout == 0 ? 30 : commandTimeout; }
set { commandTimeout = value; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/CommandType/*'/>
public override CommandType CommandType
{
get { return cmdType; }
set { cmdType = value; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/IsPrepared/*'/>
public bool IsPrepared
{
get { return statement != null && statement.IsPrepared; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/Connection/*'/>
public new MySqlConnection Connection
{
get { return connection; }
set
{
/*
* The connection is associated with the transaction
* so set the transaction object to return a null reference if the connection
* is reset.
*/
if (connection != value)
Transaction = null;
connection = value;
// if the user has not already set the command timeout, then
// take the default from the connection
if (connection != null && commandTimeout == 0)
commandTimeout = (int)connection.Settings.DefaultCommandTimeout;
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/Parameters/*'/>
public new MySqlParameterCollection Parameters
{
get { return parameters; }
}
/// <include file='docs/mysqlcommand.xml' path='docs/Transaction/*'/>
public new MySqlTransaction Transaction
{
get { return curTransaction; }
set { curTransaction = value; }
}
internal List<MySqlCommand> Batch
{
get { return batch; }
}
internal bool TimedOut
{
get { return timedOut; }
}
internal string BatchableCommandText
{
get { return batchableCommandText; }
}
#endregion
#region Methods
/// <summary>
/// Attempts to cancel the execution of a MySqlCommand.
/// </summary>
/// <remarks>
/// Cancelling a currently active query only works with MySQL versions 5.0.0 and higher.
/// </remarks>
public override void Cancel()
{
if (!connection.driver.Version.isAtLeast(5, 0, 0))
throw new NotSupportedException(Resources.CancelNotSupported);
MySqlConnectionStringBuilder cb = new MySqlConnectionStringBuilder(
connection.Settings.GetConnectionString(true));
cb.Pooling = false;
using(MySqlConnection c = new MySqlConnection(cb.ConnectionString))
{
c.Open();
MySqlCommand cmd = new MySqlCommand(String.Format("KILL QUERY {0}",
connection.ServerThread), c);
cmd.ExecuteNonQuery();
canceled = true;
}
}
/// <summary>
/// Creates a new instance of a <see cref="MySqlParameter"/> object.
/// </summary>
/// <remarks>
/// This method is a strongly-typed version of <see cref="IDbCommand.CreateParameter"/>.
/// </remarks>
/// <returns>A <see cref="MySqlParameter"/> object.</returns>
///
public new MySqlParameter CreateParameter()
{
return (MySqlParameter)CreateDbParameter();
}
/// <summary>
/// Check the connection to make sure
/// - it is open
/// - it is not currently being used by a reader
/// - and we have the right version of MySQL for the requested command type
/// </summary>
private void CheckState()
{
// There must be a valid and open connection.
if (connection == null)
throw new InvalidOperationException("Connection must be valid and open.");
if (connection.State != ConnectionState.Open && !connection.SoftClosed)
throw new InvalidOperationException("Connection must be valid and open.");
// Data readers have to be closed first
if (connection.Reader != null && cursorPageSize == 0)
throw new MySqlException("There is already an open DataReader associated with this Connection which must be closed first.");
if (CommandType == CommandType.StoredProcedure && !connection.driver.Version.isAtLeast(5, 0, 0))
throw new MySqlException("Stored procedures are not supported on this version of MySQL");
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteNonQuery/*'/>
public override int ExecuteNonQuery()
{
lastInsertedId = -1;
updatedRowCount = -1;
MySqlDataReader reader = ExecuteReader();
if (reader != null)
{
reader.Close();
lastInsertedId = reader.InsertedId;
updatedRowCount = reader.RecordsAffected;
}
return (int)updatedRowCount;
}
internal void Close()
{
if (statement != null)
statement.Close();
ResetSqlSelectLimit();
}
/// <summary>
/// Reset SQL_SELECT_LIMIT that could have been modified by CommandBehavior.
/// </summary>
internal void ResetSqlSelectLimit()
{
// if we are supposed to reset the sql select limit, do that here
if (resetSqlSelect)
new MySqlCommand("SET SQL_SELECT_LIMIT=-1", connection).ExecuteNonQuery();
resetSqlSelect = false;
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteReader/*'/>
public new MySqlDataReader ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
private void TimeoutExpired(object commandObject)
{
MySqlCommand cmd = (commandObject as MySqlCommand);
if (cmd == null)
{
Logger.LogWarning(Resources.TimeoutExpiredNullObject);
return;
}
cmd.timedOut = true;
try
{
cmd.Cancel();
}
catch (Exception ex)
{
// if something goes wrong, we log it and eat it. There's really nothing
// else we can do.
if (connection.Settings.Logging)
Logger.LogException(ex);
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteReader1/*'/>
public new MySqlDataReader ExecuteReader(CommandBehavior behavior)
{
lastInsertedId = -1;
CheckState();
if (cmdText == null ||
cmdText.Trim().Length == 0)
throw new InvalidOperationException(Resources.CommandTextNotInitialized);
string sql = TrimSemicolons(cmdText);
// now we check to see if we are executing a query that is buggy
// in 4.1
connection.IsExecutingBuggyQuery = false;
if (!connection.driver.Version.isAtLeast(5, 0, 0) &&
connection.driver.Version.isAtLeast(4, 1, 0))
{
string snippet = sql;
if (snippet.Length > 17)
snippet = sql.Substring(0, 17);
snippet = snippet.ToLower();
connection.IsExecutingBuggyQuery =
snippet.StartsWith("describe") ||
snippet.StartsWith("show table status");
}
if (statement == null || !statement.IsPrepared)
{
if (CommandType == CommandType.StoredProcedure)
statement = new StoredProcedure(this, sql);
else
statement = new PreparableStatement(this, sql);
}
// stored procs are the only statement type that need do anything during resolve
statement.Resolve();
// Now that we have completed our resolve step, we can handle our
// command behaviors
HandleCommandBehaviors(behavior);
updatedRowCount = -1;
Timer timer = null;
try
{
MySqlDataReader reader = new MySqlDataReader(this, statement, behavior);
// start a threading timer on our command timeout
timedOut = false;
canceled = false;
// execute the statement
statement.Execute();
// start a timeout timer
if (connection.driver.Version.isAtLeast(5, 0, 0) &&
commandTimeout > 0)
{
TimerCallback timerDelegate =
new TimerCallback(TimeoutExpired);
timer = new Timer(timerDelegate, this, this.CommandTimeout * 1000, Timeout.Infinite);
}
// wait for data to return
reader.NextResult();
connection.Reader = reader;
return reader;
}
catch (MySqlException ex)
{
try
{
ResetSqlSelectLimit();
}
catch (Exception) { }
// if we caught an exception because of a cancel, then just return null
if (ex.Number == 1317)
{
if (TimedOut)
throw new MySqlException(Resources.Timeout);
return null;
}
if (ex.IsFatal)
Connection.Close();
if (ex.Number == 0)
throw new MySqlException(Resources.FatalErrorDuringExecute, ex);
throw;
}
finally
{
if (timer != null)
timer.Dispose();
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/ExecuteScalar/*'/>
public override object ExecuteScalar()
{
lastInsertedId = -1;
object val = null;
MySqlDataReader reader = ExecuteReader();
if (reader == null) return null;
try
{
if (reader.Read())
val = reader.GetValue(0);
}
finally
{
if (reader != null)
{
reader.Close();
lastInsertedId = reader.InsertedId;
}
reader = null;
}
return val;
}
private void HandleCommandBehaviors(CommandBehavior behavior)
{
if ((behavior & CommandBehavior.SchemaOnly) != 0)
{
new MySqlCommand("SET SQL_SELECT_LIMIT=0", connection).ExecuteNonQuery();
resetSqlSelect = true;
}
else if ((behavior & CommandBehavior.SingleRow) != 0)
{
new MySqlCommand("SET SQL_SELECT_LIMIT=1", connection).ExecuteNonQuery();
resetSqlSelect = true;
}
}
/// <include file='docs/mysqlcommand.xml' path='docs/Prepare2/*'/>
private void Prepare(int cursorPageSize)
{
if (!connection.driver.Version.isAtLeast(5, 0, 0) && cursorPageSize > 0)
throw new InvalidOperationException("Nested commands are only supported on MySQL 5.0 and later");
// if the length of the command text is zero, then just return
string psSQL = CommandText;
if (psSQL == null ||
psSQL.Trim().Length == 0)
return;
if (CommandType == CommandType.StoredProcedure)
statement = new StoredProcedure(this, CommandText);
else
statement = new PreparableStatement(this, CommandText);
statement.Prepare();
}
/// <include file='docs/mysqlcommand.xml' path='docs/Prepare/*'/>
public override void Prepare()
{
if (connection == null)
throw new InvalidOperationException("The connection property has not been set.");
if (connection.State != ConnectionState.Open)
throw new InvalidOperationException("The connection is not open.");
if (!connection.driver.Version.isAtLeast(4, 1, 0) ||
connection.Settings.IgnorePrepare)
return;
Prepare(0);
}
#endregion
#region Async Methods
internal delegate void AsyncDelegate(int type, CommandBehavior behavior);
internal Exception thrownException;
private static string TrimSemicolons(string sql)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(sql);
int start = 0;
while (sb[start] == ';')
start++;
int end = sb.Length - 1;
while (sb[end] == ';')
end--;
return sb.ToString(start, end - start + 1);
}
internal void AsyncExecuteWrapper(int type, CommandBehavior behavior)
{
thrownException = null;
try
{
if (type == 1)
ExecuteReader(behavior);
else
ExecuteNonQuery();
}
catch (Exception ex)
{
thrownException = ex;
}
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/>, and retrieves one or more
/// result sets from the server.
/// </summary>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll, wait for results,
/// or both; this value is also needed when invoking EndExecuteReader,
/// which returns a <see cref="MySqlDataReader"/> instance that can be used to retrieve
/// the returned rows. </returns>
public IAsyncResult BeginExecuteReader()
{
return BeginExecuteReader(CommandBehavior.Default);
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/> using one of the
/// <b>CommandBehavior</b> values.
/// </summary>
/// <param name="behavior">One of the <see cref="CommandBehavior"/> values, indicating
/// options for statement execution and data retrieval.</param>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll, wait for results,
/// or both; this value is also needed when invoking EndExecuteReader,
/// which returns a <see cref="MySqlDataReader"/> instance that can be used to retrieve
/// the returned rows. </returns>
public IAsyncResult BeginExecuteReader(CommandBehavior behavior)
{
AsyncDelegate del = new AsyncDelegate(AsyncExecuteWrapper);
asyncResult = del.BeginInvoke(1, behavior, null, null);
return asyncResult;
}
/// <summary>
/// Finishes asynchronous execution of a SQL statement, returning the requested
/// <see cref="MySqlDataReader"/>.
/// </summary>
/// <param name="result">The <see cref="IAsyncResult"/> returned by the call to
/// <see cref="BeginExecuteReader()"/>.</param>
/// <returns>A <b>MySqlDataReader</b> object that can be used to retrieve the requested rows. </returns>
public MySqlDataReader EndExecuteReader(IAsyncResult result)
{
result.AsyncWaitHandle.WaitOne();
if (thrownException != null)
throw thrownException;
return connection.Reader;
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/>.
/// </summary>
/// <param name="callback">
/// An <see cref="AsyncCallback"/> delegate that is invoked when the command's
/// execution has completed. Pass a null reference (<b>Nothing</b> in Visual Basic)
/// to indicate that no callback is required.</param>
/// <param name="stateObject">A user-defined state object that is passed to the
/// callback procedure. Retrieve this object from within the callback procedure
/// using the <see cref="IAsyncResult.AsyncState"/> property.</param>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll or wait for results,
/// or both; this value is also needed when invoking <see cref="EndExecuteNonQuery"/>,
/// which returns the number of affected rows. </returns>
public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject)
{
AsyncDelegate del = new AsyncDelegate(AsyncExecuteWrapper);
asyncResult = del.BeginInvoke(2, CommandBehavior.Default,
callback, stateObject);
return asyncResult;
}
/// <summary>
/// Initiates the asynchronous execution of the SQL statement or stored procedure
/// that is described by this <see cref="MySqlCommand"/>.
/// </summary>
/// <returns>An <see cref="IAsyncResult"/> that can be used to poll or wait for results,
/// or both; this value is also needed when invoking <see cref="EndExecuteNonQuery"/>,
/// which returns the number of affected rows. </returns>
public IAsyncResult BeginExecuteNonQuery()
{
AsyncDelegate del = new AsyncDelegate(AsyncExecuteWrapper);
asyncResult = del.BeginInvoke(2, CommandBehavior.Default, null, null);
return asyncResult;
}
/// <summary>
/// Finishes asynchronous execution of a SQL statement.
/// </summary>
/// <param name="asyncResult">The <see cref="IAsyncResult"/> returned by the call
/// to <see cref="BeginExecuteNonQuery()"/>.</param>
/// <returns></returns>
public int EndExecuteNonQuery(IAsyncResult asyncResult)
{
asyncResult.AsyncWaitHandle.WaitOne();
if (thrownException != null)
throw thrownException;
return (int)updatedRowCount;
}
#endregion
#region Private Methods
internal long EstimatedSize()
{
long size = CommandText.Length;
foreach (MySqlParameter parameter in Parameters)
size += parameter.EstimatedSize();
return size;
}
#endregion
#region Batching support
internal void AddToBatch(MySqlCommand command)
{
if (batch == null)
batch = new List<MySqlCommand>();
batch.Add(command);
}
internal string GetCommandTextForBatching()
{
if (batchableCommandText == null)
{
// if the command starts with insert and is "simple" enough, then
// we can use the multi-value form of insert
if (String.Compare(CommandText.Substring(0, 6), "INSERT", true) == 0)
{
MySqlCommand cmd = new MySqlCommand("SELECT @@sql_mode", Connection);
string sql_mode = cmd.ExecuteScalar().ToString().ToLower();
SqlTokenizer tokenizer = new SqlTokenizer(CommandText);
tokenizer.AnsiQuotes = sql_mode.IndexOf("ansi_quotes") != -1;
tokenizer.BackslashEscapes = sql_mode.IndexOf("no_backslash_escapes") == -1;
string token = tokenizer.NextToken().ToLower();
while (token != null)
{
if (token.ToLower() == "values" &&
!tokenizer.Quoted)
{
token = tokenizer.NextToken();
Debug.Assert(token == "(");
while (token != null && token != ")")
{
batchableCommandText += token;
token = tokenizer.NextToken();
}
if (token != null)
batchableCommandText += token;
token = tokenizer.NextToken();
if (token != null && (token == "," ||
token.ToLower() == "on"))
{
batchableCommandText = null;
break;
}
}
token = tokenizer.NextToken();
}
}
if (batchableCommandText == null)
batchableCommandText = CommandText;
}
return batchableCommandText;
}
#endregion
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (statement != null && statement.IsPrepared)
statement.CloseStatement();
}
base.Dispose(disposing);
}
/// <summary>
/// Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control.
/// </summary>
public override bool DesignTimeVisible
{
get
{
return designTimeVisible;
}
set
{
designTimeVisible = value;
}
}
/// <summary>
/// Gets or sets how command results are applied to the DataRow when used by the
/// Update method of the DbDataAdapter.
/// </summary>
public override UpdateRowSource UpdatedRowSource
{
get
{
return updatedRowSource;
}
set
{
updatedRowSource = value;
}
}
protected override DbParameter CreateDbParameter()
{
return new MySqlParameter();
}
protected override DbConnection DbConnection
{
get { return Connection; }
set { Connection = (MySqlConnection)value; }
}
protected override DbParameterCollection DbParameterCollection
{
get { return Parameters; }
}
protected override DbTransaction DbTransaction
{
get { return Transaction; }
set { Transaction = (MySqlTransaction)value; }
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// BSB Numbers
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KAB : EduHubEntity
{
#region Foreign Navigation Properties
private IReadOnlyList<ARF> Cache_BSB_ARF_BSB;
private IReadOnlyList<CR> Cache_BSB_CR_BSB;
private IReadOnlyList<CRF> Cache_BSB_CRF_BSB;
private IReadOnlyList<DFF> Cache_BSB_DFF_BSB;
private IReadOnlyList<DRF> Cache_BSB_DRF_BSB;
private IReadOnlyList<GLCF> Cache_BSB_GLCF_BSB;
private IReadOnlyList<GLF> Cache_BSB_GLF_BSB;
private IReadOnlyList<PEPM> Cache_BSB_PEPM_BSB;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Prime Key
/// [Alphanumeric (6)]
/// </summary>
public string BSB { get; internal set; }
/// <summary>
/// Bank name
/// [Alphanumeric (10)]
/// </summary>
public string BANK { get; internal set; }
/// <summary>
/// Bank address
/// [Alphanumeric (50)]
/// </summary>
public string ADDRESS { get; internal set; }
/// <summary>
/// Bank suburb
/// [Alphanumeric (30)]
/// </summary>
public string SUBURB { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Foreign Navigation Properties
/// <summary>
/// ARF (Asset Financial Transactions) related entities by [KAB.BSB]->[ARF.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<ARF> BSB_ARF_BSB
{
get
{
if (Cache_BSB_ARF_BSB == null &&
!Context.ARF.TryFindByBSB(BSB, out Cache_BSB_ARF_BSB))
{
Cache_BSB_ARF_BSB = new List<ARF>().AsReadOnly();
}
return Cache_BSB_ARF_BSB;
}
}
/// <summary>
/// CR (Accounts Payable) related entities by [KAB.BSB]->[CR.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<CR> BSB_CR_BSB
{
get
{
if (Cache_BSB_CR_BSB == null &&
!Context.CR.TryFindByBSB(BSB, out Cache_BSB_CR_BSB))
{
Cache_BSB_CR_BSB = new List<CR>().AsReadOnly();
}
return Cache_BSB_CR_BSB;
}
}
/// <summary>
/// CRF (Creditor Financial Transaction) related entities by [KAB.BSB]->[CRF.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<CRF> BSB_CRF_BSB
{
get
{
if (Cache_BSB_CRF_BSB == null &&
!Context.CRF.TryFindByBSB(BSB, out Cache_BSB_CRF_BSB))
{
Cache_BSB_CRF_BSB = new List<CRF>().AsReadOnly();
}
return Cache_BSB_CRF_BSB;
}
}
/// <summary>
/// DFF (Family Financial Transactions) related entities by [KAB.BSB]->[DFF.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<DFF> BSB_DFF_BSB
{
get
{
if (Cache_BSB_DFF_BSB == null &&
!Context.DFF.TryFindByBSB(BSB, out Cache_BSB_DFF_BSB))
{
Cache_BSB_DFF_BSB = new List<DFF>().AsReadOnly();
}
return Cache_BSB_DFF_BSB;
}
}
/// <summary>
/// DRF (DR Transactions) related entities by [KAB.BSB]->[DRF.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<DRF> BSB_DRF_BSB
{
get
{
if (Cache_BSB_DRF_BSB == null &&
!Context.DRF.TryFindByBSB(BSB, out Cache_BSB_DRF_BSB))
{
Cache_BSB_DRF_BSB = new List<DRF>().AsReadOnly();
}
return Cache_BSB_DRF_BSB;
}
}
/// <summary>
/// GLCF (GL Combined Financial Trans) related entities by [KAB.BSB]->[GLCF.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<GLCF> BSB_GLCF_BSB
{
get
{
if (Cache_BSB_GLCF_BSB == null &&
!Context.GLCF.TryFindByBSB(BSB, out Cache_BSB_GLCF_BSB))
{
Cache_BSB_GLCF_BSB = new List<GLCF>().AsReadOnly();
}
return Cache_BSB_GLCF_BSB;
}
}
/// <summary>
/// GLF (General Ledger Transactions) related entities by [KAB.BSB]->[GLF.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<GLF> BSB_GLF_BSB
{
get
{
if (Cache_BSB_GLF_BSB == null &&
!Context.GLF.TryFindByBSB(BSB, out Cache_BSB_GLF_BSB))
{
Cache_BSB_GLF_BSB = new List<GLF>().AsReadOnly();
}
return Cache_BSB_GLF_BSB;
}
}
/// <summary>
/// PEPM (Pay Methods) related entities by [KAB.BSB]->[PEPM.BSB]
/// Prime Key
/// </summary>
public IReadOnlyList<PEPM> BSB_PEPM_BSB
{
get
{
if (Cache_BSB_PEPM_BSB == null &&
!Context.PEPM.TryFindByBSB(BSB, out Cache_BSB_PEPM_BSB))
{
Cache_BSB_PEPM_BSB = new List<PEPM>().AsReadOnly();
}
return Cache_BSB_PEPM_BSB;
}
}
#endregion
}
}
| |
/*
* A custom task that walks a directory tree and creates a WiX fragment containing
* components to recreate it in an installer.
*
* From John Hall <[email protected]>, originally named "PackageTree" and posted on the wix-users mailing list
*
* John Hatton modified a bit to make it more general and started cleaning it up.
*
* Places a "".guidsForInstaller.xml" in each directory. THIS SHOULD BE CHECKED INTO VERSION CONTROL.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using ILogger=Palaso.BuildTasks.MakeWixForDirTree.ILogger;
namespace Palaso.BuildTasks.MakeWixForDirTree
{
public class MakeWixForDirTree : Task, ILogger
{
static public string kFileNameOfGuidDatabase = ".guidsForInstaller.xml";
#region Private data
private string _rootDir;
private string _outputFilePath;
private string[] _filesAndDirsToExclude = null;
private Regex _fileMatchPattern = new Regex(@".*");
private Regex _ignoreFilePattern = new Regex(@"IGNOREME");
//todo: this should just be a list
private Dictionary<string, string> m_exclude = new Dictionary<string, string>();
private bool m_checkOnly = false;
private List<string> m_components = new List<string>();
private Dictionary<string, int> m_suffixes = new Dictionary<string, int>();
private DateTime m_refDate = DateTime.MinValue;
private bool m_filesChanged = false;
private bool _hasLoggedErrors=false;
private string _directoryReferenceId;
private string _componentGroupId;
private bool _giveAllPermissions;
private const string XMLNS = "http://schemas.microsoft.com/wix/2006/wi";
#endregion
#region Public members
[Required]
public string RootDirectory
{
get { return _rootDir; }
set { _rootDir = value; }
}
/// <summary>
/// Subfolders and files to exclude. Kinda wonky. Using Ignore makes more sense.
/// </summary>
public string[] Exclude
{
get { return _filesAndDirsToExclude; }
set { _filesAndDirsToExclude = value; }
}
/// <summary>
/// Allow normal non-administrators to write and delete the files
/// </summary>
public bool GiveAllPermissions
{
get { return _giveAllPermissions; }
set { _giveAllPermissions = value; }
}
/*
* Regex pattern to match files. Defaults to .*
*/
public string MatchRegExPattern
{
get { return _fileMatchPattern.ToString(); }
set { _fileMatchPattern = new Regex(value, RegexOptions.IgnoreCase); }
}
/// <summary>
/// Will exclude if either the filename or the full path matches the expression.
/// </summary>
public string IgnoreRegExPattern
{
get { return _ignoreFilePattern.ToString(); }
set { _ignoreFilePattern = new Regex(value, RegexOptions.IgnoreCase); }
}
/// <summary>
/// Whether to just check that all the metadata is uptodate or not. If this is true then no file is output.
/// </summary>
public bool CheckOnly
{
get { return m_checkOnly; }
set { m_checkOnly = value; }
}
[Output, Required]
public string OutputFilePath
{
get { return _outputFilePath; }
set { _outputFilePath = value; }
}
public override bool Execute()
{
if (!Directory.Exists(_rootDir))
{
LogError("Directory not found: " + _rootDir);
return false;
}
LogMessage(MessageImportance.High, "Creating Wix fragment for " + _rootDir);
//make it an absolute path
_outputFilePath = Path.GetFullPath(_outputFilePath);
/* hatton removed this... it would leave deleted files referenced in the wxs file
if (File.Exists(_outputFilePath))
{
DateTime curFileDate = File.GetLastWriteTime(_outputFilePath);
m_refDate = curFileDate;
// if this assembly has been modified since the existing file was created then
// force the output to be updated
Assembly thisAssembly = Assembly.GetExecutingAssembly();
DateTime assemblyTime = File.GetLastWriteTime(thisAssembly.Location);
if (assemblyTime > curFileDate)
m_filesChanged = true;
}
*/
//instead, start afresh every time.
if(File.Exists(_outputFilePath))
{
File.Delete(_outputFilePath);
}
SetupExclusions();
try
{
XmlDocument doc = new XmlDocument();
XmlElement elemWix = doc.CreateElement("Wix", XMLNS);
doc.AppendChild(elemWix);
XmlElement elemFrag = doc.CreateElement("Fragment", XMLNS);
elemWix.AppendChild(elemFrag);
XmlElement elemDirRef = doc.CreateElement("DirectoryRef", XMLNS);
elemDirRef.SetAttribute("Id", DirectoryReferenceId);
elemFrag.AppendChild(elemDirRef);
// recurse through the tree add elements
ProcessDir(elemDirRef, Path.GetFullPath(_rootDir), DirectoryReferenceId);
// write out components into a group
XmlElement elemGroup = doc.CreateElement("ComponentGroup", XMLNS);
elemGroup.SetAttribute("Id", _componentGroupId);
elemFrag.AppendChild(elemGroup);
AddComponentRefsToDom(doc, elemGroup);
WriteDomToFile(doc);
}
catch (IOException e)
{
LogErrorFromException(e);
return false;
}
return !HasLoggedErrors;
}
/// <summary>
/// Though the guid-tracking *should* get stuff uninstalled, sometimes it does. So as an added precaution, delete the files on install and uninstall.
/// Note that the *.* here should uninstall even files that were in the previous install but not this one.
/// </summary>
/// <param name="elemFrag"></param>
private void InsertFileDeletionInstruction(XmlElement elemFrag)
{
//awkwardly, wix only allows this in <component>, not <directory>. Further, the directory deletion equivalent (RemoveFolder) can only delete completely empty folders.
var node = elemFrag.OwnerDocument.CreateElement("RemoveFile", XMLNS);
node.SetAttribute("Id", "_"+Guid.NewGuid().ToString().Replace("-",""));
node.SetAttribute("On", "both");//both = install time and uninstall time "uninstall");
node.SetAttribute("Name", "*.*");
elemFrag.AppendChild(node);
}
private void WriteDomToFile(XmlDocument doc)
{
// write the XML out onlystringles have been modified
if (!m_checkOnly && m_filesChanged)
{
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
settings.Encoding = Encoding.UTF8;
using (var xmlWriter = XmlWriter.Create(_outputFilePath, settings))
{
doc.WriteTo(xmlWriter);
}
}
}
private void AddComponentRefsToDom(XmlDocument doc, XmlElement elemGroup)
{
foreach (string c in m_components)
{
XmlElement elem = doc.CreateElement("ComponentRef", XMLNS);
elem.SetAttribute("Id", c);
elemGroup.AppendChild(elem);
}
}
private void SetupExclusions()
{
if (_filesAndDirsToExclude != null)
{
foreach (string s in _filesAndDirsToExclude)
{
string key;
if (Path.IsPathRooted(s))
key = s.ToLower();
else
key = Path.GetFullPath(Path.Combine(_rootDir, s)).ToLower();
m_exclude.Add(key, s);
}
}
}
public bool HasLoggedErrors
{
get { return _hasLoggedErrors; }
}
/// <summary>
/// will show up as: DirectoryRef Id="this property"
/// </summary>
public string DirectoryReferenceId
{
get { return _directoryReferenceId; }
set { _directoryReferenceId = value; }
}
public string ComponentGroupId
{
get { return _componentGroupId; }
set { _componentGroupId = value; }
}
public void LogErrorFromException(Exception e)
{
_hasLoggedErrors = true;
Log.LogErrorFromException(e);
}
public void LogError(string s)
{
_hasLoggedErrors = true;
Log.LogError(s);
}
public void LogWarning(string s)
{
Log.LogWarning(s);
}
private void ProcessDir(XmlElement parent, string dirPath, string outerDirectoryId)
{
LogMessage(MessageImportance.Low, "Processing dir {0}", dirPath);
XmlDocument doc = parent.OwnerDocument;
List<string> files = new List<string>();
IdToGuidDatabase guidDatabase = IdToGuidDatabase.Create(Path.Combine(dirPath, kFileNameOfGuidDatabase), this); ;
SetupDirectoryPermissions(dirPath, parent, outerDirectoryId, doc, guidDatabase);
// Build a list of the files in this directory removing any that have been exluded
foreach (string f in Directory.GetFiles(dirPath))
{
if (_fileMatchPattern.IsMatch(f) && !_ignoreFilePattern.IsMatch(f) && !_ignoreFilePattern.IsMatch(Path.GetFileName(f)) && !m_exclude.ContainsKey(f.ToLower())
&& !f.Contains(kFileNameOfGuidDatabase) )
files.Add(f);
}
// Process all files
bool isFirst = true;
foreach (string path in files)
{
ProcessFile(parent, path, doc, guidDatabase, isFirst, outerDirectoryId);
isFirst = false;
}
// Recursively process any subdirectories
foreach (string d in Directory.GetDirectories(dirPath))
{
string shortName = Path.GetFileName(d);
if (!m_exclude.ContainsKey(d.ToLower()) && shortName != ".svn" && shortName != "CVS")
{
string id = GetSafeDirectoryId(d, outerDirectoryId);
XmlElement elemDir = doc.CreateElement("Directory", XMLNS);
elemDir.SetAttribute("Id", id);
elemDir.SetAttribute("Name", shortName);
parent.AppendChild(elemDir);
ProcessDir(elemDir, d, id);
if (elemDir.ChildNodes.Count == 0)
parent.RemoveChild(elemDir);
}
}
}
private void SetupDirectoryPermissions(string dirPath, XmlElement parent, string parentDirectoryId, XmlDocument doc, IdToGuidDatabase guidDatabase)
{
if (_giveAllPermissions)
{
/* Need to add one of these in order to set the permissions on the directory
* <Component Id="biatahCacheDir" Guid="492F2725-9DF9-46B1-9ACE-E84E70AFEE99">
<CreateFolder Directory="biatahCacheDir">
<Permission GenericAll="yes" User="Everyone" />
</CreateFolder>
</Component>
*/
string id = GetSafeDirectoryId(string.Empty, parentDirectoryId);
XmlElement componentElement = doc.CreateElement("Component", XMLNS);
componentElement.SetAttribute("Id", id);
componentElement.SetAttribute("Guid", guidDatabase.GetGuid(id, this.CheckOnly));
XmlElement createFolderElement = doc.CreateElement("CreateFolder", XMLNS);
createFolderElement.SetAttribute("Directory", id);
AddPermissionElement(doc, createFolderElement);
componentElement.AppendChild(createFolderElement);
parent.AppendChild(componentElement);
m_components.Add(id);
}
}
private string GetSafeDirectoryId(string directoryPath, string parentDirectoryId)
{
string id = parentDirectoryId;
//bit of a hack... we don't want our id to have this prefix.dir form fo the top level,
//where it is going to be referenced by other wix files, that will just be expecting the id
//the msbuild target gave for the id of this directory
//I don't have it quite right, though. See the test file, where you get
// <Component Id="common.bin.bin" (the last bin is undesirable)
if (Path.GetFullPath(_rootDir) != directoryPath)
{
id+="." + Path.GetFileName(directoryPath);
id = id.TrimEnd('.'); //for the case where directoryPath is intentionally empty
}
id = Regex.Replace(id, @"[^\p{Lu}\p{Ll}\p{Nd}._]", "_");
return id;
}
private void ProcessFile(XmlElement parent, string path, XmlDocument doc, IdToGuidDatabase guidDatabase, bool isFirst, string directoryId)
{
string guid;
string name = Path.GetFileName(path);
string id = directoryId+"."+name; //includ the parent directory id so that files with the same name (e.g. "index.html") found twice in the system will get different ids.
const int kMaxLength = 50; //I have so far not found out what the max really is
if (id.Length > kMaxLength)
{
id = id.Substring(id.Length - kMaxLength, kMaxLength); //get the last chunk of it
}
if (!Char.IsLetter(id[0]) && id[0] != '_')//probably not needed now that we're prepending the parent directory id, accept maybe at the root?
id = '_' + id;
id = Regex.Replace(id, @"[^\p{Lu}\p{Ll}\p{Nd}._]", "_");
LogMessage(MessageImportance.Normal, "Adding file {0} with id {1}", path, id);
string key = id.ToLower();
if (m_suffixes.ContainsKey(key))
{
int suffix = m_suffixes[key] + 1;
m_suffixes[key] = suffix;
id += suffix.ToString();
}
else
{
m_suffixes[key] = 0;
}
// Create <Component> and <File> for this file
XmlElement elemComp = doc.CreateElement("Component", XMLNS);
elemComp.SetAttribute("Id", id);
guid = guidDatabase.GetGuid(id,this.CheckOnly);
if (guid == null)
m_filesChanged = true; // this file is new
else
elemComp.SetAttribute("Guid", guid.ToUpper());
parent.AppendChild(elemComp);
XmlElement elemFile = doc.CreateElement("File", XMLNS);
elemFile.SetAttribute("Id", id);
elemFile.SetAttribute("Name", name);
if (isFirst)
{
elemFile.SetAttribute("KeyPath", "yes");
}
string relativePath = PathUtil.RelativePathTo(Path.GetDirectoryName(_outputFilePath), path);
elemFile.SetAttribute("Source", relativePath);
if (GiveAllPermissions)
{
AddPermissionElement(doc, elemFile);
}
elemComp.AppendChild(elemFile);
InsertFileDeletionInstruction(elemComp);
m_components.Add(id);
// check whether the file is newer
if (File.GetLastWriteTime(path) > m_refDate)
m_filesChanged = true;
}
private void AddPermissionElement(XmlDocument doc, XmlElement elementToAddPermissionTo)
{
XmlElement persmission = doc.CreateElement("Permission", XMLNS);
persmission.SetAttribute("GenericAll", "yes");
persmission.SetAttribute("User", "Everyone");
elementToAddPermissionTo.AppendChild(persmission);
}
private void LogMessage(string message, params object[] args)
{
LogMessage(MessageImportance.Normal, message, args);
}
public void LogMessage(MessageImportance importance, string message)
{
try
{
Log.LogMessage(importance.ToString(), message);
}
catch (InvalidOperationException)
{
// Swallow exceptions for testing
}
}
private void LogMessage(MessageImportance importance, string message, params object[] args)
{
try
{
Log.LogMessage(importance.ToString(), message, args);
}
catch (InvalidOperationException)
{
// Swallow exceptions for testing
}
}
private void LogError(string message, params object[] args)
{
try
{
Log.LogError(message, args);
}
catch (InvalidOperationException)
{
// Swallow exceptions for testing
}
}
#endregion
}
}
| |
namespace NEventStore.Persistence.Sql
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Transactions;
using NEventStore.Logging;
using NEventStore.Serialization;
public class SqlPersistenceEngine : IPersistStreams
{
private static readonly ILog Logger = LogFactory.BuildLogger(typeof(SqlPersistenceEngine));
private static readonly DateTime EpochTime = new DateTime(1970, 1, 1);
private readonly IConnectionFactory _connectionFactory;
private readonly ISqlDialect _dialect;
private readonly int _pageSize;
private readonly TransactionScopeOption _scopeOption;
private readonly ISerialize _serializer;
private bool _disposed;
private int _initialized;
private readonly IStreamIdHasher _streamIdHasher;
public SqlPersistenceEngine(
IConnectionFactory connectionFactory,
ISqlDialect dialect,
ISerialize serializer,
TransactionScopeOption scopeOption,
int pageSize)
: this(connectionFactory, dialect, serializer, scopeOption, pageSize, new Sha1StreamIdHasher())
{ }
public SqlPersistenceEngine(
IConnectionFactory connectionFactory,
ISqlDialect dialect,
ISerialize serializer,
TransactionScopeOption scopeOption,
int pageSize,
IStreamIdHasher streamIdHasher)
{
if (connectionFactory == null)
{
throw new ArgumentNullException("connectionFactory");
}
if (dialect == null)
{
throw new ArgumentNullException("dialect");
}
if (serializer == null)
{
throw new ArgumentNullException("serializer");
}
if (pageSize < 0)
{
throw new ArgumentException("pageSize");
}
if (streamIdHasher == null)
{
throw new ArgumentNullException("streamIdHasher");
}
_connectionFactory = connectionFactory;
_dialect = dialect;
_serializer = serializer;
_scopeOption = scopeOption;
_pageSize = pageSize;
_streamIdHasher = new StreamIdHasherValidator(streamIdHasher);
Logger.Debug(Messages.UsingScope, _scopeOption.ToString());
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Initialize()
{
if (Interlocked.Increment(ref _initialized) > 1)
{
return;
}
Logger.Debug(Messages.InitializingStorage);
ExecuteCommand(statement => statement.ExecuteWithoutExceptions(_dialect.InitializeStorage));
}
public virtual IEnumerable<ICommit> GetFrom(string bucketId, string streamId, int minRevision, int maxRevision)
{
Logger.Debug(Messages.GettingAllCommitsBetween, streamId, minRevision, maxRevision);
streamId = _streamIdHasher.GetHash(streamId);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromStartingRevision;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
query.AddParameter(_dialect.StreamRevision, minRevision);
query.AddParameter(_dialect.MaxStreamRevision, maxRevision);
query.AddParameter(_dialect.CommitSequence, 0);
return query
.ExecutePagedQuery(statement, _dialect.NextPageDelegate)
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public virtual IEnumerable<ICommit> GetFrom(string bucketId, DateTime start)
{
start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); // Rounds down to the nearest second.
start = start < EpochTime ? EpochTime : start;
Logger.Debug(Messages.GettingAllCommitsFrom, start, bucketId);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromInstant;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.CommitStamp, start);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public ICheckpoint GetCheckpoint(string checkpointToken)
{
if (string.IsNullOrWhiteSpace(checkpointToken))
{
return new LongCheckpoint(-1);
}
return LongCheckpoint.Parse(checkpointToken);
}
public virtual IEnumerable<ICommit> GetFromTo(string bucketId, DateTime start, DateTime end)
{
start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); // Rounds down to the nearest second.
start = start < EpochTime ? EpochTime : start;
end = end < EpochTime ? EpochTime : end;
Logger.Debug(Messages.GettingAllCommitsFromTo, start, end);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromToInstant;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.CommitStampStart, start);
query.AddParameter(_dialect.CommitStampEnd, end);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public virtual ICommit Commit(CommitAttempt attempt)
{
ICommit commit;
try
{
commit = PersistCommit(attempt);
Logger.Debug(Messages.CommitPersisted, attempt.CommitId);
}
catch (Exception e)
{
if (!(e is UniqueKeyViolationException))
{
throw;
}
if (DetectDuplicate(attempt))
{
Logger.Info(Messages.DuplicateCommit);
throw new DuplicateCommitException(e.Message, e);
}
Logger.Info(Messages.ConcurrentWriteDetected);
throw new ConcurrencyException(e.Message, e);
}
return commit;
}
public virtual IEnumerable<ICommit> GetUndispatchedCommits()
{
Logger.Debug(Messages.GettingUndispatchedCommits);
return
ExecuteQuery(query => query.ExecutePagedQuery(_dialect.GetUndispatchedCommits, (q, r) => { }))
.Select(x => x.GetCommit(_serializer, _dialect))
.ToArray(); // avoid paging
}
public virtual void MarkCommitAsDispatched(ICommit commit)
{
Logger.Debug(Messages.MarkingCommitAsDispatched, commit.CommitId);
string streamId = _streamIdHasher.GetHash(commit.StreamId);
ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, commit.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.CommitSequence, commit.CommitSequence);
return cmd.ExecuteWithoutExceptions(_dialect.MarkCommitAsDispatched);
});
}
public virtual IEnumerable<IStreamHead> GetStreamsToSnapshot(string bucketId, int maxThreshold)
{
Logger.Debug(Messages.GettingStreamsToSnapshot);
return ExecuteQuery(query =>
{
string statement = _dialect.GetStreamsRequiringSnapshots;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.Threshold, maxThreshold);
return
query.ExecutePagedQuery(statement,
(q, s) => q.SetParameter(_dialect.StreamId, _dialect.CoalesceParameterValue(s.StreamId()), DbType.AnsiString))
.Select(x => x.GetStreamToSnapshot());
});
}
public virtual ISnapshot GetSnapshot(string bucketId, string streamId, int maxRevision)
{
Logger.Debug(Messages.GettingRevision, streamId, maxRevision);
var streamIdHash = _streamIdHasher.GetHash(streamId);
return ExecuteQuery(query =>
{
string statement = _dialect.GetSnapshot;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.StreamId, streamIdHash, DbType.AnsiString);
query.AddParameter(_dialect.StreamRevision, maxRevision);
return query.ExecuteWithQuery(statement).Select(x => x.GetSnapshot(_serializer, streamId));
}).FirstOrDefault();
}
public virtual bool AddSnapshot(ISnapshot snapshot)
{
Logger.Debug(Messages.AddingSnapshot, snapshot.StreamId, snapshot.StreamRevision);
string streamId = _streamIdHasher.GetHash(snapshot.StreamId);
return ExecuteCommand((connection, cmd) =>
{
cmd.AddParameter(_dialect.BucketId, snapshot.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamRevision, snapshot.StreamRevision);
_dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(snapshot.Payload));
return cmd.ExecuteWithoutExceptions(_dialect.AppendSnapshotToCommit);
}) > 0;
}
public virtual void Purge()
{
Logger.Warn(Messages.PurgingStorage);
ExecuteCommand(cmd => cmd.ExecuteNonQuery(_dialect.PurgeStorage));
}
public void Purge(string bucketId)
{
Logger.Warn(Messages.PurgingBucket, bucketId);
ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
return cmd.ExecuteNonQuery(_dialect.PurgeBucket);
});
}
public void Drop()
{
Logger.Warn(Messages.DroppingTables);
ExecuteCommand(cmd => cmd.ExecuteNonQuery(_dialect.Drop));
}
public void DeleteStream(string bucketId, string streamId)
{
Logger.Warn(Messages.DeletingStream, streamId, bucketId);
streamId = _streamIdHasher.GetHash(streamId);
ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
return cmd.ExecuteNonQuery(_dialect.DeleteStream);
});
}
public IEnumerable<ICommit> GetFrom(string bucketId, string checkpointToken)
{
LongCheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken);
Logger.Debug(Messages.GettingAllCommitsFromBucketAndCheckpoint, bucketId, checkpointToken);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromBucketAndCheckpoint;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.CheckpointNumber, checkpoint.LongValue);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public IEnumerable<ICommit> GetFrom(string checkpointToken)
{
LongCheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken);
Logger.Debug(Messages.GettingAllCommitsFromCheckpoint, checkpointToken);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromCheckpoint;
query.AddParameter(_dialect.CheckpointNumber, checkpoint.LongValue);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public bool IsDisposed
{
get { return _disposed; }
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
Logger.Debug(Messages.ShuttingDownPersistence);
_disposed = true;
}
protected virtual void OnPersistCommit(IDbStatement cmd, CommitAttempt attempt)
{ }
private ICommit PersistCommit(CommitAttempt attempt)
{
Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId);
string streamId = _streamIdHasher.GetHash(attempt.StreamId);
return ExecuteCommand((connection, cmd) =>
{
cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamIdOriginal, attempt.StreamId);
cmd.AddParameter(_dialect.StreamRevision, attempt.StreamRevision);
cmd.AddParameter(_dialect.Items, attempt.Events.Count);
cmd.AddParameter(_dialect.CommitId, attempt.CommitId);
cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence);
cmd.AddParameter(_dialect.CommitStamp, attempt.CommitStamp);
cmd.AddParameter(_dialect.Headers, _serializer.Serialize(attempt.Headers));
_dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(attempt.Events.ToList()));
OnPersistCommit(cmd, attempt);
var checkpointNumber = cmd.ExecuteScalar(_dialect.PersistCommit).ToLong();
return new Commit(
attempt.BucketId,
attempt.StreamId,
attempt.StreamRevision,
attempt.CommitId,
attempt.CommitSequence,
attempt.CommitStamp,
checkpointNumber.ToString(CultureInfo.InvariantCulture),
attempt.Headers,
attempt.Events);
});
}
private bool DetectDuplicate(CommitAttempt attempt)
{
string streamId = _streamIdHasher.GetHash(attempt.StreamId);
return ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.CommitId, attempt.CommitId);
cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence);
object value = cmd.ExecuteScalar(_dialect.DuplicateCommit);
return (value is long ? (long)value : (int)value) > 0;
});
}
protected virtual IEnumerable<T> ExecuteQuery<T>(Func<IDbStatement, IEnumerable<T>> query)
{
ThrowWhenDisposed();
TransactionScope scope = OpenQueryScope();
IDbConnection connection = null;
IDbTransaction transaction = null;
IDbStatement statement = null;
try
{
connection = _connectionFactory.Open();
transaction = _dialect.OpenTransaction(connection);
statement = _dialect.BuildStatement(scope, connection, transaction);
statement.PageSize = _pageSize;
Logger.Verbose(Messages.ExecutingQuery);
return query(statement);
}
catch (Exception e)
{
if (statement != null)
{
statement.Dispose();
}
if (transaction != null)
{
transaction.Dispose();
}
if (connection != null)
{
connection.Dispose();
}
if (scope != null)
{
scope.Dispose();
}
Logger.Debug(Messages.StorageThrewException, e.GetType());
if (e is StorageUnavailableException)
{
throw;
}
throw new StorageException(e.Message, e);
}
}
protected virtual TransactionScope OpenQueryScope()
{
return OpenCommandScope() ?? new TransactionScope(TransactionScopeOption.Suppress);
}
private void ThrowWhenDisposed()
{
if (!_disposed)
{
return;
}
Logger.Warn(Messages.AlreadyDisposed);
throw new ObjectDisposedException(Messages.AlreadyDisposed);
}
private T ExecuteCommand<T>(Func<IDbStatement, T> command)
{
return ExecuteCommand((_, statement) => command(statement));
}
protected virtual T ExecuteCommand<T>(Func<IDbConnection, IDbStatement, T> command)
{
ThrowWhenDisposed();
using (TransactionScope scope = OpenCommandScope())
using (IDbConnection connection = _connectionFactory.Open())
using (IDbTransaction transaction = _dialect.OpenTransaction(connection))
using (IDbStatement statement = _dialect.BuildStatement(scope, connection, transaction))
{
try
{
Logger.Verbose(Messages.ExecutingCommand);
T rowsAffected = command(connection, statement);
Logger.Verbose(Messages.CommandExecuted, rowsAffected);
if (transaction != null)
{
transaction.Commit();
}
if (scope != null)
{
scope.Complete();
}
return rowsAffected;
}
catch (Exception e)
{
Logger.Debug(Messages.StorageThrewException, e.GetType());
if (!RecoverableException(e))
{
throw new StorageException(e.Message, e);
}
Logger.Info(Messages.RecoverableExceptionCompletesScope);
if (scope != null)
{
scope.Complete();
}
throw;
}
}
}
protected virtual TransactionScope OpenCommandScope()
{
return new TransactionScope(_scopeOption);
}
private static bool RecoverableException(Exception e)
{
return e is UniqueKeyViolationException || e is StorageUnavailableException;
}
private class StreamIdHasherValidator : IStreamIdHasher
{
private readonly IStreamIdHasher _streamIdHasher;
private const int MaxStreamIdHashLength = 40;
public StreamIdHasherValidator(IStreamIdHasher streamIdHasher)
{
if (streamIdHasher == null)
{
throw new ArgumentNullException("streamIdHasher");
}
_streamIdHasher = streamIdHasher;
}
public string GetHash(string streamId)
{
if (string.IsNullOrWhiteSpace(streamId))
{
throw new ArgumentException(Messages.StreamIdIsNullEmptyOrWhiteSpace);
}
string streamIdHash = _streamIdHasher.GetHash(streamId);
if (string.IsNullOrWhiteSpace(streamIdHash))
{
throw new InvalidOperationException(Messages.StreamIdHashIsNullEmptyOrWhiteSpace);
}
if (streamIdHash.Length > MaxStreamIdHashLength)
{
throw new InvalidOperationException(Messages.StreamIdHashTooLong.FormatWith(streamId, streamIdHash, streamIdHash.Length, MaxStreamIdHashLength));
}
return streamIdHash;
}
}
}
}
| |
using System;
using DAQ.Environment;
using DAQ.HAL;
using DAQ.Pattern;
namespace ScanMaster.Acquire.Patterns
{
/// <summary>
/// See the documentation for the PumpProbePatternPlugin
/// </summary>
public class PumpProbeDualCCDPatternBuilder : DAQ.Pattern.PatternBuilder32
{
public PumpProbeDualCCDPatternBuilder()
{
}
// private const int FLASH_PULSE_LENGTH = 100;
private const int Q_PULSE_LENGTH = 100;
private const int DETECTOR_TRIGGER_LENGTH = 20;
public int ShotSequence( int startTime, int numberOfOnOffShots, int padShots, int padStart, int flashlampPulseInterval,
int valvePulseLength, int valveToQ, int flashToQ, int flashlampPulseLength, int aomStart1, int aomDuration1,
int aomStart2, int aomDuration2, int aom2Duration1, int delayToDetectorTrigger,
int ttlSwitchPort, int ttlSwitchLine, int switchLineDuration, int switchLineDelay, int chirpStart, int chirpDuration, bool modulation)
{
int time;
if (padStart == 0)
{
time = startTime;
}
else
{
time = startTime + padStart;
}
for (int i = 0 ; i < numberOfOnOffShots ; i++ )
{
int switchChannel = PatternBuilder32.ChannelFromNIPort(ttlSwitchPort,ttlSwitchLine);
// first the pulse with the switch line high
Pulse(time, valveToQ + switchLineDelay, switchLineDuration, switchChannel);
Shot(time, valvePulseLength, valveToQ, flashToQ, flashlampPulseLength, aomStart1, aomDuration1, aomStart2, aomDuration2, aom2Duration1, delayToDetectorTrigger, chirpStart, chirpDuration, "detector");
time += flashlampPulseInterval;
for (int p = 0 ; p < padShots ; p++)
{
FlashlampPulse(time, valveToQ, flashToQ, flashlampPulseLength);
time += flashlampPulseInterval;
}
// now with the switch line low, if modulation is true (otherwise another with line high)
if (modulation)
{
Shot(time, valvePulseLength, valveToQ, flashToQ, flashlampPulseLength, aomStart1, aomDuration1, aomStart2, aomDuration2, aom2Duration1, delayToDetectorTrigger, chirpStart, chirpDuration, "detectorprime");
time += flashlampPulseInterval;
for (int p = 0; p < padShots; p++)
{
FlashlampPulse(time, valveToQ, flashToQ, flashlampPulseLength);
time += flashlampPulseInterval;
}
}
else
{
Pulse(time, valveToQ + switchLineDelay, switchLineDuration, switchChannel);
Shot(time, valvePulseLength, valveToQ, flashToQ, flashlampPulseLength, aomStart1, aomDuration1, aomStart2, aomDuration2, aom2Duration1, delayToDetectorTrigger, chirpStart, chirpDuration, "detector");
time += flashlampPulseInterval;
for (int p = 0; p < padShots; p++)
{
FlashlampPulse(time, valveToQ, flashToQ, flashlampPulseLength);
time += flashlampPulseInterval;
}
}
//// first the pulse with the switch line high
//Pulse(time, valveToQ + switchLineDelay, switchLineDuration, switchChannel);
//Shot2(time, valvePulseLength, valveToQ, flashToQ, flashlampPulseLength, aomStart1, aomDuration1, aomStart2, aomDuration2, aom2Duration1, delayToDetectorTrigger, chirpStart, chirpDuration, "detector");
//time += flashlampPulseInterval;
//for (int p = 0; p < padShots; p++)
//{
// FlashlampPulse(time, valveToQ, flashToQ, flashlampPulseLength);
// time += flashlampPulseInterval;
//}
//// now with the switch line low, if modulation is true (otherwise another with line high)
//if (modulation)
//{
// Shot2(time, valvePulseLength, valveToQ, flashToQ, flashlampPulseLength, aomStart1, aomDuration1, aomStart2, aomDuration2, aom2Duration1, delayToDetectorTrigger, chirpStart, chirpDuration, "detectorprime");
// time += flashlampPulseInterval;
// for (int p = 0; p < padShots; p++)
// {
// FlashlampPulse(time, valveToQ, flashToQ, flashlampPulseLength);
// time += flashlampPulseInterval;
// }
//}
//else
//{
// Pulse(time, valveToQ + switchLineDelay, switchLineDuration, switchChannel);
// Shot2(time, valvePulseLength, valveToQ, flashToQ, flashlampPulseLength, aomStart1, aomDuration1, aomStart2, aomDuration2, aom2Duration1, delayToDetectorTrigger, chirpStart, chirpDuration, "detector");
// time += flashlampPulseInterval;
// for (int p = 0; p < padShots; p++)
// {
// FlashlampPulse(time, valveToQ, flashToQ, flashlampPulseLength);
// time += flashlampPulseInterval;
// }
//}
}
return time;
}
public int FlashlampPulse(int startTime, int valveToQ, int flashToQ, int flashlampPulseLength)
{
return Pulse(startTime, valveToQ - flashToQ, flashlampPulseLength,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["flash"]).BitNumber);
}
public int Shot( int startTime, int valvePulseLength, int valveToQ, int flashToQ, int flashlampPulseLength, int aomStart1, int aomDuration1,
int aomStart2, int aomDuration2, int aom2Duration1, int delayToDetectorTrigger, int chirpStart, int chirpDuration, string detectorTriggerSource)
{
int time = 0;
int tempTime = 0;
// valve pulse
tempTime = Pulse(startTime, 0, valvePulseLength,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["valve"]).BitNumber);
if (tempTime > time) time = tempTime;
// Flash pulse
tempTime = Pulse(startTime, valveToQ - flashToQ, flashlampPulseLength,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["flash"]).BitNumber);
if (tempTime > time) time = tempTime;
// Q pulse
tempTime = Pulse(startTime, valveToQ, Q_PULSE_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["q"]).BitNumber);
if (tempTime > time) time = tempTime;
// chirp pulse
tempTime = Pulse(startTime, valveToQ + chirpStart, chirpDuration,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["chirpTrigger"]).BitNumber);
if (tempTime > time) time = tempTime;
// aom1 pulse 1
tempTime = Pulse(startTime, aomStart1 + valveToQ, aomDuration1,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom"]).BitNumber);
// aom2 pulse 1, it is used to control a shutter which alternate probe beams for eac CCD
tempTime = Pulse(startTime, aomStart1 + valveToQ, aomDuration1,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom2"]).BitNumber);
if (tempTime > time) time = tempTime;
// aom1 pulse 2
tempTime = Pulse(startTime, aomStart2 + valveToQ, aomDuration2,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom"]).BitNumber);
// aom2 pulse 2
tempTime = Pulse(startTime, aomStart2 + valveToQ, aomDuration2,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom2"]).BitNumber);
if (tempTime > time) time = tempTime;
// Detector trigger
tempTime = Pulse(startTime, delayToDetectorTrigger + valveToQ, DETECTOR_TRIGGER_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[detectorTriggerSource]).BitNumber);
if (tempTime > time) time = tempTime;
return time;
}
//public int Shot2(int startTime, int valvePulseLength, int valveToQ, int flashToQ, int flashlampPulseLength, int aomStart1, int aomDuration1,
// int aomStart2, int aomDuration2, int aom2Duration1, int delayToDetectorTrigger, int chirpStart, int chirpDuration, string detectorTriggerSource)
//{
// int time = 0;
// int tempTime = 0;
// // valve pulse
// tempTime = Pulse(startTime, 0, valvePulseLength,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["valve"]).BitNumber);
// if (tempTime > time) time = tempTime;
// // Flash pulse
// tempTime = Pulse(startTime, valveToQ - flashToQ, flashlampPulseLength,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["flash"]).BitNumber);
// if (tempTime > time) time = tempTime;
// // Q pulse
// tempTime = Pulse(startTime, valveToQ, Q_PULSE_LENGTH,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["q"]).BitNumber);
// if (tempTime > time) time = tempTime;
// // chirp pulse
// tempTime = Pulse(startTime, valveToQ + chirpStart, chirpDuration,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["chirpTrigger"]).BitNumber);
// if (tempTime > time) time = tempTime;
// // aom1 pulse 1
// tempTime = Pulse(startTime, aomStart1 + valveToQ, aomDuration1,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom"]).BitNumber);
// // aom2 pulse 1, it is used to
// //tempTime = Pulse(startTime, 0, aom2Duration1,
// // ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom2"]).BitNumber);
// if (tempTime > time) time = tempTime;
// // aom1 pulse 2
// tempTime = Pulse(startTime, aomStart2 + valveToQ, aomDuration2,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom"]).BitNumber);
// // aom2 pulse 2
// //tempTime = Pulse(startTime, aomStart2 + valveToQ, aomDuration2,
// // ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["aom2"]).BitNumber);
// if (tempTime > time) time = tempTime;
// // Detector trigger
// tempTime = Pulse(startTime, delayToDetectorTrigger + valveToQ, DETECTOR_TRIGGER_LENGTH,
// ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[detectorTriggerSource]).BitNumber);
// if (tempTime > time) time = tempTime;
// return time;
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
namespace GodotTools.Utils
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
public static class OS
{
[MethodImpl(MethodImplOptions.InternalCall)]
static extern string GetPlatformName();
[MethodImpl(MethodImplOptions.InternalCall)]
static extern bool UnixFileHasExecutableAccess(string filePath);
public static class Names
{
public const string Windows = "Windows";
public const string OSX = "OSX";
public const string Linux = "Linux";
public const string FreeBSD = "FreeBSD";
public const string NetBSD = "NetBSD";
public const string BSD = "BSD";
public const string Server = "Server";
public const string UWP = "UWP";
public const string Haiku = "Haiku";
public const string Android = "Android";
public const string iOS = "iOS";
public const string HTML5 = "HTML5";
}
public static class Platforms
{
public const string Windows = "windows";
public const string OSX = "osx";
public const string LinuxBSD = "linuxbsd";
public const string Server = "server";
public const string UWP = "uwp";
public const string Haiku = "haiku";
public const string Android = "android";
public const string iOS = "iphone";
public const string HTML5 = "javascript";
}
public static readonly Dictionary<string, string> PlatformNameMap = new Dictionary<string, string>
{
[Names.Windows] = Platforms.Windows,
[Names.OSX] = Platforms.OSX,
[Names.Linux] = Platforms.LinuxBSD,
[Names.FreeBSD] = Platforms.LinuxBSD,
[Names.NetBSD] = Platforms.LinuxBSD,
[Names.BSD] = Platforms.LinuxBSD,
[Names.Server] = Platforms.Server,
[Names.UWP] = Platforms.UWP,
[Names.Haiku] = Platforms.Haiku,
[Names.Android] = Platforms.Android,
[Names.iOS] = Platforms.iOS,
[Names.HTML5] = Platforms.HTML5
};
private static bool IsOS(string name)
{
return name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
}
private static bool IsAnyOS(IEnumerable<string> names)
{
return names.Any(p => p.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase));
}
private static readonly IEnumerable<string> LinuxBSDPlatforms =
new[] {Names.Linux, Names.FreeBSD, Names.NetBSD, Names.BSD};
private static readonly IEnumerable<string> UnixLikePlatforms =
new[] {Names.OSX, Names.Server, Names.Haiku, Names.Android, Names.iOS}
.Concat(LinuxBSDPlatforms).ToArray();
private static readonly Lazy<bool> _isWindows = new Lazy<bool>(() => IsOS(Names.Windows));
private static readonly Lazy<bool> _isOSX = new Lazy<bool>(() => IsOS(Names.OSX));
private static readonly Lazy<bool> _isLinuxBSD = new Lazy<bool>(() => IsAnyOS(LinuxBSDPlatforms));
private static readonly Lazy<bool> _isServer = new Lazy<bool>(() => IsOS(Names.Server));
private static readonly Lazy<bool> _isUWP = new Lazy<bool>(() => IsOS(Names.UWP));
private static readonly Lazy<bool> _isHaiku = new Lazy<bool>(() => IsOS(Names.Haiku));
private static readonly Lazy<bool> _isAndroid = new Lazy<bool>(() => IsOS(Names.Android));
private static readonly Lazy<bool> _isiOS = new Lazy<bool>(() => IsOS(Names.iOS));
private static readonly Lazy<bool> _isHTML5 = new Lazy<bool>(() => IsOS(Names.HTML5));
private static readonly Lazy<bool> _isUnixLike = new Lazy<bool>(() => IsAnyOS(UnixLikePlatforms));
public static bool IsWindows => _isWindows.Value || IsUWP;
public static bool IsOSX => _isOSX.Value;
public static bool IsLinuxBSD => _isLinuxBSD.Value;
public static bool IsServer => _isServer.Value;
public static bool IsUWP => _isUWP.Value;
public static bool IsHaiku => _isHaiku.Value;
public static bool IsAndroid => _isAndroid.Value;
public static bool IsiOS => _isiOS.Value;
public static bool IsHTML5 => _isHTML5.Value;
public static bool IsUnixLike => _isUnixLike.Value;
public static char PathSep => IsWindows ? ';' : ':';
public static string PathWhich([NotNull] string name)
{
return IsWindows ? PathWhichWindows(name) : PathWhichUnix(name);
}
private static string PathWhichWindows([NotNull] string name)
{
string[] windowsExts = Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) ?? new string[] { };
string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep);
var searchDirs = new List<string>();
if (pathDirs != null)
searchDirs.AddRange(pathDirs);
string nameExt = Path.GetExtension(name);
bool hasPathExt = !string.IsNullOrEmpty(nameExt) && windowsExts.Contains(nameExt, StringComparer.OrdinalIgnoreCase);
searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list
if (hasPathExt)
return searchDirs.Select(dir => Path.Combine(dir, name)).FirstOrDefault(File.Exists);
return (from dir in searchDirs
select Path.Combine(dir, name)
into path
from ext in windowsExts
select path + ext).FirstOrDefault(File.Exists);
}
private static string PathWhichUnix([NotNull] string name)
{
string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep);
var searchDirs = new List<string>();
if (pathDirs != null)
searchDirs.AddRange(pathDirs);
searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list
return searchDirs.Select(dir => Path.Combine(dir, name))
.FirstOrDefault(path => File.Exists(path) && UnixFileHasExecutableAccess(path));
}
public static void RunProcess(string command, IEnumerable<string> arguments)
{
// TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead
string CmdLineArgsToString(IEnumerable<string> args)
{
// Not perfect, but as long as we are careful...
return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg));
}
var startInfo = new ProcessStartInfo(command, CmdLineArgsToString(arguments))
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
if (process == null)
throw new Exception("No process was started");
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (IsWindows && process.Id > 0)
User32Dll.AllowSetForegroundWindow(process.Id); // allows application to focus itself
}
}
public static int ExecuteCommand(string command, IEnumerable<string> arguments)
{
// TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead
string CmdLineArgsToString(IEnumerable<string> args)
{
// Not perfect, but as long as we are careful...
return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg));
}
var startInfo = new ProcessStartInfo(command, CmdLineArgsToString(arguments));
Console.WriteLine($"Executing: \"{startInfo.FileName}\" {startInfo.Arguments}");
// Print the output
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardError = false;
startInfo.UseShellExecute = false;
using (var process = new Process {StartInfo = startInfo})
{
process.Start();
process.WaitForExit();
return process.ExitCode;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{
/// <summary>
/// A virtual class designed to have methods overloaded,
/// this class provides an interface for a generic image
/// saving and loading mechanism, but does not specify the
/// format. It should not be insubstantiated directly.
/// </summary>
public class GenericSystemDrawing : ITerrainLoader
{
#region ITerrainLoader Members
public string FileExtension
{
get { return ".gsd"; }
}
/// <summary>
/// Loads a file from a specified filename on the disk,
/// parses the image using the System.Drawing parsers
/// then returns a terrain channel. Values are
/// returned based on HSL brightness between 0m and 128m
/// </summary>
/// <param name="filename">The target image to load</param>
/// <returns>A terrain channel generated from the image.</returns>
public virtual ITerrainChannel LoadFile(string filename)
{
using (Bitmap b = new Bitmap(filename))
return LoadBitmap(b);
}
public virtual ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int w, int h)
{
using (Bitmap bitmap = new Bitmap(filename))
{
ITerrainChannel retval = new TerrainChannel(w, h);
for (int x = 0; x < retval.Width; x++)
{
for (int y = 0; y < retval.Height; y++)
{
retval[x, y] = bitmap.GetPixel(offsetX * retval.Width + x, (bitmap.Height - (retval.Height * (offsetY + 1))) + retval.Height - y - 1).GetBrightness() * 128;
}
}
return retval;
}
}
public virtual ITerrainChannel LoadStream(Stream stream)
{
using (Bitmap b = new Bitmap(stream))
return LoadBitmap(b);
}
protected virtual ITerrainChannel LoadBitmap(Bitmap bitmap)
{
ITerrainChannel retval = new TerrainChannel(bitmap.Width, bitmap.Height);
int x;
for (x = 0; x < bitmap.Width; x++)
{
int y;
for (y = 0; y < bitmap.Height; y++)
{
retval[x, y] = bitmap.GetPixel(x, bitmap.Height - y - 1).GetBrightness() * 128;
}
}
return retval;
}
/// <summary>
/// Exports a file to a image on the disk using a System.Drawing exporter.
/// </summary>
/// <param name="filename">The target filename</param>
/// <param name="map">The terrain channel being saved</param>
public virtual void SaveFile(string filename, ITerrainChannel map)
{
Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(filename, ImageFormat.Png);
}
/// <summary>
/// Exports a stream using a System.Drawing exporter.
/// </summary>
/// <param name="stream">The target stream</param>
/// <param name="map">The terrain channel being saved</param>
public virtual void SaveStream(Stream stream, ITerrainChannel map)
{
Bitmap colours = CreateGrayscaleBitmapFromMap(map);
colours.Save(stream, ImageFormat.Png);
}
public virtual void SaveFile(ITerrainChannel m_channel, string filename,
int offsetX, int offsetY,
int fileWidth, int fileHeight,
int regionSizeX, int regionSizeY)
{
// We need to do this because:
// "Saving the image to the same file it was constructed from is not allowed and throws an exception."
string tempName = Path.GetTempFileName();
Bitmap existingBitmap = null;
Bitmap thisBitmap = null;
Bitmap newBitmap = null;
try
{
if (File.Exists(filename))
{
File.Copy(filename, tempName, true);
existingBitmap = new Bitmap(tempName);
if (existingBitmap.Width != fileWidth * regionSizeX || existingBitmap.Height != fileHeight * regionSizeY)
{
// old file, let's overwrite it
newBitmap = new Bitmap(fileWidth * regionSizeX, fileHeight * regionSizeY);
}
else
{
newBitmap = existingBitmap;
}
}
else
{
newBitmap = new Bitmap(fileWidth * regionSizeX, fileHeight * regionSizeY);
}
thisBitmap = CreateGrayscaleBitmapFromMap(m_channel);
// Console.WriteLine("offsetX=" + offsetX + " offsetY=" + offsetY);
for (int x = 0; x < regionSizeX; x++)
for (int y = 0; y < regionSizeY; y++)
newBitmap.SetPixel(x + offsetX * regionSizeX, y + (fileHeight - 1 - offsetY) * regionSizeY, thisBitmap.GetPixel(x, y));
Save(newBitmap, filename);
}
finally
{
if (existingBitmap != null)
existingBitmap.Dispose();
if (thisBitmap != null)
thisBitmap.Dispose();
if (newBitmap != null)
newBitmap.Dispose();
if (File.Exists(tempName))
File.Delete(tempName);
}
}
protected virtual void Save(Bitmap bmp, string filename)
{
bmp.Save(filename, ImageFormat.Png);
}
#endregion
public override string ToString()
{
return "SYS.DRAWING";
}
//Returns true if this extension is supported for terrain save-tile
public virtual bool SupportsTileSave()
{
return false;
}
/// <summary>
/// Protected method, generates a grayscale bitmap
/// image from a specified terrain channel.
/// </summary>
/// <param name="map">The terrain channel to export to bitmap</param>
/// <returns>A System.Drawing.Bitmap containing a grayscale image</returns>
protected static Bitmap CreateGrayscaleBitmapFromMap(ITerrainChannel map)
{
Bitmap bmp = new Bitmap(map.Width, map.Height);
const int pallete = 256;
Color[] grays = new Color[pallete];
for (int i = 0; i < grays.Length; i++)
{
grays[i] = Color.FromArgb(i, i, i);
}
for (int y = 0; y < map.Height; y++)
{
for (int x = 0; x < map.Width; x++)
{
// 512 is the largest possible height before colours clamp
int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 128.0), 0.0) * (pallete - 1));
// Handle error conditions
if (colorindex > pallete - 1 || colorindex < 0)
bmp.SetPixel(x, map.Height - y - 1, Color.Red);
else
bmp.SetPixel(x, map.Height - y - 1, grays[colorindex]);
}
}
return bmp;
}
/// <summary>
/// Protected method, generates a coloured bitmap
/// image from a specified terrain channel.
/// </summary>
/// <param name="map">The terrain channel to export to bitmap</param>
/// <returns>A System.Drawing.Bitmap containing a coloured image</returns>
protected static Bitmap CreateBitmapFromMap(ITerrainChannel map)
{
int pallete;
Bitmap bmp;
Color[] colours;
using (Bitmap gradientmapLd = new Bitmap("defaultstripe.png"))
{
pallete = gradientmapLd.Height;
bmp = new Bitmap(map.Width, map.Height);
colours = new Color[pallete];
for (int i = 0; i < pallete; i++)
{
colours[i] = gradientmapLd.GetPixel(0, i);
}
}
for (int y = 0; y < map.Height; y++)
{
for (int x = 0; x < map.Width; x++)
{
// 512 is the largest possible height before colours clamp
int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1));
// Handle error conditions
if (colorindex > pallete - 1 || colorindex < 0)
bmp.SetPixel(x, map.Height - y - 1, Color.Red);
else
bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]);
}
}
return bmp;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// <OWNER>[....]</OWNER>
//
namespace System.Reflection.Emit {
using System;
using IList = System.Collections.IList;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Diagnostics;
using CultureInfo = System.Globalization.CultureInfo;
#if !FEATURE_CORECLR
using ResourceWriter = System.Resources.ResourceWriter;
#else // FEATURE_CORECLR
using IResourceWriter = System.Resources.IResourceWriter;
#endif // !FEATURE_CORECLR
using System.IO;
using System.Runtime.Versioning;
using System.Diagnostics.SymbolStore;
using System.Diagnostics.Contracts;
// This is a package private class. This class hold all of the managed
// data member for AssemblyBuilder. Note that what ever data members added to
// this class cannot be accessed from the EE.
internal class AssemblyBuilderData
{
[SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal AssemblyBuilderData(
InternalAssemblyBuilder assembly,
String strAssemblyName,
AssemblyBuilderAccess access,
String dir)
{
m_assembly = assembly;
m_strAssemblyName = strAssemblyName;
m_access = access;
m_moduleBuilderList = new List<ModuleBuilder>();
m_resWriterList = new List<ResWriterData>();
//Init to null/0 done for you by the CLR. FXCop has spoken
if (dir == null && access != AssemblyBuilderAccess.Run)
m_strDir = Environment.CurrentDirectory;
else
m_strDir = dir;
m_peFileKind = PEFileKinds.Dll;
}
// Helper to add a dynamic module into the tracking list
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal void AddModule(ModuleBuilder dynModule)
{
m_moduleBuilderList.Add(dynModule);
}
// Helper to add a resource information into the tracking list
internal void AddResWriter(ResWriterData resData)
{
m_resWriterList.Add(resData);
}
// Helper to track CAs to persist onto disk
internal void AddCustomAttribute(CustomAttributeBuilder customBuilder)
{
// make sure we have room for this CA
if (m_CABuilders == null)
{
m_CABuilders = new CustomAttributeBuilder[m_iInitialSize];
}
if (m_iCABuilder == m_CABuilders.Length)
{
CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2];
Array.Copy(m_CABuilders, tempCABuilders, m_iCABuilder);
m_CABuilders = tempCABuilders;
}
m_CABuilders[m_iCABuilder] = customBuilder;
m_iCABuilder++;
}
// Helper to track CAs to persist onto disk
internal void AddCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
// make sure we have room for this CA
if (m_CABytes == null)
{
m_CABytes = new byte[m_iInitialSize][];
m_CACons = new ConstructorInfo[m_iInitialSize];
}
if (m_iCAs == m_CABytes.Length)
{
// enlarge the arrays
byte[][] temp = new byte[m_iCAs * 2][];
ConstructorInfo[] tempCon = new ConstructorInfo[m_iCAs * 2];
for (int i=0; i < m_iCAs; i++)
{
temp[i] = m_CABytes[i];
tempCon[i] = m_CACons[i];
}
m_CABytes = temp;
m_CACons = tempCon;
}
byte[] attrs = new byte[binaryAttribute.Length];
Array.Copy(binaryAttribute, attrs, binaryAttribute.Length);
m_CABytes[m_iCAs] = attrs;
m_CACons[m_iCAs] = con;
m_iCAs++;
}
#if !FEATURE_PAL
// Helper to calculate unmanaged version info from Assembly's custom attributes.
// If DefineUnmanagedVersionInfo is called, the parameter provided will override
// the CA's value.
//
[System.Security.SecurityCritical] // auto-generated
internal void FillUnmanagedVersionInfo()
{
// Get the lcid set on the assembly name as default if available
// Note that if LCID is not avaible from neither AssemblyName or AssemblyCultureAttribute,
// it is default to -1 which is treated as language neutral.
//
CultureInfo locale = m_assembly.GetLocale();
#if FEATURE_USE_LCID
if (locale != null)
m_nativeVersion.m_lcid = locale.LCID;
#endif
for (int i = 0; i < m_iCABuilder; i++)
{
// check for known attributes
Type conType = m_CABuilders[i].m_con.DeclaringType;
if (m_CABuilders[i].m_constructorArgs.Length == 0 || m_CABuilders[i].m_constructorArgs[0] == null)
continue;
if (conType.Equals(typeof(System.Reflection.AssemblyCopyrightAttribute)))
{
// assert that we should only have one argument for this CA and the type should
// be a string.
//
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
if (m_OverrideUnmanagedVersionInfo == false)
{
m_nativeVersion.m_strCopyright = m_CABuilders[i].m_constructorArgs[0].ToString();
}
}
else if (conType.Equals(typeof(System.Reflection.AssemblyTrademarkAttribute)))
{
// assert that we should only have one argument for this CA and the type should
// be a string.
//
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
if (m_OverrideUnmanagedVersionInfo == false)
{
m_nativeVersion.m_strTrademark = m_CABuilders[i].m_constructorArgs[0].ToString();
}
}
else if (conType.Equals(typeof(System.Reflection.AssemblyProductAttribute)))
{
if (m_OverrideUnmanagedVersionInfo == false)
{
// assert that we should only have one argument for this CA and the type should
// be a string.
//
m_nativeVersion.m_strProduct = m_CABuilders[i].m_constructorArgs[0].ToString();
}
}
else if (conType.Equals(typeof(System.Reflection.AssemblyCompanyAttribute)))
{
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
if (m_OverrideUnmanagedVersionInfo == false)
{
// assert that we should only have one argument for this CA and the type should
// be a string.
//
m_nativeVersion.m_strCompany = m_CABuilders[i].m_constructorArgs[0].ToString();
}
}
else if (conType.Equals(typeof(System.Reflection.AssemblyDescriptionAttribute)))
{
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
m_nativeVersion.m_strDescription = m_CABuilders[i].m_constructorArgs[0].ToString();
}
else if (conType.Equals(typeof(System.Reflection.AssemblyTitleAttribute)))
{
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
m_nativeVersion.m_strTitle = m_CABuilders[i].m_constructorArgs[0].ToString();
}
else if (conType.Equals(typeof(System.Reflection.AssemblyInformationalVersionAttribute)))
{
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
if (m_OverrideUnmanagedVersionInfo == false)
{
m_nativeVersion.m_strProductVersion = m_CABuilders[i].m_constructorArgs[0].ToString();
}
}
else if (conType.Equals(typeof(System.Reflection.AssemblyCultureAttribute)))
{
// retrieve the LCID
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
// CultureInfo attribute overrides the lcid from AssemblyName.
CultureInfo culture = new CultureInfo(m_CABuilders[i].m_constructorArgs[0].ToString());
#if FEATURE_USE_LCID
m_nativeVersion.m_lcid = culture.LCID;
#endif
}
else if (conType.Equals(typeof(System.Reflection.AssemblyFileVersionAttribute)))
{
if (m_CABuilders[i].m_constructorArgs.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString(
"Argument_BadCAForUnmngRSC",
m_CABuilders[i].m_con.ReflectedType.Name));
}
if (m_OverrideUnmanagedVersionInfo == false)
{
m_nativeVersion.m_strFileVersion = m_CABuilders[i].m_constructorArgs[0].ToString();
}
}
}
}
#endif //!FEATURE_PAL
// Helper to ensure the resource name is unique underneath assemblyBuilder
internal void CheckResNameConflict(String strNewResName)
{
int size = m_resWriterList.Count;
int i;
for (i = 0; i < size; i++)
{
ResWriterData resWriter = m_resWriterList[i];
if (resWriter.m_strName.Equals(strNewResName))
{
// Cannot have two resources with the same name
throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateResourceName"));
}
}
}
// Helper to ensure the module name is unique underneath assemblyBuilder
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.Machine | ResourceScope.Assembly)]
internal void CheckNameConflict(String strNewModuleName)
{
int size = m_moduleBuilderList.Count;
int i;
for (i = 0; i < size; i++)
{
ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
if (moduleBuilder.m_moduleData.m_strModuleName.Equals(strNewModuleName))
{
// Cannot have two dynamic modules with the same name
throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName"));
}
}
// Right now dynamic modules can only be added to dynamic assemblies in which
// all modules are dynamic. Otherwise we would also need to check the static modules
// with this:
// if (m_assembly.GetModule(strNewModuleName) != null)
// {
// // Cannot have two dynamic modules with the same name
// throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName"));
// }
}
// Helper to ensure the type name is unique underneath assemblyBuilder
internal void CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType)
{
BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.CheckTypeNameConflict( " + strTypeName + " )");
for (int i = 0; i < m_moduleBuilderList.Count; i++)
{
ModuleBuilder curModule = m_moduleBuilderList[i];
curModule.CheckTypeNameConflict(strTypeName, enclosingType);
}
// Right now dynamic modules can only be added to dynamic assemblies in which
// all modules are dynamic. Otherwise we would also need to check loaded types.
// We only need to make this test for non-nested types since any
// duplicates in nested types will be caught at the top level.
// if (enclosingType == null && m_assembly.GetType(strTypeName, false, false) != null)
// {
// // Cannot have two types with the same name
// throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName"));
// }
}
// Helper to ensure the file name is unique underneath assemblyBuilder. This includes
// modules and resources.
//
//
//
internal void CheckFileNameConflict(String strFileName)
{
int size = m_moduleBuilderList.Count;
int i;
for (i = 0; i < size; i++)
{
ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
if (moduleBuilder.m_moduleData.m_strFileName != null)
{
if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
// Cannot have two dynamic module with the same name
throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName"));
}
}
}
size = m_resWriterList.Count;
for (i = 0; i < size; i++)
{
ResWriterData resWriter = m_resWriterList[i];
if (resWriter.m_strFileName != null)
{
if (String.Compare(resWriter.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
// Cannot have two dynamic module with the same name
throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName"));
}
}
}
}
// Helper to look up which module that assembly is supposed to be stored at
//
//
//
internal ModuleBuilder FindModuleWithFileName(String strFileName)
{
int size = m_moduleBuilderList.Count;
int i;
for (i = 0; i < size; i++)
{
ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
if (moduleBuilder.m_moduleData.m_strFileName != null)
{
if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
return moduleBuilder;
}
}
}
return null;
}
// Helper to look up module by name.
//
//
//
internal ModuleBuilder FindModuleWithName(String strName)
{
int size = m_moduleBuilderList.Count;
int i;
for (i = 0; i < size; i++)
{
ModuleBuilder moduleBuilder = m_moduleBuilderList[i];
if (moduleBuilder.m_moduleData.m_strModuleName != null)
{
if (String.Compare(moduleBuilder.m_moduleData.m_strModuleName, strName, StringComparison.OrdinalIgnoreCase) == 0)
return moduleBuilder;
}
}
return null;
}
// add type to public COMType tracking list
internal void AddPublicComType(Type type)
{
BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPublicComType( " + type.FullName + " )");
if (m_isSaved == true)
{
// assembly has been saved before!
throw new InvalidOperationException(Environment.GetResourceString(
"InvalidOperation_CannotAlterAssembly"));
}
EnsurePublicComTypeCapacity();
m_publicComTypeList[m_iPublicComTypeCount] = type;
m_iPublicComTypeCount++;
}
// add security permission requests
internal void AddPermissionRequests(
PermissionSet required,
PermissionSet optional,
PermissionSet refused)
{
BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPermissionRequests");
if (m_isSaved == true)
{
// assembly has been saved before!
throw new InvalidOperationException(Environment.GetResourceString(
"InvalidOperation_CannotAlterAssembly"));
}
m_RequiredPset = required;
m_OptionalPset = optional;
m_RefusedPset = refused;
}
private void EnsurePublicComTypeCapacity()
{
if (m_publicComTypeList == null)
{
m_publicComTypeList = new Type[m_iInitialSize];
}
if (m_iPublicComTypeCount == m_publicComTypeList.Length)
{
Type[] tempTypeList = new Type[m_iPublicComTypeCount * 2];
Array.Copy(m_publicComTypeList, tempTypeList, m_iPublicComTypeCount);
m_publicComTypeList = tempTypeList;
}
}
internal List<ModuleBuilder> m_moduleBuilderList;
internal List<ResWriterData> m_resWriterList;
internal String m_strAssemblyName;
internal AssemblyBuilderAccess m_access;
private InternalAssemblyBuilder m_assembly;
internal Type[] m_publicComTypeList;
internal int m_iPublicComTypeCount;
internal bool m_isSaved;
internal const int m_iInitialSize = 16;
internal String m_strDir;
// hard coding the assembly def token
internal const int m_tkAssembly = 0x20000001;
// Security permission requests
internal PermissionSet m_RequiredPset;
internal PermissionSet m_OptionalPset;
internal PermissionSet m_RefusedPset;
// tracking AssemblyDef's CAs for persistence to disk
internal CustomAttributeBuilder[] m_CABuilders;
internal int m_iCABuilder;
internal byte[][] m_CABytes;
internal ConstructorInfo[] m_CACons;
internal int m_iCAs;
internal PEFileKinds m_peFileKind; // assembly file kind
internal MethodInfo m_entryPointMethod;
internal Assembly m_ISymWrapperAssembly;
#if !FEATURE_CORECLR
internal ModuleBuilder m_entryPointModule;
#endif //!FEATURE_CORECLR
#if !FEATURE_PAL
// For unmanaged resources
internal String m_strResourceFileName;
internal byte[] m_resourceBytes;
internal NativeVersionInfo m_nativeVersion;
internal bool m_hasUnmanagedVersionInfo;
internal bool m_OverrideUnmanagedVersionInfo;
#endif // !FEATURE_PAL
}
/**********************************************
*
* Internal structure to track the list of ResourceWriter for
* AssemblyBuilder & ModuleBuilder.
*
**********************************************/
internal class ResWriterData
{
#if FEATURE_CORECLR
internal ResWriterData(
IResourceWriter resWriter,
Stream memoryStream,
String strName,
String strFileName,
String strFullFileName,
ResourceAttributes attribute)
{
m_resWriter = resWriter;
m_memoryStream = memoryStream;
m_strName = strName;
m_strFileName = strFileName;
m_strFullFileName = strFullFileName;
m_nextResWriter = null;
m_attribute = attribute;
}
#else
internal ResWriterData(
ResourceWriter resWriter,
Stream memoryStream,
String strName,
String strFileName,
String strFullFileName,
ResourceAttributes attribute)
{
m_resWriter = resWriter;
m_memoryStream = memoryStream;
m_strName = strName;
m_strFileName = strFileName;
m_strFullFileName = strFullFileName;
m_nextResWriter = null;
m_attribute = attribute;
}
#endif
#if !FEATURE_CORECLR
internal ResourceWriter m_resWriter;
#else // FEATURE_CORECLR
internal IResourceWriter m_resWriter;
#endif // !FEATURE_CORECLR
internal String m_strName;
internal String m_strFileName;
internal String m_strFullFileName;
internal Stream m_memoryStream;
internal ResWriterData m_nextResWriter;
internal ResourceAttributes m_attribute;
}
#if !FEATURE_PAL
internal class NativeVersionInfo
{
internal NativeVersionInfo()
{
m_strDescription = null;
m_strCompany = null;
m_strTitle = null;
m_strCopyright = null;
m_strTrademark = null;
m_strProduct = null;
m_strProductVersion = null;
m_strFileVersion = null;
m_lcid = -1;
}
internal String m_strDescription;
internal String m_strCompany;
internal String m_strTitle;
internal String m_strCopyright;
internal String m_strTrademark;
internal String m_strProduct;
internal String m_strProductVersion;
internal String m_strFileVersion;
internal int m_lcid;
}
#endif //!FEATURE_PAL
}
| |
// 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.Globalization;
using System.Reflection;
using NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class GroupingCollectionTest
{
private BuildPropertyGroup pg1;
private BuildPropertyGroup pg2;
private BuildPropertyGroup pg3;
private Choose choose1;
private Choose choose2;
private Choose choose3;
private BuildItemGroup ig1;
private BuildItemGroup ig2;
private BuildItemGroup ig3;
private void SetupMembers()
{
pg1 = new BuildPropertyGroup();
pg1.SetProperty("foo", "bar");
pg1.SetProperty("abc", "true");
pg1.SetProperty("Unit", "inches");
pg2 = new BuildPropertyGroup();
pg2.SetProperty("foo", "bar");
pg2.SetProperty("abc", "true");
pg3 = new BuildPropertyGroup();
// These Choose objects are only suitable for
// holding a place in the GroupingCollection.
choose1 = new Choose();
choose2 = new Choose();
choose3 = new Choose();
ig1 = new BuildItemGroup();
ig1.AddNewItem("x", "x1");
ig1.AddNewItem("x", "x2");
ig1.AddNewItem("y", "y1");
ig1.AddNewItem("y", "y2");
ig1.AddNewItem("y", "y3");
ig1.AddNewItem("y", "y4");
ig2 = new BuildItemGroup();
ig2.AddNewItem("jacksonfive", "germaine");
ig2.AddNewItem("jacksonfive", "tito");
ig2.AddNewItem("jacksonfive", "michael");
ig2.AddNewItem("jacksonfive", "latoya");
ig2.AddNewItem("jacksonfive", "janet");
ig3 = new BuildItemGroup();
}
private void AssertNPropertyGroupsInCollection(GroupingCollection group, int n)
{
int count;
count = 0;
foreach (IItemPropertyGrouping pg in new GroupEnumeratorHelper(group, GroupEnumeratorHelper.ListType.PropertyGroupsAll))
{
count++;
}
Assertion.AssertEquals(n, count);
// PropertyGroupCount uses a different mechanism to obtain the total count, so verify it as well
Assertion.AssertEquals(n, group.PropertyGroupCount);
}
private void AssertNItemGroupsInCollection(GroupingCollection group, int n)
{
int count;
count = 0;
foreach (IItemPropertyGrouping pg in new GroupEnumeratorHelper(group, GroupEnumeratorHelper.ListType.ItemGroupsAll))
{
count++;
}
Assertion.AssertEquals(n, count);
// ItemGroupCount uses a different mechanism to obtain the total count, so verify it as well
Assertion.AssertEquals(n, group.ItemGroupCount);
}
private void AssertNPropertyGroupsAndChoosesInCollection(GroupingCollection group, int n)
{
int count;
count = 0;
foreach (IItemPropertyGrouping pg in new GroupEnumeratorHelper(group, GroupEnumeratorHelper.ListType.PropertyGroupsTopLevelAndChoose))
{
count++;
}
Assertion.AssertEquals(n, count);
}
private void AssertNItemGroupsAndChoosesInCollection(GroupingCollection group, int n)
{
int count;
count = 0;
foreach (IItemPropertyGrouping pg in new GroupEnumeratorHelper(group, GroupEnumeratorHelper.ListType.ItemGroupsTopLevelAndChoose))
{
count++;
}
Assertion.AssertEquals(n, count);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void EnumerationTest()
{
SetupMembers();
GroupingCollection group = new GroupingCollection(null);
group.InsertAtEnd(this.pg1);
group.InsertAtEnd(this.ig1);
group.InsertAtEnd(this.pg2);
group.InsertAtEnd(this.ig2);
group.InsertAtEnd(this.ig3);
AssertNPropertyGroupsInCollection(group, 2);
Assertion.Assert(group.PropertyGroupCount == 2);
AssertNItemGroupsInCollection(group, 3);
Assertion.Assert(group.ItemGroupCount == 3);
group.InsertAtEnd(this.choose1);
group.InsertAtEnd(this.choose2);
AssertNPropertyGroupsInCollection(group, 2);
Assertion.Assert(group.PropertyGroupCount == 2);
AssertNItemGroupsInCollection(group, 3);
Assertion.Assert(group.ItemGroupCount == 3);
AssertNPropertyGroupsAndChoosesInCollection(group, 4);
AssertNItemGroupsAndChoosesInCollection(group, 5);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void InsertionTest()
{
SetupMembers();
GroupingCollection group = new GroupingCollection(null);
group.InsertAtEnd(this.pg1);
group.InsertAtEnd(this.ig1);
group.InsertAtBeginning(this.pg2);
group.InsertAtEnd(this.ig2);
group.InsertAfter(this.ig3, this.ig2);
group.InsertAfter(this.pg3, this.pg2);
AssertNPropertyGroupsInCollection(group, 3);
Assertion.Assert(group.PropertyGroupCount == 3);
AssertNItemGroupsInCollection(group, 3);
Assertion.Assert(group.ItemGroupCount == 3);
group.InsertAtEnd(this.choose1);
group.InsertAtEnd(this.choose2);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void RemoveTest()
{
SetupMembers();
GroupingCollection group = new GroupingCollection(null);
group.InsertAtEnd(this.pg1);
group.InsertAtEnd(this.ig1);
group.InsertAtBeginning(this.pg2);
group.InsertAtEnd(this.ig2);
group.InsertAfter(this.ig3, this.ig2);
group.InsertAfter(this.pg3, this.pg2);
AssertNPropertyGroupsInCollection(group, 3);
AssertNItemGroupsInCollection(group, 3);
group.RemovePropertyGroup(this.pg3);
AssertNPropertyGroupsInCollection(group, 2);
AssertNItemGroupsInCollection(group, 3);
group.RemovePropertyGroup(this.pg2);
AssertNPropertyGroupsInCollection(group, 1);
AssertNItemGroupsInCollection(group, 3);
group.RemoveItemGroup(this.ig2);
AssertNPropertyGroupsInCollection(group, 1);
AssertNItemGroupsInCollection(group, 2);
}
/// <summary>
/// Make sure linked property group and item group counting works correctly.
/// Parent grouping collections depend on child grouping collections to update the count for nested groups.
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void LinkedCount()
{
SetupMembers();
GroupingCollection masterGroup = new GroupingCollection(null);
GroupingCollection childGroup1 = new GroupingCollection(masterGroup);
GroupingCollection childGroup2 = new GroupingCollection(masterGroup);
GroupingCollection nestedGroup = new GroupingCollection(childGroup1);
nestedGroup.InsertAtEnd(this.ig1);
nestedGroup.InsertAfter(this.ig2, this.ig1);
nestedGroup.InsertAtBeginning(this.pg1);
childGroup1.InsertAtEnd(this.ig1);
childGroup1.InsertAtBeginning(this.pg1);
childGroup2.InsertAtBeginning(this.pg1);
masterGroup.InsertAtEnd(this.ig1);
masterGroup.InsertAfter(this.ig2, this.ig1);
masterGroup.InsertAtEnd(this.pg2);
Assertion.AssertEquals(nestedGroup.ItemGroupCount, 2);
Assertion.AssertEquals(nestedGroup.PropertyGroupCount, 1);
Assertion.AssertEquals(childGroup1.ItemGroupCount, 1 + 2);
Assertion.AssertEquals(childGroup1.PropertyGroupCount, 1 + 1);
Assertion.AssertEquals(childGroup2.ItemGroupCount, 0);
Assertion.AssertEquals(childGroup2.PropertyGroupCount, 1);
Assertion.AssertEquals(masterGroup.ItemGroupCount, 2 + 0 + 1 + 2);
Assertion.AssertEquals(masterGroup.PropertyGroupCount, 1 + 1 + 1 + 1);
nestedGroup.Clear();
nestedGroup.InsertAtEnd(this.ig2);
nestedGroup.InsertAfter(this.ig3, this.ig2);
childGroup1.RemovePropertyGroup(this.pg1);
childGroup1.RemoveItemGroup(this.ig1);
childGroup1.InsertAtEnd(this.ig3);
childGroup2.RemovePropertyGroup(this.pg1);
masterGroup.RemoveItemGroup(this.ig2);
Assertion.AssertEquals(nestedGroup.ItemGroupCount, 2);
Assertion.AssertEquals(nestedGroup.PropertyGroupCount, 0);
Assertion.AssertEquals(childGroup1.ItemGroupCount, 1 + 2);
Assertion.AssertEquals(childGroup1.PropertyGroupCount, 0 + 0);
Assertion.AssertEquals(childGroup2.ItemGroupCount, 0);
Assertion.AssertEquals(childGroup2.PropertyGroupCount, 0);
Assertion.AssertEquals(masterGroup.ItemGroupCount, 1 + 0 + 1 + 2);
Assertion.AssertEquals(masterGroup.PropertyGroupCount, 1 + 0 + 0 + 0);
}
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
namespace Tilde.TildeApp
{
partial class MainWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
private WeifenLuo.WinFormsUI.Docking.DockPanel mDockPanel;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow));
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.tsiFile = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileNewProject = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileOpenProject = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileSaveProject = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileCloseProject = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.tsiFileOpenFile = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileSave = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.tsiFileSaveAll = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.tsiFileRecentProjects = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.tsiFileExit = new System.Windows.Forms.ToolStripMenuItem();
this.tsiEdit = new System.Windows.Forms.ToolStripMenuItem();
this.goToNextLocationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.goToPreviousLocationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pluginsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sourceControlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeAllDocumentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findFileInProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.projectWebSiteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reportBugToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.requestFeatureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.statusMessage = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar = new System.Windows.Forms.ToolStripProgressBar();
this.saveProjectDialog = new System.Windows.Forms.SaveFileDialog();
this.openProjectDialog = new System.Windows.Forms.OpenFileDialog();
this.statusMessageTimer = new System.Windows.Forms.Timer(this.components);
this.saveDocumentDialog = new System.Windows.Forms.SaveFileDialog();
this.openDocumentDialog = new System.Windows.Forms.OpenFileDialog();
this.toolStripPanelTop = new System.Windows.Forms.ToolStripPanel();
this.toolStripPanelBottom = new System.Windows.Forms.ToolStripPanel();
this.toolStripPanelLeft = new System.Windows.Forms.ToolStripPanel();
this.toolStripPanelRight = new System.Windows.Forms.ToolStripPanel();
this.mDockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel();
this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
this.persistWindowComponent = new Tilde.Framework.View.PersistWindowComponent(this.components);
this.menuStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
this.toolStripPanelTop.SuspendLayout();
this.toolStripPanelBottom.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.BackColor = System.Drawing.SystemColors.Control;
this.menuStrip.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsiFile,
this.tsiEdit,
this.viewToolStripMenuItem,
this.toolsToolStripMenuItem,
this.windowToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.MdiWindowListItem = this.windowToolStripMenuItem;
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(843, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip1";
//
// tsiFile
//
this.tsiFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsiFileNewProject,
this.tsiFileOpenProject,
this.tsiFileSaveProject,
this.tsiFileCloseProject,
this.toolStripSeparator2,
this.tsiFileOpenFile,
this.tsiFileSave,
this.tsiFileSaveAs,
this.tsiFileSaveAll,
this.toolStripSeparator4,
this.tsiFileRecentProjects,
this.toolStripSeparator1,
this.tsiFileExit});
this.tsiFile.MergeIndex = 1;
this.tsiFile.Name = "tsiFile";
this.tsiFile.Size = new System.Drawing.Size(35, 20);
this.tsiFile.Text = "&File";
//
// tsiFileNewProject
//
this.tsiFileNewProject.Name = "tsiFileNewProject";
this.tsiFileNewProject.Size = new System.Drawing.Size(180, 22);
this.tsiFileNewProject.Text = "New Project";
//
// tsiFileOpenProject
//
this.tsiFileOpenProject.Name = "tsiFileOpenProject";
this.tsiFileOpenProject.Size = new System.Drawing.Size(180, 22);
this.tsiFileOpenProject.Text = "Open Project...";
this.tsiFileOpenProject.Click += new System.EventHandler(this.tsiFileOpenProject_Click);
//
// tsiFileSaveProject
//
this.tsiFileSaveProject.Name = "tsiFileSaveProject";
this.tsiFileSaveProject.Size = new System.Drawing.Size(180, 22);
this.tsiFileSaveProject.Text = "Save Project";
this.tsiFileSaveProject.Click += new System.EventHandler(this.tsiFileSaveProject_Click);
//
// tsiFileCloseProject
//
this.tsiFileCloseProject.Name = "tsiFileCloseProject";
this.tsiFileCloseProject.Size = new System.Drawing.Size(180, 22);
this.tsiFileCloseProject.Text = "Close Project";
this.tsiFileCloseProject.Click += new System.EventHandler(this.tsiFileCloseProject_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.MergeIndex = 1;
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(177, 6);
//
// tsiFileOpenFile
//
this.tsiFileOpenFile.Name = "tsiFileOpenFile";
this.tsiFileOpenFile.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.tsiFileOpenFile.Size = new System.Drawing.Size(180, 22);
this.tsiFileOpenFile.Text = "&Open File...";
this.tsiFileOpenFile.Click += new System.EventHandler(this.tsiFileOpenFile_Click);
//
// tsiFileSave
//
this.tsiFileSave.Name = "tsiFileSave";
this.tsiFileSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.tsiFileSave.Size = new System.Drawing.Size(180, 22);
this.tsiFileSave.Text = "&Save";
this.tsiFileSave.Click += new System.EventHandler(this.tsiFileSave_Click);
//
// tsiFileSaveAs
//
this.tsiFileSaveAs.Name = "tsiFileSaveAs";
this.tsiFileSaveAs.Size = new System.Drawing.Size(180, 22);
this.tsiFileSaveAs.Text = "Save As...";
this.tsiFileSaveAs.Click += new System.EventHandler(this.tsiFileSaveAs_Click);
//
// tsiFileSaveAll
//
this.tsiFileSaveAll.Name = "tsiFileSaveAll";
this.tsiFileSaveAll.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.S)));
this.tsiFileSaveAll.Size = new System.Drawing.Size(180, 22);
this.tsiFileSaveAll.Text = "Save &All";
this.tsiFileSaveAll.Click += new System.EventHandler(this.tsiFileSaveAll_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.MergeIndex = 2;
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(177, 6);
//
// tsiFileRecentProjects
//
this.tsiFileRecentProjects.Name = "tsiFileRecentProjects";
this.tsiFileRecentProjects.Size = new System.Drawing.Size(180, 22);
this.tsiFileRecentProjects.Text = "Recent Projects";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(177, 6);
//
// tsiFileExit
//
this.tsiFileExit.Name = "tsiFileExit";
this.tsiFileExit.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.tsiFileExit.Size = new System.Drawing.Size(180, 22);
this.tsiFileExit.Text = "E&xit";
this.tsiFileExit.Click += new System.EventHandler(this.tsiFileExit_Click);
//
// tsiEdit
//
this.tsiEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.goToNextLocationToolStripMenuItem,
this.goToPreviousLocationToolStripMenuItem});
this.tsiEdit.MergeIndex = 2;
this.tsiEdit.Name = "tsiEdit";
this.tsiEdit.Size = new System.Drawing.Size(37, 20);
this.tsiEdit.Text = "&Edit";
//
// goToNextLocationToolStripMenuItem
//
this.goToNextLocationToolStripMenuItem.Name = "goToNextLocationToolStripMenuItem";
this.goToNextLocationToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F8;
this.goToNextLocationToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.goToNextLocationToolStripMenuItem.Text = "Go to next location";
this.goToNextLocationToolStripMenuItem.Click += new System.EventHandler(this.goToNextLocationToolStripMenuItem_Click);
//
// goToPreviousLocationToolStripMenuItem
//
this.goToPreviousLocationToolStripMenuItem.Name = "goToPreviousLocationToolStripMenuItem";
this.goToPreviousLocationToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F8)));
this.goToPreviousLocationToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.goToPreviousLocationToolStripMenuItem.Text = "Go to previous location";
this.goToPreviousLocationToolStripMenuItem.Click += new System.EventHandler(this.goToPreviousLocationToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.MergeIndex = 3;
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(41, 20);
this.viewToolStripMenuItem.Text = "&View";
this.viewToolStripMenuItem.DropDownOpening += new System.EventHandler(this.viewToolStripMenuItem_DropDownOpening);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pluginsToolStripMenuItem,
this.optionsToolStripMenuItem,
this.sourceControlToolStripMenuItem});
this.toolsToolStripMenuItem.MergeIndex = 4;
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.toolsToolStripMenuItem.Text = "Tools";
//
// pluginsToolStripMenuItem
//
this.pluginsToolStripMenuItem.Name = "pluginsToolStripMenuItem";
this.pluginsToolStripMenuItem.Size = new System.Drawing.Size(157, 22);
this.pluginsToolStripMenuItem.Text = "Plugins...";
this.pluginsToolStripMenuItem.Click += new System.EventHandler(this.pluginsToolStripMenuItem_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(157, 22);
this.optionsToolStripMenuItem.Text = "Options...";
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click);
//
// sourceControlToolStripMenuItem
//
this.sourceControlToolStripMenuItem.Name = "sourceControlToolStripMenuItem";
this.sourceControlToolStripMenuItem.Size = new System.Drawing.Size(157, 22);
this.sourceControlToolStripMenuItem.Text = "Source Control...";
this.sourceControlToolStripMenuItem.Click += new System.EventHandler(this.sourceControlToolStripMenuItem_Click);
//
// windowToolStripMenuItem
//
this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.closeAllDocumentsToolStripMenuItem,
this.findFileInProjectToolStripMenuItem,
this.toolStripSeparator3});
this.windowToolStripMenuItem.MergeIndex = 5;
this.windowToolStripMenuItem.Name = "windowToolStripMenuItem";
this.windowToolStripMenuItem.Size = new System.Drawing.Size(57, 20);
this.windowToolStripMenuItem.Text = "Window";
//
// closeAllDocumentsToolStripMenuItem
//
this.closeAllDocumentsToolStripMenuItem.Name = "closeAllDocumentsToolStripMenuItem";
this.closeAllDocumentsToolStripMenuItem.Size = new System.Drawing.Size(239, 22);
this.closeAllDocumentsToolStripMenuItem.Text = "Close All Documents";
this.closeAllDocumentsToolStripMenuItem.Click += new System.EventHandler(this.closeAllDocumentsToolStripMenuItem_Click);
//
// findFileInProjectToolStripMenuItem
//
this.findFileInProjectToolStripMenuItem.Name = "findFileInProjectToolStripMenuItem";
this.findFileInProjectToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.O)));
this.findFileInProjectToolStripMenuItem.Size = new System.Drawing.Size(239, 22);
this.findFileInProjectToolStripMenuItem.Text = "Find File in Project...";
this.findFileInProjectToolStripMenuItem.Click += new System.EventHandler(this.findFileInProjectToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(236, 6);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem,
this.projectWebSiteToolStripMenuItem,
this.reportBugToolStripMenuItem,
this.requestFeatureToolStripMenuItem});
this.helpToolStripMenuItem.MergeAction = System.Windows.Forms.MergeAction.Insert;
this.helpToolStripMenuItem.MergeIndex = 6;
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(167, 22);
this.aboutToolStripMenuItem.Text = "About";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// projectWebSiteToolStripMenuItem
//
this.projectWebSiteToolStripMenuItem.Name = "projectWebSiteToolStripMenuItem";
this.projectWebSiteToolStripMenuItem.Size = new System.Drawing.Size(167, 22);
this.projectWebSiteToolStripMenuItem.Text = "Project Web Site...";
this.projectWebSiteToolStripMenuItem.Click += new System.EventHandler(this.projectWebSiteToolStripMenuItem_Click);
//
// reportBugToolStripMenuItem
//
this.reportBugToolStripMenuItem.Name = "reportBugToolStripMenuItem";
this.reportBugToolStripMenuItem.Size = new System.Drawing.Size(167, 22);
this.reportBugToolStripMenuItem.Text = "Report Bug...";
this.reportBugToolStripMenuItem.Click += new System.EventHandler(this.reportBugToolStripMenuItem_Click);
//
// requestFeatureToolStripMenuItem
//
this.requestFeatureToolStripMenuItem.Name = "requestFeatureToolStripMenuItem";
this.requestFeatureToolStripMenuItem.Size = new System.Drawing.Size(167, 22);
this.requestFeatureToolStripMenuItem.Text = "Request Feature...";
this.requestFeatureToolStripMenuItem.Click += new System.EventHandler(this.requestFeatureToolStripMenuItem_Click);
//
// statusStrip
//
this.statusStrip.Dock = System.Windows.Forms.DockStyle.None;
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusMessage,
this.toolStripProgressBar});
this.statusStrip.Location = new System.Drawing.Point(0, 0);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(843, 22);
this.statusStrip.TabIndex = 1;
this.statusStrip.Text = "statusStrip1";
//
// statusMessage
//
this.statusMessage.Name = "statusMessage";
this.statusMessage.Size = new System.Drawing.Size(828, 17);
this.statusMessage.Spring = true;
this.statusMessage.Text = "Status message";
this.statusMessage.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// toolStripProgressBar
//
this.toolStripProgressBar.Name = "toolStripProgressBar";
this.toolStripProgressBar.Size = new System.Drawing.Size(100, 16);
this.toolStripProgressBar.Visible = false;
//
// saveProjectDialog
//
this.saveProjectDialog.DefaultExt = "vcproj";
this.saveProjectDialog.Filter = "Visual Studio Project Files (*.vcproj)|*.vcproj|XML Project Files (*.xml)|*.xml|A" +
"ll Files (*.*)|*.*";
this.saveProjectDialog.RestoreDirectory = true;
this.saveProjectDialog.Title = "Save Project";
//
// openProjectDialog
//
this.openProjectDialog.DefaultExt = "vcproj";
this.openProjectDialog.Filter = "Visual Studio Project Files (*.vcproj)|*.vcproj|XML Project Files (*.xml)|*.xml|A" +
"ll Files (*.*)|*.*";
this.openProjectDialog.RestoreDirectory = true;
//
// statusMessageTimer
//
this.statusMessageTimer.Tick += new System.EventHandler(this.statusMessageTimer_Tick);
//
// saveDocumentDialog
//
this.saveDocumentDialog.RestoreDirectory = true;
this.saveDocumentDialog.SupportMultiDottedExtensions = true;
//
// openDocumentDialog
//
this.openDocumentDialog.Multiselect = true;
this.openDocumentDialog.RestoreDirectory = true;
this.openDocumentDialog.SupportMultiDottedExtensions = true;
//
// toolStripPanelTop
//
this.toolStripPanelTop.Controls.Add(this.menuStrip);
this.toolStripPanelTop.Dock = System.Windows.Forms.DockStyle.Top;
this.toolStripPanelTop.Location = new System.Drawing.Point(0, 0);
this.toolStripPanelTop.Name = "toolStripPanelTop";
this.toolStripPanelTop.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.toolStripPanelTop.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.toolStripPanelTop.Size = new System.Drawing.Size(843, 24);
//
// toolStripPanelBottom
//
this.toolStripPanelBottom.Controls.Add(this.statusStrip);
this.toolStripPanelBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
this.toolStripPanelBottom.Location = new System.Drawing.Point(0, 372);
this.toolStripPanelBottom.Name = "toolStripPanelBottom";
this.toolStripPanelBottom.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.toolStripPanelBottom.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.toolStripPanelBottom.Size = new System.Drawing.Size(843, 22);
//
// toolStripPanelLeft
//
this.toolStripPanelLeft.Dock = System.Windows.Forms.DockStyle.Left;
this.toolStripPanelLeft.Location = new System.Drawing.Point(0, 24);
this.toolStripPanelLeft.Name = "toolStripPanelLeft";
this.toolStripPanelLeft.Orientation = System.Windows.Forms.Orientation.Vertical;
this.toolStripPanelLeft.RowMargin = new System.Windows.Forms.Padding(0, 3, 0, 0);
this.toolStripPanelLeft.Size = new System.Drawing.Size(0, 348);
//
// toolStripPanelRight
//
this.toolStripPanelRight.Dock = System.Windows.Forms.DockStyle.Right;
this.toolStripPanelRight.Location = new System.Drawing.Point(843, 24);
this.toolStripPanelRight.Name = "toolStripPanelRight";
this.toolStripPanelRight.Orientation = System.Windows.Forms.Orientation.Vertical;
this.toolStripPanelRight.RowMargin = new System.Windows.Forms.Padding(0, 3, 0, 0);
this.toolStripPanelRight.Size = new System.Drawing.Size(0, 348);
//
// mDockPanel
//
this.mDockPanel.ActiveAutoHideContent = null;
this.mDockPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.mDockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.mDockPanel.Location = new System.Drawing.Point(0, 0);
this.mDockPanel.Name = "mDockPanel";
this.mDockPanel.Size = new System.Drawing.Size(843, 394);
this.mDockPanel.TabIndex = 3;
this.mDockPanel.ActiveContentChanged += new System.EventHandler(this.mDockPanel_ActiveContentChanged);
this.mDockPanel.ContentAdded += new System.EventHandler<WeifenLuo.WinFormsUI.Docking.DockContentEventArgs>(this.mDockPanel_ContentAdded);
this.mDockPanel.ActiveDocumentChanged += new System.EventHandler(this.mDockPanel_ActiveDocumentChanged);
this.mDockPanel.ContentRemoved += new System.EventHandler<WeifenLuo.WinFormsUI.Docking.DockContentEventArgs>(this.mDockPanel_ContentRemoved);
//
// notifyIcon
//
this.notifyIcon.Text = "Notify Icon";
this.notifyIcon.Visible = true;
this.notifyIcon.BalloonTipClicked += new System.EventHandler(this.notifyIcon_BalloonTipClicked);
this.notifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick);
//
// persistWindowComponent
//
this.persistWindowComponent.Form = this;
this.persistWindowComponent.RegistryKey = "MainWindow";
//
// MainWindow
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(843, 394);
this.Controls.Add(this.toolStripPanelRight);
this.Controls.Add(this.toolStripPanelLeft);
this.Controls.Add(this.toolStripPanelBottom);
this.Controls.Add(this.toolStripPanelTop);
this.Controls.Add(this.mDockPanel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.MainMenuStrip = this.menuStrip;
this.Name = "MainWindow";
this.Text = "Tilde";
this.Load += new System.EventHandler(this.MainWindow_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.MainWindow_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.MainWindow_DragEnter);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainWindow_FormClosing);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.toolStripPanelTop.ResumeLayout(false);
this.toolStripPanelTop.PerformLayout();
this.toolStripPanelBottom.ResumeLayout(false);
this.toolStripPanelBottom.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStripMenuItem tsiFile;
private System.Windows.Forms.ToolStripMenuItem tsiFileOpenProject;
private System.Windows.Forms.ToolStripMenuItem tsiFileSaveProject;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem tsiFileExit;
private System.Windows.Forms.ToolStripMenuItem tsiEdit;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsiFileNewProject;
private System.Windows.Forms.SaveFileDialog saveProjectDialog;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pluginsToolStripMenuItem;
public System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripStatusLabel statusMessage;
public System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.OpenFileDialog openProjectDialog;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem tsiFileRecentProjects;
private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeAllDocumentsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem tsiFileOpenFile;
private System.Windows.Forms.ToolStripMenuItem tsiFileSaveAll;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private Tilde.Framework.View.PersistWindowComponent persistWindowComponent;
private System.Windows.Forms.ToolStripMenuItem tsiFileSave;
private System.Windows.Forms.Timer statusMessageTimer;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar;
private System.Windows.Forms.SaveFileDialog saveDocumentDialog;
private System.Windows.Forms.OpenFileDialog openDocumentDialog;
public System.Windows.Forms.ToolStripPanel toolStripPanelTop;
public System.Windows.Forms.ToolStripPanel toolStripPanelRight;
public System.Windows.Forms.ToolStripPanel toolStripPanelLeft;
public System.Windows.Forms.ToolStripPanel toolStripPanelBottom;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
internal System.Windows.Forms.NotifyIcon notifyIcon;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findFileInProjectToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem reportBugToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem requestFeatureToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsiFileCloseProject;
private System.Windows.Forms.ToolStripMenuItem goToNextLocationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem goToPreviousLocationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsiFileSaveAs;
private System.Windows.Forms.ToolStripMenuItem sourceControlToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem projectWebSiteToolStripMenuItem;
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Engine.CodeGeneration
{
public class LogicCodeGenerator
{
public string SolutionName = null!;
public string SolutionFolder = null!;
public Schema CurrentSchema = null!;
protected bool? overwriteFiles = null;
public virtual void GenerateLogicFromEntities()
{
CurrentSchema = Schema.Current;
GetSolutionInfo(out SolutionFolder, out SolutionName);
string projectFolder = GetProjectFolder();
if (!Directory.Exists(projectFolder))
throw new InvalidOperationException("{0} not found. Override GetProjectFolder".FormatWith(projectFolder));
foreach (var mod in GetModules())
{
string str = WriteFile(mod);
string fileName = Path.Combine(projectFolder, GetFileName(mod));
FileTools.CreateParentDirectory(fileName);
if (!File.Exists(fileName) || SafeConsole.Ask(ref overwriteFiles, "Overwrite {0}?".FormatWith(fileName)))
{
File.WriteAllText(fileName, str);
}
}
}
protected virtual string GetProjectFolder()
{
return Path.Combine(SolutionFolder, SolutionName + ".Logic");
}
protected virtual void GetSolutionInfo(out string solutionFolder, out string solutionName)
{
CodeGenerator.GetSolutionInfo(out solutionFolder, out solutionName);
}
protected virtual string GetFileName(Module t)
{
return t.ModuleName + "\\" + t.ModuleName + "Logic.cs";
}
protected virtual IEnumerable<Module> GetModules()
{
Dictionary<Type, bool> types = CandidateTypes().ToDictionary(a => a, Schema.Current.Tables.ContainsKey);
return CodeGenerator.GetModules(types, this.SolutionName);
}
protected virtual List<Type> CandidateTypes()
{
var assembly = Assembly.Load(Assembly.GetEntryAssembly()!.GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities"));
return assembly.GetTypes().Where(t => t.IsEntity() && !t.IsAbstract).ToList();
}
protected virtual string WriteFile(Module mod)
{
var expression = mod.Types.SelectMany(t => GetExpressions(t)).ToList();
StringBuilder sb = new StringBuilder();
foreach (var item in GetUsingNamespaces(mod, expression))
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine("namespace " + GetNamespace(mod));
sb.AppendLine("{");
sb.Append(WriteLogicClass(mod, expression).Indent(4));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WriteLogicClass(Module mod, List<ExpressionInfo> expressions)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public static class " + mod.ModuleName + "Logic");
sb.AppendLine("{");
foreach (var ei in expressions)
{
string info = WriteExpressionMethod(ei);
if (info != null)
{
sb.Append(info.Indent(4));
sb.AppendLine();
}
}
sb.Append(WriteStartMethod(mod, expressions).Indent(4));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string GetNamespace(Module mod)
{
return SolutionName + ".Logic." + mod.ModuleName;
}
protected virtual List<string> GetUsingNamespaces(Module mod, List<ExpressionInfo> expressions)
{
var result = new List<string>()
{
"System",
"System.Collections.Generic",
"System.Linq",
"System.Linq.Expressions",
"System.Text",
"System.Reflection",
"Signum.Utilities",
"Signum.Utilities.ExpressionTrees",
"Signum.Entities",
"Signum.Engine",
"Signum.Engine.Operations",
"Signum.Engine.Maps",
"Signum.Engine.DynamicQuery",
};
result.AddRange(mod.Types.Concat(expressions.Select(e => e.FromType)).Select(t => t.Namespace!).Distinct());
return result;
}
protected virtual string WriteStartMethod(Module mod, List<ExpressionInfo> expressions)
{
var allExpressions = expressions.ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine("public static void Start(SchemaBuilder sb)");
sb.AppendLine("{");
sb.AppendLine(" if (sb.NotDefined(MethodInfo.GetCurrentMethod()))");
sb.AppendLine(" {");
foreach (var item in mod.Types)
{
string include = WriteInclude(item, allExpressions);
if (include != null)
{
sb.Append(include.Indent(8));
sb.AppendLine();
}
string? query = WriteQuery(item);
if (query != null)
{
sb.Append(query.Indent(8));
sb.AppendLine();
}
string opers = WriteOperations(item);
if (opers != null)
{
sb.Append(opers.Indent(8));
sb.AppendLine();
}
}
if (allExpressions.Any())
{
foreach (var ei in allExpressions)
{
string register = GetRegisterExpression(ei);
if (register != null)
sb.AppendLine(register.Indent(8));
}
sb.AppendLine();
}
sb.AppendLine(" }");
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string GetRegisterExpression(ExpressionInfo ei)
{
return "QueryLogic.Expressions.Register(({from} {f}) => {f}.{name}(), () => typeof({to}).{NiceName}());"
.Replace("{from}", ei.FromType.Name)
.Replace("{to}", ei.ToType.Name)
.Replace("{f}", GetVariableName(ei.FromType))
.Replace("{name}", ei.Name)
.Replace("{NiceName}", ei.IsUnique ? "NiceName" : "NicePluralName");
}
protected virtual string WriteInclude(Type type, List<ExpressionInfo> expression)
{
var ops = GetOperationsSymbols(type);
var save = ops.SingleOrDefaultEx(o => GetOperationType(o) == OperationType.Execute && IsSave(o));
var delete = ops.SingleOrDefaultEx(o => GetOperationType(o) == OperationType.Delete);
var p = ShouldWriteSimpleQuery(type) ? GetVariableName(type) : null;
var simpleExpressions = expression.Extract(exp => IsSimpleExpression(exp, type));
return new[]
{
"sb.Include<" + type.TypeName() + ">()",
GetWithVirtualMLists(type),
save != null && ShouldWriteSimpleOperations(save) ? (" .WithSave(" + save.Symbol.ToString() + ")") : null,
delete != null && ShouldWriteSimpleOperations(delete) ? (" .WithDelete(" + delete.Symbol.ToString() + ")") : null,
simpleExpressions.HasItems() ? simpleExpressions.ToString(e => $" .WithExpressionFrom(({e.FromType.Name} {GetVariableName(e.FromType)}) => {GetVariableName(e.FromType)}.{e.Name}())", "\r\n") : null,
p == null ? null : $" .WithQuery(() => {p} => {WriteQueryConstructor(type, p)})"
}.NotNull().ToString("\r\n") + ";";
}
private bool IsSimpleExpression(ExpressionInfo exp, Type type)
{
return !exp.IsUnique && type == exp.ToType;
}
protected virtual string? WriteQuery(Type type)
{
if (ShouldWriteSimpleQuery(type))
return null;
string typeName = type.TypeName();
var v = GetVariableName(type);
StringBuilder sb = new StringBuilder();
sb.AppendLine("QueryLogic.Queries.Register(typeof({0}), () =>".FormatWith(typeName));
sb.AppendLine(" from {0} in Database.Query<{1}>()".FormatWith(v, typeName));
sb.AppendLine(" select " + WriteQueryConstructor(type, v) + ");");
return sb.ToString();
}
private string WriteQueryConstructor(Type type, string v)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("new");
sb.AppendLine(" {");
sb.AppendLine(" Entity = {0},".FormatWith(v));
sb.AppendLine(" {0}.Id,".FormatWith(v));
foreach (var prop in GetQueryProperties(type))
{
sb.AppendLine(" {0}.{1},".FormatWith(v, prop.Name));
}
sb.Append(" }");
return sb.ToString();
}
protected virtual bool ShouldWriteSimpleQuery(Type type)
{
return true;
}
protected internal class ExpressionInfo
{
public Type FromType;
public Type ToType;
public PropertyInfo Property;
public bool IsUnique;
public string Name = null!;
public ExpressionInfo(Type fromType, Type toType, PropertyInfo property, bool isUnique)
{
FromType = fromType;
ToType = toType;
Property = property;
IsUnique = isUnique;
}
}
protected virtual List<ExpressionInfo> GetExpressions(Type toType)
{
var result = (from pi in Reflector.PublicInstanceDeclaredPropertiesInOrder(toType)
let fromType = pi.PropertyType.CleanType()
where fromType.IsEntity() && !fromType.IsAbstract
let fi = Reflector.TryFindFieldInfo(toType, pi)
where fi != null
let isUnique = fi.GetCustomAttribute<UniqueIndexAttribute>() != null
select new ExpressionInfo(fromType, toType, pi, isUnique))
.ToList();
foreach (var ei in result)
{
ei.Name = GetExpressionName(ei);
}
result = result.GroupBy(ei => new { ei.FromType, ei.ToType }).Where(g => g.Count() == 1).SelectMany(g => g).ToList();
result = result.Where(ShouldWriteExpression).ToList();
return result;
}
protected virtual string GetExpressionName(ExpressionInfo ei)
{
if (ei.Property.Name == "Parent")
return "Children";
if(ei.IsUnique)
return Reflector.CleanTypeName(ei.ToType);
return NaturalLanguageTools.Pluralize(Reflector.CleanTypeName(ei.ToType).SpacePascal()).ToPascal();
}
protected virtual bool ShouldWriteExpression(ExpressionInfo ei)
{
switch (EntityKindCache.GetEntityKind(ei.FromType))
{
case EntityKind.Part:
case EntityKind.String:
case EntityKind.SystemString: return false;
default: return true;
}
}
protected virtual string WriteExpressionMethod(ExpressionInfo info)
{
Type from = info.Property.PropertyType.CleanType();
string varFrom = GetVariableName(from);
string varTo = GetVariableName(info.ToType);
if (varTo == varFrom)
varTo += "2";
string filter = info.Property.PropertyType.IsLite() ? "{t} => {t}.{prop}.Is({f})" : "{t} => {t}.{prop} == {f}";
string str = info.IsUnique?
@"[AutoExpressionField]
public static {to} {Method}(this {from} {f}) => As.Expression(() => Database.Query<{to}>().SingleOrDefaultEx({filter}));
" :
@"[AutoExpressionField]
public static IQueryable<{to}> {Method}(this {from} {f}) => As.Expression(() => Database.Query<{to}>().Where({filter}));
";
return str.Replace("{filter}", filter)
.Replace("{from}", from.Name)
.Replace("{to}", info.ToType.Name)
.Replace("{t}", varTo)
.Replace("{f}", varFrom)
.Replace("{prop}", info.Property.Name)
.Replace("{Method}", info.Name);
}
protected virtual IEnumerable<PropertyInfo> GetQueryProperties(Type type)
{
return (from p in Reflector.PublicInstancePropertiesInOrder(type)
where Reflector.QueryableProperty(type, p)
where IsSimpleValueType(p.PropertyType) || p.PropertyType.IsEntity() || p.PropertyType.IsLite()
orderby p.Name.Contains("Name") ? 1 : 2
select p).Take(10);
}
protected virtual string? GetWithVirtualMLists(Type type)
{
return (from p in Reflector.PublicInstancePropertiesInOrder(type)
let bp = GetVirtualMListBackReference(p)
where bp != null
select GetWithVirtualMList(type, p, bp)).ToString("\r\n").DefaultText(null!);
}
protected virtual string GetWithVirtualMList(Type type, PropertyInfo p, PropertyInfo bp)
{
var p1 = GetVariableName(type);
var p2 = GetVariableName(p.PropertyType.ElementType()!);
if (p1 == p2)
p2 += "2";
var cast = p.DeclaringType == bp.PropertyType.CleanType() ? "" : $"(Lite<{p.DeclaringType!.Name}>)";
return $" .WithVirtualMList({p1} => {p1}.{p.Name}, {p2} => {cast}{p2}.{bp.Name})";
}
protected virtual PropertyInfo? GetVirtualMListBackReference(PropertyInfo pi)
{
if (!pi.PropertyType.IsMList())
return null;
if (!pi.PropertyType.ElementType()!.IsEntity())
return null;
if (!pi.HasAttribute<IgnoreAttribute>())
return null;
var t = pi.PropertyType.ElementType()!;
var backProperty = Reflector.PublicInstancePropertiesInOrder(t).SingleOrDefaultEx(bp => IsVirtualMListBackReference(bp, pi.DeclaringType!));
return backProperty;
}
protected virtual bool IsVirtualMListBackReference(PropertyInfo pi, Type targetType)
{
if (!pi.PropertyType.IsLite())
return false;
if (pi.PropertyType.CleanType() == targetType)
return true;
if (pi.GetCustomAttribute<ImplementedByAttribute>()?.ImplementedTypes.Contains(targetType) == true)
return true;
return false;
}
protected virtual bool IsSimpleValueType(Type type)
{
var t = CurrentSchema.Settings.TryGetSqlDbTypePair(type.UnNullify());
return t != null && t.UserDefinedTypeName == null && (t.DbType.IsNumber() || t.DbType.IsString() || t.DbType.IsDate());
}
protected virtual string WriteOperations(Type type)
{
StringBuilder sb = new StringBuilder();
foreach (var oper in GetOperationsSymbols(type))
{
string? operation = WriteOperation(oper);
if (operation != null)
{
sb.Append(operation);
sb.AppendLine();
}
}
return sb.ToString();
}
protected virtual string? WriteOperation(IOperationSymbolContainer oper)
{
switch (GetOperationType(oper))
{
case OperationType.Execute:
if (IsSave(oper) && ShouldWriteSimpleOperations(oper))
return null;
return WriteExecuteOperation(oper);
case OperationType.Delete:
return WriteDeleteOperation(oper);
case OperationType.Constructor:
return WriteConstructSimple(oper);
case OperationType.ConstructorFrom:
return WriteConstructFrom(oper);
case OperationType.ConstructorFromMany:
return WriteConstructFromMany(oper);
default:
throw new InvalidOperationException();
}
}
private OperationType GetOperationType(IOperationSymbolContainer oper)
{
string type = oper.GetType().TypeName();
if (type.Contains("ExecuteSymbolImp"))
return OperationType.Execute;
if (type.Contains("DeleteSymbolImp"))
return OperationType.Delete;
if (type.Contains("SimpleImp"))
return OperationType.Constructor;
if (type.Contains("FromImp"))
return OperationType.ConstructorFrom;
if (type.Contains("FromManyImp"))
return OperationType.ConstructorFromMany;
;
throw new InvalidOperationException();
}
protected virtual string WriteExecuteOperation(IOperationSymbolContainer oper)
{
Type type = oper.GetType().GetGenericArguments().Single();
var v = GetVariableName(type);
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Graph<{0}>.Execute({1})".FormatWith(type.TypeName(), oper.Symbol.ToString()));
sb.AppendLine("{");
if (IsSave(oper))
{
sb.AppendLine(" CanBeNew = true,");
sb.AppendLine(" CanBeModified = true,");
}
sb.AppendLine(" Execute = ({0}, _) => {{ }}".FormatWith(v));
sb.AppendLine("}.Register();");
return sb.ToString();
}
private bool ShouldWriteSimpleOperations(IOperationSymbolContainer oper)
{
return true;
}
protected virtual bool IsSave(IOperationSymbolContainer oper)
{
return oper.ToString()!.Contains("Save");
}
protected virtual string? WriteDeleteOperation(IOperationSymbolContainer oper)
{
if (ShouldWriteSimpleOperations(oper))
return null;
Type type = oper.GetType().GetGenericArguments().Single();
string v = GetVariableName(type);
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Graph<{0}>.Delete({1})".FormatWith(type.TypeName(), oper.Symbol.ToString()));
sb.AppendLine("{");
sb.AppendLine(" Delete = ({0}, _) => {0}.Delete()".FormatWith(v));
sb.AppendLine("}.Register();");
return sb.ToString();
}
protected virtual string GetVariableName(Type type)
{
return type.Name.Substring(0, 1).ToLower();
}
protected virtual string WriteConstructSimple(IOperationSymbolContainer oper)
{
Type type = oper.GetType().GetGenericArguments().Single();
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Graph<{0}>.Construct({1})".FormatWith(type.TypeName(), oper.Symbol.ToString()));
sb.AppendLine("{");
sb.AppendLine(" Construct = (_) => new {0}".FormatWith(type.TypeName()));
sb.AppendLine(" {");
sb.AppendLine(" }");
sb.AppendLine("}.Register();");
return sb.ToString();
}
protected virtual string WriteConstructFrom(IOperationSymbolContainer oper)
{
List<Type> type = oper.GetType().GetGenericArguments().ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Graph<{0}>.ConstructFrom<{1}>({2})".FormatWith(type[0].TypeName(), type[1].TypeName(), oper.Symbol.ToString()));
sb.AppendLine("{");
sb.AppendLine(" Construct = ({0}, _) => new {1}".FormatWith(GetVariableName(type[1]), type[0].TypeName()));
sb.AppendLine(" {");
sb.AppendLine(" }");
sb.AppendLine("}.Register();");
return sb.ToString();
}
protected virtual string WriteConstructFromMany(IOperationSymbolContainer oper)
{
List<Type> type = oper.GetType().GetGenericArguments().ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Graph<{0}>.ConstructFromMany<{1}>({2})".FormatWith(type[0].TypeName(), type[1].TypeName(), oper.Symbol.ToString()));
sb.AppendLine("{");
sb.AppendLine(" Construct = ({0}s, _) => new {1}".FormatWith(GetVariableName(type[1]), type[0].TypeName()));
sb.AppendLine(" {");
sb.AppendLine(" }");
sb.AppendLine("}.Register();");
return sb.ToString();
}
protected virtual IEnumerable<IOperationSymbolContainer> GetOperationsSymbols(Type type)
{
string name = type.FullName!.RemoveSuffix("Entity") + "Operation";
var operType = type.Assembly.GetType(name);
if (operType == null)
return Enumerable.Empty<IOperationSymbolContainer>();
return (from fi in operType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)
select (IOperationSymbolContainer)fi.GetValue(null)!).ToList();
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Citrina
{
public class UsersSubscriptionsItem
{
/// <summary>
/// Returns if a profile is deleted or blocked.
/// </summary>
public string Deactivated { get; set; }
/// <summary>
/// User first name.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Returns if a profile is hidden.
/// </summary>
public int? Hidden { get; set; }
/// <summary>
/// User ID.
/// </summary>
public int? Id { get; set; }
/// <summary>
/// User last name.
/// </summary>
public string LastName { get; set; }
public bool? CanAccessClosed { get; set; }
public bool? IsClosed { get; set; }
/// <summary>
/// User sex.
/// </summary>
public int? Sex { get; set; }
/// <summary>
/// Domain name of the user's page.
/// </summary>
public string ScreenName { get; set; }
/// <summary>
/// URL of square photo of the user with 50 pixels in width.
/// </summary>
public string Photo50 { get; set; }
/// <summary>
/// URL of square photo of the user with 100 pixels in width.
/// </summary>
public string Photo100 { get; set; }
/// <summary>
/// Information whether the user is online.
/// </summary>
public bool? Online { get; set; }
/// <summary>
/// Information whether the user is online in mobile site or application.
/// </summary>
public bool? OnlineMobile { get; set; }
/// <summary>
/// Application ID.
/// </summary>
public int? OnlineApp { get; set; }
/// <summary>
/// Information whether the user is verified.
/// </summary>
public bool? Verified { get; set; }
/// <summary>
/// Information whether the user has a "fire" pictogram.
/// </summary>
public bool? Trending { get; set; }
public int? FriendStatus { get; set; }
public FriendsRequestsMutual Mutual { get; set; }
public string Type { get; set; }
public int? AdminLevel { get; set; }
/// <summary>
/// Information whether community is banned.
/// </summary>
public string Deactivated { get; set; }
/// <summary>
/// Finish date in Unixtime format.
/// </summary>
public int? FinishDate { get; set; }
/// <summary>
/// Community ID.
/// </summary>
public int? Id { get; set; }
/// <summary>
/// Information whether current user is administrator.
/// </summary>
public bool? IsAdmin { get; set; }
/// <summary>
/// Information whether current user is advertiser.
/// </summary>
public bool? IsAdvertiser { get; set; }
public int? IsClosed { get; set; }
/// <summary>
/// Information whether current user is member.
/// </summary>
public bool? IsMember { get; set; }
/// <summary>
/// Community name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// URL of square photo of the community with 100 pixels in width.
/// </summary>
public string Photo100 { get; set; }
/// <summary>
/// URL of square photo of the community with 200 pixels in width.
/// </summary>
public string Photo200 { get; set; }
/// <summary>
/// URL of square photo of the community with 50 pixels in width.
/// </summary>
public string Photo50 { get; set; }
/// <summary>
/// Domain of the community page.
/// </summary>
public string ScreenName { get; set; }
/// <summary>
/// Start date in Unixtime format.
/// </summary>
public int? StartDate { get; set; }
public string Type { get; set; }
public GroupsMarketInfo Market { get; set; }
/// <summary>
/// Current user's member status.
/// </summary>
public int? MemberStatus { get; set; }
/// <summary>
/// Information whether community is in faves.
/// </summary>
public bool? IsFavorite { get; set; }
/// <summary>
/// Information whether current user is subscribed.
/// </summary>
public bool? IsSubscribed { get; set; }
public BaseObject City { get; set; }
public BaseCountry Country { get; set; }
/// <summary>
/// Information whether community is verified.
/// </summary>
public bool? Verified { get; set; }
/// <summary>
/// Community description.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Community's main wiki page title.
/// </summary>
public string WikiPage { get; set; }
/// <summary>
/// Community members number.
/// </summary>
public int? MembersCount { get; set; }
public GroupsCountersGroup Counters { get; set; }
public GroupsCover Cover { get; set; }
/// <summary>
/// Information whether current user can post on community's wall.
/// </summary>
public bool? CanPost { get; set; }
/// <summary>
/// Information whether current user can see all posts on community's wall.
/// </summary>
public bool? CanSeeAllPosts { get; set; }
/// <summary>
/// Type of group, start date of event or category of public page.
/// </summary>
public string Activity { get; set; }
/// <summary>
/// Fixed post ID.
/// </summary>
public int? FixedPost { get; set; }
/// <summary>
/// Information whether current user can create topic.
/// </summary>
public bool? CanCreateTopic { get; set; }
/// <summary>
/// Information whether current user can upload video.
/// </summary>
public bool? CanUploadVideo { get; set; }
/// <summary>
/// Information whether community has photo.
/// </summary>
public bool? HasPhoto { get; set; }
/// <summary>
/// Community status.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Community's main photo album ID.
/// </summary>
public int? MainAlbumId { get; set; }
public IEnumerable<GroupsLinksItem> Links { get; set; }
public IEnumerable<GroupsContactsItem> Contacts { get; set; }
/// <summary>
/// Community's website.
/// </summary>
public string Site { get; set; }
public int? MainSection { get; set; }
/// <summary>
/// Information whether the community has a "fire" pictogram.
/// </summary>
public bool? Trending { get; set; }
/// <summary>
/// Information whether current user can send a message to community.
/// </summary>
public bool? CanMessage { get; set; }
/// <summary>
/// Information whether community can send a message to current user.
/// </summary>
public bool? IsMessagesBlocked { get; set; }
/// <summary>
/// Information whether community can send notifications by phone number to current user.
/// </summary>
public bool? CanSendNotify { get; set; }
/// <summary>
/// Status of replies in community messages.
/// </summary>
public GroupsOnlineStatus OnlineStatus { get; set; }
/// <summary>
/// Information whether age limit.
/// </summary>
public int? AgeLimits { get; set; }
/// <summary>
/// User ban info.
/// </summary>
public GroupsGroupBanInfo BanInfo { get; set; }
/// <summary>
/// Info about addresses in groups.
/// </summary>
public GroupsAddressesInfo Addresses { get; set; }
/// <summary>
/// Information whether current user is subscribed to podcasts.
/// </summary>
public bool? IsSubscribedPodcasts { get; set; }
/// <summary>
/// Owner in whitelist or not.
/// </summary>
public bool? CanSubscribePodcasts { get; set; }
/// <summary>
/// Can subscribe to wall.
/// </summary>
public bool? CanSubscribePosts { get; set; }
}
}
| |
using System.Collections.Generic;
using Shouldly;
using Xunit;
using System.Linq;
namespace AutoMapper.UnitTests
{
public class When_a_source_child_object_is_null : AutoMapperSpecBase
{
public class Source
{
public Child Child { get; set; }
}
public class Destination
{
public Child Child { get; set; } = new Child();
}
public class Child
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>().ForMember(d => d.Child, o => o.MapAtRuntime());
});
[Fact]
public void Should_overwrite_the_existing_child_destination()
{
var destination = new Destination();
Mapper.Map(new Source(), destination);
destination.Child.ShouldBeNull();
}
}
public class When_the_destination_object_is_specified : AutoMapperSpecBase
{
private Source _source;
private Destination _originalDest;
private Destination _dest;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_source = new Source
{
Value = 10,
};
_originalDest = new Destination { Value = 1111 };
_dest = Mapper.Map<Source, Destination>(_source, _originalDest);
}
[Fact]
public void Should_do_the_translation()
{
_dest.Value.ShouldBe(10);
}
[Fact]
public void Should_return_the_destination_object_that_was_passed_in()
{
_originalDest.ShouldBeSameAs(_dest);
}
}
public class When_the_destination_object_is_specified_with_child_objects : AutoMapperSpecBase
{
private Source _source;
private Destination _originalDest;
private Destination _dest;
public class Source
{
public int Value { get; set; }
public ChildSource Child { get; set; }
}
public class Destination
{
public int Value { get; set; }
public string Name { get; set; }
public ChildDestination Child { get; set; }
}
public class ChildSource
{
public int Value { get; set; }
}
public class ChildDestination
{
public int Value { get; set; }
public string Name { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source)
.ForMember(d => d.Child, opt => opt.UseDestinationValue());
cfg.CreateMap<ChildSource, ChildDestination>(MemberList.Source)
.ForMember(d => d.Name, opt => opt.UseDestinationValue());
});
protected override void Because_of()
{
_source = new Source
{
Value = 10,
Child = new ChildSource
{
Value = 20
}
};
_originalDest = new Destination
{
Value = 1111,
Name = "foo",
Child = new ChildDestination
{
Name = "bar"
}
};
_dest = Mapper.Map<Source, Destination>(_source, _originalDest);
}
[Fact]
public void Should_do_the_translation()
{
_dest.Value.ShouldBe(10);
_dest.Child.Value.ShouldBe(20);
}
[Fact]
public void Should_return_the_destination_object_that_was_passed_in()
{
_dest.Name.ShouldBe("foo");
_dest.Child.Name.ShouldBe("bar");
}
}
public class When_the_destination_object_has_child_objects : AutoMapperSpecBase
{
private Source _source;
private Destination _originalDest;
private ChildDestination _originalDestChild;
private Destination _dest;
public class Source
{
public ChildSource Child { get; set; }
}
public class Destination
{
public ChildDestination Child { get; set; }
}
public class ChildSource
{
public int Value { get; set; }
}
public class ChildDestination
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<ChildSource, ChildDestination>();
});
protected override void Because_of()
{
_source = new Source
{
Child = new ChildSource
{
Value = 20
}
};
_originalDestChild = new ChildDestination
{
Value = 10
};
_originalDest = new Destination
{
Child = _originalDestChild
};
_dest = Mapper.Map(_source, _originalDest);
}
[Fact]
public void Should_return_the_destination_object_that_was_passed_in()
{
_dest.ShouldBeSameAs(_originalDest);
_dest.Child.ShouldBeSameAs(_originalDestChild);
_dest.Child.Value.ShouldBe(20);
}
}
public class When_the_destination_object_is_specified_and_you_are_converting_an_enum : NonValidatingSpecBase
{
private string _result;
public enum SomeEnum
{
One,
Two,
Three
}
protected override MapperConfiguration CreateConfiguration() => new(cfg => { });
protected override void Because_of()
{
_result = Mapper.Map<SomeEnum, string>(SomeEnum.Two, "test");
}
[Fact]
public void Should_return_the_enum_as_a_string()
{
_result.ShouldBe("Two");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Creates the helper class for known folders.
/// </summary>
public static class KnownFolderHelper
{
static KnownFolderHelper()
{
// Private constructor to prevent the compiler from generating the default one.
}
/// <summary>
/// Returns the native known folder (IKnownFolderNative) given a PID list
/// </summary>
/// <param name="pidl"></param>
/// <returns></returns>
internal static IKnownFolderNative FromPIDL(IntPtr pidl)
{
IKnownFolderManager knownFolderManager = (IKnownFolderManager)new KnownFolderManagerClass();
IKnownFolderNative knownFolder;
HRESULT hr = knownFolderManager.FindFolderFromIDList(pidl, out knownFolder);
if (hr != HRESULT.S_OK)
return null;
else
return knownFolder;
}
/// <summary>
/// Returns a known folder given a globally unique identifier.
/// </summary>
/// <param name="knownFolderId">A GUID for the requested known folder.</param>
/// <returns>A known folder representing the specified name.</returns>
/// <exception cref="System.ArgumentException">Thrown if the given Known Folder ID is invalid.</exception>
public static IKnownFolder FromKnownFolderId(Guid knownFolderId)
{
IKnownFolderNative knownFolderNative;
IKnownFolderManager knownFolderManager = (IKnownFolderManager)new KnownFolderManagerClass();
HRESULT hr = knownFolderManager.GetFolder(knownFolderId, out knownFolderNative);
if (hr == HRESULT.S_OK)
{
IKnownFolder kf = GetKnownFolder(knownFolderNative);
if (kf != null)
return kf;
else
throw new ArgumentException("Given Known Folder ID is invalid.", "knownFolderId");
}
else
throw Marshal.GetExceptionForHR((int)hr);
}
/// <summary>
/// Returns a known folder given a globally unique identifier.
/// </summary>
/// <param name="knownFolderId">A GUID for the requested known folder.</param>
/// <returns>A known folder representing the specified name. Returns null if Known Folder is not found or could not be created.</returns>
internal static IKnownFolder FromKnownFolderIdInternal(Guid knownFolderId)
{
IKnownFolderNative knownFolderNative;
IKnownFolderManager knownFolderManager = (IKnownFolderManager)new KnownFolderManagerClass();
HRESULT hr = knownFolderManager.GetFolder(knownFolderId, out knownFolderNative);
if (hr == HRESULT.S_OK)
{
return GetKnownFolder(knownFolderNative);
}
else
return null;
}
/// <summary>
/// Given a native KnownFolder (IKnownFolderNative), create the right type of
/// IKnownFolder object (FileSystemKnownFolder or NonFileSystemKnownFolder)
/// </summary>
/// <param name="knownFolderNative">Native Known Folder</param>
/// <returns></returns>
private static IKnownFolder GetKnownFolder(IKnownFolderNative knownFolderNative)
{
Debug.Assert(knownFolderNative != null, "Native IKnownFolder should not be null.");
// Get the native IShellItem2 from the native IKnownFolder
IShellItem2 shellItem;
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
HRESULT hr = knownFolderNative.GetShellItem(0, ref guid, out shellItem);
if (!CoreErrorHelper.Succeeded((int)hr))
return null;
bool isFileSystem = false;
// If we have a valid IShellItem, try to get the FileSystem attribute.
if (shellItem != null)
{
ShellNativeMethods.SFGAO sfgao;
shellItem.GetAttributes(ShellNativeMethods.SFGAO.SFGAO_FILESYSTEM, out sfgao);
// Is this item a FileSystem item?
isFileSystem = (sfgao & ShellNativeMethods.SFGAO.SFGAO_FILESYSTEM) != 0;
}
// If it's FileSystem, create a FileSystemKnownFolder, else NonFileSystemKnownFolder
if (isFileSystem)
{
FileSystemKnownFolder kf = new FileSystemKnownFolder(knownFolderNative);
return kf;
}
else
{
NonFileSystemKnownFolder kf = new NonFileSystemKnownFolder(knownFolderNative);
return kf;
}
}
/// <summary>
/// Returns the known folder given its canonical name.
/// </summary>
/// <param name="canonicalName">A non-localized canonical name for the known folder, such as MyComputer.</param>
/// <returns>A known folder representing the specified name.</returns>
/// <exception cref="System.ArgumentException">Thrown if the given canonical name is invalid or if the KnownFolder could not be created.</exception>
public static IKnownFolder FromCanonicalName(string canonicalName)
{
IKnownFolderNative knownFolderNative;
IKnownFolderManager knownFolderManager = (IKnownFolderManager)new KnownFolderManagerClass();
knownFolderManager.GetFolderByName(canonicalName, out knownFolderNative);
IKnownFolder kf = KnownFolderHelper.GetKnownFolder(knownFolderNative);
if (kf != null)
return kf;
else
throw new ArgumentException("Canonical name is invalid.", "canonicalName");
}
/// <summary>
/// Returns a known folder given its shell path, such as <c>C:\users\public\documents</c> or
/// <c>::{645FF040-5081-101B-9F08-00AA002F954E}</c> for the Recycle Bin.
/// </summary>
/// <param name="path">The path for the requested known folder; either a physical path or a virtual path.</param>
/// <returns>A known folder representing the specified name.</returns>
public static IKnownFolder FromPath(string path)
{
return KnownFolderHelper.FromParsingName(path);
}
/// <summary>
/// Returns a known folder given its shell namespace parsing name, such as
/// <c>::{645FF040-5081-101B-9F08-00AA002F954E}</c> for the Recycle Bin.
/// </summary>
/// <param name="parsingName">The parsing name (or path) for the requested known folder.</param>
/// <returns>A known folder representing the specified name.</returns>
/// <exception cref="System.ArgumentException">Thrown if the given parsing name is invalid.</exception>
public static IKnownFolder FromParsingName(string parsingName)
{
IntPtr pidl = IntPtr.Zero;
IntPtr pidl2 = IntPtr.Zero;
try
{
pidl = ShellHelper.PidlFromParsingName(parsingName);
if (pidl == IntPtr.Zero)
{
throw new ArgumentException("Parsing name is invalid.", "parsingName");
}
// It's probably a special folder, try to get it
IKnownFolderNative knownFolderNative = KnownFolderHelper.FromPIDL(pidl);
if (knownFolderNative != null)
{
IKnownFolder kf = KnownFolderHelper.GetKnownFolder(knownFolderNative);
if (kf != null)
return kf;
else
throw new ArgumentException("Parsing name is invalid.", "parsingName");
}
else
{
// No physical storage was found for this known folder
// We'll try again with a different name
// try one more time with a trailing \0
pidl2 = ShellHelper.PidlFromParsingName(parsingName.PadRight(1, '\0'));
if (pidl2 == IntPtr.Zero)
{
throw new ArgumentException("Parsing name is invalid.", "parsingName");
}
IKnownFolder kf = KnownFolderHelper.GetKnownFolder(KnownFolderHelper.FromPIDL(pidl));
if (kf != null)
return kf;
else
throw new ArgumentException("Parsing name is invalid.", "parsingName");
}
}
finally
{
ShellNativeMethods.ILFree(pidl);
ShellNativeMethods.ILFree(pidl2);
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.ImportExport.CS
{
/// <summary>
/// Provide a dialog which provides the options of lower priority information for export
/// </summary>
partial class ExportBaseOptionsForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelLayersAndProperties = new System.Windows.Forms.Label();
this.comboBoxLayersAndProperties = new System.Windows.Forms.ComboBox();
this.labelLinetypeScaling = new System.Windows.Forms.Label();
this.comboBoxLinetypeScaling = new System.Windows.Forms.ComboBox();
this.labelCoorSystem = new System.Windows.Forms.Label();
this.comboBoxCoorSystem = new System.Windows.Forms.ComboBox();
this.labelDWGUnit = new System.Windows.Forms.Label();
this.comboBoxDWGUnit = new System.Windows.Forms.ComboBox();
this.labelSolids = new System.Windows.Forms.Label();
this.comboBoxSolids = new System.Windows.Forms.ComboBox();
this.checkBoxExportingAreas = new System.Windows.Forms.CheckBox();
this.buttonOK = new System.Windows.Forms.Button();
this.labelLayerSettings = new System.Windows.Forms.Label();
this.comboBoxLayerSettings = new System.Windows.Forms.ComboBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.checkBoxMergeViews = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// labelLayersAndProperties
//
this.labelLayersAndProperties.AutoSize = true;
this.labelLayersAndProperties.Location = new System.Drawing.Point(13, 13);
this.labelLayersAndProperties.Name = "labelLayersAndProperties";
this.labelLayersAndProperties.Size = new System.Drawing.Size(111, 13);
this.labelLayersAndProperties.TabIndex = 0;
this.labelLayersAndProperties.Text = "Layers and properties:";
//
// comboBoxLayersAndProperties
//
this.comboBoxLayersAndProperties.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxLayersAndProperties.FormattingEnabled = true;
this.comboBoxLayersAndProperties.Location = new System.Drawing.Point(16, 30);
this.comboBoxLayersAndProperties.Name = "comboBoxLayersAndProperties";
this.comboBoxLayersAndProperties.Size = new System.Drawing.Size(301, 21);
this.comboBoxLayersAndProperties.TabIndex = 1;
//
// labelLinetypeScaling
//
this.labelLinetypeScaling.AutoSize = true;
this.labelLinetypeScaling.Location = new System.Drawing.Point(13, 96);
this.labelLinetypeScaling.Name = "labelLinetypeScaling";
this.labelLinetypeScaling.Size = new System.Drawing.Size(86, 13);
this.labelLinetypeScaling.TabIndex = 0;
this.labelLinetypeScaling.Text = "Linetype scaling:";
//
// comboBoxLinetypeScaling
//
this.comboBoxLinetypeScaling.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxLinetypeScaling.FormattingEnabled = true;
this.comboBoxLinetypeScaling.Location = new System.Drawing.Point(16, 113);
this.comboBoxLinetypeScaling.Name = "comboBoxLinetypeScaling";
this.comboBoxLinetypeScaling.Size = new System.Drawing.Size(301, 21);
this.comboBoxLinetypeScaling.TabIndex = 3;
//
// labelCoorSystem
//
this.labelCoorSystem.AutoSize = true;
this.labelCoorSystem.Location = new System.Drawing.Point(13, 142);
this.labelCoorSystem.Name = "labelCoorSystem";
this.labelCoorSystem.Size = new System.Drawing.Size(123, 13);
this.labelCoorSystem.TabIndex = 0;
this.labelCoorSystem.Text = "Coordinate system basis:";
//
// comboBoxCoorSystem
//
this.comboBoxCoorSystem.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxCoorSystem.FormattingEnabled = true;
this.comboBoxCoorSystem.Location = new System.Drawing.Point(16, 157);
this.comboBoxCoorSystem.Name = "comboBoxCoorSystem";
this.comboBoxCoorSystem.Size = new System.Drawing.Size(301, 21);
this.comboBoxCoorSystem.TabIndex = 4;
//
// labelDWGUnit
//
this.labelDWGUnit.AutoSize = true;
this.labelDWGUnit.Location = new System.Drawing.Point(13, 184);
this.labelDWGUnit.Name = "labelDWGUnit";
this.labelDWGUnit.Size = new System.Drawing.Size(90, 13);
this.labelDWGUnit.TabIndex = 0;
this.labelDWGUnit.Text = "One DWG unit is:";
//
// comboBoxDWGUnit
//
this.comboBoxDWGUnit.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxDWGUnit.FormattingEnabled = true;
this.comboBoxDWGUnit.Location = new System.Drawing.Point(16, 198);
this.comboBoxDWGUnit.Name = "comboBoxDWGUnit";
this.comboBoxDWGUnit.Size = new System.Drawing.Size(301, 21);
this.comboBoxDWGUnit.TabIndex = 5;
//
// labelSolids
//
this.labelSolids.AutoSize = true;
this.labelSolids.Location = new System.Drawing.Point(13, 224);
this.labelSolids.Name = "labelSolids";
this.labelSolids.Size = new System.Drawing.Size(113, 13);
this.labelSolids.TabIndex = 0;
this.labelSolids.Text = "Solids (3D views only):";
//
// comboBoxSolids
//
this.comboBoxSolids.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSolids.FormattingEnabled = true;
this.comboBoxSolids.Location = new System.Drawing.Point(16, 241);
this.comboBoxSolids.Name = "comboBoxSolids";
this.comboBoxSolids.Size = new System.Drawing.Size(301, 21);
this.comboBoxSolids.TabIndex = 6;
//
// checkBoxExportingAreas
//
this.checkBoxExportingAreas.AutoSize = true;
this.checkBoxExportingAreas.Location = new System.Drawing.Point(16, 271);
this.checkBoxExportingAreas.Name = "checkBoxExportingAreas";
this.checkBoxExportingAreas.Size = new System.Drawing.Size(194, 17);
this.checkBoxExportingAreas.TabIndex = 7;
this.checkBoxExportingAreas.Text = "Export rooms and areas as polylines";
this.checkBoxExportingAreas.UseVisualStyleBackColor = true;
//
// buttonOK
//
this.buttonOK.Location = new System.Drawing.Point(161, 335);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 0;
this.buttonOK.Text = "&OK";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// labelLayerSettings
//
this.labelLayerSettings.AutoSize = true;
this.labelLayerSettings.Location = new System.Drawing.Point(13, 55);
this.labelLayerSettings.Name = "labelLayerSettings";
this.labelLayerSettings.Size = new System.Drawing.Size(75, 13);
this.labelLayerSettings.TabIndex = 0;
this.labelLayerSettings.Text = "Layer settings:";
//
// comboBoxLayerSettings
//
this.comboBoxLayerSettings.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxLayerSettings.FormattingEnabled = true;
this.comboBoxLayerSettings.Location = new System.Drawing.Point(16, 72);
this.comboBoxLayerSettings.Name = "comboBoxLayerSettings";
this.comboBoxLayerSettings.Size = new System.Drawing.Size(301, 21);
this.comboBoxLayerSettings.TabIndex = 2;
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(242, 335);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "&Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// checkBoxMergeViews
//
this.checkBoxMergeViews.AutoSize = true;
this.checkBoxMergeViews.Location = new System.Drawing.Point(16, 294);
this.checkBoxMergeViews.Name = "checkBoxMergeViews";
this.checkBoxMergeViews.Size = new System.Drawing.Size(220, 17);
this.checkBoxMergeViews.TabIndex = 9;
this.checkBoxMergeViews.Text = "Create separate files for each view/sheet";
this.checkBoxMergeViews.UseVisualStyleBackColor = true;
//
// ExportBaseOptionsForm
//
this.AcceptButton = this.buttonOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(336, 368);
this.Controls.Add(this.checkBoxMergeViews);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.checkBoxExportingAreas);
this.Controls.Add(this.comboBoxSolids);
this.Controls.Add(this.labelSolids);
this.Controls.Add(this.comboBoxDWGUnit);
this.Controls.Add(this.labelDWGUnit);
this.Controls.Add(this.comboBoxCoorSystem);
this.Controls.Add(this.labelCoorSystem);
this.Controls.Add(this.comboBoxLinetypeScaling);
this.Controls.Add(this.labelLinetypeScaling);
this.Controls.Add(this.comboBoxLayerSettings);
this.Controls.Add(this.labelLayerSettings);
this.Controls.Add(this.comboBoxLayersAndProperties);
this.Controls.Add(this.labelLayersAndProperties);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExportBaseOptionsForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelLayersAndProperties;
private System.Windows.Forms.ComboBox comboBoxLayersAndProperties;
private System.Windows.Forms.Label labelLinetypeScaling;
private System.Windows.Forms.ComboBox comboBoxLinetypeScaling;
private System.Windows.Forms.Label labelCoorSystem;
private System.Windows.Forms.ComboBox comboBoxCoorSystem;
private System.Windows.Forms.Label labelDWGUnit;
private System.Windows.Forms.ComboBox comboBoxDWGUnit;
private System.Windows.Forms.Label labelSolids;
private System.Windows.Forms.ComboBox comboBoxSolids;
private System.Windows.Forms.CheckBox checkBoxExportingAreas;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Label labelLayerSettings;
private System.Windows.Forms.ComboBox comboBoxLayerSettings;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.CheckBox checkBoxMergeViews;
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuantConnect.Data;
using System.Collections.Concurrent;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Logging;
namespace QuantConnect.Securities
{
/// <summary>
/// Provides a means of keeping track of the different cash holdings of an algorithm
/// </summary>
public class CashBook : IDictionary<string, Cash>
{
/// <summary>
/// Gets the base currency used
/// </summary>
public const string AccountCurrency = "USD";
private readonly ConcurrentDictionary<string, Cash> _currencies;
/// <summary>
/// Gets the total value of the cash book in units of the base currency
/// </summary>
public decimal TotalValueInAccountCurrency
{
get { return _currencies.Sum(x => x.Value.ValueInAccountCurrency); }
}
/// <summary>
/// Initializes a new instance of the <see cref="CashBook"/> class.
/// </summary>
public CashBook()
{
_currencies = new ConcurrentDictionary<string, Cash>();
_currencies.AddOrUpdate(AccountCurrency, new Cash(AccountCurrency, 0, 1.0m));
}
/// <summary>
/// Adds a new cash of the specified symbol and quantity
/// </summary>
/// <param name="symbol">The symbol used to reference the new cash</param>
/// <param name="quantity">The amount of new cash to start</param>
/// <param name="conversionRate">The conversion rate used to determine the initial
/// portfolio value/starting capital impact caused by this currency position.</param>
public void Add(string symbol, decimal quantity, decimal conversionRate)
{
var cash = new Cash(symbol, quantity, conversionRate);
_currencies.AddOrUpdate(symbol, cash);
}
/// <summary>
/// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data
/// </summary>
/// <param name="securities">The SecurityManager for the algorithm</param>
/// <param name="subscriptions">The SubscriptionManager for the algorithm</param>
/// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param>
/// <param name="symbolPropertiesDatabase">A symbol properties database instance</param>
/// <param name="marketMap">The market map that decides which market the new security should be in</param>
/// <returns>Returns a list of added currency securities</returns>
public List<Security> EnsureCurrencyDataFeeds(SecurityManager securities, SubscriptionManager subscriptions, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase, IReadOnlyDictionary<SecurityType, string> marketMap, SecurityChanges changes)
{
var addedSecurities = new List<Security>();
foreach (var kvp in _currencies)
{
var cash = kvp.Value;
var security = cash.EnsureCurrencyDataFeed(securities, subscriptions, marketHoursDatabase, symbolPropertiesDatabase, marketMap, this, changes);
if (security != null)
{
addedSecurities.Add(security);
}
}
return addedSecurities;
}
/// <summary>
/// Converts a quantity of source currency units into the specified destination currency
/// </summary>
/// <param name="sourceQuantity">The quantity of source currency to be converted</param>
/// <param name="sourceCurrency">The source currency symbol</param>
/// <param name="destinationCurrency">The destination currency symbol</param>
/// <returns>The converted value</returns>
public decimal Convert(decimal sourceQuantity, string sourceCurrency, string destinationCurrency)
{
var source = this[sourceCurrency];
var destination = this[destinationCurrency];
if (source.ConversionRate == 0)
{
throw new Exception($"The conversion rate for {sourceCurrency} is not available.");
}
if (destination.ConversionRate == 0)
{
throw new Exception($"The conversion rate for {destinationCurrency} is not available.");
}
var conversionRate = source.ConversionRate / destination.ConversionRate;
return sourceQuantity * conversionRate;
}
/// <summary>
/// Converts a quantity of source currency units into the account currency
/// </summary>
/// <param name="sourceQuantity">The quantity of source currency to be converted</param>
/// <param name="sourceCurrency">The source currency symbol</param>
/// <returns>The converted value</returns>
public decimal ConvertToAccountCurrency(decimal sourceQuantity, string sourceCurrency)
{
return Convert(sourceQuantity, sourceCurrency, AccountCurrency);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("{0} {1,13} {2,10} = {3}", "Symbol", "Quantity", "Conversion", "Value in " + AccountCurrency));
foreach (var value in _currencies.Select(x => x.Value))
{
sb.AppendLine(value.ToString());
}
sb.AppendLine("-------------------------------------------------");
sb.AppendLine(string.Format("CashBook Total Value: {0}{1}",
Currencies.GetCurrencySymbol(AccountCurrency),
Math.Round(TotalValueInAccountCurrency, 2))
);
return sb.ToString();
}
#region IDictionary Implementation
/// <summary>
/// Gets the count of Cash items in this CashBook.
/// </summary>
/// <value>The count.</value>
public int Count => _currencies.Skip(0).Count();
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly
{
get { return ((IDictionary<string, Cash>) _currencies).IsReadOnly; }
}
/// <summary>
/// Add the specified item to this CashBook.
/// </summary>
/// <param name="item">KeyValuePair of symbol -> Cash item</param>
public void Add(KeyValuePair<string, Cash> item)
{
_currencies.AddOrUpdate(item.Key, item.Value);
}
/// <summary>
/// Add the specified key and value.
/// </summary>
/// <param name="symbol">The symbol of the Cash value.</param>
/// <param name="value">Value.</param>
public void Add(string symbol, Cash value)
{
_currencies.AddOrUpdate(symbol, value);
}
/// <summary>
/// Clear this instance of all Cash entries.
/// </summary>
public void Clear()
{
_currencies.Clear();
}
/// <summary>
/// Remove the Cash item corresponding to the specified symbol
/// </summary>
/// <param name="symbol">The symbolto be removed</param>
public bool Remove(string symbol)
{
Cash cash = null;
var removed = _currencies.TryRemove(symbol, out cash);
if (!removed)
{
Log.Error(string.Format("CashBook.Remove(): Failed to remove the cash book record for symbol {0}", symbol));
}
return removed;
}
/// <summary>
/// Remove the specified item.
/// </summary>
/// <param name="item">Item.</param>
public bool Remove(KeyValuePair<string, Cash> item)
{
Cash cash = null;
var removed = _currencies.TryRemove(item.Key, out cash);
if (!removed)
{
Log.Error(string.Format("CashBook.Remove(): Failed to remove the cash book record for symbol {0} - {1}", item.Key, item.Value != null ? item.Value.ToString() : "(null)"));
}
return removed;
}
/// <summary>
/// Determines whether the current instance contains an entry with the specified symbol.
/// </summary>
/// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns>
/// <param name="symbol">Key.</param>
public bool ContainsKey(string symbol)
{
return _currencies.ContainsKey(symbol);
}
/// <summary>
/// Try to get the value.
/// </summary>
/// <remarks>To be added.</remarks>
/// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns>
/// <param name="symbol">The symbol.</param>
/// <param name="value">Value.</param>
public bool TryGetValue(string symbol, out Cash value)
{
return _currencies.TryGetValue(symbol, out value);
}
/// <summary>
/// Determines whether the current collection contains the specified value.
/// </summary>
/// <param name="item">Item.</param>
public bool Contains(KeyValuePair<string, Cash> item)
{
return _currencies.Contains(item);
}
/// <summary>
/// Copies to the specified array.
/// </summary>
/// <param name="array">Array.</param>
/// <param name="arrayIndex">Array index.</param>
public void CopyTo(KeyValuePair<string, Cash>[] array, int arrayIndex)
{
((IDictionary<string, Cash>) _currencies).CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets or sets the <see cref="QuantConnect.Securities.Cash"/> with the specified symbol.
/// </summary>
/// <param name="symbol">Symbol.</param>
public Cash this[string symbol]
{
get
{
Cash cash;
if (!_currencies.TryGetValue(symbol, out cash))
{
throw new Exception("This cash symbol (" + symbol + ") was not found in your cash book.");
}
return cash;
}
set
{
_currencies[symbol] = value;
}
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys => _currencies.Select(x => x.Key).ToList();
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public ICollection<Cash> Values => _currencies.Select(x => x.Value).ToList();
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<KeyValuePair<string, Cash>> GetEnumerator()
{
return _currencies.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _currencies).GetEnumerator();
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Conditions
{
using System;
using System.Globalization;
using System.Collections.Generic;
using Common;
/// <summary>
/// Condition relational (<b>==</b>, <b>!=</b>, <b><</b>, <b><=</b>,
/// <b>></b> or <b>>=</b>) expression.
/// </summary>
internal sealed class ConditionRelationalExpression : ConditionExpression
{
/// <summary>
/// Initializes a new instance of the <see cref="ConditionRelationalExpression" /> class.
/// </summary>
/// <param name="leftExpression">The left expression.</param>
/// <param name="rightExpression">The right expression.</param>
/// <param name="relationalOperator">The relational operator.</param>
public ConditionRelationalExpression(ConditionExpression leftExpression, ConditionExpression rightExpression, ConditionRelationalOperator relationalOperator)
{
LeftExpression = leftExpression;
RightExpression = rightExpression;
RelationalOperator = relationalOperator;
}
/// <summary>
/// Gets the left expression.
/// </summary>
/// <value>The left expression.</value>
public ConditionExpression LeftExpression { get; private set; }
/// <summary>
/// Gets the right expression.
/// </summary>
/// <value>The right expression.</value>
public ConditionExpression RightExpression { get; private set; }
/// <summary>
/// Gets the relational operator.
/// </summary>
/// <value>The operator.</value>
public ConditionRelationalOperator RelationalOperator { get; private set; }
/// <summary>
/// Returns a string representation of the expression.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the condition expression.
/// </returns>
public override string ToString()
{
return "(" + LeftExpression + " " + GetOperatorString() + " " + RightExpression + ")";
}
/// <summary>
/// Evaluates the expression.
/// </summary>
/// <param name="context">Evaluation context.</param>
/// <returns>Expression result.</returns>
protected override object EvaluateNode(LogEventInfo context)
{
object v1 = LeftExpression.Evaluate(context);
object v2 = RightExpression.Evaluate(context);
return Compare(v1, v2, RelationalOperator);
}
/// <summary>
/// Compares the specified values using specified relational operator.
/// </summary>
/// <param name="leftValue">The first value.</param>
/// <param name="rightValue">The second value.</param>
/// <param name="relationalOperator">The relational operator.</param>
/// <returns>Result of the given relational operator.</returns>
private static object Compare(object leftValue, object rightValue, ConditionRelationalOperator relationalOperator)
{
StringComparer comparer = StringComparer.InvariantCulture;
PromoteTypes(ref leftValue, ref rightValue);
switch (relationalOperator)
{
case ConditionRelationalOperator.Equal:
return comparer.Compare(leftValue, rightValue) == 0;
case ConditionRelationalOperator.NotEqual:
return comparer.Compare(leftValue, rightValue) != 0;
case ConditionRelationalOperator.Greater:
return comparer.Compare(leftValue, rightValue) > 0;
case ConditionRelationalOperator.GreaterOrEqual:
return comparer.Compare(leftValue, rightValue) >= 0;
case ConditionRelationalOperator.LessOrEqual:
return comparer.Compare(leftValue, rightValue) <= 0;
case ConditionRelationalOperator.Less:
return comparer.Compare(leftValue, rightValue) < 0;
default:
throw new NotSupportedException("Relational operator " + relationalOperator + " is not supported.");
}
}
/// <summary>
/// Promote values to the type needed for the comparision, e.g. parse a string to int.
/// </summary>
/// <param name="val1"></param>
/// <param name="val2"></param>
private static void PromoteTypes(ref object val1, ref object val2)
{
if (val1 == null || val2 == null)
{
return;
}
var type1 = val1.GetType();
var type2 = val2.GetType();
if (type1 == type2)
{
return;
}
//types are not equal
var type1Order = GetOrder(type1);
var type2Order = GetOrder(type2);
if (type1Order < type2Order)
{
// first try promote val 2 with type 1
if (TryPromoteTypes(ref val2, type1, ref val1, type2)) return;
}
else
{
// first try promote val 1 with type 2
if (TryPromoteTypes(ref val1, type2, ref val2, type1)) return;
}
throw new ConditionEvaluationException("Cannot find common type for '" + type1.Name + "' and '" + type2.Name + "'.");
}
/// <summary>
/// Promoto <paramref name="val"/> to type
/// </summary>
/// <param name="val"></param>
/// <param name="type1"></param>
/// <returns>success?</returns>
private static bool TryPromoteType(ref object val, Type type1)
{
try
{
if (type1 == typeof(DateTime))
{
val = Convert.ToDateTime(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(double))
{
val = Convert.ToDouble(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(float))
{
val = Convert.ToSingle(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(decimal))
{
val = Convert.ToDecimal(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(long))
{
val = Convert.ToInt64(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(int))
{
val = Convert.ToInt32(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(bool))
{
val = Convert.ToBoolean(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(string))
{
val = Convert.ToString(val, CultureInfo.InvariantCulture);
InternalLogger.Debug("Using string comparision");
return true;
}
}
catch (Exception)
{
InternalLogger.Debug("conversion of {0} to {1} failed", val, type1.Name);
}
return false;
}
/// <summary>
/// Try to promote both values. First try to promote <paramref name="val1"/> to <paramref name="type1"/>,
/// when failed, try <paramref name="val2"/> to <paramref name="type2"/>.
/// </summary>
/// <returns></returns>
private static bool TryPromoteTypes(ref object val1, Type type1, ref object val2, Type type2)
{
if (TryPromoteType(ref val1, type1))
{
return true;
}
return TryPromoteType(ref val2, type2);
}
/// <summary>
/// Get the order for the type for comparision.
/// </summary>
/// <param name="type1"></param>
/// <returns>index, 0 to maxint. Lower is first</returns>
private static int GetOrder(Type type1)
{
int order;
var success = TypePromoteOrder.TryGetValue(type1, out order);
if (success)
{
return order;
}
//not found, try as last
return int.MaxValue;
}
/// <summary>
/// Dictionary from type to index. Lower index should be tested first.
/// </summary>
private static Dictionary<Type, int> TypePromoteOrder = BuildTypeOrderDictionary();
/// <summary>
/// Build the dictionary needed for the order of the types.
/// </summary>
/// <returns></returns>
private static Dictionary<Type, int> BuildTypeOrderDictionary()
{
var list = new List<Type>
{
typeof(DateTime),
typeof(double),
typeof(float),
typeof(decimal),
typeof(long),
typeof(int),
typeof(bool),
typeof(string),
};
var dict = new Dictionary<Type, int>(list.Count);
for (int i = 0; i < list.Count; i++)
{
dict.Add(list[i], i);
}
return dict;
}
/// <summary>
/// Get the string representing the current <see cref="ConditionRelationalOperator"/>
/// </summary>
/// <returns></returns>
private string GetOperatorString()
{
switch (RelationalOperator)
{
case ConditionRelationalOperator.Equal:
return "==";
case ConditionRelationalOperator.NotEqual:
return "!=";
case ConditionRelationalOperator.Greater:
return ">";
case ConditionRelationalOperator.Less:
return "<";
case ConditionRelationalOperator.GreaterOrEqual:
return ">=";
case ConditionRelationalOperator.LessOrEqual:
return "<=";
default:
throw new NotSupportedException("Relational operator " + RelationalOperator + " is not supported.");
}
}
}
}
| |
/* ====================================================================
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 [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace fyiReporting.Data
{
/// <summary>
/// LogCommand allows specifying the command for the web log.
/// </summary>
public class LogCommand : IDbCommand
{
LogConnection _lc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Url; // url of the file
string _Domain; // Domain for the log's web site; e.g. www.fyireporting.com
string _IndexFile; // name of the index file; e.g. what's the default page when none (e.g. index.html)
DataParameterCollection _Parameters = new DataParameterCollection();
public LogCommand(LogConnection conn)
{
_lc = conn;
}
internal string Url
{
get
{
// Check to see if "Url" or "@Url" is a parameter
IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Url"] as IDbDataParameter;
// Then check to see if the Url value is a parameter?
if (dp == null)
dp = _Parameters[_Url] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value
return _Url; // the value must be a constant
}
set {_Url = value;}
}
internal string Domain
{
get
{
// Check to see if "Domain" or "@Domain" is a parameter
IDbDataParameter dp= _Parameters["Domain"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Domain"] as IDbDataParameter;
// Then check to see if the Domain value is a parameter?
if (dp == null)
dp = _Parameters[_Domain] as IDbDataParameter;
return (dp == null || dp.Value == null)? _Domain: dp.Value.ToString();
}
set {_Domain = value;}
}
internal string IndexFile
{
get
{
// Check to see if "IndexFile" or "@IndexFile" is a parameter
IDbDataParameter dp= _Parameters["IndexFile"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@IndexFile"] as IDbDataParameter;
// Then check to see if the IndexFile value is a parameter?
if (dp == null)
dp = _Parameters[_IndexFile] as IDbDataParameter;
return (dp == null || dp.Value == null)? _IndexFile: dp.Value.ToString();
}
set {_IndexFile = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new LogDataReader(behavior, _lc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new LogDataParameter();
}
public IDbConnection Connection
{
get
{
return this._lc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string url=null;
string domain=null;
string indexfile=null;
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "url":
case "file":
url = val;
break;
case "domain":
domain = val;
break;
case "indexfile":
indexfile = val;
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (url == null)
throw new ArgumentException("CommandText requires a 'Url=' parameter.");
_cmd = value;
_Url = url;
_Domain = domain;
_IndexFile = indexfile;
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
//
// SlideShow.cs
//
// Author:
// Stephane Delcroix <[email protected]>
//
// Copyright (C) 2009 Novell, Inc.
// Copyright (C) 2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Gtk;
using Gdk;
using Mono.Addins;
using FSpot.Core;
using FSpot.Bling;
using FSpot.Extensions;
using FSpot.Imaging;
using FSpot.Settings;
using FSpot.Transitions;
using FSpot.Utils;
namespace FSpot.Widgets
{
public class SlideShow : DrawingArea
{
bool running;
BrowsablePointer item;
int loadRetries;
#region Public API
public SlideShow (BrowsablePointer item) : this (item, 6000, false)
{
}
public SlideShow (BrowsablePointer item, uint interval_ms, bool init)
{
this.item = item;
DoubleBuffered = false;
AppPaintable = true;
CanFocus = true;
item.Changed += HandleItemChanged;
foreach (TransitionNode transition in AddinManager.GetExtensionNodes ("/FSpot/SlideShow")) {
if (this.transition == null)
this.transition = transition.Transition;
transitions.Add (transition.Transition);
}
flip = new DelayedOperation (interval_ms, delegate {item.MoveNext (true); return true;});
animation = new DoubleAnimation (0, 1, new TimeSpan (0, 0, 2), HandleProgressChanged, GLib.Priority.Default);
if (init) {
HandleItemChanged (null, null);
}
}
SlideShowTransition transition;
public SlideShowTransition Transition {
get { return transition; }
set {
if (value == transition)
return;
transition = value;
QueueDraw ();
}
}
List<SlideShowTransition> transitions = new List<SlideShowTransition> ();
public IEnumerable<SlideShowTransition> Transitions {
get { return transitions; }
}
DoubleAnimation animation;
DelayedOperation flip;
public void Start ()
{
running = true;
flip.Start ();
}
public void Stop ()
{
running = false;
flip.Stop ();
}
#endregion
#region Event Handlers
Pixbuf prev, next;
object sync_handle = new object ();
void HandleItemChanged (object sender, EventArgs e)
{
flip.Stop ();
if (running)
flip.Start ();
lock (sync_handle) {
if (prev != null && prev != PixbufUtils.ErrorPixbuf)
prev.Dispose ();
prev = next;
LoadNext ();
if (animation.IsRunning)
animation.Stop ();
progress = 0;
animation.Start ();
}
}
void LoadNext ()
{
if (next != null) {
next = null;
}
if (item == null || item.Current == null)
return;
using (var img = App.Instance.Container.Resolve<IImageFileFactory> ().Create (item.Current.DefaultVersion.Uri)) {
try {
using (var pb = img.Load ()) {
double scale = Math.Min ((double)Allocation.Width/(double)pb.Width, (double)Allocation.Height/(double)pb.Height);
int w = (int)(pb.Width * scale);
int h = (int)(pb.Height * scale);
if (w > 0 && h > 0)
next = pb.ScaleSimple ((int)(pb.Width * scale), (int)(pb.Height * scale), InterpType.Bilinear);
}
Cms.Profile screen_profile;
if (FSpot.ColorManagement.Profiles.TryGetValue (Preferences.Get<string> (Preferences.ColorManagementDisplayProfile), out screen_profile))
FSpot.ColorManagement.ApplyProfile (next, screen_profile);
loadRetries = 0;
} catch (Exception) {
next = PixbufUtils.ErrorPixbuf;
if (++loadRetries < 10)
item.MoveNext (true);
else
loadRetries = 0;
}
}
}
double progress;
void HandleProgressChanged (double progress)
{
lock (sync_handle) {
this.progress = progress;
QueueDraw ();
}
}
#endregion
#region Gtk Widgetry
protected override bool OnExposeEvent (Gdk.EventExpose args)
{
lock (sync_handle) {
transition.Draw (args.Window, prev, next, Allocation.Width, Allocation.Height, progress);
}
return true;
}
protected override void OnDestroyed ()
{
if (prev != null && prev != PixbufUtils.ErrorPixbuf)
prev.Dispose ();
if (next != null && next != PixbufUtils.ErrorPixbuf)
next.Dispose ();
base.OnDestroyed ();
}
protected override void OnSizeAllocated (Rectangle allocation)
{
base.OnSizeAllocated (allocation);
LoadNext ();
QueueDraw ();
}
protected override void OnUnrealized ()
{
flip.Stop ();
base.OnUnrealized ();
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
/*
* 2013 WyrmTale Games | MIT License
*
* Based on MiniJSON.cs by Calvin Rien | https://gist.github.com/darktable/1411710
* that was Based on the JSON parser by Patrick van Bergen | http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Extended it so it includes/returns a JSON object that can be accessed using
* indexers. also easy custom class to JSON object mapping by implecit and explicit asignment overloading
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace WyrmTale {
public class JSON {
public Dictionary<string, object> fields = new Dictionary<string, object>();
// Indexer to provide read/write access to the fields
public object this[string fieldName]
{
// Read one byte at offset index and return it.
get
{
if (fields.ContainsKey(fieldName))
return(fields[fieldName]);
return null;
}
// Write one byte at offset index and return it.
set
{
if (fields.ContainsKey(fieldName))
fields[fieldName] = value;
else
fields.Add(fieldName,value);
}
}
public string ToString(string fieldName)
{
if (fields.ContainsKey(fieldName))
return System.Convert.ToString(fields[fieldName]);
else
return "";
}
public int ToInt(string fieldName)
{
if (fields.ContainsKey(fieldName))
return System.Convert.ToInt32(fields[fieldName]);
else
return 0;
}
public float ToFloat(string fieldName)
{
if (fields.ContainsKey(fieldName))
return System.Convert.ToSingle(fields[fieldName]);
else
return 0.0f;
}
public bool ToBoolean(string fieldName)
{
if (fields.ContainsKey(fieldName))
return System.Convert.ToBoolean(fields[fieldName]);
else
return false;
}
public string serialized
{
get
{
return _JSON.Serialize(this);
}
set
{
JSON o = _JSON.Deserialize(value);
if (o!=null)
fields = o.fields;
}
}
public JSON ToJSON(string fieldName)
{
if (!fields.ContainsKey(fieldName))
fields.Add(fieldName, new JSON());
return (JSON)this[fieldName];
}
// to serialize/deserialize a Vector2
public static implicit operator Vector2(JSON value)
{
return new Vector3(
System.Convert.ToSingle(value["x"]),
System.Convert.ToSingle(value["y"]));
}
public static explicit operator JSON(Vector2 value)
{
checked
{
JSON o = new JSON();
o["x"] = value.x;
o["y"] = value.y;
return o;
}
}
// to serialize/deserialize a Vector3
public static implicit operator Vector3(JSON value)
{
return new Vector3(
System.Convert.ToSingle(value["x"]),
System.Convert.ToSingle(value["y"]),
System.Convert.ToSingle(value["z"]));
}
public static explicit operator JSON(Vector3 value)
{
checked
{
JSON o = new JSON();
o["x"] = value.x;
o["y"] = value.y;
o["z"] = value.z;
return o;
}
}
// to serialize/deserialize a Quaternion
public static implicit operator Quaternion(JSON value)
{
return new Quaternion(
System.Convert.ToSingle(value["x"]),
System.Convert.ToSingle(value["y"]),
System.Convert.ToSingle(value["z"]),
System.Convert.ToSingle(value["w"])
);
}
public static explicit operator JSON(Quaternion value)
{
checked
{
JSON o = new JSON();
o["x"] = value.x;
o["y"] = value.y;
o["z"] = value.z;
o["w"] = value.w;
return o;
}
}
// to serialize/deserialize a Color
public static implicit operator Color(JSON value)
{
return new Color(
System.Convert.ToSingle(value["r"]),
System.Convert.ToSingle(value["g"]),
System.Convert.ToSingle(value["b"]),
System.Convert.ToSingle(value["a"])
);
}
public static explicit operator JSON(Color value)
{
checked
{
JSON o = new JSON();
o["r"] = value.r;
o["g"] = value.g;
o["b"] = value.b;
o["a"] = value.a;
return o;
}
}
// to serialize/deserialize a Color32
public static implicit operator Color32(JSON value)
{
return new Color32(
System.Convert.ToByte(value["r"]),
System.Convert.ToByte(value["g"]),
System.Convert.ToByte(value["b"]),
System.Convert.ToByte(value["a"])
);
}
public static explicit operator JSON(Color32 value)
{
checked
{
JSON o = new JSON();
o["r"] = value.r;
o["g"] = value.g;
o["b"] = value.b;
o["a"] = value.a;
return o;
}
}
// to serialize/deserialize a Rect
public static implicit operator Rect(JSON value)
{
return new Rect(
System.Convert.ToByte(value["left"]),
System.Convert.ToByte(value["top"]),
System.Convert.ToByte(value["width"]),
System.Convert.ToByte(value["height"])
);
}
public static explicit operator JSON(Rect value)
{
checked
{
JSON o = new JSON();
o["left"] = value.xMin;
o["top"] = value.yMax;
o["width"] = value.width;
o["height"] = value.height;
return o; }
}
// get typed array out of the object as object[]
public T[] ToArray<T>(string fieldName)
{
if (fields.ContainsKey(fieldName))
{
if (fields[fieldName] is IEnumerable)
{
List<T> l = new List<T>();
foreach (object o in (fields[fieldName] as IEnumerable))
{
if (l is List<string>)
(l as List<string>).Add(System.Convert.ToString(o));
else
if (l is List<int>)
(l as List<int>).Add(System.Convert.ToInt32(o));
else
if (l is List<float>)
(l as List<float>).Add(System.Convert.ToSingle(o));
else
if (l is List<bool>)
(l as List<bool>).Add(System.Convert.ToBoolean(o));
else
if (l is List<Vector2>)
(l as List<Vector2>).Add((Vector2)((JSON)o));
else
if (l is List<Vector3>)
(l as List<Vector3>).Add((Vector3)((JSON)o));
else
if (l is List<Rect>)
(l as List<Rect>).Add((Rect)((JSON)o));
else
if (l is List<Color>)
(l as List<Color>).Add((Color)((JSON)o));
else
if (l is List<Color32>)
(l as List<Color32>).Add((Color32)((JSON)o));
else
if (l is List<Quaternion>)
(l as List<Quaternion>).Add((Quaternion)((JSON)o));
else
if (l is List<JSON>)
(l as List<JSON>).Add((JSON)o);
}
return l.ToArray();
}
}
return new T[]{};
}
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
sealed class _JSON {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static JSON Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static JSON Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return (instance.ParseValue() as JSON);
}
}
public void Dispose() {
json.Dispose();
json = null;
}
JSON ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
JSON obj = new JSON();
obj.fields = table;
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return obj;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(JSON obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(JSON obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
if (value == null) {
builder.Append("null");
}
else if (value as string != null) {
SerializeString(value as string);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if (value as JSON != null) {
SerializeObject(value as JSON);
}
else if (value as IDictionary != null) {
SerializeDictionary(value as IDictionary);
}
else if (value as IList != null) {
SerializeArray(value as IList);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(JSON obj) {
SerializeDictionary(obj.fields);
}
void SerializeDictionary(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Caliburn.Micro;
namespace AllGreen.Runner.WPF.Core
{
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage()]
public class BindableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged
{
private const string CountString = "Count";
private const string IndexerName = "Item[]";
private const string KeysName = "Keys";
private const string ValuesName = "Values";
private IDictionary<TKey, TValue> _Dictionary;
protected IDictionary<TKey, TValue> Dictionary
{
get { return _Dictionary; }
}
#region Constructors
public BindableDictionary()
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public BindableDictionary(IDictionary<TKey, TValue> dictionary)
{
_Dictionary = new Dictionary<TKey, TValue>(dictionary);
}
public BindableDictionary(IEqualityComparer<TKey> comparer)
{
_Dictionary = new Dictionary<TKey, TValue>(comparer);
}
public BindableDictionary(int capacity)
{
_Dictionary = new Dictionary<TKey, TValue>(capacity);
}
public BindableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_Dictionary = new Dictionary<TKey, TValue>(dictionary, comparer);
}
public BindableDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_Dictionary = new Dictionary<TKey, TValue>(capacity, comparer);
}
#endregion
#region IDictionary<TKey,TValue> Members
public void Add(TKey key, TValue value)
{
Insert(key, value, true);
}
public bool ContainsKey(TKey key)
{
return Dictionary.ContainsKey(key);
}
public ICollection<TKey> Keys
{
//get { return Dictionary.Keys; }
get { return new BindableCollection<TKey>(Dictionary.Keys); }
}
public bool Remove(TKey key)
{
if (key == null) throw new ArgumentNullException("key");
TValue value;
Dictionary.TryGetValue(key, out value);
var removed = Dictionary.Remove(key);
if (removed)
OnCollectionChanged(NotifyCollectionChangedAction.Remove, new KeyValuePair<TKey, TValue>(key, value));
return removed;
}
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
//get { return Dictionary.Values; }
get { return new BindableCollection<TValue>(Dictionary.Values); }
}
public TValue this[TKey key]
{
get
{
return Dictionary[key];
}
set
{
Insert(key, value, false);
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
Insert(item.Key, item.Value, true);
}
public void Clear()
{
if (Dictionary.Count > 0)
{
Dictionary.Clear();
OnCollectionChanged();
}
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return Dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Dictionary.CopyTo(array, arrayIndex);
}
public int Count
{
get { return Dictionary.Count; }
}
public bool IsReadOnly
{
get { return Dictionary.IsReadOnly; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return Remove(item.Key);
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return Dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)Dictionary).GetEnumerator();
}
#endregion
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void Insert(TKey key, TValue value, bool add)
{
if (key == null) throw new ArgumentNullException("key");
TValue item;
if (Dictionary.TryGetValue(key, out item))
{
if (add) throw new ArgumentException("An item with the same key has already been added.");
if (Equals(item, value)) return;
Dictionary[key] = value;
OnCollectionChanged(NotifyCollectionChangedAction.Replace, new KeyValuePair<TKey, TValue>(key, value), new KeyValuePair<TKey, TValue>(key, item));
}
else
{
Dictionary[key] = value;
OnCollectionChanged(NotifyCollectionChangedAction.Add, new KeyValuePair<TKey, TValue>(key, value));
}
}
private void OnPropertyChanged()
{
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnPropertyChanged(KeysName);
OnPropertyChanged(ValuesName);
}
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler eventHandler = PropertyChanged;
if (eventHandler != null)
{
Delegate[] delegates = eventHandler.GetInvocationList();
foreach (PropertyChangedEventHandler handler in delegates)
{
var dispatcherObject = handler.Target as System.Windows.Threading.DispatcherObject;
if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
dispatcherObject.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.DataBind,
handler, this, e);
else
handler(this, e);
}
}
}
private void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var eventHandler = CollectionChanged;
if (eventHandler != null)
{
Delegate[] delegates = eventHandler.GetInvocationList();
foreach (NotifyCollectionChangedEventHandler handler in delegates)
{
var dispatcherObject = handler.Target as System.Windows.Threading.DispatcherObject;
if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
dispatcherObject.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.DataBind,
handler, this, e);
else
handler(this, e);
}
}
}
private void OnCollectionChanged()
{
OnPropertyChanged();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> changedItem)
{
OnPropertyChanged();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, changedItem));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> newItem, KeyValuePair<TKey, TValue> oldItem)
{
OnPropertyChanged();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, IList newItems)
{
OnPropertyChanged();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItems));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Automation;
using Microsoft.WindowsAzure.Management.Automation.Models;
namespace Microsoft.WindowsAzure.Management.Automation
{
public static partial class ScheduleOperationsExtensions
{
/// <summary>
/// Create a schedule. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create schedule operation.
/// </param>
/// <returns>
/// The response model for the create schedule operation.
/// </returns>
public static ScheduleCreateResponse Create(this IScheduleOperations operations, string automationAccount, ScheduleCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IScheduleOperations)s).CreateAsync(automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a schedule. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create schedule operation.
/// </param>
/// <returns>
/// The response model for the create schedule operation.
/// </returns>
public static Task<ScheduleCreateResponse> CreateAsync(this IScheduleOperations operations, string automationAccount, ScheduleCreateParameters parameters)
{
return operations.CreateAsync(automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='scheduleName'>
/// Required. The schedule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IScheduleOperations operations, string automationAccount, string scheduleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IScheduleOperations)s).DeleteAsync(automationAccount, scheduleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='scheduleName'>
/// Required. The schedule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IScheduleOperations operations, string automationAccount, string scheduleName)
{
return operations.DeleteAsync(automationAccount, scheduleName, CancellationToken.None);
}
/// <summary>
/// Retrieve the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='scheduleName'>
/// Required. The schedule name.
/// </param>
/// <returns>
/// The response model for the get schedule operation.
/// </returns>
public static ScheduleGetResponse Get(this IScheduleOperations operations, string automationAccount, string scheduleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IScheduleOperations)s).GetAsync(automationAccount, scheduleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='scheduleName'>
/// Required. The schedule name.
/// </param>
/// <returns>
/// The response model for the get schedule operation.
/// </returns>
public static Task<ScheduleGetResponse> GetAsync(this IScheduleOperations operations, string automationAccount, string scheduleName)
{
return operations.GetAsync(automationAccount, scheduleName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list schedule operation.
/// </returns>
public static ScheduleListResponse List(this IScheduleOperations operations, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((IScheduleOperations)s).ListAsync(automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list schedule operation.
/// </returns>
public static Task<ScheduleListResponse> ListAsync(this IScheduleOperations operations, string automationAccount)
{
return operations.ListAsync(automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list schedule operation.
/// </returns>
public static ScheduleListResponse ListNext(this IScheduleOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IScheduleOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list schedule operation.
/// </returns>
public static Task<ScheduleListResponse> ListNextAsync(this IScheduleOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Update the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the update schedule operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Update(this IScheduleOperations operations, string automationAccount, ScheduleUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IScheduleOperations)s).UpdateAsync(automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the update schedule operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UpdateAsync(this IScheduleOperations operations, string automationAccount, ScheduleUpdateParameters parameters)
{
return operations.UpdateAsync(automationAccount, parameters, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using CALI.Database.Contracts;
using CALI.Database.Contracts.Auth;
///////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend.//
///////////////////////////////////////////////////////////
// This file contains static implementations of the UserRoleLogic
// Add your own static methods by making a new partial class.
// You cannot override static methods, instead override the methods
// located in UserRoleLogicBase by making a partial class of UserRoleLogic
// and overriding the base methods.
namespace CALI.Database.Logic.Auth
{
public partial class UserRoleLogic
{
//Put your code in a separate file. This is auto generated.
/// <summary>
/// Run UserRole_Insert.
/// </summary>
/// <param name="fldUserId">Value for UserId</param>
/// <param name="fldRoleId">Value for RoleId</param>
public static int? InsertNow(int fldUserId
, int fldRoleId
)
{
return (new UserRoleLogic()).Insert(fldUserId
, fldRoleId
);
}
/// <summary>
/// Run UserRole_Insert.
/// </summary>
/// <param name="fldUserId">Value for UserId</param>
/// <param name="fldRoleId">Value for RoleId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
public static int? InsertNow(int fldUserId
, int fldRoleId
, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Insert(fldUserId
, fldRoleId
, connection, transaction);
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public static int InsertNow(UserRoleContract row)
{
return (new UserRoleLogic()).Insert(row);
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int InsertNow(UserRoleContract row, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Insert(row, connection, transaction);
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public static int InsertAllNow(List<UserRoleContract> rows)
{
return (new UserRoleLogic()).InsertAll(rows);
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int InsertAllNow(List<UserRoleContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).InsertAll(rows, connection, transaction);
}
/// <summary>
/// Run UserRole_Update.
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <param name="fldUserId">Value for UserId</param>
/// <param name="fldRoleId">Value for RoleId</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(int fldUserRoleId
, int fldUserId
, int fldRoleId
)
{
return (new UserRoleLogic()).Update(fldUserRoleId
, fldUserId
, fldRoleId
);
}
/// <summary>
/// Run UserRole_Update.
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <param name="fldUserId">Value for UserId</param>
/// <param name="fldRoleId">Value for RoleId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(int fldUserRoleId
, int fldUserId
, int fldRoleId
, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Update(fldUserRoleId
, fldUserId
, fldRoleId
, connection, transaction);
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(UserRoleContract row)
{
return (new UserRoleLogic()).Update(row);
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(UserRoleContract row, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Update(row, connection, transaction);
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateAllNow(List<UserRoleContract> rows)
{
return (new UserRoleLogic()).UpdateAll(rows);
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateAllNow(List<UserRoleContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).UpdateAll(rows, connection, transaction);
}
/// <summary>
/// Run UserRole_Delete.
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(int fldUserRoleId
)
{
return (new UserRoleLogic()).Delete(fldUserRoleId
);
}
/// <summary>
/// Run UserRole_Delete.
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(int fldUserRoleId
, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Delete(fldUserRoleId
, connection, transaction);
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(UserRoleContract row)
{
return (new UserRoleLogic()).Delete(row);
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(UserRoleContract row, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Delete(row, connection, transaction);
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteAllNow(List<UserRoleContract> rows)
{
return (new UserRoleLogic()).DeleteAll(rows);
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteAllNow(List<UserRoleContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).DeleteAll(rows, connection, transaction);
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <returns>True, if the values exist, or false.</returns>
public static bool ExistsNow(int fldUserRoleId
)
{
return (new UserRoleLogic()).Exists(fldUserRoleId
);
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public static bool ExistsNow(int fldUserRoleId
, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).Exists(fldUserRoleId
, connection, transaction);
}
/// <summary>
/// Run UserRole_SelectAll, and return results as a list of UserRoleRow.
/// </summary>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectAllNow()
{
var driver = new UserRoleLogic();
driver.SelectAll();
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectAll, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction)
{
var driver = new UserRoleLogic();
driver.SelectAll(connection, transaction);
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectBy_UserRoleId, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectBy_UserRoleIdNow(int fldUserRoleId
)
{
var driver = new UserRoleLogic();
driver.SelectBy_UserRoleId(fldUserRoleId
);
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectBy_UserRoleId, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="fldUserRoleId">Value for UserRoleId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectBy_UserRoleIdNow(int fldUserRoleId
, SqlConnection connection, SqlTransaction transaction)
{
var driver = new UserRoleLogic();
driver.SelectBy_UserRoleId(fldUserRoleId
, connection, transaction);
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectBy_RoleId, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="fldRoleId">Value for RoleId</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectBy_RoleIdNow(int fldRoleId
)
{
var driver = new UserRoleLogic();
driver.SelectBy_RoleId(fldRoleId
);
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectBy_RoleId, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="fldRoleId">Value for RoleId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectBy_RoleIdNow(int fldRoleId
, SqlConnection connection, SqlTransaction transaction)
{
var driver = new UserRoleLogic();
driver.SelectBy_RoleId(fldRoleId
, connection, transaction);
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectBy_UserId, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="fldUserId">Value for UserId</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectBy_UserIdNow(int fldUserId
)
{
var driver = new UserRoleLogic();
driver.SelectBy_UserId(fldUserId
);
return driver.Results;
}
/// <summary>
/// Run UserRole_SelectBy_UserId, and return results as a list of UserRoleRow.
/// </summary>
/// <param name="fldUserId">Value for UserId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of UserRoleRow.</returns>
public static List<UserRoleContract> SelectBy_UserIdNow(int fldUserId
, SqlConnection connection, SqlTransaction transaction)
{
var driver = new UserRoleLogic();
driver.SelectBy_UserId(fldUserId
, connection, transaction);
return driver.Results;
}
/// <summary>
/// Read all UserRole rows from the provided reader into the list structure of UserRoleRows
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
/// <returns>A populated UserRoleRows or an empty UserRoleRows if there are no results.</returns>
public static List<UserRoleContract> ReadAllNow(SqlDataReader reader)
{
var driver = new UserRoleLogic();
driver.ReadAll(reader);
return driver.Results;
}
/// <summary>");
/// Advance one, and read values into a UserRole
/// </summary>
/// <param name="reader">The result of running a sql command.</param>");
/// <returns>A UserRole or null if there are no results.</returns>
public static UserRoleContract ReadOneNow(SqlDataReader reader)
{
var driver = new UserRoleLogic();
return driver.ReadOne(reader) ? driver.Results[0] : null;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public static int SaveNow(UserRoleContract row)
{
if(row.UserRoleId == null)
{
return InsertNow(row);
}
else
{
return UpdateNow(row);
}
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int SaveNow(UserRoleContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row.UserRoleId == null)
{
return InsertNow(row, connection, transaction);
}
else
{
return UpdateNow(row, connection, transaction);
}
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public static int SaveAllNow(List<UserRoleContract> rows)
{
return (new UserRoleLogic()).SaveAll(rows);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int SaveAllNow(List<UserRoleContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new UserRoleLogic()).SaveAll(rows, connection, transaction);
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LogReceiverService
{
using System;
using System.ComponentModel;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
/// <summary>
/// Log Receiver Client facade. It allows the use either of the one way or two way
/// service contract using WCF through its unified interface.
/// </summary>
/// <remarks>
/// Delegating methods are generated with Resharper.
/// 1. change ProxiedClient to private field (instead of public property)
/// 2. delegate members
/// 3. change ProxiedClient back to public property.
///
/// </remarks>
public sealed class WcfLogReceiverClient : IWcfLogReceiverClient
{
/// <summary>
/// The client getting proxied
/// </summary>
public IWcfLogReceiverClient ProxiedClient { get; private set; }
/// <summary>
/// Do we use one-way or two-way messaging?
/// </summary>
public bool UseOneWay { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClient"/> class.
/// </summary>
/// <param name="useOneWay">Whether to use the one way or two way WCF client.</param>
public WcfLogReceiverClient(bool useOneWay)
{
UseOneWay = useOneWay;
ProxiedClient = useOneWay ? (IWcfLogReceiverClient)new WcfLogReceiverOneWayClient() : new WcfLogReceiverTwoWayClient();
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClient"/> class.
/// </summary>
/// <param name="useOneWay">Whether to use the one way or two way WCF client.</param>
/// <param name="endpointConfigurationName">Name of the endpoint configuration.</param>
public WcfLogReceiverClient(bool useOneWay, string endpointConfigurationName)
{
UseOneWay = useOneWay;
ProxiedClient = useOneWay ? (IWcfLogReceiverClient)new WcfLogReceiverOneWayClient(endpointConfigurationName) : new WcfLogReceiverTwoWayClient(endpointConfigurationName);
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClient"/> class.
/// </summary>
/// <param name="useOneWay">Whether to use the one way or two way WCF client.</param>
/// <param name="endpointConfigurationName">Name of the endpoint configuration.</param>
/// <param name="remoteAddress">The remote address.</param>
public WcfLogReceiverClient(bool useOneWay, string endpointConfigurationName, string remoteAddress)
{
UseOneWay = useOneWay;
ProxiedClient = useOneWay ? (IWcfLogReceiverClient)new WcfLogReceiverOneWayClient(endpointConfigurationName, remoteAddress) : new WcfLogReceiverTwoWayClient(endpointConfigurationName, remoteAddress);
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClient"/> class.
/// </summary>
/// <param name="useOneWay">Whether to use the one way or two way WCF client.</param>
/// <param name="endpointConfigurationName">Name of the endpoint configuration.</param>
/// <param name="remoteAddress">The remote address.</param>
public WcfLogReceiverClient(bool useOneWay, string endpointConfigurationName, EndpointAddress remoteAddress)
{
UseOneWay = useOneWay;
ProxiedClient = useOneWay ? (IWcfLogReceiverClient)new WcfLogReceiverOneWayClient(endpointConfigurationName, remoteAddress) : new WcfLogReceiverTwoWayClient(endpointConfigurationName, remoteAddress);
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClient"/> class.
/// </summary>
/// <param name="useOneWay">Whether to use the one way or two way WCF client.</param>
/// <param name="binding">The binding.</param>
/// <param name="remoteAddress">The remote address.</param>
public WcfLogReceiverClient(bool useOneWay, Binding binding, EndpointAddress remoteAddress)
{
UseOneWay = useOneWay;
ProxiedClient = useOneWay ? (IWcfLogReceiverClient)new WcfLogReceiverOneWayClient(binding, remoteAddress) : new WcfLogReceiverTwoWayClient(binding, remoteAddress);
}
#region delegating
/// <summary>
/// Causes a communication object to transition immediately from its current state into the closed state.
/// </summary>
public void Abort()
{
ProxiedClient.Abort();
}
/// <summary>
/// Begins an asynchronous operation to close a communication object.
/// </summary>
/// <returns>
/// The <see cref="T:System.IAsyncResult"/> that references the asynchronous close operation.
/// </returns>
/// <param name="callback">The <see cref="T:System.AsyncCallback"/> delegate that receives notification of the completion of the asynchronous close operation.</param>
/// <param name="state">An object, specified by the application, that contains state information associated with the asynchronous close operation.</param>
/// <exception cref="T:System.ServiceModel.CommunicationObjectFaultedException"><see cref="M:System.ServiceModel.ICommunicationObject.BeginClose"/> was called on an object in the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The default timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to close gracefully.</exception>
public IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return ProxiedClient.BeginClose(callback, state);
}
/// <summary>
/// Begins an asynchronous operation to close a communication object with a specified timeout.
/// </summary>
/// <returns>
/// The <see cref="T:System.IAsyncResult"/> that references the asynchronous close operation.
/// </returns>
/// <param name="timeout">The <see cref="T:System.Timespan"/> that specifies how long the send operation has to complete before timing out.</param>
/// <param name="callback">The <see cref="T:System.AsyncCallback"/> delegate that receives notification of the completion of the asynchronous close operation.</param><param name="state">An object, specified by the application, that contains state information associated with the asynchronous close operation.</param>
/// <exception cref="T:System.ServiceModel.CommunicationObjectFaultedException"><see cref="M:System.ServiceModel.ICommunicationObject.BeginClose"/> was called on an object in the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The specified timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to close gracefully.</exception>
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return ProxiedClient.BeginClose(timeout, callback, state);
}
/// <summary>
/// Begins an asynchronous operation to open a communication object.
/// </summary>
/// <returns>
/// The <see cref="T:System.IAsyncResult"/> that references the asynchronous open operation.
/// </returns>
/// <param name="callback">The <see cref="T:System.AsyncCallback"/> delegate that receives notification of the completion of the asynchronous open operation.</param>
/// <param name="state">An object, specified by the application, that contains state information associated with the asynchronous open operation.</param>
/// <exception cref="T:System.ServiceModel.CommunicationException">The <see cref="T:System.ServiceModel.ICommunicationObject"/> was unable to be opened and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The default open timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to enter the <see cref="F:System.ServiceModel.CommunicationState.Opened"/> state and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return ProxiedClient.BeginOpen(callback, state);
}
/// <summary>
/// Begins an asynchronous operation to open a communication object within a specified interval of time.
/// </summary>
/// <returns>
/// The <see cref="T:System.IAsyncResult"/> that references the asynchronous open operation.
/// </returns>
/// <param name="timeout">The <see cref="T:System.Timespan"/> that specifies how long the send operation has to complete before timing out.</param><param name="callback">The <see cref="T:System.AsyncCallback"/> delegate that receives notification of the completion of the asynchronous open operation.</param>
/// <param name="state">An object, specified by the application, that contains state information associated with the asynchronous open operation.</param>
/// <exception cref="T:System.ServiceModel.CommunicationException">The <see cref="T:System.ServiceModel.ICommunicationObject"/> was unable to be opened and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The specified timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to enter the <see cref="F:System.ServiceModel.CommunicationState.Opened"/> state and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return ProxiedClient.BeginOpen(timeout, callback, state);
}
/// <summary>
/// Begins processing of log messages.
/// </summary>
/// <param name="events">The events to send.</param>
/// <param name="callback">The callback.</param>
/// <param name="asyncState">Asynchronous state.</param>
/// <returns>
/// IAsyncResult value which can be passed to <see cref="ILogReceiverOneWayClient.EndProcessLogMessages"/>.
/// </returns>
public IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState)
{
return ProxiedClient.BeginProcessLogMessages(events, callback, asyncState);
}
/// <summary>
/// Enables the user to configure client and service credentials as well as service credential authentication settings for use on the client side of communication.
/// </summary>
public ClientCredentials ClientCredentials => ProxiedClient.ClientCredentials;
/// <summary>
/// Causes a communication object to transition from its current state into the closed state.
/// </summary>
/// <param name="timeout">The <see cref="T:System.Timespan"/> that specifies how long the send operation has to complete before timing out.</param>
/// <exception cref="T:System.ServiceModel.CommunicationObjectFaultedException"><see cref="M:System.ServiceModel.ICommunicationObject.Close"/> was called on an object in the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to close gracefully.</exception>
public void Close(TimeSpan timeout)
{
ProxiedClient.Close(timeout);
}
/// <summary>
/// Causes a communication object to transition from its current state into the closed state.
/// </summary>
/// <exception cref="T:System.ServiceModel.CommunicationObjectFaultedException"><see cref="M:System.ServiceModel.ICommunicationObject.Close"/> was called on an object in the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The default close timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to close gracefully.</exception>
public void Close()
{
ProxiedClient.Close();
}
/// <summary>
/// Closes the client asynchronously.
/// </summary>
/// <param name="userState">User-specific state.</param>
public void CloseAsync(object userState)
{
ProxiedClient.CloseAsync(userState);
}
/// <summary>
/// Closes the client asynchronously.
/// </summary>
public void CloseAsync()
{
ProxiedClient.CloseAsync();
}
/// <summary>
/// Occurs when Close operation has completed.
/// </summary>
public event EventHandler<AsyncCompletedEventArgs> CloseCompleted
{
add => ProxiedClient.CloseCompleted += value;
remove => ProxiedClient.CloseCompleted -= value;
}
/// <summary>
/// Occurs when the communication object completes its transition from the closing state into the closed state.
/// </summary>
public event EventHandler Closed
{
add => ProxiedClient.Closed += value;
remove => ProxiedClient.Closed -= value;
}
/// <summary>
/// Occurs when the communication object first enters the closing state.
/// </summary>
public event EventHandler Closing
{
add => ProxiedClient.Closing += value;
remove => ProxiedClient.Closing -= value;
}
#if !NETSTANDARD
/// <summary>
/// Instructs the inner channel to display a user interface if one is required to initialize the channel prior to using it.
/// </summary>
public void DisplayInitializationUI()
{
ProxiedClient.DisplayInitializationUI();
}
#endif
#if !NET35 && !NET40 && !NETSTANDARD
/// <summary>
/// Gets or sets the cookie container.
/// </summary>
/// <value>The cookie container.</value>
public CookieContainer CookieContainer
{
get => ProxiedClient.CookieContainer;
set => ProxiedClient.CookieContainer = value;
}
#endif
/// <summary>
/// Completes an asynchronous operation to close a communication object.
/// </summary>
/// <param name="result">The <see cref="T:System.IAsyncResult"/> that is returned by a call to the <see cref="M:System.ServiceModel.ICommunicationObject.BeginClose"/> method.</param>
/// <exception cref="T:System.ServiceModel.CommunicationObjectFaultedException"><see cref="M:System.ServiceModel.ICommunicationObject.BeginClose"/> was called on an object in the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to close gracefully.</exception>
public void EndClose(IAsyncResult result)
{
ProxiedClient.EndClose(result);
}
/// <summary>
/// Completes an asynchronous operation to open a communication object.
/// </summary>
/// <param name="result">The <see cref="T:System.IAsyncResult"/> that is returned by a call to the <see cref="M:System.ServiceModel.ICommunicationObject.BeginOpen"/> method.</param>
/// <exception cref="T:System.ServiceModel.CommunicationException">The <see cref="T:System.ServiceModel.ICommunicationObject"/> was unable to be opened and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to enter the <see cref="F:System.ServiceModel.CommunicationState.Opened"/> state and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
public void EndOpen(IAsyncResult result)
{
ProxiedClient.EndOpen(result);
}
/// <summary>
/// Gets the target endpoint for the service to which the WCF client can connect.
/// </summary>
public ServiceEndpoint Endpoint => ProxiedClient.Endpoint;
/// <summary>
/// Ends asynchronous processing of log messages.
/// </summary>
/// <param name="result">The result.</param>
public void EndProcessLogMessages(IAsyncResult result)
{
ProxiedClient.EndProcessLogMessages(result);
}
/// <summary>
/// Occurs when the communication object first enters the faulted state.
/// </summary>
public event EventHandler Faulted
{
add => ProxiedClient.Faulted += value;
remove => ProxiedClient.Faulted -= value;
}
/// <summary>
/// Gets the underlying <see cref="IClientChannel"/> implementation.
/// </summary>
public IClientChannel InnerChannel => ProxiedClient.InnerChannel;
/// <summary>
/// Causes a communication object to transition from the created state into the opened state.
/// </summary>
/// <exception cref="T:System.ServiceModel.CommunicationException">The <see cref="T:System.ServiceModel.ICommunicationObject"/> was unable to be opened and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The default open timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to enter the <see cref="F:System.ServiceModel.CommunicationState.Opened"/> state and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
public void Open()
{
ProxiedClient.Open();
}
/// <summary>
/// Causes a communication object to transition from the created state into the opened state within a specified interval of time.
/// </summary>
/// <param name="timeout">The <see cref="T:System.Timespan"/> that specifies how long the send operation has to complete before timing out.</param>
/// <exception cref="T:System.ServiceModel.CommunicationException">The <see cref="T:System.ServiceModel.ICommunicationObject"/> was unable to be opened and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
/// <exception cref="T:System.TimeoutException">The specified timeout elapsed before the <see cref="T:System.ServiceModel.ICommunicationObject"/> was able to enter the <see cref="F:System.ServiceModel.CommunicationState.Opened"/> state and has entered the <see cref="F:System.ServiceModel.CommunicationState.Faulted"/> state.</exception>
public void Open(TimeSpan timeout)
{
ProxiedClient.Open(timeout);
}
/// <summary>
/// Opens the client asynchronously.
/// </summary>
public void OpenAsync()
{
ProxiedClient.OpenAsync();
}
/// <summary>
/// Opens the client asynchronously.
/// </summary>
/// <param name="userState">User-specific state.</param>
public void OpenAsync(object userState)
{
ProxiedClient.OpenAsync(userState);
}
/// <summary>
/// Occurs when Open operation has completed.
/// </summary>
public event EventHandler<AsyncCompletedEventArgs> OpenCompleted
{
add => ProxiedClient.OpenCompleted += value;
remove => ProxiedClient.OpenCompleted -= value;
}
/// <summary>
/// Occurs when the communication object completes its transition from the opening state into the opened state.
/// </summary>
public event EventHandler Opened
{
add => ProxiedClient.Opened += value;
remove => ProxiedClient.Opened -= value;
}
/// <summary>
/// Occurs when the communication object first enters the opening state.
/// </summary>
public event EventHandler Opening
{
add => ProxiedClient.Opening += value;
remove => ProxiedClient.Opening -= value;
}
/// <summary>
/// Processes the log messages asynchronously.
/// </summary>
/// <param name="events">The events to send.</param>
public void ProcessLogMessagesAsync(NLogEvents events)
{
ProxiedClient.ProcessLogMessagesAsync(events);
}
/// <summary>
/// Processes the log messages asynchronously.
/// </summary>
/// <param name="events">The events to send.</param>
/// <param name="userState">User-specific state.</param>
public void ProcessLogMessagesAsync(NLogEvents events, object userState)
{
ProxiedClient.ProcessLogMessagesAsync(events, userState);
}
/// <summary>
/// Occurs when the log message processing has completed.
/// </summary>
public event EventHandler<AsyncCompletedEventArgs> ProcessLogMessagesCompleted
{
add => ProxiedClient.ProcessLogMessagesCompleted += value;
remove => ProxiedClient.ProcessLogMessagesCompleted -= value;
}
/// <summary>
/// Gets the current state of the communication-oriented object.
/// </summary>
/// <returns>
/// The value of the <see cref="T:System.ServiceModel.CommunicationState"/> of the object.
/// </returns>
public CommunicationState State => ProxiedClient.State;
#endregion
/// <summary>
/// Causes a communication object to transition from its current state into the closed state.
/// </summary>
public void CloseCommunicationObject()
{
ProxiedClient.Close();
}
}
}
| |
/*
* Copyright 2013 Monoscape
*
* 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.
*
* History:
* 2011/11/10 Imesh Gunaratne <[email protected]> Created.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Web;
using System.Web.Mvc;
using Monoscape.ApplicationGridController.Model;
using Monoscape.ApplicationGridController.Api.Services.Dashboard;
using Monoscape.ApplicationGridController.Api.Services.Dashboard.Model;
using Monoscape.Common;
using Monoscape.Common.Exceptions;
using Monoscape.Common.Model;
using Monoscape.Dashboard.Runtime;
using Monoscape.Common.Services.FileServer;
using Monoscape.Common.Services.FileServer.Model;
using Monoscape.Common.WCFExtensions;
using Monoscape.Dashboard.Models;
using System.Net;
using Monoscape.ApplicationGridController.Sockets;
namespace Monoscape.Dashboard.Controllers
{
public class ApplicationGridController : AbstractController
{
#region Private Properties
private MonoscapeCredentials Credentials
{
get
{
MonoscapeCredentials credentials = new MonoscapeCredentials(Settings.MonoscapeAccessKey, Settings.MonoscapeSecretKey);
return credentials;
}
}
#endregion
#region Private Methods
private void UploadFile(Stream fileStream, Application application)
{
ApGetConfigurationSettingsRequest request1 = new ApGetConfigurationSettingsRequest(Credentials);
ApGetConfigurationSettingsResponse response1 = EndPoints.ApDashboardService.GetConfigurationSettings(request1);
IPAddress appGridIpAddress = response1.ConfigurationSettings.IpAddress;
ApFileTransferSocket socket = new ApFileTransferSocket(appGridIpAddress, Settings.ApFileTransferSocketPort);
socket.SendFile(fileStream, application.FileName);
ApAddApplicationRequest request = new ApAddApplicationRequest(Credentials);
request.Application = application;
EndPoints.ApDashboardService.AddApplication(request);
}
private Application GetApplication(int applicationId)
{
ApGetApplicationRequest request = new ApGetApplicationRequest(Credentials);
request.ApplicationId = applicationId;
ApGetApplicationResponse response = EndPoints.ApDashboardService.GetApplication(request);
return response.Application;
}
private object FindImageName(List<Image> images, string imageId)
{
if ((images != null) && (imageId != null))
{
foreach (Image image in images)
{
if (image.ImageId.Equals(imageId))
return image.Name;
}
}
return string.Empty;
}
private List<Node> DescribeNodes()
{
ApDescribeNodesRequest request = new ApDescribeNodesRequest(Credentials);
ApDescribeNodesResponse response = EndPoints.ApDashboardService.DescribeNodes(request);
return response.Nodes;
}
private List<Image> DescribeImages()
{
ApDescribeImagesRequest request = new ApDescribeImagesRequest(Credentials);
ApDescribeImagesResponse response = EndPoints.ApDashboardService.DescribeImages(request);
return response.Images;
}
private List<Instance> DescribeInstances()
{
ApDescribeInstancesRequest request = new ApDescribeInstancesRequest(Credentials);
ApDescribeInstancesResponse response = EndPoints.ApDashboardService.DescribeInstances(request);
return response.Instances;
}
private List<Application> DescribeApplications()
{
ApDescribeApplicationsRequest request = new ApDescribeApplicationsRequest(Credentials);
ApDescribeApplicationsResponse response = EndPoints.ApDashboardService.DescribeApplications(request);
return response.Applications;
}
private List<ScalingHistoryItem> DescribeScalingHistory()
{
ApDescribeScalingHistoryRequest request = new ApDescribeScalingHistoryRequest(Credentials);
ApDescribeScalingHistoryResponse response = EndPoints.ApDashboardService.DescribeScalingHistory(request);
return response.ScalingHistory;
}
#endregion
//
// GET: /applicationgrid/
public ActionResult Index()
{
try
{
ViewData["MonoscapeAccessKey"] = Credentials.AccessKey;
ViewData["MonoscapeSecretKey"] = Credentials.SecretKey;
ViewData["ApplicationGridEndPointURL"] = Settings.ApplicationGridEndPointURL;
ViewData["ApplicationGridStatus"] = "Offline";
try
{
ApGetConfigurationSettingsRequest request = new ApGetConfigurationSettingsRequest(Credentials);
ApGetConfigurationSettingsResponse response = EndPoints.ApDashboardService.GetConfigurationSettings(request);
if (response != null)
{
ViewData["IaasName"] = response.ConfigurationSettings.IaasName;
ViewData["IaasAccessKey"] = response.ConfigurationSettings.IaasAccessKey;
ViewData["IaasSecretKey"] = response.ConfigurationSettings.IaasSecretKey;
ViewData["IaasServiceURL"] = response.ConfigurationSettings.IaasServiceURL;
ViewData["IaasKeyName"] = response.ConfigurationSettings.IaasKeyName;
ViewData["RunningOnMono"] = response.ConfigurationSettings.RunningOnMono.ToString().ToUpper();
ViewData["MonoRuntime"] = response.ConfigurationSettings.MonoRuntime;
ViewData["DotNetRuntime"] = response.ConfigurationSettings.DotNetRuntime;
ViewData["OperatingSystem"] = response.ConfigurationSettings.OperatingSystem;
ViewData["ApplicationGridStatus"] = "Authorized";
try
{
ApAuthorizeRequest authRequest = new ApAuthorizeRequest(Credentials);
ApAuthorizeResponse authResponse = EndPoints.ApDashboardService.Authorize(authRequest);
if (authResponse.Authorized)
ViewData["IaasStatus"] = "Authorized";
else
ViewData["IaasStatus"] = "Authentication failed";
}
catch (Exception e)
{
ViewData["IaasStatus"] = "Authentication failed";
ViewData["IaasError"] = e.Message;
}
}
}
catch (Exception e)
{
ViewData["ApplicationGridError"] = e.Message;
}
return View();
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/nodes
public ActionResult Nodes()
{
try
{
return View(DescribeNodes());
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/images
public ActionResult Images()
{
try
{
return View(DescribeImages());
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/instances
public ActionResult Instances()
{
try
{
return View(DescribeInstances());
}
catch (Exception e)
{
return ShowError(e);
}
}
public ActionResult ScalingHistory()
{
try
{
return View(DescribeScalingHistory());
}
catch (Exception e)
{
return ShowError(e);
}
}
public ActionResult Applications()
{
try
{
return View(DescribeApplications());
}
catch (Exception e)
{
return ShowError(e);
}
}
public ActionResult ApplicationInfo(int applicationId)
{
try
{
Application app = GetApplication(applicationId);
if (app != null)
{
return View(app);
}
else
{
throw new MonoscapeException("Application not found");
}
}
catch (Exception e)
{
return ShowError(e);
}
}
public ActionResult ApplicationInstances()
{
try
{
return View(DescribeNodes());
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/startapplication
public ActionResult StartApplication(int applicationId)
{
try
{
StartApplicationModel model = new StartApplicationModel();
Application app = GetApplication(applicationId);
if(app != null)
{
model.ApplicationId = applicationId;
model.Name = app.Name;
model.NumberOfInstances = 1;
ViewData["Tenants"] = PrepareTenants(app.Tenants);
return View("StartApplication", model);
}
else
{
throw new MonoscapeException("Application not found");
}
}
catch (Exception e)
{
return ShowError(e);
}
}
private object PrepareTenants(List<Tenant> list)
{
if ((list != null) && (list.Count > 0))
{
string text = string.Empty;
foreach (Tenant tenant in list)
{
text += tenant.Name;
if (list.IndexOf(tenant) < (list.Count - 1))
text += ", ";
}
return text;
}
return "No tenants defined";
}
//
// POST: /applicationgrid/startapplication
[HttpPost]
public ActionResult StartApplication(StartApplicationModel model)
{
try
{
ApStartApplicationRequest request = new ApStartApplicationRequest(Credentials);
request.ApplicationId = model.ApplicationId;
request.TenantName = model.TenantName;
request.NumberOfInstances = model.NumberOfInstances;
EndPoints.ApDashboardService.StartApplication(request);
return RedirectToAction("ApplicationInstances");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/addapplicationtenant
public ActionResult AddApplicationTenant(int applicationId)
{
try
{
Application app = GetApplication(applicationId);
if (app != null)
{
Tenant tenant = new Tenant();
tenant.ApplicationId = app.Id;
tenant.UpperScaleLimit = 1;
ViewData["ApplicationName"] = app.Name;
return View("AddApplicationTenant", tenant);
}
else
{
throw new MonoscapeException("Application not found");
}
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// POST: /applicationgrid/addapplicationtenant
[HttpPost]
public ActionResult AddApplicationTenant(Tenant tenant)
{
try
{
ApAddApplicationTenantsRequest request = new ApAddApplicationTenantsRequest(Credentials);
request.ApplicationId = tenant.ApplicationId;
List<Tenant> tenants = new List<Tenant>();
tenants.Add(tenant);
request.Tenants = tenants;
EndPoints.ApDashboardService.AddApplicationTenants(request);
return RedirectToAction("ApplicationInfo", new { applicationId = tenant.ApplicationId });
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/stopapplicationinstance
public ActionResult StopApplicationInstance(int nodeId, int applicationId, int instanceId)
{
try
{
ApStopApplicationInstanceRequest request = new ApStopApplicationInstanceRequest(Credentials);
request.NodeId = nodeId;
request.ApplicationId = applicationId;
request.InstanceId = instanceId;
EndPoints.ApDashboardService.StopApplicationInstance(request);
return RedirectToAction("ApplicationInstances");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/runinstance/{imageId}
public ActionResult RunInstance(string imageId)
{
try
{
Instance instance = new Instance();
instance.ImageId = imageId;
ViewData["ImageName"] = FindImageName(DescribeImages(), instance.ImageId);
return View(instance);
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// POST: /applicationgrid/runinstance
[HttpPost]
public ActionResult RunInstance(Instance instance)
{
try
{
ApRunInstancesRequest request = new ApRunInstancesRequest(Credentials);
request.ImageId = instance.ImageId;
request.InstanceType = instance.Type;
request.NoOfInstances = 1;
ApRunInstancesResponse response = EndPoints.ApDashboardService.RunInstances(request);
Reservation reservation = response.Reservation;
if ((reservation != null) && ((reservation.Instances == null) || (reservation.Instances.Count < 1)))
return View("Reservation", reservation);
else
return RedirectToAction("Instances");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/deregisterimage/{imageId}
public ActionResult DeregisterImage(string imageId)
{
try
{
ApDeregisterImageRequest request = new ApDeregisterImageRequest(Credentials);
request.ImageId = imageId;
EndPoints.ApDashboardService.DeregisterImage(request);
return RedirectToAction("Images");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/assignpublicip/{instanceId}
public ActionResult AssignPublicIp(string instanceId)
{
try
{
ApAllocateAddressRequest allocateRequest = new ApAllocateAddressRequest(Credentials);
ApAllocateAddressResponse allocateResponse = EndPoints.ApDashboardService.AllocateAddress(allocateRequest);
ApAssociateAddressRequest associateRequest = new ApAssociateAddressRequest(Credentials);
associateRequest.InstanceId = instanceId;
associateRequest.IpAddress = allocateResponse.Address;
EndPoints.ApDashboardService.AssociateAddress(associateRequest);
return RedirectToAction("Instances");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/terminateinstance/{instanceId}
public ActionResult TerminateInstance(string instanceId)
{
try
{
ApTerminateInstanceRequest request = new ApTerminateInstanceRequest(Credentials);
request.InstanceId = instanceId;
EndPoints.ApDashboardService.TerminateInstance(request);
return RedirectToAction("Instances");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/rebootinstance/{instanceId}
public ActionResult RebootInstance(string instanceId)
{
try
{
ApRebootInstanceRequest request = new ApRebootInstanceRequest(Credentials);
request.InstanceId = instanceId;
EndPoints.ApDashboardService.RebootInstance(request);
return RedirectToAction("Instances");
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/consoleoutput/{instanceId}
public ActionResult ConsoleOutput(string instanceId)
{
try
{
ApGetConsoleOutputRequest request = new ApGetConsoleOutputRequest(Credentials);
request.InstanceId = instanceId;
ApGetConsoleOutputResponse response = EndPoints.ApDashboardService.GetConsoleOutput(request);
ConsoleOutput output = new ConsoleOutput();
output.InstanceId = response.ConsoleOutput.InstanceId;
output.Output = ApCloudControllerUtil.DecodeConsoleOutput(response.ConsoleOutput.Output);
output.Timestamp = response.ConsoleOutput.Timestamp;
return View(output);
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// GET: /applicationgrid/uploadapplication/
public ActionResult UploadApplication()
{
try
{
return View(new Application());
}
catch (Exception e)
{
return ShowError(e);
}
}
//
// POST: /applicationgrid/uploadapplication/
[HttpPost]
public ActionResult UploadApplication(Application application)
{
try
{
if (!IsApplicationValid(application))
{
return View(application);
}
// Check application exists in Application Grid
ApApplicationExistsRequest request = new ApApplicationExistsRequest(Credentials);
ApApplicationExistsResponse response = EndPoints.ApDashboardService.ApplicationExists(request);
if (response.Exists)
{
ModelState.AddModelError("Application", "Application version already exists.");
return View(application);
}
else
{
HttpPostedFileBase file = Request.Files["applicationPackage"];
application.FileName = file.FileName;
UploadFile(file.InputStream, application);
return RedirectToAction("Applications");
}
}
catch (Exception e)
{
return ShowError(e);
}
}
private bool IsApplicationValid(Application application)
{
bool valid = true;
if (string.IsNullOrEmpty(application.Name))
{
ModelState.AddModelError("Name", "Application name is required");
valid = false;
}
if (string.IsNullOrEmpty(application.Version))
{
ModelState.AddModelError("Version", "Application version is required");
valid = false;
}
if (Request.Files["applicationPackage"].ContentLength == 0)
{
ModelState.AddModelError("applicationPackage", "Application package is required");
valid = false;
}
return valid;
}
//
// GET: /applicationgrid/removeapplication/{applicationId}
public ActionResult RemoveApplication(int applicationId)
{
try
{
ApRemoveApplicationRequest request = new ApRemoveApplicationRequest(Credentials);
request.ApplicationId = applicationId;
EndPoints.ApDashboardService.RemoveApplication(request);
return RedirectToAction("Applications");
}
catch (Exception e)
{
return ShowError(e);
}
}
}
}
| |
// 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 {
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
using System.Security.Permissions;
[Serializable]
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Attribute))]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Attribute : _Attribute
{
#region Private Statics
#region PropertyInfo
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(type != null);
Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (!inherit)
return attributes;
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
attributes = GetCustomAttributes(baseProp, type, false);
AddAttributesToList(attributeList, attributes, types);
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
if (baseProp.IsDefined(attributeType, false))
return true;
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
}
return false;
}
private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
{
Contract.Requires(property != null);
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
MethodInfo propAccessor = property.GetGetMethod(true);
if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;
if (rtPropAccessor != null)
{
rtPropAccessor = rtPropAccessor.GetParentDefinition();
if (rtPropAccessor != null)
{
// There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
// However, we cannot use that because it doesn't accept null for "types".
return rtPropAccessor.DeclaringType.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
null, //will use default binder
property.PropertyType,
propertyParameters, //used for index properties
null);
}
}
return null;
}
#endregion
#region EventInfo
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(type != null);
Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit)
{
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
attributes = GetCustomAttributes(baseEvent, type, false);
AddAttributesToList(attributeList, attributes, types);
baseEvent = GetParentDefinition(baseEvent);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
else
return attributes;
}
private static EventInfo GetParentDefinition(EventInfo ev)
{
Contract.Requires(ev != null);
// note that this only works for RuntimeMethodInfo
MethodInfo add = ev.GetAddMethod(true);
RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo;
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
if (rtAdd != null)
return rtAdd.DeclaringType.GetEvent(ev.Name);
}
return null;
}
private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
if (baseEvent.IsDefined(attributeType, false))
return true;
baseEvent = GetParentDefinition(baseEvent);
}
}
return false;
}
#endregion
#region ParameterInfo
private static ParameterInfo GetParentDefinition(ParameterInfo param)
{
Contract.Requires(param != null);
// note that this only works for RuntimeMethodInfo
RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo;
if (rtMethod != null)
{
rtMethod = rtMethod.GetParentDefinition();
if (rtMethod != null)
{
// Find the ParameterInfo on this method
int position = param.Position;
if (position == -1)
{
return rtMethod.ReturnParameter;
}
else
{
ParameterInfo[] parameters = rtMethod.GetParameters();
return parameters[position]; // Point to the correct ParameterInfo of the method
}
}
}
return null;
}
private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
{
Contract.Requires(param != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
// have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
Object [] objAttr;
if (type == null)
type = typeof(Attribute);
objAttr = param.GetCustomAttributes(type, false);
for (int i =0;i < objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
Attribute [] ret = null;
if (objAttr.Length == 0)
ret = CreateAttributeArrayHelper(type,0);
else
ret = (Attribute[])objAttr;
if (param.Member.DeclaringType == null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
objAttr = baseParam.GetCustomAttributes(type, false);
int count = 0;
for (int i =0;i < objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
{
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
count++;
}
else
objAttr[i] = null;
}
// Get all the attributes that have Attribute as the base class
Attribute [] attributes = CreateAttributeArrayHelper(type,count);
count = 0;
for (int i =0;i < objAttr.Length;i++)
{
if (objAttr[i] != null)
{
attributes[count] = (Attribute)objAttr[i];
count++;
}
}
Attribute [] temp = ret;
ret = CreateAttributeArrayHelper(type,temp.Length + count);
Array.Copy(temp,ret,temp.Length);
int offset = temp.Length;
for (int i =0;i < attributes.Length;i++)
ret[offset + i] = attributes[i];
baseParam = GetParentDefinition(baseParam);
}
return ret;
}
private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
{
Contract.Requires(param != null);
Contract.Requires(type != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
// We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.
if (param.IsDefined(type, false))
return true;
if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
return false;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
Object[] objAttr = baseParam.GetCustomAttributes(type, false);
for (int i =0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
return true;
}
baseParam = GetParentDefinition(baseParam);
}
return false;
}
#endregion
#region Utility
private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
if (!types.ContainsKey(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
private static Type[] GetIndexParameterTypes(PropertyInfo element)
{
ParameterInfo[] indexParams = element.GetIndexParameters();
if (indexParams.Length > 0)
{
Type[] indexParamTypes = new Type[indexParams.Length];
for (int i = 0; i < indexParams.Length; i++)
{
indexParamTypes[i] = indexParams[i].ParameterType;
}
return indexParamTypes;
}
return Array.Empty<Type>();
}
private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
AttributeUsageAttribute usage = null;
types.TryGetValue(attrType, out usage);
if (usage == null)
{
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
{
// we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
}
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
// Check if the custom attributes is Inheritable
Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
if (obj.Length == 1)
return (AttributeUsageAttribute)obj[0];
if (obj.Length == 0)
return AttributeUsageAttribute.Default;
throw new FormatException(
Environment.GetResourceString("Format_AttributeUsage", type));
}
[System.Security.SecuritySafeCritical]
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
}
#endregion
#endregion
#region Public Statics
#region MemberInfo
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
{
return GetCustomAttributes(element, type, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (type == null)
throw new ArgumentNullException("type");
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
return element.GetCustomAttributes(type, inherit) as Attribute[];
}
}
public static Attribute[] GetCustomAttributes(MemberInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);
default:
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
}
public static bool IsDefined(MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
{
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
switch(element.MemberType)
{
case MemberTypes.Property:
return InternalIsDefined((PropertyInfo)element, attributeType, inherit);
case MemberTypes.Event:
return InternalIsDefined((EventInfo)element, attributeType, inherit);
default:
return element.IsDefined(attributeType, inherit);
}
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region ParameterInfo
public static Attribute[] GetCustomAttributes(ParameterInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
return (Attribute[])GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
if (element.Member == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];
return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (element.Member == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
public static bool IsDefined(ParameterInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
MemberInfo member = element.Member;
switch(member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
case MemberTypes.Constructor:
return element.IsDefined(attributeType, false);
case MemberTypes.Property:
return element.IsDefined(attributeType, false);
default:
Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
}
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region Module
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
{
return GetCustomAttributes (element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Module element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static bool IsDefined(Module element, Type attributeType)
{
return IsDefined(element, attributeType, false);
}
public static bool IsDefined(Module element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return element.IsDefined(attributeType,false);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region Assembly
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(Assembly element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static bool IsDefined (Assembly element, Type attributeType)
{
return IsDefined (element, attributeType, true);
}
public static bool IsDefined (Assembly element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return element.IsDefined(attributeType, false);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#endregion
#region Constructor
protected Attribute() { }
#endregion
#region Object Overrides
[SecuritySafeCritical]
public override bool Equals(Object obj)
{
if (obj == null)
return false;
Type thisType = this.GetType();
Type thatType = obj.GetType();
if (thatType != thisType)
return false;
Object thisObj = this;
Object thisResult, thatResult;
while (thisType != typeof(Attribute))
{
FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (int i = 0; i < thisFields.Length; i++)
{
// Visibility check and consistency check are not necessary.
thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
if (!AreFieldValuesEqual(thisResult, thatResult))
{
return false;
}
}
thisType = thisType.BaseType;
}
return true;
}
// Compares values of custom-attribute fields.
private static bool AreFieldValuesEqual(Object thisValue, Object thatValue)
{
if (thisValue == null && thatValue == null)
return true;
if (thisValue == null || thatValue == null)
return false;
if (thisValue.GetType().IsArray)
{
// Ensure both are arrays of the same type.
if (!thisValue.GetType().Equals(thatValue.GetType()))
{
return false;
}
Array thisValueArray = thisValue as Array;
Array thatValueArray = thatValue as Array;
if (thisValueArray.Length != thatValueArray.Length)
{
return false;
}
// Attributes can only contain single-dimension arrays, so we don't need to worry about
// multidimensional arrays.
Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
for (int j = 0; j < thisValueArray.Length; j++)
{
if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
{
return false;
}
}
}
else
{
// An object of type Attribute will cause a stack overflow.
// However, this should never happen because custom attributes cannot contain values other than
// constants, single-dimensional arrays and typeof expressions.
Contract.Assert(!(thisValue is Attribute));
if (!thisValue.Equals(thatValue))
return false;
}
return true;
}
[SecuritySafeCritical]
public override int GetHashCode()
{
Type type = GetType();
while (type != typeof(Attribute))
{
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
Object vThis = null;
for (int i = 0; i < fields.Length; i++)
{
// Visibility check and consistency check are not necessary.
Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
// The hashcode of an array ignores the contents of the array, so it can produce
// different hashcodes for arrays with the same contents.
// Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
// be inconsistent for arrays. Therefore, we ignore hashes of arrays.
if (fieldValue != null && !fieldValue.GetType().IsArray)
vThis = fieldValue;
if (vThis != null)
break;
}
if (vThis != null)
return vThis.GetHashCode();
type = type.BaseType;
}
return type.GetHashCode();
}
#endregion
#region Public Virtual Members
public virtual Object TypeId { get { return GetType(); } }
public virtual bool Match(Object obj) { return Equals(obj); }
#endregion
#region Public Members
public virtual bool IsDefaultAttribute() { return false; }
#endregion
#if !FEATURE_CORECLR
void _Attribute.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Linq;
using System.Xml;
using Gallio.Common;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Model.Schema;
using Gallio.ReSharperRunner.Provider.Facade;
using Gallio.ReSharperRunner.Reflection;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.TaskRunnerFramework;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Util;
namespace Gallio.ReSharperRunner.Provider
{
/// <summary>
/// Represents a Gallio test.
/// </summary>
public class GallioTestElement : IUnitTestElement, IEquatable<GallioTestElement>, IComparable<GallioTestElement>, IComparable
{
private readonly string testName;
private readonly GallioTestProvider provider;
private readonly bool isTestCase;
private readonly IProject project;
private readonly IDeclaredElementResolver declaredElementResolver;
private readonly string assemblyPath;
private readonly string typeName;
private readonly string namespaceName;
private Memoizer<string> shortNameMemoizer = new Memoizer<string>();
private GallioTestElement(GallioTestProvider provider, IUnitTestElement parent, string testId, string testName, string kind, bool isTestCase,
IProject project, IDeclaredElementResolver declaredElementResolver, string assemblyPath, string typeName, string namespaceName)
{
this.provider = provider;
Id = testId;
TestId = testId;
this.testName = testName;
Parent = parent;
if (Parent != null)
parent.Children.Add(this);
Kind = kind;
this.isTestCase = isTestCase;
this.project = project;
this.declaredElementResolver = declaredElementResolver;
this.assemblyPath = assemblyPath;
this.typeName = typeName;
this.namespaceName = namespaceName;
Children = new List<IUnitTestElement>();
}
public string TestId { get; private set; }
public static GallioTestElement CreateFromTest(TestData test, ICodeElementInfo codeElement, GallioTestProvider provider, GallioTestElement parent)
{
if (test == null)
throw new ArgumentNullException("test");
// The idea here is to generate a test element object that does not retain any direct
// references to the code element info and other heavyweight objects. A test element may
// survive in memory for quite a long time so we don't want it holding on to all sorts of
// irrelevant stuff. Basically we flatten out the test to just those properties that we
// need to keep.
var element = new GallioTestElement(provider, parent,
test.Id,
test.Name,
test.Metadata.GetValue(MetadataKeys.TestKind) ?? "Unknown",
test.IsTestCase,
ReSharperReflectionPolicy.GetProject(codeElement),
ReSharperReflectionPolicy.GetDeclaredElementResolver(codeElement),
GetAssemblyPath(codeElement),
GetTypeName(codeElement),
GetNamespaceName(codeElement));
var categories = test.Metadata[MetadataKeys.Category];
element.Categories = UnitTestElementCategory.Create(categories);
var reason = test.Metadata.GetValue(MetadataKeys.IgnoreReason);
if (reason != null)
{
element.Explicit = true;
element.ExplicitReason = reason;
}
return element;
}
private static string GetAssemblyPath(ICodeElementInfo codeElement)
{
IAssemblyInfo assembly = ReflectionUtils.GetAssembly(codeElement);
return assembly != null ? assembly.Path : null;
}
private static string GetTypeName(ICodeElementInfo codeElement)
{
ITypeInfo type = ReflectionUtils.GetType(codeElement);
return type != null ? type.FullName : "";
}
private static string GetNamespaceName(ICodeElementInfo codeElement)
{
INamespaceInfo @namespace = ReflectionUtils.GetNamespace(codeElement);
return @namespace != null ? @namespace.Name : "";
}
public string GetAssemblyLocation()
{
return assemblyPath;
}
public string TestName
{
get { return testName; }
}
public ICollection<IUnitTestElement> Children { get; private set; }
// R# uses this name as a filter for declared elements so that it can quickly determine
// whether a given declared element is likely to be a test before asking the provider about
// it. The result must be equal to IDeclaredElement.ShortName.
public string ShortName
{
get
{
return shortNameMemoizer.Memoize(() =>
{
IDeclaredElement declaredElement = GetDeclaredElement();
return declaredElement != null && declaredElement.IsValid()
? declaredElement.ShortName
: testName;
});
}
}
public bool Explicit { get; private set; }
public UnitTestElementState State { get; set; }
public bool IsTestCase
{
get { return isTestCase; }
}
private string GetTitle()
{
return testName;
}
public string GetTypeClrName()
{
return typeName;
}
public string GetPresentation()
{
return "";
}
#if RESHARPER_70
public string GetPresentation(IUnitTestElement parent = null)
{
return GetPresentation();
}
#endif
public UnitTestNamespace GetNamespace()
{
return new UnitTestNamespace(namespaceName);
}
public IProject GetProject()
{
return project;
}
public IEnumerable<IProjectFile> GetProjectFiles()
{
ITypeElement declaredType = GetDeclaredType();
if (declaredType == null)
{
return EmptyArray<IProjectFile>.Instance;
}
return declaredType.GetSourceFiles().Select(x => x.ToProjectFile());
}
private ITypeElement GetDeclaredType()
{
var psiModule = provider.PsiModuleManager.GetPrimaryPsiModule(project);
if (psiModule == null)
{
return null;
}
var declarationsCache = provider.CacheManager.GetDeclarationsCache(psiModule, true, true);
return declarationsCache.GetTypeElementByCLRName(typeName);
}
#if RESHARPER_60
public IList<UnitTestTask> GetTaskSequence(IEnumerable<IUnitTestElement> explicitElements)
#elif RESHARPER_61
public IList<UnitTestTask> GetTaskSequence(IList<IUnitTestElement> explicitElements)
#else
public IList<UnitTestTask> GetTaskSequence(ICollection<IUnitTestElement> explicitElements, IUnitTestLaunch launch)
#endif
{
// Add the run task. Must always be first.
var tasks = new List<UnitTestTask> { new UnitTestTask(null, FacadeTaskFactory.CreateRootTask()) };
// Add the test case branch.
AddTestTasksFromRootToLeaf(tasks, this);
// Now that we're done with the critical parts of the task tree, we can add other
// arbitrary elements. We don't care about the structure of the task tree beyond this depth.
// Add the assembly location.
tasks.Add(new UnitTestTask(null, new AssemblyLoadTask(GetAssemblyLocation())));
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateAssemblyTaskFrom(this)));
if (explicitElements.Count() != 0)
{
// Add explicit element markers.
foreach (GallioTestElement explicitElement in explicitElements)
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateExplicitTestTaskFrom(explicitElement)));
}
else
{
// No explicit elements but we must have at least one to filter by, so we consider
// the top test explicitly selected.
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateExplicitTestTaskFrom(this)));
}
return tasks;
}
private void AddTestTasksFromRootToLeaf(ICollection<UnitTestTask> tasks, GallioTestElement element)
{
var parentElement = element.Parent as GallioTestElement;
if (parentElement != null)
AddTestTasksFromRootToLeaf(tasks, parentElement);
tasks.Add(new UnitTestTask(element, FacadeTaskFactory.CreateTestTaskFrom(element)));
}
public string Kind { get; private set; }
public IEnumerable<UnitTestElementCategory> Categories { get; private set; }
public string ExplicitReason { get; private set; }
public string Id { get; private set; }
public IUnitTestProvider Provider
{
get { return provider; }
}
public IUnitTestElement Parent { get; set; }
public UnitTestElementDisposition GetDisposition()
{
var element = GetDeclaredElement();
if (element == null || !element.IsValid())
{
return UnitTestElementDisposition.InvalidDisposition;
}
var locations = new List<UnitTestElementLocation>();
element.GetDeclarations().ForEach(declaration =>
{
var file = declaration.GetContainingFile();
if (file != null)
{
var projectFile = file.GetSourceFile().ToProjectFile();
var navigationRange = declaration.GetNameDocumentRange().TextRange;
var containingRange = declaration.GetDocumentRange().TextRange;
locations.Add(new UnitTestElementLocation(projectFile, navigationRange, containingRange));
}
});
return new UnitTestElementDisposition(locations, this);
}
public IDeclaredElement GetDeclaredElement()
{
return declaredElementResolver.ResolveDeclaredElement();
}
public bool Equals(GallioTestElement other)
{
return other != null && Id == other.Id;
}
public override bool Equals(object obj)
{
return Equals(obj as GallioTestElement);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public int CompareTo(GallioTestElement other)
{
// Find common ancestor.
var branches = new Dictionary<GallioTestElement, GallioTestElement>();
for (GallioTestElement thisAncestor = this, thisBranch = null;
thisAncestor != null;
thisBranch = thisAncestor, thisAncestor = thisAncestor.Parent as GallioTestElement)
branches.Add(thisAncestor, thisBranch);
for (GallioTestElement otherAncestor = other, otherBranch = null;
otherAncestor != null;
otherBranch = otherAncestor, otherAncestor = otherAncestor.Parent as GallioTestElement)
{
GallioTestElement thisBranch;
if (!branches.TryGetValue(otherAncestor, out thisBranch))
continue;
// Compare the relative ordering of the branches leading from
// the common ancestor to each child.
var children = new List<IUnitTestElement>(otherAncestor.Children);
var thisOrder = thisBranch != null ? children.IndexOf(thisBranch) : -1;
var otherOrder = otherBranch != null ? children.IndexOf(otherBranch) : -1;
return thisOrder.CompareTo(otherOrder);
}
// No common ancestor, compare ids.
return Id.CompareTo(other.Id);
}
public int CompareTo(object obj)
{
var other = obj as GallioTestElement;
return other != null ? CompareTo(other) : 1; // sort gallio test elements after all other kinds
}
public bool Equals(IUnitTestElement other)
{
return Equals(other as GallioTestElement);
}
public override string ToString()
{
return GetTitle();
}
public void Serialize(XmlElement parent)
{
parent.SetAttribute("projectId", GetProject().GetPersistentID());
parent.SetAttribute("testId", TestId);
}
public static IUnitTestElement Deserialize(XmlElement parent, IUnitTestElement parentElement, GallioTestProvider provider)
{
//var projectId = parent.GetAttribute("projectId");
//var project = ProjectUtil.FindProjectElementByPersistentID(provider.Solution, projectId) as IProject;
//if (project == null)
//{
// return null;
//}
//var testId = parent.GetAttribute("testId");
//var element = provider.UnitTestManager.GetElementById(project, testId) as GallioTestElement;
//if (element != null)
//{
// element.Parent = parentElement;
// element.State = UnitTestElementState.Valid;
// return element;
//}
return null;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OpenMetaverse;
namespace Aurora.Modules.WorldMap.Warp3DMap
{
public static class Perlin
{
// We use a hardcoded seed to keep the noise generation consistent between runs
private const int SEED = 42;
private const int SAMPLE_SIZE = 1024;
private const int B = SAMPLE_SIZE;
private const int BM = SAMPLE_SIZE - 1;
private const int N = 0x1000;
private static readonly int[] p = new int[SAMPLE_SIZE + SAMPLE_SIZE + 2];
private static readonly float[,] g3 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2,3];
private static readonly float[,] g2 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2,2];
private static readonly float[] g1 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2];
static Perlin()
{
Random rng = new Random(SEED);
int i, j, k;
for (i = 0; i < B; i++)
{
p[i] = i;
g1[i] = (float) ((rng.Next()%(B + B)) - B)/B;
for (j = 0; j < 2; j++)
g2[i, j] = (float) ((rng.Next()%(B + B)) - B)/B;
normalize2(g2, i);
for (j = 0; j < 3; j++)
g3[i, j] = (float) ((rng.Next()%(B + B)) - B)/B;
normalize3(g3, i);
}
while (--i > 0)
{
k = p[i];
p[i] = p[j = rng.Next()%B];
p[j] = k;
}
for (i = 0; i < B + 2; i++)
{
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0; j < 2; j++)
g2[B + i, j] = g2[i, j];
for (j = 0; j < 3; j++)
g3[B + i, j] = g3[i, j];
}
}
public static float noise1(float arg)
{
int bx0, bx1;
float rx0, rx1, sx, t, u, v;
t = arg + N;
bx0 = ((int) t) & BM;
bx1 = (bx0 + 1) & BM;
rx0 = t - (int) t;
rx1 = rx0 - 1f;
sx = s_curve(rx0);
u = rx0*g1[p[bx0]];
v = rx1*g1[p[bx1]];
return Utils.Lerp(u, v, sx);
}
public static float noise2(float x, float y)
{
int bx0, bx1, by0, by1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v;
int i, j;
t = x + N;
bx0 = ((int) t) & BM;
bx1 = (bx0 + 1) & BM;
rx0 = t - (int) t;
rx1 = rx0 - 1f;
t = y + N;
by0 = ((int) t) & BM;
by1 = (by0 + 1) & BM;
ry0 = t - (int) t;
ry1 = ry0 - 1f;
i = p[bx0];
j = p[bx1];
b00 = p[i + by0];
b10 = p[j + by0];
b01 = p[i + by1];
b11 = p[j + by1];
sx = s_curve(rx0);
sy = s_curve(ry0);
u = rx0*g2[b00, 0] + ry0*g2[b00, 1];
v = rx1*g2[b10, 0] + ry0*g2[b10, 1];
a = Utils.Lerp(u, v, sx);
u = rx0*g2[b01, 0] + ry1*g2[b01, 1];
v = rx1*g2[b11, 0] + ry1*g2[b11, 1];
b = Utils.Lerp(u, v, sx);
return Utils.Lerp(a, b, sy);
}
public static float noise3(float x, float y, float z)
{
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, rz0, rz1, sy, sz, a, b, c, d, t, u, v;
int i, j;
t = x + N;
bx0 = ((int) t) & BM;
bx1 = (bx0 + 1) & BM;
rx0 = t - (int) t;
rx1 = rx0 - 1f;
t = y + N;
by0 = ((int) t) & BM;
by1 = (by0 + 1) & BM;
ry0 = t - (int) t;
ry1 = ry0 - 1f;
t = z + N;
bz0 = ((int) t) & BM;
bz1 = (bz0 + 1) & BM;
rz0 = t - (int) t;
rz1 = rz0 - 1f;
i = p[bx0];
j = p[bx1];
b00 = p[i + by0];
b10 = p[j + by0];
b01 = p[i + by1];
b11 = p[j + by1];
t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);
u = rx0*g3[b00 + bz0, 0] + ry0*g3[b00 + bz0, 1] + rz0*g3[b00 + bz0, 2];
v = rx1*g3[b10 + bz0, 0] + ry0*g3[b10 + bz0, 1] + rz0*g3[b10 + bz0, 2];
a = Utils.Lerp(u, v, t);
u = rx0*g3[b01 + bz0, 0] + ry1*g3[b01 + bz0, 1] + rz0*g3[b01 + bz0, 2];
v = rx1*g3[b11 + bz0, 0] + ry1*g3[b11 + bz0, 1] + rz0*g3[b11 + bz0, 2];
b = Utils.Lerp(u, v, t);
c = Utils.Lerp(a, b, sy);
u = rx0*g3[b00 + bz1, 0] + ry0*g3[b00 + bz1, 1] + rz1*g3[b00 + bz1, 2];
v = rx1*g3[b10 + bz1, 0] + ry0*g3[b10 + bz1, 1] + rz1*g3[b10 + bz1, 2];
a = Utils.Lerp(u, v, t);
u = rx0*g3[b01 + bz1, 0] + ry1*g3[b01 + bz1, 1] + rz1*g3[b01 + bz1, 2];
v = rx1*g3[b11 + bz1, 0] + ry1*g3[b11 + bz1, 1] + rz1*g3[b11 + bz1, 2];
b = Utils.Lerp(u, v, t);
d = Utils.Lerp(a, b, sy);
return Utils.Lerp(c, d, sz);
}
public static float turbulence1(float x, float freq)
{
float t;
float v;
for (t = 0f; freq >= 1f; freq *= 0.5f)
{
v = freq*x;
t += noise1(v)/freq;
}
return t;
}
public static float turbulence2(float x, float y, float freq)
{
float t;
Vector2 vec;
for (t = 0f; freq >= 1f; freq *= 0.5f)
{
vec.X = freq*x;
vec.Y = freq*y;
t += noise2(vec.X, vec.Y)/freq;
}
return t;
}
public static float turbulence3(float x, float y, float z, float freq)
{
float t;
Vector3 vec;
for (t = 0f; freq >= 1f; freq *= 0.5f)
{
vec.X = freq*x;
vec.Y = freq*y;
vec.Z = freq*z;
t += noise3(vec.X, vec.Y, vec.Z)/freq;
}
return t;
}
private static void normalize2(float[,] v, int i)
{
float s;
s = (float) Math.Sqrt(v[i, 0]*v[i, 0] + v[i, 1]*v[i, 1]);
s = 1.0f/s;
v[i, 0] = v[i, 0]*s;
v[i, 1] = v[i, 1]*s;
}
private static void normalize3(float[,] v, int i)
{
float s;
s = (float) Math.Sqrt(v[i, 0]*v[i, 0] + v[i, 1]*v[i, 1] + v[i, 2]*v[i, 2]);
s = 1.0f/s;
v[i, 0] = v[i, 0]*s;
v[i, 1] = v[i, 1]*s;
v[i, 2] = v[i, 2]*s;
}
private static float s_curve(float t)
{
return t*t*(3f - 2f*t);
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <[email protected]> for Imazen LLC (Ported from Java to C#)
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using System.Collections.Generic;
using System.IO;
using System.Text;
using Com.Drew.Lang;
using JetBrains.Annotations;
using Sharpen;
using Sharpen.Reflect;
namespace Com.Drew.Metadata
{
/// <summary>Base class for all tag descriptor classes.</summary>
/// <remarks>
/// Base class for all tag descriptor classes. Implementations are responsible for
/// providing the human-readable string representation of tag values stored in a directory.
/// The directory is provided to the tag descriptor via its constructor.
/// </remarks>
/// <author>Drew Noakes https://drewnoakes.com</author>
public class TagDescriptor<T> : ITagDescriptor
where T : Com.Drew.Metadata.Directory
{
[NotNull]
protected internal readonly T _directory;
public TagDescriptor([NotNull] T directory)
{
_directory = directory;
}
/// <summary>Returns a descriptive value of the specified tag for this image.</summary>
/// <remarks>
/// Returns a descriptive value of the specified tag for this image.
/// Where possible, known values will be substituted here in place of the raw
/// tokens actually kept in the metadata segment. If no substitution is
/// available, the value provided by <code>getString(tagType)</code> will be returned.
/// </remarks>
/// <param name="tagType">the tag to find a description for</param>
/// <returns>
/// a description of the image's value for the specified tag, or
/// <code>null</code> if the tag hasn't been defined.
/// </returns>
[CanBeNull]
public virtual string GetDescription(int tagType)
{
object @object = _directory.GetObject(tagType);
if (@object == null)
{
return null;
}
// special presentation for long arrays
if (@object.GetType().IsArray)
{
int length = Sharpen.Runtime.GetArrayLength(@object);
if (length > 16)
{
string componentTypeName = @object.GetType().GetElementType().FullName;
return Sharpen.Extensions.StringFormat("[%d %s%s]", length, componentTypeName, length == 1 ? string.Empty : "s");
}
}
// no special handling required, so use default conversion to a string
return _directory.GetString(tagType);
}
/// <summary>
/// Takes a series of 4 bytes from the specified offset, and converts these to a
/// well-known version number, where possible.
/// </summary>
/// <remarks>
/// Takes a series of 4 bytes from the specified offset, and converts these to a
/// well-known version number, where possible.
/// <p>
/// Two different formats are processed:
/// <ul>
/// <li>[30 32 31 30] -> 2.10</li>
/// <li>[0 1 0 0] -> 1.00</li>
/// </ul>
/// </remarks>
/// <param name="components">the four version values</param>
/// <param name="majorDigits">the number of components to be</param>
/// <returns>the version as a string of form "2.10" or null if the argument cannot be converted</returns>
[CanBeNull]
public static string ConvertBytesToVersionString([CanBeNull] int[] components, int majorDigits)
{
if (components == null)
{
return null;
}
StringBuilder version = new StringBuilder();
for (int i = 0; i < 4 && i < components.Length; i++)
{
if (i == majorDigits)
{
version.Append('.');
}
char c = (char)components[i];
if (c < '0')
{
c += '0';
}
if (i == 0 && c == '0')
{
continue;
}
version.Append(c);
}
return Sharpen.Extensions.ConvertToString(version);
}
[CanBeNull]
protected internal virtual string GetVersionBytesDescription(int tagType, int majorDigits)
{
int[] values = _directory.GetIntArray(tagType);
return values == null ? null : ConvertBytesToVersionString(values, majorDigits);
}
[CanBeNull]
protected internal virtual string GetIndexedDescription(int tagType, [NotNull] params string[] descriptions)
{
return GetIndexedDescription(tagType, 0, descriptions);
}
[CanBeNull]
protected internal virtual string GetIndexedDescription(int tagType, int baseIndex, [NotNull] params string[] descriptions)
{
int? index = _directory.GetInteger(tagType);
if (index == null)
{
return null;
}
int arrayIndex = (int)index - baseIndex;
if (arrayIndex >= 0 && arrayIndex < descriptions.Length)
{
string description = descriptions[arrayIndex];
if (description != null)
{
return description;
}
}
return "Unknown (" + index + ")";
}
[CanBeNull]
protected internal virtual string GetByteLengthDescription(int tagType)
{
sbyte[] bytes = _directory.GetByteArray(tagType);
if (bytes == null)
{
return null;
}
return Sharpen.Extensions.StringFormat("(%d byte%s)", bytes.Length, bytes.Length == 1 ? string.Empty : "s");
}
[CanBeNull]
protected internal virtual string GetSimpleRational(int tagType)
{
Rational value = _directory.GetRational(tagType);
if (value == null)
{
return null;
}
return value.ToSimpleString(true);
}
[CanBeNull]
protected internal virtual string GetDecimalRational(int tagType, int decimalPlaces)
{
Rational value = _directory.GetRational(tagType);
if (value == null)
{
return null;
}
return Sharpen.Extensions.StringFormat("%." + decimalPlaces + "f", value.DoubleValue());
}
[CanBeNull]
protected internal virtual string GetFormattedInt(int tagType, [NotNull] string format)
{
int? value = _directory.GetInteger(tagType);
if (value == null)
{
return null;
}
return Sharpen.Extensions.StringFormat(format, value);
}
[CanBeNull]
protected internal virtual string GetFormattedFloat(int tagType, [NotNull] string format)
{
float? value = _directory.GetFloatObject(tagType);
if (value == null)
{
return null;
}
return Sharpen.Extensions.StringFormat(format, value);
}
[CanBeNull]
protected internal virtual string GetFormattedString(int tagType, [NotNull] string format)
{
string value = _directory.GetString(tagType);
if (value == null)
{
return null;
}
return Sharpen.Extensions.StringFormat(format, value);
}
[CanBeNull]
protected internal virtual string GetEpochTimeDescription(int tagType)
{
// TODO have observed a byte[8] here which is likely some kind of date (ticks as long?)
long? value = _directory.GetLongObject(tagType);
if (value == null)
{
return null;
}
return Sharpen.Extensions.ConvertToString(Sharpen.Extensions.CreateDate((long)value));
}
/// <summary>LSB first.</summary>
/// <remarks>LSB first. Labels may be null, a String, or a String[2] with (low label,high label) values.</remarks>
[CanBeNull]
protected internal virtual string GetBitFlagDescription(int tagType, [NotNull] params object[] labels)
{
int? value = _directory.GetInteger(tagType);
if (value == null)
{
return null;
}
IList<CharSequence> parts = new AList<CharSequence>();
int bitIndex = 0;
while (labels.Length > bitIndex)
{
object labelObj = labels[bitIndex];
if (labelObj != null)
{
bool isBitSet = ((int)value & 1) == 1;
if (labelObj is string[])
{
string[] labelPair = (string[])labelObj;
System.Diagnostics.Debug.Assert((labelPair.Length == 2));
parts.Add(labelPair[isBitSet ? 1 : 0]);
}
else
{
if (isBitSet && labelObj is string)
{
parts.Add((string)labelObj);
}
}
}
value >>= 1;
bitIndex++;
}
return StringUtil.Join(parts.AsIterable(), ", ");
}
[CanBeNull]
protected internal virtual string Get7BitStringFromBytes(int tagType)
{
sbyte[] bytes = _directory.GetByteArray(tagType);
if (bytes == null)
{
return null;
}
int length = bytes.Length;
for (int index = 0; index < bytes.Length; index++)
{
int i = bytes[index] & unchecked((int)(0xFF));
if (i == 0 || i > unchecked((int)(0x7F)))
{
length = index;
break;
}
}
return Sharpen.Runtime.GetStringForBytes(bytes, 0, length);
}
[CanBeNull]
protected internal virtual string GetAsciiStringFromBytes(int tag)
{
sbyte[] values = _directory.GetByteArray(tag);
if (values == null)
{
return null;
}
try
{
return Sharpen.Extensions.Trim(Sharpen.Runtime.GetStringForBytes(values, "ASCII"));
}
catch (UnsupportedEncodingException)
{
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Data object holding Silo configuration parameters.
/// </summary>
[Serializable]
public class ClusterConfiguration
{
/// <summary>
/// The global configuration parameters that apply uniformly to all silos.
/// </summary>
public GlobalConfiguration Globals { get; private set; }
/// <summary>
/// The default configuration parameters that apply to each and every silo.
/// These can be over-written on a per silo basis.
/// </summary>
public NodeConfiguration Defaults { get; private set; }
/// <summary>
/// The configuration file.
/// </summary>
public string SourceFile { get; private set; }
private IPEndPoint primaryNode;
/// <summary>
/// The Primary Node IP and port (in dev setting).
/// </summary>
public IPEndPoint PrimaryNode { get { return primaryNode; } set { SetPrimaryNode(value); } }
/// <summary>
/// Per silo configuration parameters overrides.
/// </summary>
public IDictionary<string, NodeConfiguration> Overrides { get; private set; }
private Dictionary<string, string> overrideXml;
private readonly Dictionary<string, List<Action>> listeners = new Dictionary<string, List<Action>>();
internal bool IsRunningAsUnitTest { get; set; }
/// <summary>
/// ClusterConfiguration constructor.
/// </summary>
public ClusterConfiguration()
{
Init();
}
/// <summary>
/// ClusterConfiguration constructor.
/// </summary>
public ClusterConfiguration(TextReader input)
{
Load(input);
}
private void Init()
{
Globals = new GlobalConfiguration();
Defaults = new NodeConfiguration();
Overrides = new Dictionary<string, NodeConfiguration>();
overrideXml = new Dictionary<string, string>();
SourceFile = "";
IsRunningAsUnitTest = false;
}
/// <summary>
/// Loads configuration from a given input text reader.
/// </summary>
/// <param name="input">The TextReader to use.</param>
public void Load(TextReader input)
{
Init();
LoadFromXml(ParseXml(input));
}
internal void LoadFromXml(XmlElement root)
{
foreach (XmlNode c in root.ChildNodes)
{
var child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Globals":
Globals.Load(child);
// set subnets so this is independent of order
Defaults.Subnet = Globals.Subnet;
foreach (var o in Overrides.Values)
{
o.Subnet = Globals.Subnet;
}
if (Globals.SeedNodes.Count > 0)
{
primaryNode = Globals.SeedNodes[0];
}
break;
case "Defaults":
Defaults.Load(child);
Defaults.Subnet = Globals.Subnet;
break;
case "Override":
overrideXml[child.GetAttribute("Node")] = WriteXml(child);
break;
}
}
CalculateOverrides();
}
private static string WriteXml(XmlElement element)
{
using(var sw = new StringWriter())
{
using(var xw = XmlWriter.Create(sw))
{
element.WriteTo(xw);
xw.Flush();
return sw.ToString();
}
}
}
private void CalculateOverrides()
{
if (Globals.LivenessEnabled &&
Globals.LivenessType == GlobalConfiguration.LivenessProviderType.NotSpecified)
{
if (Globals.UseSqlSystemStore)
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.SqlServer;
}
else if (Globals.UseAzureSystemStore)
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
}
else if (Globals.UseZooKeeperSystemStore)
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.ZooKeeper;
}
else
{
Globals.LivenessType = GlobalConfiguration.LivenessProviderType.MembershipTableGrain;
}
}
if (Globals.UseMockReminderTable)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.MockTable);
}
else if (Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified)
{
if (Globals.UseSqlSystemStore)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.SqlServer);
}
else if (Globals.UseAzureSystemStore)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
else if (Globals.UseZooKeeperSystemStore)
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.Disabled);
}
else
{
Globals.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain);
}
}
foreach (var p in overrideXml)
{
var n = new NodeConfiguration(Defaults);
n.Load(ParseXml(new StringReader(p.Value)));
InitNodeSettingsFromGlobals(n);
Overrides[n.SiloName] = n;
}
}
private void InitNodeSettingsFromGlobals(NodeConfiguration n)
{
if (n.Endpoint.Equals(this.PrimaryNode)) n.IsPrimaryNode = true;
if (Globals.SeedNodes.Contains(n.Endpoint)) n.IsSeedNode = true;
}
public void LoadFromFile(string fileName)
{
using (TextReader input = File.OpenText(fileName))
{
Load(input);
SourceFile = fileName;
}
}
/// <summary>
/// Obtains the configuration for a given silo.
/// </summary>
/// <param name="siloName">Silo name.</param>
/// <param name="siloNode">NodeConfiguration associated with the specified silo.</param>
/// <returns>true if node was found</returns>
public bool TryGetNodeConfigurationForSilo(string siloName, out NodeConfiguration siloNode)
{
return Overrides.TryGetValue(siloName, out siloNode);
}
/// <summary>
/// Creates a configuration node for a given silo.
/// </summary>
/// <param name="siloName">Silo name.</param>
/// <returns>NodeConfiguration associated with the specified silo.</returns>
public NodeConfiguration CreateNodeConfigurationForSilo(string siloName)
{
var siloNode = new NodeConfiguration(Defaults) { SiloName = siloName };
InitNodeSettingsFromGlobals(siloNode);
Overrides[siloName] = siloNode;
return siloNode;
}
/// <summary>
/// Creates a node config for the specified silo if one does not exist. Returns existing node if one already exists
/// </summary>
/// <param name="siloName">Silo name.</param>
/// <returns>NodeConfiguration associated with the specified silo.</returns>
public NodeConfiguration GetOrCreateNodeConfigurationForSilo(string siloName)
{
NodeConfiguration siloNode;
return !TryGetNodeConfigurationForSilo(siloName, out siloNode) ? CreateNodeConfigurationForSilo(siloName) : siloNode;
}
private void SetPrimaryNode(IPEndPoint primary)
{
primaryNode = primary;
foreach (NodeConfiguration node in Overrides.Values)
{
if (node.Endpoint.Equals(primary))
{
node.IsPrimaryNode = true;
}
}
}
/// <summary>
/// Loads the configuration from the standard paths
/// </summary>
/// <returns></returns>
public void StandardLoad()
{
string fileName = ConfigUtilities.FindConfigFile(true); // Throws FileNotFoundException
LoadFromFile(fileName);
}
/// <summary>
/// Subset of XML configuration file that is updatable at runtime
/// </summary>
private static readonly XmlElement updatableXml = ParseXml(new StringReader(@"
<OrleansConfiguration>
<Globals>
<Messaging ResponseTimeout=""?""/>
<Caching CacheSize=""?""/>
<Liveness ProbeTimeout=""?"" TableRefreshTimeout=""?"" NumMissedProbesLimit=""?""/>
</Globals>
<Defaults>
<LoadShedding Enabled=""?"" LoadLimit=""?""/>
<Tracing DefaultTraceLevel=""?"" PropagateActivityId=""?"">
<TraceLevelOverride LogPrefix=""?"" TraceLevel=""?""/>
</Tracing>
</Defaults>
</OrleansConfiguration>"));
/// <summary>
/// Updates existing configuration.
/// </summary>
/// <param name="input">The input string in XML format to use to update the existing configuration.</param>
/// <returns></returns>
public void Update(string input)
{
var xml = ParseXml(new StringReader(input));
var disallowed = new List<string>();
CheckSubtree(updatableXml, xml, "", disallowed);
if (disallowed.Count > 0)
throw new ArgumentException("Cannot update configuration with" + disallowed.ToStrings());
var dict = ToChildDictionary(xml);
XmlElement globals;
if (dict.TryGetValue("Globals", out globals))
{
Globals.Load(globals);
ConfigChanged("Globals");
foreach (var key in ToChildDictionary(globals).Keys)
{
ConfigChanged("Globals/" + key);
}
}
XmlElement defaults;
if (dict.TryGetValue("Defaults", out defaults))
{
Defaults.Load(defaults);
CalculateOverrides();
ConfigChanged("Defaults");
foreach (var key in ToChildDictionary(defaults).Keys)
{
ConfigChanged("Defaults/" + key);
}
}
}
private static void CheckSubtree(XmlElement allowed, XmlElement test, string prefix, List<string> disallowed)
{
prefix = prefix + "/" + test.LocalName;
if (allowed.LocalName != test.LocalName)
{
disallowed.Add(prefix);
return;
}
foreach (var attribute in AttributeNames(test))
{
if (! allowed.HasAttribute(attribute))
{
disallowed.Add(prefix + "/@" + attribute);
}
}
var allowedChildren = ToChildDictionary(allowed);
foreach (var t in test.ChildNodes)
{
var testChild = t as XmlElement;
if (testChild == null)
continue;
XmlElement allowedChild;
if (! allowedChildren.TryGetValue(testChild.LocalName, out allowedChild))
{
disallowed.Add(prefix + "/" + testChild.LocalName);
}
else
{
CheckSubtree(allowedChild, testChild, prefix, disallowed);
}
}
}
private static Dictionary<string, XmlElement> ToChildDictionary(XmlElement xml)
{
var result = new Dictionary<string, XmlElement>();
foreach (var c in xml.ChildNodes)
{
var child = c as XmlElement;
if (child == null)
continue;
result[child.LocalName] = child;
}
return result;
}
private static IEnumerable<string> AttributeNames(XmlElement element)
{
foreach (var a in element.Attributes)
{
var attr = a as XmlAttribute;
if (attr != null)
yield return attr.LocalName;
}
}
internal void OnConfigChange(string path, Action action, bool invokeNow = true)
{
List<Action> list;
if (listeners.TryGetValue(path, out list))
list.Add(action);
else
listeners.Add(path, new List<Action> { action });
if (invokeNow)
action();
}
internal void ConfigChanged(string path)
{
List<Action> list;
if (!listeners.TryGetValue(path, out list)) return;
foreach (var action in list)
action();
}
/// <summary>
/// Prints the current config for a given silo.
/// </summary>
/// <param name="siloName">The name of the silo to print its configuration.</param>
/// <returns></returns>
public string ToString(string siloName)
{
var sb = new StringBuilder();
sb.Append("Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile));
sb.Append("Host: ").AppendLine(Dns.GetHostName());
sb.Append("Start time: ").AppendLine(TraceLogger.PrintDate(DateTime.UtcNow));
sb.Append("Primary node: ").AppendLine(PrimaryNode == null ? "null" : PrimaryNode.ToString());
sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo());
sb.AppendLine("Global configuration:").Append(Globals.ToString());
NodeConfiguration nc;
if (TryGetNodeConfigurationForSilo(siloName, out nc))
{
sb.AppendLine("Silo configuration:").Append(nc);
}
sb.AppendLine();
return sb.ToString();
}
internal static async Task<IPAddress> ResolveIPAddress(string addrOrHost, byte[] subnet, AddressFamily family)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
if (addrOrHost.Equals("loopback", StringComparison.OrdinalIgnoreCase) ||
addrOrHost.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
addrOrHost.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase))
{
return loopback;
}
else if (addrOrHost == "0.0.0.0")
{
return IPAddress.Any;
}
else
{
// IF the address is an empty string, default to the local machine, but not the loopback address
if (String.IsNullOrEmpty(addrOrHost))
{
addrOrHost = Dns.GetHostName();
// If for some reason we get "localhost" back. This seems to have happened to somebody.
if (addrOrHost.Equals("localhost", StringComparison.OrdinalIgnoreCase))
return loopback;
}
var candidates = new List<IPAddress>();
IPAddress[] nodeIps = await Dns.GetHostAddressesAsync(addrOrHost);
foreach (var nodeIp in nodeIps)
{
if (nodeIp.AddressFamily != family || nodeIp.Equals(loopback)) continue;
// If the subnet does not match - we can't resolve this address.
// If subnet is not specified - pick smallest address deterministically.
if (subnet == null)
{
candidates.Add(nodeIp);
}
else
{
IPAddress ip = nodeIp;
if (subnet.Select((b, i) => ip.GetAddressBytes()[i] == b).All(x => x))
{
candidates.Add(nodeIp);
}
}
}
if (candidates.Count > 0)
{
return PickIPAddress(candidates);
}
var subnetStr = Utils.EnumerableToString(subnet, null, ".", false);
throw new ArgumentException("Hostname '" + addrOrHost + "' with subnet " + subnetStr + " and family " + family + " is not a valid IP address or DNS name");
}
}
private static IPAddress PickIPAddress(IReadOnlyList<IPAddress> candidates)
{
IPAddress chosen = null;
foreach (IPAddress addr in candidates)
{
if (chosen == null)
{
chosen = addr;
}
else
{
if(CompareIPAddresses(addr, chosen)) // pick smallest address deterministically
chosen = addr;
}
}
return chosen;
}
// returns true if lhs is "less" (in some repeatable sense) than rhs
private static bool CompareIPAddresses(IPAddress lhs, IPAddress rhs)
{
byte[] lbytes = lhs.GetAddressBytes();
byte[] rbytes = rhs.GetAddressBytes();
if (lbytes.Length != rbytes.Length) return lbytes.Length < rbytes.Length;
// compare starting from most significant octet.
// 10.68.20.21 < 10.98.05.04
for (int i = 0; i < lbytes.Length; i++)
{
if (lbytes[i] != rbytes[i])
{
return lbytes[i] < rbytes[i];
}
}
// They're equal
return false;
}
/// <summary>
/// Gets the address of the local server.
/// If there are multiple addresses in the correct family in the server's DNS record, the first will be returned.
/// </summary>
/// <returns>The server's IPv4 address.</returns>
internal static IPAddress GetLocalIPAddress(AddressFamily family = AddressFamily.InterNetwork, string interfaceName = null)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
// get list of all network interfaces
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var candidates = new List<IPAddress>();
// loop through interfaces
for (int i=0; i < netInterfaces.Length; i++)
{
NetworkInterface netInterface = netInterfaces[i];
if (netInterface.OperationalStatus != OperationalStatus.Up)
{
// Skip network interfaces that are not operational
continue;
}
if (!string.IsNullOrWhiteSpace(interfaceName) &&
!netInterface.Name.StartsWith(interfaceName, StringComparison.Ordinal)) continue;
bool isLoopbackInterface = (netInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback);
// get list of all unicast IPs from current interface
UnicastIPAddressInformationCollection ipAddresses = netInterface.GetIPProperties().UnicastAddresses;
// loop through IP address collection
foreach (UnicastIPAddressInformation ip in ipAddresses)
{
if (ip.Address.AddressFamily == family) // Picking the first address of the requested family for now. Will need to revisit later
{
//don't pick loopback address, unless we were asked for a loopback interface
if(!(isLoopbackInterface && ip.Address.Equals(loopback)))
{
candidates.Add(ip.Address); // collect all candidates.
}
}
}
}
if (candidates.Count > 0) return PickIPAddress(candidates);
throw new OrleansException("Failed to get a local IP address.");
}
private static XmlElement ParseXml(TextReader input)
{
var doc = new XmlDocument();
var xmlReader = XmlReader.Create(input);
doc.Load(xmlReader);
return doc.DocumentElement;
}
/// <summary>
/// Returns a prepopulated ClusterConfiguration object for a primary local silo (for testing)
/// </summary>
/// <param name="siloPort">TCP port for silo to silo communication</param>
/// <param name="gatewayPort">Client gateway TCP port</param>
/// <returns>ClusterConfiguration object that can be passed to Silo or SiloHost classes for initialization</returns>
public static ClusterConfiguration LocalhostPrimarySilo(int siloPort = 22222, int gatewayPort = 40000)
{
var config = new ClusterConfiguration();
var siloAddress = new IPEndPoint(IPAddress.Loopback, siloPort);
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.MembershipTableGrain;
config.Globals.SeedNodes.Add(siloAddress);
config.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain;
config.Defaults.HostNameOrIPAddress = "localhost";
config.Defaults.Port = siloPort;
config.Defaults.ProxyGatewayEndpoint = new IPEndPoint(IPAddress.Loopback, gatewayPort);
config.PrimaryNode = siloAddress;
return config;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureParameterGrouping
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
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>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestParameterGroupingTestService : ServiceClient<AutoRestParameterGroupingTestService>, IAutoRestParameterGroupingTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IParameterGroupingOperations.
/// </summary>
public virtual IParameterGroupingOperations ParameterGrouping { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestParameterGroupingTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestParameterGroupingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestParameterGroupingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestParameterGroupingTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.ParameterGrouping = new ParameterGroupingOperations(this);
this.BaseUri = new Uri("https://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#region Import
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Collections;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.CRM.Core.Entities;
using ASC.Web.CRM.Resources;
#endregion
namespace ASC.CRM.Core.Dao
{
public class CachedDealMilestoneDao : DealMilestoneDao
{
private readonly HttpRequestDictionary<DealMilestone> _dealMilestoneCache =
new HttpRequestDictionary<DealMilestone>("crm_deal_milestone");
public CachedDealMilestoneDao(int tenantID)
: base(tenantID)
{
}
private void ResetCache(int id)
{
_dealMilestoneCache.Reset(id.ToString());
}
public override int Create(DealMilestone item)
{
item.ID = base.Create(item);
_dealMilestoneCache.Add(item.ID.ToString(), item);
return item.ID;
}
public override void Delete(int id)
{
ResetCache(id);
base.Delete(id);
}
public override void Edit(DealMilestone item)
{
ResetCache(item.ID);
base.Edit(item);
}
private DealMilestone GetByIDBase(int id)
{
return base.GetByID(id);
}
public override DealMilestone GetByID(int id)
{
return _dealMilestoneCache.Get(id.ToString(), () => GetByIDBase(id));
}
public override void Reorder(int[] ids)
{
_dealMilestoneCache.Clear();
base.Reorder(ids);
}
}
public class DealMilestoneDao : AbstractDao
{
#region Constructor
public DealMilestoneDao(int tenantID)
: base(tenantID)
{
}
#endregion
public virtual void Reorder(int[] ids)
{
using (var tx = Db.BeginTransaction())
{
for (int index = 0; index < ids.Length; index++)
Db.ExecuteNonQuery(Update("crm_deal_milestone")
.Set("sort_order", index)
.Where(Exp.Eq("id", ids[index])));
tx.Commit();
}
}
public int GetCount()
{
return Db.ExecuteScalar<int>(Query("crm_deal_milestone").SelectCount());
}
public Dictionary<int, int> GetRelativeItemsCount()
{
var sqlQuery = Query("crm_deal_milestone tbl_deal_milestone")
.Select("tbl_deal_milestone.id")
.OrderBy("tbl_deal_milestone.sort_order", true)
.GroupBy("tbl_deal_milestone.id");
sqlQuery.LeftOuterJoin("crm_deal tbl_crm_deal",
Exp.EqColumns("tbl_deal_milestone.id", "tbl_crm_deal.deal_milestone_id"))
.Select("count(tbl_crm_deal.deal_milestone_id)");
var queryResult = Db.ExecuteList(sqlQuery);
return queryResult.ToDictionary(x => Convert.ToInt32(x[0]), y => Convert.ToInt32(y[1]));
}
public int GetRelativeItemsCount(int id)
{
var sqlQuery = Query("crm_deal")
.Select("count(*)")
.Where(Exp.Eq("deal_milestone_id", id));
return Db.ExecuteScalar<int>(sqlQuery);
}
public virtual int Create(DealMilestone item)
{
if (String.IsNullOrEmpty(item.Title) || String.IsNullOrEmpty(item.Color))
throw new ArgumentException();
int id;
using (var tx = Db.BeginTransaction())
{
if (item.SortOrder == 0)
item.SortOrder = Db.ExecuteScalar<int>(Query("crm_deal_milestone")
.SelectMax("sort_order")) + 1;
id = Db.ExecuteScalar<int>(
Insert("crm_deal_milestone")
.InColumnValue("id", 0)
.InColumnValue("title", item.Title)
.InColumnValue("description", item.Description)
.InColumnValue("color", item.Color)
.InColumnValue("probability", item.Probability)
.InColumnValue("status", (int)item.Status)
.InColumnValue("sort_order", item.SortOrder)
.Identity(1, 0, true));
tx.Commit();
}
return id;
}
public virtual void ChangeColor(int id, String newColor)
{
Db.ExecuteNonQuery(Update("crm_deal_milestone")
.Set("color", newColor)
.Where(Exp.Eq("id", id)));
}
public virtual void Edit(DealMilestone item)
{
if (HaveContactLink(item.ID))
throw new ArgumentException(String.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeEdited, CRMErrorsResource.DealMilestoneHasRelatedDeals));
Db.ExecuteNonQuery(Update("crm_deal_milestone")
.Set("title", item.Title)
.Set("description", item.Description)
.Set("color", item.Color)
.Set("probability", item.Probability)
.Set("status", (int)item.Status)
.Where(Exp.Eq("id", item.ID)));
}
public bool HaveContactLink(int dealMilestoneID)
{
SqlQuery sqlQuery = Query("crm_deal")
.Where(Exp.Eq("deal_milestone_id", dealMilestoneID))
.SelectCount()
.SetMaxResults(1);
return Db.ExecuteScalar<int>(sqlQuery) >= 1;
}
public virtual void Delete(int id)
{
if (HaveContactLink(id))
throw new ArgumentException(String.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeDeleted, CRMErrorsResource.DealMilestoneHasRelatedDeals));
Db.ExecuteNonQuery(Delete("crm_deal_milestone").Where(Exp.Eq("id", id)));
}
public virtual DealMilestone GetByID(int id)
{
var dealMilestones = Db.ExecuteList(GetDealMilestoneQuery(Exp.Eq("id", id))).ConvertAll(row => ToDealMilestone(row));
if (dealMilestones.Count == 0)
return null;
return dealMilestones[0];
}
public Boolean IsExist(int id)
{
return Db.ExecuteScalar<bool>("select exists(select 1 from crm_deal_milestone where tenant_id = @tid and id = @id)",
new { tid = TenantID, id = id });
}
public List<DealMilestone> GetAll(int[] id)
{
return Db.ExecuteList(GetDealMilestoneQuery(Exp.In("id", id))).ConvertAll(row => ToDealMilestone(row));
}
public List<DealMilestone> GetAll()
{
return Db.ExecuteList(GetDealMilestoneQuery(null)).ConvertAll(row => ToDealMilestone(row));
}
private SqlQuery GetDealMilestoneQuery(Exp where)
{
SqlQuery sqlQuery = Query("crm_deal_milestone")
.Select("id",
"title",
"description",
"color",
"probability",
"status",
"sort_order")
.OrderBy("sort_order", true);
if (where != null)
sqlQuery.Where(where);
return sqlQuery;
}
private static DealMilestone ToDealMilestone(object[] row)
{
return new DealMilestone
{
ID = Convert.ToInt32(row[0]),
Title = Convert.ToString(row[1]),
Description = Convert.ToString(row[2]),
Color = Convert.ToString(row[3]),
Probability = Convert.ToInt32(row[4]),
Status = (DealMilestoneStatus)Convert.ToInt32(row[5]),
SortOrder = Convert.ToInt32(row[6])
};
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Search
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
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>
/// Client that can be used to manage Azure Search services and API keys.
/// </summary>
public partial class SearchManagementClient : ServiceClient<SearchManagementClient>, ISearchManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAdminKeysOperations.
/// </summary>
public virtual IAdminKeysOperations AdminKeys { get; private set; }
/// <summary>
/// Gets the IQueryKeysOperations.
/// </summary>
public virtual IQueryKeysOperations QueryKeys { get; private set; }
/// <summary>
/// Gets the IServicesOperations.
/// </summary>
public virtual IServicesOperations Services { get; private set; }
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SearchManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SearchManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SearchManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SearchManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SearchManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.AdminKeys = new AdminKeysOperations(this);
this.QueryKeys = new QueryKeysOperations(this);
this.Services = new ServicesOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2015-02-28";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SelectTest
{
private readonly ITestOutputHelper _log;
public SelectTest(ITestOutputHelper output)
{
_log = output;
}
private const int SmallTimeoutMicroseconds = 10 * 1000;
private const int FailTimeoutMicroseconds = 30 * 1000 * 1000;
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
[Theory]
[InlineData(90, 0)]
[InlineData(0, 90)]
[InlineData(45, 45)]
public void Select_ReadWrite_AllReady_ManySockets(int reads, int writes)
{
Select_ReadWrite_AllReady(reads, writes);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadWrite_AllReady(int reads, int writes)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var writePairs = Enumerable.Range(0, writes).Select(_ => CreateConnectedSockets()).ToArray();
try
{
foreach (var pair in readPairs)
{
pair.Value.Send(new byte[1] { 42 });
}
ArrayList readList = new ArrayList(readPairs.Select(p => p.Key).ToArray());
ArrayList writeList = new ArrayList(writePairs.Select(p => p.Key).ToArray());
Socket.Select(readList, writeList, null, FailTimeoutMicroseconds);
// Since no buffers are full, all writes should be available.
Assert.Equal(writePairs.Length, writeList.Count);
// We could wake up from Select for writes even if reads are about to become available,
// so there's very little we can assert if writes is non-zero.
if (writes == 0 && reads > 0)
{
Assert.InRange(readList.Count, 1, readPairs.Length);
}
// When we do the select again, the lists shouldn't change at all, as they've already
// been filtered to ones that were ready.
int readListCountBefore = readList.Count;
int writeListCountBefore = writeList.Count;
Socket.Select(readList, writeList, null, FailTimeoutMicroseconds);
Assert.Equal(readListCountBefore, readList.Count);
Assert.Equal(writeListCountBefore, writeList.Count);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(writePairs);
}
}
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_ReadError_NoneReady_ManySockets()
{
Select_ReadError_NoneReady(45, 45);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadError_NoneReady(int reads, int errors)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var errorPairs = Enumerable.Range(0, errors).Select(_ => CreateConnectedSockets()).ToArray();
try
{
ArrayList readList = new ArrayList(readPairs.Select(p => p.Key).ToArray());
ArrayList errorList = new ArrayList(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, errorList, SmallTimeoutMicroseconds);
Assert.Empty(readList);
Assert.Empty(errorList);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(errorPairs);
}
}
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
public void Select_Read_OneReadyAtATime_ManySockets(int reads)
{
Select_Read_OneReadyAtATime(90); // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
}
[Theory]
[InlineData(2)]
public void Select_Read_OneReadyAtATime(int reads)
{
var rand = new Random(42);
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (readPairs.Count > 0)
{
int next = rand.Next(0, readPairs.Count);
readPairs[next].Value.Send(new byte[1] { 42 });
IList readList = new ArrayList(readPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, null, FailTimeoutMicroseconds);
Assert.Equal(1, readList.Count);
Assert.Same(readPairs[next].Key, readList[0]);
readPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(readPairs);
}
}
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_Error_OneReadyAtATime()
{
const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
var rand = new Random(42);
var errorPairs = Enumerable.Range(0, Errors).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (errorPairs.Count > 0)
{
int next = rand.Next(0, errorPairs.Count);
errorPairs[next].Value.Send(new byte[1] { 42 }, SocketFlags.OutOfBand);
IList errorList = new ArrayList(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(null, null, errorList, FailTimeoutMicroseconds);
Assert.Equal(1, errorList.Count);
Assert.Same(errorPairs[next].Key, errorList[0]);
errorPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(errorPairs);
}
}
[Theory]
[InlineData(SelectMode.SelectRead)]
[InlineData(SelectMode.SelectError)]
public void Poll_NotReady(SelectMode mode)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Assert.False(pair.Key.Poll(SmallTimeoutMicroseconds, mode));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
[Theory]
[InlineData(-1)]
[InlineData(FailTimeoutMicroseconds)]
public void Poll_ReadReady_LongTimeouts(int microsecondsTimeout)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Task.Delay(1).ContinueWith(_ => pair.Value.Send(new byte[1] { 42 }),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Assert.True(pair.Key.Poll(microsecondsTimeout, SelectMode.SelectRead));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
private static KeyValuePair<Socket, Socket> CreateConnectedSockets()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.LingerState = new LingerOption(true, 0);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.LingerState = new LingerOption(true, 0);
Task<Socket> acceptTask = listener.AcceptAsync();
client.Connect(listener.LocalEndPoint);
Socket server = acceptTask.GetAwaiter().GetResult();
return new KeyValuePair<Socket, Socket>(client, server);
}
}
private static void DisposeSockets(IEnumerable<KeyValuePair<Socket, Socket>> sockets)
{
foreach (var pair in sockets)
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
}
}
| |
#region Licensing notice
// Copyright (C) 2012, Alexander Wieser-Kuciel <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
#region Using directives
using System;
using System.Runtime.InteropServices;
using Crystalbyte.Spectre.Interop;
using Crystalbyte.Spectre.Projections.Internal;
#endregion
namespace Crystalbyte.Spectre {
public sealed class ApplicationSettings : CefTypeAdapter {
public ApplicationSettings()
: base(typeof (CefSettings)) {
Handle = Marshal.AllocHGlobal(NativeSize);
MarshalToNative(new CefSettings {
Size = NativeSize,
LogSeverity = CefLogSeverity.LogseverityInfo
});
// TODO: Implementation is incomplete, must implement free calls for all containing strings on dispose
}
public string ProductVersion {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.ProductVersion.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.ProductVersion = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public int RemoteDebuggingPort {
get {
var r = MarshalFromNative<CefSettings>();
return r.RemoteDebuggingPort;
}
set {
var r = MarshalFromNative<CefSettings>();
r.RemoteDebuggingPort = value;
MarshalToNative(r);
}
}
public string CacheDirectory {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.CachePath.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.CachePath = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public string UserAgent {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.UserAgent.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.UserAgent = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public bool IsPackLoadingDisabled {
get {
var r = MarshalFromNative<CefSettings>();
return r.PackLoadingDisabled;
}
set {
var r = MarshalFromNative<CefSettings>();
r.PackLoadingDisabled = value;
MarshalToNative(r);
}
}
public string BrowserSubprocessPath {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.BrowserSubprocessPath.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.BrowserSubprocessPath = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public string LocalesDirectory {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.LocalesDirPath.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.LocalesDirPath = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public string Locale {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.Locale.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.Locale = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public string ResourceDirectory {
get {
var r = MarshalFromNative<CefSettings>();
return Marshal.PtrToStringUni(r.ResourcesDirPath.Str);
}
set {
var r = MarshalFromNative<CefSettings>();
r.ResourcesDirPath = new CefStringUtf16 {
//Dtor = Marshal.GetFunctionPointerForDelegate(StringUtf16.FreeCallback),
Length = value.Length,
Str = Marshal.StringToHGlobalUni(value)
};
MarshalToNative(r);
}
}
public LogSeverity LogSeverity {
get {
var r = MarshalFromNative<CefSettings>();
return (LogSeverity) r.LogSeverity;
}
set {
var reflection = MarshalFromNative<CefSettings>();
reflection.LogSeverity = (CefLogSeverity) value;
MarshalToNative(reflection);
}
}
public bool IsMessageLoopMultiThreaded {
get {
var r = MarshalFromNative<CefSettings>();
return r.MultiThreadedMessageLoop;
}
set {
var r = MarshalFromNative<CefSettings>();
r.MultiThreadedMessageLoop = value;
MarshalToNative(r);
}
}
public bool IsSingleProcess {
get {
var r = MarshalFromNative<CefSettings>();
return r.SingleProcess;
}
set {
var r = MarshalFromNative<CefSettings>();
r.SingleProcess = value;
MarshalToNative(r);
}
}
protected override void DisposeNative() {
if (Handle != IntPtr.Zero) {
Marshal.FreeHGlobal(Handle);
}
base.DisposeNative();
}
}
}
| |
#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.Drawing;
using Axiom.Controllers;
using Axiom.Controllers.Canned;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
using Axiom.Utility;
using Demos;
namespace Axiom.Demos {
/// <summary>
/// Sample class which shows the classic spinning triangle, done in the Axiom engine.
/// </summary>
public class Tutorial1 : DemoBase {
#region Methods
private Vector4 color = new Vector4(1, 0, 0, 1);
protected override void OnFrameStarted(object source, FrameEventArgs e) {
base.OnFrameStarted (source, e);
color.x += e.TimeSinceLastFrame * .6f;
if(color.x > 1) color.x = 0;
color.y += e.TimeSinceLastFrame * .6f;
if(color.y > 1) color.y = 0;
color.z += e.TimeSinceLastFrame * .6f;
if(color.z > 1) color.z = 0;
}
protected override void CreateScene() {
// create a 3d line
Line3d line = new Line3d(new Vector3(0, 0, 30), Vector3.UnitY, 50, ColorEx.Blue);
Triangle tri = new Triangle(
new Vector3(-25, 0, 0),
new Vector3(0, 50, 0),
new Vector3(25, 0, 0),
ColorEx.Red,
ColorEx.Blue,
ColorEx.Green);
// create a node for the line
SceneNode node = scene.RootSceneNode.CreateChildSceneNode();
SceneNode lineNode = node.CreateChildSceneNode();
SceneNode triNode = node.CreateChildSceneNode();
triNode.Position = new Vector3(50, 0, 0);
// add the line and triangle to the scene
lineNode.AttachObject(line);
triNode.AttachObject(tri);
// create a node rotation controller value, which will mark the specified scene node as a target of the rotation
// we want to rotate along the Y axis for the triangle and Z for the line (just for the hell of it)
NodeRotationControllerValue rotate = new NodeRotationControllerValue(triNode, Vector3.UnitY);
NodeRotationControllerValue rotate2 = new NodeRotationControllerValue(lineNode, Vector3.UnitZ);
// the multiply controller function will multiply the source controller value by the specified value each frame.
MultipyControllerFunction func = new MultipyControllerFunction(50);
// create a new controller, using the rotate and func objects created above. there are 2 overloads to this method. the one being
// used uses an internal FrameTimeControllerValue as the source value by default. The destination value will be the node, which
// is implemented to simply call Rotate on the specified node along the specified axis. The function will mutiply the given value
// against the source value, which in this case is the current frame time. The end result in this demo is that if 50 is specified in the
// MultiplyControllerValue, then the node will rotate 50 degrees per second. since the value is scaled by the frame time, the speed
// of the rotation will be consistent on all machines regardless of CPU speed.
ControllerManager.Instance.CreateController(rotate, func);
ControllerManager.Instance.CreateController(rotate2, func);
// place the camera in an optimal position
camera.Position = new Vector3(30, 30, 220);
window.DebugText = "Spinning triangle - Using custom built geometry";
}
#endregion
}
/// <summary>
/// A class for rendering lines in 3d.
/// </summary>
public class Line3d : SimpleRenderable {
// constants for buffer source bindings
const int POSITION = 0;
const int COLOR = 1;
/// <summary>
///
/// </summary>
/// <param name="startPoint">Point where the line will start.</param>
/// <param name="direction">The direction the vector is heading in.</param>
/// <param name="length">The length (magnitude) of the line vector.</param>
/// <param name="color">The color which this line should be.</param>
public Line3d(Vector3 startPoint, Vector3 direction, float length, ColorEx color) {
// normalize the direction vector to ensure all elements fall in [0,1] range.
direction.Normalize();
// calculate the actual endpoint
Vector3 endPoint = startPoint + (direction * length);
vertexData = new VertexData();
vertexData.vertexCount = 2;
vertexData.vertexStart = 0;
VertexDeclaration decl = vertexData.vertexDeclaration;
VertexBufferBinding binding = vertexData.vertexBufferBinding;
// add a position and color element to the declaration
decl.AddElement(POSITION, 0, VertexElementType.Float3, VertexElementSemantic.Position);
decl.AddElement(COLOR, 0, VertexElementType.Color, VertexElementSemantic.Diffuse);
// create a vertex buffer for the position
HardwareVertexBuffer buffer =
HardwareBufferManager.Instance.CreateVertexBuffer(
decl.GetVertexSize(POSITION),
vertexData.vertexCount,
BufferUsage.StaticWriteOnly);
Vector3[] pos = new Vector3[] { startPoint, endPoint };
// write the data to the position buffer
buffer.WriteData(0, buffer.Size, pos, true);
// bind the position buffer
binding.SetBinding(POSITION, buffer);
// create a color buffer
buffer = HardwareBufferManager.Instance.CreateVertexBuffer(
decl.GetVertexSize(COLOR),
vertexData.vertexCount,
BufferUsage.StaticWriteOnly);
uint colorValue = Root.Instance.RenderSystem.ConvertColor(color);
uint[] colors = new uint[] { colorValue, colorValue };
// write the data to the position buffer
buffer.WriteData(0, buffer.Size, colors, true);
// bind the color buffer
binding.SetBinding(COLOR, buffer);
// MATERIAL
// grab a copy of the BaseWhite material for our use
Material material = MaterialManager.Instance.GetByName("BaseWhite");
material = material.Clone("LineMat");
// disable lighting to vertex colors are used
material.Lighting = false;
// set culling to none so the triangle is drawn 2 sided
material.CullingMode = CullingMode.None;
this.Material = material;
// set the bounding box of the line
this.box = new AxisAlignedBox(startPoint, endPoint);
}
/// <summary>
///
/// </summary>
/// <param name="camera"></param>
/// <returns></returns>
public override float GetSquaredViewDepth(Camera camera) {
Vector3 min, max, mid, dist;
min = box.Minimum;
max = box.Maximum;
mid = ((min - max) * 0.5f) + min;
dist = camera.DerivedPosition - mid;
return dist.LengthSquared;
}
/// <summary>
///
/// </summary>
/// <param name="op"></param>
public override void GetRenderOperation(RenderOperation op) {
op.vertexData = vertexData;
op.indexData = null;
op.operationType = OperationType.LineList;
op.useIndices = false;
}
public override float BoundingRadius {
get {
return 0;
}
}
}
/// <summary>
/// A class for rendering a simple triangle with colored vertices.
/// </summary>
public class Triangle : SimpleRenderable {
// constants for buffer source bindings
const int POSITION = 0;
const int COLOR = 1;
/// <summary>
///
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <param name="v3"></param>
public Triangle(Vector3 v1, Vector3 v2, Vector3 v3, ColorEx c1, ColorEx c2, ColorEx c3) {
vertexData = new VertexData();
vertexData.vertexCount = 3;
vertexData.vertexStart = 0;
VertexDeclaration decl = vertexData.vertexDeclaration;
VertexBufferBinding binding = vertexData.vertexBufferBinding;
// add a position and color element to the declaration
decl.AddElement(POSITION, 0, VertexElementType.Float3, VertexElementSemantic.Position);
decl.AddElement(COLOR, 0, VertexElementType.Color, VertexElementSemantic.Diffuse);
// POSITIONS
// create a vertex buffer for the position
HardwareVertexBuffer buffer =
HardwareBufferManager.Instance.CreateVertexBuffer(
decl.GetVertexSize(POSITION),
vertexData.vertexCount,
BufferUsage.StaticWriteOnly);
Vector3[] positions = new Vector3[] { v1, v2, v3 };
// write the positions to the buffer
buffer.WriteData(0, buffer.Size, positions, true);
// bind the position buffer
binding.SetBinding(POSITION, buffer);
// COLORS
// create a color buffer
buffer = HardwareBufferManager.Instance.CreateVertexBuffer(
decl.GetVertexSize(COLOR),
vertexData.vertexCount,
BufferUsage.StaticWriteOnly);
// create an int array of the colors to use.
// note: these must be converted to the current API's
// preferred packed int format
uint[] colors = new uint[] {
Root.Instance.RenderSystem.ConvertColor(c1),
Root.Instance.RenderSystem.ConvertColor(c2),
Root.Instance.RenderSystem.ConvertColor(c3)
};
// write the colors to the color buffer
buffer.WriteData(0, buffer.Size, colors, true);
// bind the color buffer
binding.SetBinding(COLOR, buffer);
// MATERIAL
// grab a copy of the BaseWhite material for our use
Material material = MaterialManager.Instance.GetByName("BaseWhite");
material = material.Clone("TriMat");
// disable lighting to vertex colors are used
material.Lighting = false;
// set culling to none so the triangle is drawn 2 sided
material.CullingMode = CullingMode.None;
materialName = "TriMat";
this.Material = material;
// set the bounding box of the tri
// TODO: not right, but good enough for now
this.box = new AxisAlignedBox(new Vector3(25, 50, 0), new Vector3(-25, 0, 0));
}
/// <summary>
///
/// </summary>
/// <param name="camera"></param>
/// <returns></returns>
public override float GetSquaredViewDepth(Camera camera) {
Vector3 min, max, mid, dist;
min = box.Minimum;
max = box.Maximum;
mid = ((min - max) * 0.5f) + min;
dist = camera.DerivedPosition - mid;
return dist.LengthSquared;
}
/// <summary>
///
/// </summary>
/// <param name="op"></param>
public override void GetRenderOperation(RenderOperation op) {
op.vertexData = vertexData;
op.indexData = null;
op.operationType = OperationType.TriangleList;
op.useIndices = false;
}
public override float BoundingRadius {
get {
return 0;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("WorkItemGroup Name={Name} State={state}")]
internal class WorkItemGroup : IWorkItem
{
private enum WorkGroupStatus
{
Waiting = 0,
Runnable = 1,
Running = 2
}
private readonly ILogger log;
private readonly OrleansTaskScheduler masterScheduler;
private WorkGroupStatus state;
private readonly Object lockable;
private readonly Queue<Task> workItems;
private long totalItemsEnQueued; // equals total items queued, + 1
private long totalItemsProcessed;
private TimeSpan totalQueuingDelay;
private Task currentTask;
private DateTime currentTaskStarted;
private long shutdownSinceTimestamp;
private long lastShutdownWarningTimestamp;
private readonly QueueTrackingStatistic queueTracking;
private readonly long quantumExpirations;
private readonly int workItemGroupStatisticsNumber;
private readonly CancellationToken cancellationToken;
private readonly SchedulerStatisticsGroup schedulerStatistics;
internal ActivationTaskScheduler TaskScheduler { get; private set; }
public DateTime TimeQueued { get; set; }
public TimeSpan TimeSinceQueued
{
get { return Utils.Since(TimeQueued); }
}
public ISchedulingContext SchedulingContext { get; set; }
public bool IsSystemPriority
{
get { return SchedulingUtils.IsSystemPriorityContext(SchedulingContext); }
}
internal bool IsSystemGroup
{
get { return SchedulingUtils.IsSystemContext(SchedulingContext); }
}
public string Name { get { return SchedulingContext == null ? "unknown" : SchedulingContext.Name; } }
internal int ExternalWorkItemCount
{
get { lock (lockable) { return WorkItemCount; } }
}
private Task CurrentTask
{
get => currentTask;
set
{
currentTask = value;
currentTaskStarted = DateTime.UtcNow;
}
}
private int WorkItemCount
{
get { return workItems.Count; }
}
internal float AverageQueueLenght
{
get
{
return 0;
}
}
internal float NumEnqueuedRequests
{
get
{
return 0;
}
}
internal float ArrivalRate
{
get
{
return 0;
}
}
private bool HasWork => this.WorkItemCount != 0;
private bool IsShutdown => this.shutdownSinceTimestamp > 0;
// This is the maximum number of work items to be processed in an activation turn.
// If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing).
private const int MaxWorkItemsPerTurn = 0; // Unlimited
// This is the maximum number of waiting threads (blocked in WaitForResponse) allowed
// per ActivationWorker. An attempt to wait when there are already too many threads waiting
// will result in a TooManyWaitersException being thrown.
//private static readonly int MaxWaitingThreads = 500;
internal WorkItemGroup(
OrleansTaskScheduler sched,
ISchedulingContext schedulingContext,
ILoggerFactory loggerFactory,
CancellationToken ct,
SchedulerStatisticsGroup schedulerStatistics,
IOptions<StatisticsOptions> statisticsOptions)
{
masterScheduler = sched;
SchedulingContext = schedulingContext;
cancellationToken = ct;
this.schedulerStatistics = schedulerStatistics;
state = WorkGroupStatus.Waiting;
workItems = new Queue<Task>();
lockable = new Object();
totalItemsEnQueued = 0;
totalItemsProcessed = 0;
totalQueuingDelay = TimeSpan.Zero;
quantumExpirations = 0;
TaskScheduler = new ActivationTaskScheduler(this, loggerFactory);
log = IsSystemPriority ? loggerFactory.CreateLogger($"{this.GetType().Namespace} {Name}.{this.GetType().Name}") : loggerFactory.CreateLogger<WorkItemGroup>();
if (schedulerStatistics.CollectShedulerQueuesStats)
{
queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name, statisticsOptions);
queueTracking.OnStartExecution();
}
if (schedulerStatistics.CollectPerWorkItemStats)
{
workItemGroupStatisticsNumber = schedulerStatistics.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext,
() =>
{
var sb = new StringBuilder();
lock (lockable)
{
sb.Append("QueueLength = " + WorkItemCount);
sb.Append(String.Format(", State = {0}", state));
if (state == WorkGroupStatus.Runnable)
sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null"));
}
return sb.ToString();
});
}
}
/// <summary>
/// Adds a task to this activation.
/// If we're adding it to the run list and we used to be waiting, now we're runnable.
/// </summary>
/// <param name="task">The work item to add.</param>
public void EnqueueTask(Task task)
{
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace(
"EnqueueWorkItem {Task} into {SchedulingContext} when TaskScheduler.Current={TaskScheduler}",
task,
this.SchedulingContext,
System.Threading.Tasks.TaskScheduler.Current);
}
#endif
if (this.IsShutdown)
{
// Log diagnostics and continue to schedule the task.
LogEnqueueOnStoppedScheduler(task);
}
lock (lockable)
{
long thisSequenceNumber = totalItemsEnQueued++;
int count = WorkItemCount;
workItems.Enqueue(task);
int maxPendingItemsLimit = masterScheduler.MaxPendingItemsSoftLimit;
if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit)
{
log.LogWarning(
(int)ErrorCode.SchedulerTooManyPendingItems,
"{PendingWorkItemCount} pending work items for group {WorkGroupName}, exceeding the warning threshold of {WarningThreshold}",
count,
this.Name,
maxPendingItemsLimit);
}
if (state != WorkGroupStatus.Waiting) return;
state = WorkGroupStatus.Runnable;
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
log.LogTrace(
"Add to RunQueue {Task}, #{SequenceNumber}, onto {SchedulingContext}",
task,
thisSequenceNumber,
SchedulingContext);
}
#endif
masterScheduler.ScheduleExecution(this);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void LogEnqueueOnStoppedScheduler(Task task)
{
var now = ValueStopwatch.GetTimestamp();
if (this.lastShutdownWarningTimestamp == 0)
{
this.log.LogWarning(
(int)ErrorCode.SchedulerEnqueueWorkWhenShutdown,
"Enqueuing task {Task} to a work item group which should have terminated. "
+ "Likely reasons are that the task is not being 'awaited' properly or a TaskScheduler was captured and is being used to schedule tasks "
+ "after a grain has been deactivated.\nWorkItemGroup: {Status}\nTask.AsyncState: {TaskState}\n{Stack}",
OrleansTaskExtentions.ToString(task),
this.DumpStatus(),
task.AsyncState,
Utils.GetStackTrace());
this.lastShutdownWarningTimestamp = now;
}
else if (ValueStopwatch.FromTimestamp(this.lastShutdownWarningTimestamp, now).Elapsed > this.masterScheduler.StoppedWorkItemGroupWarningInterval)
{
// Upgrade the warning to an error after 1 minute, include a stack trace, and continue to log up to once per minute.
this.log.LogError(
(int)ErrorCode.SchedulerEnqueueWorkWhenShutdown,
"Enqueuing task {Task} to a work item group which should have terminated. "
+ "Likely reasons are that the task is not being 'awaited' properly or a TaskScheduler was captured and is being used to schedule tasks "
+ "after a grain has been deactivated.\nWorkItemGroup: {Status}\nTask.AsyncState: {TaskState}\n{Stack}",
OrleansTaskExtentions.ToString(task),
this.DumpStatus(),
task.AsyncState,
Utils.GetStackTrace());
this.lastShutdownWarningTimestamp = now;
}
}
/// <summary>
/// Shuts down this work item group so that it will not process any additional work items, even if they
/// have already been queued.
/// </summary>
internal void Stop()
{
lock (lockable)
{
if (this.HasWork)
{
ReportWorkGroupProblem(
String.Format("WorkItemGroup is being shutdown while still active. workItemCount = {0}."
+ "The likely reason is that the task is not being 'awaited' properly.", WorkItemCount),
ErrorCode.SchedulerWorkGroupStopping);
}
if (this.IsShutdown)
{
log.LogWarning(
(int)ErrorCode.SchedulerWorkGroupShuttingDown,
"WorkItemGroup is already shutting down {WorkItemGroup}",
this.ToString());
return;
}
this.shutdownSinceTimestamp = ValueStopwatch.GetTimestamp();
if (this.schedulerStatistics.CollectPerWorkItemStats)
this.schedulerStatistics.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber);
if (this.schedulerStatistics.CollectShedulerQueuesStats)
queueTracking.OnStopExecution();
}
}
public WorkItemType ItemType
{
get { return WorkItemType.WorkItemGroup; }
}
// Execute one or more turns for this activation.
// This method is always called in a single-threaded environment -- that is, no more than one
// thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc.
public void Execute()
{
try
{
// Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation
int count = 0;
var stopwatch = ValueStopwatch.StartNew();
do
{
lock (lockable)
{
state = WorkGroupStatus.Running;
// Check the cancellation token (means that the silo is stopping)
if (cancellationToken.IsCancellationRequested)
{
this.log.LogWarning(
(int)ErrorCode.SchedulerSkipWorkCancelled,
"Thread {Thread} is exiting work loop due to cancellation token. WorkItemGroup: {WorkItemGroup}, Have {WorkItemCount} work items in the queue.",
Thread.CurrentThread.ToString(),
this.ToString(),
this.WorkItemCount);
break;
}
}
// Get the first Work Item on the list
Task task;
lock (lockable)
{
if (workItems.Count > 0)
CurrentTask = task = workItems.Dequeue();
else // If the list is empty, then we're done
break;
}
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
log.LogTrace(
"About to execute task {Task} in SchedulingContext={SchedulingContext}",
OrleansTaskExtentions.ToString(task),
this.SchedulingContext);
}
#endif
var taskStart = stopwatch.Elapsed;
try
{
TaskScheduler.RunTask(task);
}
catch (Exception ex)
{
this.log.LogError(
(int)ErrorCode.SchedulerExceptionFromExecute,
ex,
"Worker thread caught an exception thrown from Execute by task {Task}. Exception: {Exception}",
OrleansTaskExtentions.ToString(task),
ex);
throw;
}
finally
{
totalItemsProcessed++;
var taskLength = stopwatch.Elapsed - taskStart;
if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold)
{
this.schedulerStatistics.NumLongRunningTurns.Increment();
this.log.LogWarning(
(int)ErrorCode.SchedulerTurnTooLong3,
"Task {Task} in WorkGroup {SchedulingContext} took elapsed time {Duration} for execution, which is longer than {TurnWarningLengthThreshold}. Running on thread {Thread}",
OrleansTaskExtentions.ToString(task),
this.SchedulingContext.ToString(),
taskLength.ToString("g"),
OrleansTaskScheduler.TurnWarningLengthThreshold,
Thread.CurrentThread.ToString());
}
CurrentTask = null;
}
count++;
}
while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) &&
((masterScheduler.SchedulingOptions.ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < masterScheduler.SchedulingOptions.ActivationSchedulingQuantum)));
}
catch (Exception ex)
{
this.log.LogError(
(int)ErrorCode.Runtime_Error_100032,
ex,
"Worker thread {Thread} caught an exception thrown from IWorkItem.Execute: {Exception}",
Thread.CurrentThread,
ex);
}
finally
{
// Now we're not Running anymore.
// If we left work items on our run list, we're Runnable, and need to go back on the silo run queue;
// If our run list is empty, then we're waiting.
lock (lockable)
{
if (WorkItemCount > 0)
{
state = WorkGroupStatus.Runnable;
masterScheduler.ScheduleExecution(this);
}
else
{
state = WorkGroupStatus.Waiting;
}
}
}
}
public override string ToString()
{
return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}",
IsSystemGroup ? "System*" : "",
Name,
state);
}
public string DumpStatus()
{
lock (lockable)
{
var sb = new StringBuilder();
sb.Append(this);
sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ",
WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations);
if (CurrentTask != null)
{
sb.AppendFormat(" Executing Task Id={0} Status={1} for {2}.",
CurrentTask.Id, CurrentTask.Status, Utils.Since(currentTaskStarted));
}
if (AverageQueueLenght > 0)
{
sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLenght);
if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0)
{
sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds);
}
}
sb.AppendFormat("TaskRunner={0}; ", TaskScheduler);
if (SchedulingContext != null)
{
sb.AppendFormat("Detailed SchedulingContext=<{0}>", SchedulingContext.DetailedStatus());
}
return sb.ToString();
}
}
private void ReportWorkGroupProblem(string what, ErrorCode errorCode)
{
var msg = string.Format("{0} {1}", what, DumpStatus());
log.Warn(errorCode, msg);
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections.Generic;
using JsonFx.Model;
using JsonFx.Model.Filters;
using JsonFx.Serialization.Filters;
using JsonFx.Serialization.GraphCycles;
using JsonFx.Serialization.Resolvers;
namespace JsonFx.Serialization
{
/// <summary>
/// Controls the serialization settings for IDataWriter
/// </summary>
public sealed class DataWriterSettings :
IResolverCacheContainer
{
#region Fields
private bool prettyPrint;
private GraphCycleType graphCycles = GraphCycleType.Ignore;
private string tab = "\t";
private int maxDepth;
private string newLine = Environment.NewLine;
private readonly ResolverCache ResolverCache;
private readonly IEnumerable<IDataFilter<ModelTokenType>> ModelFilters;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
public DataWriterSettings()
: this(new PocoResolverStrategy(), new Iso8601DateFilter())
{
}
/// <summary>
/// Ctor
/// </summary>
public DataWriterSettings(params IDataFilter<ModelTokenType>[] filters)
: this(new PocoResolverStrategy(), filters)
{
}
/// <summary>
/// Ctor
/// </summary>
public DataWriterSettings(IEnumerable<IDataFilter<ModelTokenType>> filters)
: this(new PocoResolverStrategy(), filters)
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="strategy"></param>
public DataWriterSettings(IResolverStrategy strategy, params IDataFilter<ModelTokenType>[] filters)
: this(new ResolverCache(strategy), filters)
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="strategy"></param>
public DataWriterSettings(IResolverStrategy strategy, IEnumerable<IDataFilter<ModelTokenType>> filters)
: this(new ResolverCache(strategy), filters)
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="resolverCache"></param>
public DataWriterSettings(ResolverCache resolverCache, params IDataFilter<ModelTokenType>[] filters)
: this(resolverCache, (IEnumerable<IDataFilter<ModelTokenType>>) filters)
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="resolverCache"></param>
public DataWriterSettings(ResolverCache resolverCache, IEnumerable<IDataFilter<ModelTokenType>> filters)
{
this.ResolverCache = resolverCache;
this.ModelFilters = filters;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets what to do when graph cycles (repeated references) are encounted
/// </summary>
public GraphCycleType GraphCycles
{
get { return this.graphCycles; }
set { this.graphCycles = value; }
}
/// <summary>
/// Gets and sets the maximum nesting depth
/// </summary>
/// <remarks>
/// Depth is a fast and easy safegaurd against detecting graph cycles but may produce false positives
/// </remarks>
public int MaxDepth
{
get { return this.maxDepth; }
set { this.maxDepth = value; }
}
/// <summary>
/// Gets and sets if output will be formatted for human reading.
/// </summary>
public bool PrettyPrint
{
get { return this.prettyPrint; }
set { this.prettyPrint = value; }
}
/// <summary>
/// Gets and sets the string to use for indentation
/// </summary>
public string Tab
{
get { return this.tab; }
set { this.tab = value; }
}
/// <summary>
/// Gets and sets the line terminator string
/// </summary>
public string NewLine
{
get { return this.newLine; }
set { this.newLine = value; }
}
/// <summary>
/// Gets manager of name resolution for IDataReader
/// </summary>
public ResolverCache Resolver
{
get { return this.ResolverCache; }
}
/// <summary>
/// Gets the custom filters
/// </summary>
public IEnumerable<IDataFilter<ModelTokenType>> Filters
{
get { return this.ModelFilters; }
}
#endregion Properties
#region IResolverCacheContainer Members
ResolverCache IResolverCacheContainer.ResolverCache
{
get { return this.ResolverCache; }
}
#endregion IResolverCacheContainer Members
}
}
| |
// 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 Internal.IL;
using Internal.TypeSystem;
using Internal.Text;
using ILCompiler.DependencyAnalysis;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler
{
/// <summary>
/// Captures information required to generate a ReadyToRun helper to create a delegate type instance
/// pointing to a specific target method.
/// </summary>
public sealed class DelegateCreationInfo
{
private enum TargetKind
{
CanonicalEntrypoint,
ExactCallableAddress,
InterfaceDispatch,
VTableLookup,
MethodHandle,
}
private TargetKind _targetKind;
/// <summary>
/// Gets the node corresponding to the method that initializes the delegate.
/// </summary>
public IMethodNode Constructor
{
get;
}
public MethodDesc TargetMethod
{
get;
}
private bool TargetMethodIsUnboxingThunk
{
get
{
return TargetMethod.OwningType.IsValueType && !TargetMethod.Signature.IsStatic;
}
}
public bool TargetNeedsVTableLookup => _targetKind == TargetKind.VTableLookup;
public bool NeedsVirtualMethodUseTracking
{
get
{
return _targetKind == TargetKind.VTableLookup || _targetKind == TargetKind.InterfaceDispatch;
}
}
public bool NeedsRuntimeLookup
{
get
{
switch (_targetKind)
{
case TargetKind.VTableLookup:
return false;
case TargetKind.CanonicalEntrypoint:
case TargetKind.ExactCallableAddress:
case TargetKind.InterfaceDispatch:
case TargetKind.MethodHandle:
return TargetMethod.IsRuntimeDeterminedExactMethod;
default:
Debug.Assert(false);
return false;
}
}
}
// None of the data structures that support shared generics have been ported to the JIT
// codebase which makes this a huge PITA. Not including the method for JIT since nobody
// uses it in that mode anyway.
#if !SUPPORT_JIT
public GenericLookupResult GetLookupKind(NodeFactory factory)
{
Debug.Assert(NeedsRuntimeLookup);
switch (_targetKind)
{
case TargetKind.ExactCallableAddress:
return factory.GenericLookup.MethodEntry(TargetMethod, TargetMethodIsUnboxingThunk);
case TargetKind.InterfaceDispatch:
return factory.GenericLookup.VirtualDispatchCell(TargetMethod);
case TargetKind.MethodHandle:
return factory.GenericLookup.MethodHandle(TargetMethod);
default:
Debug.Assert(false);
return null;
}
}
#endif
/// <summary>
/// Gets the node representing the target method of the delegate if no runtime lookup is needed.
/// </summary>
public ISymbolNode GetTargetNode(NodeFactory factory)
{
Debug.Assert(!NeedsRuntimeLookup);
switch (_targetKind)
{
case TargetKind.CanonicalEntrypoint:
return factory.CanonicalEntrypoint(TargetMethod, TargetMethodIsUnboxingThunk);
case TargetKind.ExactCallableAddress:
return factory.ExactCallableAddress(TargetMethod, TargetMethodIsUnboxingThunk);
case TargetKind.InterfaceDispatch:
return factory.InterfaceDispatchCell(TargetMethod);
case TargetKind.MethodHandle:
return factory.RuntimeMethodHandle(TargetMethod);
case TargetKind.VTableLookup:
Debug.Fail("Need to do runtime lookup");
return null;
default:
Debug.Assert(false);
return null;
}
}
/// <summary>
/// Gets an optional node passed as an additional argument to the constructor.
/// </summary>
public IMethodNode Thunk
{
get;
}
private DelegateCreationInfo(IMethodNode constructor, MethodDesc targetMethod, TargetKind targetKind, IMethodNode thunk = null)
{
Constructor = constructor;
TargetMethod = targetMethod;
_targetKind = targetKind;
Thunk = thunk;
}
/// <summary>
/// Constructs a new instance of <see cref="DelegateCreationInfo"/> set up to construct a delegate of type
/// '<paramref name="delegateType"/>' pointing to '<paramref name="targetMethod"/>'.
/// </summary>
public static DelegateCreationInfo Create(TypeDesc delegateType, MethodDesc targetMethod, NodeFactory factory, bool followVirtualDispatch)
{
TypeSystemContext context = delegateType.Context;
DefType systemDelegate = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType;
int paramCountTargetMethod = targetMethod.Signature.Length;
if (!targetMethod.Signature.IsStatic)
{
paramCountTargetMethod++;
}
DelegateInfo delegateInfo = context.GetDelegateInfo(delegateType.GetTypeDefinition());
int paramCountDelegateClosed = delegateInfo.Signature.Length + 1;
bool closed = false;
if (paramCountDelegateClosed == paramCountTargetMethod)
{
closed = true;
}
else
{
Debug.Assert(paramCountDelegateClosed == paramCountTargetMethod + 1);
}
if (targetMethod.Signature.IsStatic)
{
MethodDesc invokeThunk;
MethodDesc initMethod;
if (!closed)
{
// Open delegate to a static method
if (targetMethod.IsNativeCallable)
{
// If target method is native callable, create a reverse PInvoke delegate
initMethod = systemDelegate.GetKnownMethod("InitializeReversePInvokeThunk", null);
invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ReversePinvokeThunk];
// You might hit this when the delegate is generic: you need to make the delegate non-generic.
// If the code works on Project N, it's because the delegate is used in connection with
// AddrOf intrinsic (please validate that). We don't have the necessary AddrOf expansion in
// the codegen to make this work without actually constructing the delegate. You can't construct
// the delegate if it's generic, even on Project N.
// TODO: Make this throw something like "TypeSystemException.InvalidProgramException"?
Debug.Assert(invokeThunk != null, "Delegate with a non-native signature for a NativeCallable method");
}
else
{
initMethod = systemDelegate.GetKnownMethod("InitializeOpenStaticThunk", null);
invokeThunk = delegateInfo.Thunks[DelegateThunkKind.OpenStaticThunk];
}
}
else
{
// Closed delegate to a static method (i.e. delegate to an extension method that locks the first parameter)
invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ClosedStaticThunk];
initMethod = systemDelegate.GetKnownMethod("InitializeClosedStaticThunk", null);
}
var instantiatedDelegateType = delegateType as InstantiatedType;
if (instantiatedDelegateType != null)
invokeThunk = context.GetMethodForInstantiatedType(invokeThunk, instantiatedDelegateType);
return new DelegateCreationInfo(
factory.MethodEntrypoint(initMethod),
targetMethod,
TargetKind.ExactCallableAddress,
factory.MethodEntrypoint(invokeThunk));
}
else
{
if (!closed)
throw new NotImplementedException("Open instance delegates");
string initializeMethodName = "InitializeClosedInstance";
MethodDesc targetCanonMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
TargetKind kind;
if (targetMethod.HasInstantiation)
{
if (followVirtualDispatch && targetMethod.IsVirtual)
{
initializeMethodName = "InitializeClosedInstanceWithGVMResolution";
kind = TargetKind.MethodHandle;
}
else
{
if (targetMethod != targetCanonMethod)
{
// Closed delegates to generic instance methods need to be constructed through a slow helper that
// checks for the fat function pointer case (function pointer + instantiation argument in a single
// pointer) and injects an invocation thunk to unwrap the fat function pointer as part of
// the invocation if necessary.
initializeMethodName = "InitializeClosedInstanceSlow";
}
kind = TargetKind.ExactCallableAddress;
}
}
else
{
if (followVirtualDispatch && targetMethod.IsVirtual)
{
if (targetMethod.OwningType.IsInterface)
{
kind = TargetKind.InterfaceDispatch;
initializeMethodName = "InitializeClosedInstanceToInterface";
}
else
{
kind = TargetKind.VTableLookup;
targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
}
}
else
{
kind = TargetKind.CanonicalEntrypoint;
targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
}
}
return new DelegateCreationInfo(
factory.MethodEntrypoint(systemDelegate.GetKnownMethod(initializeMethodName, null)),
targetMethod,
kind);
}
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append("__DelegateCtor_");
if (TargetNeedsVTableLookup)
sb.Append("FromVtbl_");
Constructor.AppendMangledName(nameMangler, sb);
sb.Append("__");
sb.Append(nameMangler.GetMangledMethodName(TargetMethod));
if (Thunk != null)
{
sb.Append("__");
Thunk.AppendMangledName(nameMangler, sb);
}
}
public override bool Equals(object obj)
{
var other = obj as DelegateCreationInfo;
return other != null
&& Constructor == other.Constructor
&& TargetMethod == other.TargetMethod
&& _targetKind == other._targetKind
&& Thunk == other.Thunk;
}
public override int GetHashCode()
{
return Constructor.GetHashCode() ^ TargetMethod.GetHashCode();
}
#if !SUPPORT_JIT
internal int CompareTo(DelegateCreationInfo other, TypeSystemComparer comparer)
{
var compare = _targetKind - other._targetKind;
if (compare != 0)
return compare;
compare = comparer.Compare(TargetMethod, other.TargetMethod);
if (compare != 0)
return compare;
compare = comparer.Compare(Constructor.Method, other.Constructor.Method);
if (compare != 0)
return compare;
if (Thunk == other.Thunk)
return 0;
if (Thunk == null)
return -1;
if (other.Thunk == null)
return 1;
return comparer.Compare(Thunk.Method, other.Thunk.Method);
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
using System.Threading.Tasks;
using TelemData = System.Collections.Generic.KeyValuePair<string, object>;
namespace System.Diagnostics.Tracing.Telemetry.Tests
{
/// <summary>
/// Tests for TelemetrySource and TelemetryListener
/// </summary>
public class TelemetryTest
{
/// <summary>
/// Trivial example of passing an integer
/// </summary>
[Fact]
public void IntPayload()
{
var result = new List<KeyValuePair<string, object>>();
var observer = new ObserverToList<TelemData>(result);
using (TelemetryListener.DefaultListener.Subscribe(new ObserverToList<TelemData>(result)))
{
TelemetrySource.DefaultSource.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
Assert.Equal("IntPayload", result[0].Key);
Assert.Equal(5, result[0].Value);
} // unsubscribe
// Make sure that after unsubscribing, we don't get more events.
TelemetrySource.DefaultSource.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
}
/// <summary>
/// slightly less trivial of passing a structure with a couple of fields
/// </summary>
[Fact]
public void StructPayload()
{
var result = new List<KeyValuePair<string, object>>();
using (TelemetryListener.DefaultListener.Subscribe(new ObserverToList<TelemData>(result)))
{
TelemetrySource.DefaultSource.WriteTelemetry("StructPayload", new Payload() { Name = "Hi", Id = 67 });
Assert.Equal(1, result.Count);
Assert.Equal("StructPayload", result[0].Key);
var payload = (Payload)result[0].Value;
Assert.Equal(67, payload.Id);
Assert.Equal("Hi", payload.Name);
}
TelemetrySource.DefaultSource.WriteTelemetry("StructPayload", new Payload() { Name = "Hi", Id = 67 });
Assert.Equal(1, result.Count);
}
/// <summary>
/// Tests the IObserver OnCompleted callback.
/// </summary>
[Fact]
public void Completed()
{
var result = new List<KeyValuePair<string, object>>();
var observer = new ObserverToList<TelemData>(result);
var listener = new TelemetryListener("MyListener");
var subscription = listener.Subscribe(observer);
listener.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
Assert.Equal("IntPayload", result[0].Key);
Assert.Equal(5, result[0].Value);
Assert.False(observer.Completed);
// The listener dies
listener.Dispose();
Assert.True(observer.Completed);
// confirm that we can unsubscribe without crashing
subscription.Dispose();
// If we resubscribe after dispose, but it does not do anything.
subscription = listener.Subscribe(observer);
listener.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
}
/// <summary>
/// Simple tests for the IsEnabled method.
/// </summary>
[Fact]
public void BasicIsEnabled()
{
var result = new List<KeyValuePair<string, object>>();
bool seenUninteresting = false;
bool seenStructPayload = false;
Predicate<string> predicate = delegate (string telemetryName)
{
if (telemetryName == "Uninteresting")
seenUninteresting = true;
if (telemetryName == "StructPayload")
seenStructPayload = true;
return telemetryName == "StructPayload";
};
using (TelemetryListener.DefaultListener.Subscribe(new ObserverToList<TelemData>(result), predicate))
{
Assert.False(TelemetrySource.DefaultSource.IsEnabled("Uninteresting"));
Assert.True(TelemetrySource.DefaultSource.IsEnabled("StructPayload"));
Assert.True(seenUninteresting);
Assert.True(seenStructPayload);
}
}
/// <summary>
/// Test if it works when you have two subscribers active simultaneously
/// </summary>
[Fact]
public void MultiSubscriber()
{
var subscriber1Result = new List<KeyValuePair<string, object>>();
Predicate<string> subscriber1Predicate = telemetryName => (telemetryName == "DataForSubscriber1");
var subscriber1Oberserver = new ObserverToList<TelemData>(subscriber1Result);
var subscriber2Result = new List<KeyValuePair<string, object>>();
Predicate<string> subscriber2Predicate = telemetryName => (telemetryName == "DataForSubscriber2");
var subscriber2Oberserver = new ObserverToList<TelemData>(subscriber2Result);
// Get two subscribers going.
using (var subscription1 = TelemetryListener.DefaultListener.Subscribe(subscriber1Oberserver, subscriber1Predicate))
{
using (var subscription2 = TelemetryListener.DefaultListener.Subscribe(subscriber2Oberserver, subscriber2Predicate))
{
// Things that neither subscribe to get filtered out.
if (TelemetryListener.DefaultListener.IsEnabled("DataToFilterOut"))
TelemetryListener.DefaultListener.WriteTelemetry("DataToFilterOut", -1);
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// If a Source does not use the IsEnabled, then every subscriber gets it.
subscriber1Result.Clear();
subscriber2Result.Clear();
TelemetryListener.DefaultListener.WriteTelemetry("UnfilteredData", 3);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("UnfilteredData", subscriber1Result[0].Key);
Assert.Equal(3, (int)subscriber1Result[0].Value);
Assert.Equal(1, subscriber2Result.Count);
Assert.Equal("UnfilteredData", subscriber2Result[0].Key);
Assert.Equal(3, (int)subscriber2Result[0].Value);
/****************************************************/
// Filters not filter out everything, they are just a performance optimization.
// Here you actually get more than you want even though you use a filter
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber1"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber1", 1);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key);
Assert.Equal(1, (int)subscriber1Result[0].Value);
// Subscriber 2 happens to get it
Assert.Equal(1, subscriber2Result.Count);
Assert.Equal("DataForSubscriber1", subscriber2Result[0].Key);
Assert.Equal(1, (int)subscriber2Result[0].Value);
/****************************************************/
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber2"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber2", 2);
// Subscriber 1 happens to get it
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("DataForSubscriber2", subscriber1Result[0].Key);
Assert.Equal(2, (int)subscriber1Result[0].Value);
Assert.Equal(1, subscriber2Result.Count);
Assert.Equal("DataForSubscriber2", subscriber2Result[0].Key);
Assert.Equal(2, (int)subscriber2Result[0].Value);
} // subscriber2 drops out
/*********************************************************************/
/* Only Subscriber 1 is left */
/*********************************************************************/
// Things that neither subscribe to get filtered out.
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataToFilterOut"))
TelemetryListener.DefaultListener.WriteTelemetry("DataToFilterOut", -1);
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// If a Source does not use the IsEnabled, then every subscriber gets it.
subscriber1Result.Clear();
TelemetryListener.DefaultListener.WriteTelemetry("UnfilteredData", 3);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("UnfilteredData", subscriber1Result[0].Key);
Assert.Equal(3, (int)subscriber1Result[0].Value);
// Subscriber 2 has dropped out.
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// Filters not filter out everything, they are just a performance optimization.
// Here you actually get more than you want even though you use a filter
subscriber1Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber1"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber1", 1);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key);
Assert.Equal(1, (int)subscriber1Result[0].Value);
// Subscriber 2 has dropped out.
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
subscriber1Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber2"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber2", 2);
// Subscriber 1 filters
Assert.Equal(0, subscriber1Result.Count);
// Subscriber 2 has dropped out
Assert.Equal(0, subscriber2Result.Count);
} // subscriber1 drops out
/*********************************************************************/
/* No Subscribers are left */
/*********************************************************************/
// Things that neither subscribe to get filtered out.
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataToFilterOut"))
TelemetryListener.DefaultListener.WriteTelemetry("DataToFilterOut", -1);
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// If a Source does not use the IsEnabled, then every subscriber gets it.
TelemetryListener.DefaultListener.WriteTelemetry("UnfilteredData", 3);
// No one subscribing
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// Filters not filter out everything, they are just a performance optimization.
// Here you actually get more than you want even though you use a filter
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber1"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber1", 1);
// No one subscribing
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber2"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber2", 2);
// No one subscribing
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
}
/// <summary>
/// Stresses the Subscription routine by having many threads subscribe and
/// unsubscribe concurrently
/// </summary>
[Fact]
public void MultiSubscriberStress()
{
var random = new Random();
// Beat on the default listener by subscribing and unsubscribing on many threads simultaneously.
var factory = new TaskFactory();
// To the whole stress test 10 times. This keeps the task array size needed down while still
// having lots of concurrency.
for (int j = 0; j < 20; j++)
{
// Spawn off lots of concurrent activity
var tasks = new Task[1000];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = factory.StartNew(delegate (object taskData)
{
int taskNum = (int)taskData;
var taskName = "Task" + taskNum;
var result = new List<KeyValuePair<string, object>>();
Predicate<string> predicate = (name) => name == taskName;
Predicate<KeyValuePair<string, object>> filter = (keyValue) => keyValue.Key == taskName;
// set up the observer to only see events set with the task name as the telemetry nname.
var observer = new ObserverToList<TelemData>(result, filter, taskName);
using (TelemetryListener.DefaultListener.Subscribe(observer, predicate))
{
TelemetrySource.DefaultSource.WriteTelemetry(taskName, taskNum);
Assert.Equal(1, result.Count);
Assert.Equal(taskName, result[0].Key);
Assert.Equal(taskNum, result[0].Value);
// Spin a bit randomly. This mixes of the lifetimes of the subscriptions and makes it
// more stressful
var cnt = random.Next(10, 100) * 1000;
while (0 < --cnt)
GC.KeepAlive("");
} // Unsubscribe
// Send the telemetry again, to see if it now does NOT come through (count remains unchanged).
TelemetrySource.DefaultSource.WriteTelemetry(taskName, -1);
Assert.Equal(1, result.Count);
}, i);
}
Task.WaitAll(tasks);
}
}
/// <summary>
/// Tests if as we create new TelemetryListerns, we get callbacks for them
/// </summary>
[Fact]
public void AllListenersAddRemove()
{
// This callback will return the listener that happens on the callback
TelemetryListener returnedListener = null;
Action<TelemetryListener> onNewListener = delegate (TelemetryListener listener)
{
Assert.Null(returnedListener);
Assert.NotNull(listener);
returnedListener = listener;
};
// Subscribe, which delivers catch-up event for the Default listener
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.Equal(TelemetryListener.DefaultListener, returnedListener);
returnedListener = null;
} // Now we unsubscribe
// Create an dispose a listener, but we won't get a callback for it.
using (new TelemetryListener("TestListen"))
{ }
Assert.Null(returnedListener); // No callback was made
// Resubscribe
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.Equal(TelemetryListener.DefaultListener, returnedListener);
returnedListener = null;
// add two new subscribers
using (var listener1 = new TelemetryListener("TestListen1"))
{
Assert.Equal(listener1.Name, "TestListen1");
Assert.Equal(listener1, returnedListener);
returnedListener = null;
using (var listener2 = new TelemetryListener("TestListen2"))
{
Assert.Equal(listener2.Name, "TestListen2");
Assert.Equal(listener2, returnedListener);
returnedListener = null;
} // Dispose of listener2
} // Dispose of listener1
} // Unsubscribe
// Check that we are back to just the DefaultListener.
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.Equal(TelemetryListener.DefaultListener, returnedListener);
returnedListener = null;
} // cleanup
}
/// <summary>
/// Tests that the 'catchupList' of active listeners is accurate even as we
/// add and remove TelemetryListeners randomly.
/// </summary>
[Fact]
public void AllListenersCheckCatchupList()
{
var expected = new List<TelemetryListener>();
var list = GetActiveNonDefaultListeners();
Assert.Equal(list, expected);
for (int i = 0; i < 50; i++)
{
expected.Insert(0, (new TelemetryListener("TestListener" + i)));
list = GetActiveNonDefaultListeners();
Assert.Equal(list, expected);
}
// Remove the element randomly.
var random = new Random(0);
while (0 < expected.Count)
{
var toRemoveIdx = random.Next(0, expected.Count - 1); // Always leave the Default listener.
var toRemoveListener = expected[toRemoveIdx];
toRemoveListener.Dispose(); // Kill it (which removes it from the list)
expected.RemoveAt(toRemoveIdx);
list = GetActiveNonDefaultListeners();
Assert.Equal(list.Count, expected.Count);
Assert.Equal(list, expected);
}
}
/// <summary>
/// Stresses the AllListeners by having many threads be added and removed.
/// </summary>
[Fact]
public void AllSubscriberStress()
{
var list = GetActiveNonDefaultListeners();
Assert.Equal(0, list.Count);
var factory = new TaskFactory();
// To the whole stress test 10 times. This keeps the task array size needed down while still
// having lots of concurrency.
for (int k = 0; k < 10; k++)
{
var tasks = new Task[1]; // TODO FIX NOW should be 100 reduced to avoid failures while we investigate the race.
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = (factory.StartNew(delegate ()
{
// Create a set of TelemetryListeners (which add themselves to the AllListeners list.
var listeners = new List<TelemetryListener>();
for (int j = 0; j < 100; j++)
listeners.Insert(0, (new TelemetryListener("Task " + i + " TestListener" + j)));
// They are all in the list
list = GetActiveNonDefaultListeners();
foreach (var listener in listeners)
Assert.Contains(listener, list);
// Dispose them all
foreach (var listener in listeners)
listener.Dispose();
// And now they are not in the list.
list = GetActiveNonDefaultListeners();
foreach (var listener in listeners)
Assert.DoesNotContain(listener, list);
}));
}
// Wait for all the tasks to finish.
Task.WaitAll(tasks);
}
// There should be no listeners left.
list = GetActiveNonDefaultListeners();
Assert.Equal(0, list.Count);
}
[Fact]
public void DoubleDisposeOfListener()
{
var listener = new TelemetryListener("MyListener");
int completionCount = 0;
IDisposable subscription = listener.Subscribe(MakeObserver<KeyValuePair<string, object>>(_ => { }, () => completionCount++));
listener.Dispose();
listener.Dispose();
subscription.Dispose();
subscription.Dispose();
Assert.Equal(1, completionCount);
}
[Fact]
public void ListenerToString()
{
string name = Guid.NewGuid().ToString();
using (var listener = new TelemetryListener(name))
{
Assert.Equal(name, listener.ToString());
}
}
[Fact]
public void DisposeAllListenerSubscriptionInSameOrderSubscribed()
{
int count1 = 0, count2 = 0, count3 = 0;
IDisposable sub1 = TelemetryListener.AllListeners.Subscribe(MakeObserver<TelemetryListener>(onCompleted: () => count1++));
IDisposable sub2 = TelemetryListener.AllListeners.Subscribe(MakeObserver<TelemetryListener>(onCompleted: () => count2++));
IDisposable sub3 = TelemetryListener.AllListeners.Subscribe(MakeObserver<TelemetryListener>(onCompleted: () => count3++));
Assert.Equal(0, count1);
Assert.Equal(0, count2);
Assert.Equal(0, count3);
sub1.Dispose();
Assert.Equal(1, count1);
Assert.Equal(0, count2);
Assert.Equal(0, count3);
sub1.Dispose(); // dispose again just to make sure nothing bad happens
sub2.Dispose();
Assert.Equal(1, count1);
Assert.Equal(1, count2);
Assert.Equal(0, count3);
sub2.Dispose();
sub3.Dispose();
Assert.Equal(1, count1);
Assert.Equal(1, count2);
Assert.Equal(1, count3);
sub3.Dispose();
}
#region Helpers
/// <summary>
/// Returns the list of active telemetry listeners.
/// </summary>
/// <returns></returns>
private static List<TelemetryListener> GetActiveNonDefaultListeners()
{
var ret = new List<TelemetryListener>();
var seenDefault = false;
Action<TelemetryListener> onNewListener = delegate (TelemetryListener listener)
{
if (listener == TelemetryListener.DefaultListener)
{
Assert.False(seenDefault);
seenDefault = true;
}
else
ret.Add(listener);
};
// Subscribe, which gives you the list
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.True(seenDefault);
} // Unsubscribe to remove side effects.
return ret;
}
/// <summary>
/// Used to make an observer out of a action delegate.
/// </summary>
private static IObserver<T> MakeObserver<T>(
Action<T> onNext = null, Action onCompleted = null)
{
return new Observer<T>(onNext, onCompleted);
}
/// <summary>
/// Used in the implementation of MakeObserver.
/// </summary>
/// <typeparam name="T"></typeparam>
private class Observer<T> : IObserver<T>
{
public Observer(Action<T> onNext, Action onCompleted)
{
_onNext = onNext ?? new Action<T>(_ => { });
_onCompleted = onCompleted ?? new Action(() => { });
}
public void OnCompleted() { _onCompleted(); }
public void OnError(Exception error) { }
public void OnNext(T value) { _onNext(value); }
private Action<T> _onNext;
private Action _onCompleted;
}
#endregion
}
// Takes an IObserver and returns a List<T> that are the elements observed.
// Will assert on error and 'Completed' is set if the 'OnCompleted' callback
// is issued.
internal class ObserverToList<T> : IObserver<T>
{
public ObserverToList(List<T> output, Predicate<T> filter = null, string name = null)
{
_output = output;
_output.Clear();
_filter = filter;
_name = name;
}
public bool Completed { get; private set; }
#region private
public void OnCompleted()
{
Completed = true;
}
public void OnError(Exception error)
{
Assert.True(false, "Error happened on IObserver");
}
public void OnNext(T value)
{
Assert.False(Completed);
if (_filter == null || _filter(value))
_output.Add(value);
}
private List<T> _output;
private Predicate<T> _filter;
private string _name; // for debugging
#endregion
}
/// <summary>
/// Trivial class used for payloads. (Usually anonymous types are used.
/// </summary>
internal class Payload
{
public string Name { get; set; }
public int Id { get; set; }
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace SpyUO
{
public delegate void PacketHandler( byte[] data, bool send );
public delegate void ProcessTerminatedHandler();
public class PacketSpy : IDisposable
{
private abstract class PacketSpyStarter
{
public static void Start( PacketSpy packetSpy, string path )
{
PacketSpyStarter starter = new PathStarter( packetSpy, path );
Start( starter );
}
public static void Start( PacketSpy packetSpy, Process process )
{
PacketSpyStarter starter = new ProcessStarter( packetSpy, process );
Start( starter );
}
private static void Start( PacketSpyStarter starter )
{
Thread thread = new Thread( new ThreadStart( starter.Start ) );
thread.Start();
}
private PacketSpy m_PacketSpy;
public PacketSpy PacketSpy { get { return m_PacketSpy; } }
public PacketSpyStarter( PacketSpy packetSpy )
{
m_PacketSpy = packetSpy;
}
public abstract void Start();
private class PathStarter : PacketSpyStarter
{
string m_Path;
public PathStarter( PacketSpy packetSpy, string path ) : base( packetSpy )
{
m_Path = path;
}
public override void Start()
{
PacketSpy.Init( m_Path );
PacketSpy.MainLoop();
}
}
private class ProcessStarter : PacketSpyStarter
{
private Process m_Process;
public ProcessStarter( PacketSpy packetSpy, Process process ) : base( packetSpy )
{
m_Process = process;
}
public override void Start()
{
PacketSpy.Init( m_Process );
PacketSpy.MainLoop();
}
}
}
private Process m_Process;
private IntPtr m_hProcess;
private bool m_Enhanced;
private AddressAndRegisters m_Send;
private byte m_OrSCode;
private AddressAndRegisters m_Recv;
private byte m_OrRCode;
private PacketHandler m_PacketHandler;
private NativeMethods.CONTEXT m_ContextBuffer;
private NativeMethods.WOW64_CONTEXT m_X64ContextBuffer;
private NativeMethods.DEBUG_EVENT_EXCEPTION m_DEventBuffer;
private bool m_ToStop;
private ManualResetEvent m_Stopped;
private bool SafeToStop
{
get { lock ( this ) return m_ToStop; }
set { lock ( this ) m_ToStop = value; }
}
private bool ProcessTerminated { get { return m_Process.HasExited; } }
public event ProcessTerminatedHandler OnProcessTerminated;
public PacketSpy( bool enhanced, AddressAndRegisters send, AddressAndRegisters recv, PacketHandler packetHandler )
{
m_Enhanced = enhanced;
m_Send = send;
m_Recv = recv;
m_PacketHandler = packetHandler;
m_ContextBuffer = new NativeMethods.CONTEXT();
m_ContextBuffer.ContextFlags = NativeMethods.ContextFlags.CONTEXT_CONTROL | NativeMethods.ContextFlags.CONTEXT_INTEGER;
m_X64ContextBuffer = new NativeMethods.WOW64_CONTEXT();
m_X64ContextBuffer.ContextFlags = NativeMethods.ContextFlags.CONTEXT_CONTROL | NativeMethods.ContextFlags.CONTEXT_INTEGER;
m_DEventBuffer = new NativeMethods.DEBUG_EVENT_EXCEPTION();
m_ToStop = false;
m_Stopped = new ManualResetEvent( true );
}
public void Spy( string path )
{
PacketSpyStarter.Start( this, path );
}
public void Spy( Process process )
{
PacketSpyStarter.Start( this, process );
}
private void Init( string path )
{
string pathDir = Path.GetDirectoryName( path );
NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO();
NativeMethods.PROCESS_INFORMATION processInfo;
if ( !NativeMethods.CreateProcess( path, null, IntPtr.Zero, IntPtr.Zero, false,
NativeMethods.CreationFlag.DEBUG_PROCESS, IntPtr.Zero, pathDir, ref startupInfo, out processInfo ) )
throw new Win32Exception();
NativeMethods.CloseHandle( processInfo.hThread );
m_Process = Process.GetProcessById( (int)processInfo.dwProcessId );
m_hProcess = processInfo.hProcess;
InitBreakpoints();
}
private void Init( Process process )
{
uint id = (uint)process.Id;
m_Process = process;
m_hProcess = NativeMethods.OpenProcess( NativeMethods.DesiredAccessProcess.PROCESS_ALL_ACCESS, false, id );
if ( m_hProcess == IntPtr.Zero )
throw new Win32Exception();
if ( !NativeMethods.DebugActiveProcess( id ) )
throw new Win32Exception();
InitBreakpoints();
}
private void InitBreakpoints()
{
m_OrSCode = AddBreakpoint( m_Send.Address );
m_OrRCode = AddBreakpoint( m_Recv.Address );
}
private static readonly byte[] BreakCode = { 0xCC };
private byte AddBreakpoint( uint address )
{
byte[] orOpCode = ReadProcessMemory( address, 1 );
WriteProcessMemory( address, BreakCode );
return orOpCode[0];
}
private void RemoveBreakpoints()
{
WriteProcessMemory( m_Send.Address, new byte[] { m_OrSCode } );
WriteProcessMemory( m_Recv.Address, new byte[] { m_OrRCode } );
}
private void MainLoop()
{
m_Stopped.Reset();
try
{
while ( !SafeToStop && !ProcessTerminated )
{
if ( NativeMethods.WaitForDebugEvent( ref m_DEventBuffer, 1000 ) )
{
if ( m_DEventBuffer.dwDebugEventCode == NativeMethods.DebugEventCode.EXCEPTION_DEBUG_EVENT )
{
uint address = (uint)m_DEventBuffer.u.Exception.ExceptionRecord.ExceptionAddress.ToInt32();
if ( address == m_Send.Address )
{
SpySendPacket( m_DEventBuffer.dwThreadId );
continue;
}
else if ( address == m_Recv.Address )
{
SpyRecvPacket( m_DEventBuffer.dwThreadId );
continue;
}
}
ContinueDebugEvent( m_DEventBuffer.dwThreadId );
}
}
}
finally
{
EndSpy();
if ( ProcessTerminated && OnProcessTerminated != null )
OnProcessTerminated();
}
}
private void SpySendPacket( uint threadId )
{
SpyPacket( threadId, true );
}
private void SpyRecvPacket( uint threadId )
{
SpyPacket( threadId, false );
}
private void SpyPacket( uint threadId, bool send )
{
IntPtr hThread = NativeMethods.OpenThread( NativeMethods.DesiredAccessThread.THREAD_GET_CONTEXT | NativeMethods.DesiredAccessThread.THREAD_SET_CONTEXT | NativeMethods.DesiredAccessThread.THREAD_QUERY_INFORMATION, false, threadId );
GetThreadContext( hThread );
AddressAndRegisters ar = send ? m_Send : m_Recv;
uint dataAddress = GetContextRegister( ar.AddressRegister );
uint dataLength = GetContextRegister( ar.LengthRegister ) & 0xFFFF;
byte[] data = null;
if ( m_Enhanced )
{
data = ReadProcessMemory( dataAddress + 4, 8 );
using ( MemoryStream stream = new MemoryStream( data ) )
{
using ( BinaryReader reader = new BinaryReader( stream ) )
{
uint start = reader.ReadUInt32();
uint length = reader.ReadUInt32() - start;
data = ReadProcessMemory( start, length );
}
}
}
else
data = ReadProcessMemory( dataAddress, dataLength );
#region Breakpoint Recovery
WriteProcessMemory( ar.Address, new byte[] { send ? m_OrSCode : m_OrRCode } );
if ( SystemInfo.IsX64 )
{
m_X64ContextBuffer.Eip--;
m_X64ContextBuffer.EFlags |= 0x100; // Single step
}
else
{
m_ContextBuffer.Eip--;
m_ContextBuffer.EFlags |= 0x100; // Single step
}
SetThreadContext( hThread );
ContinueDebugEvent( threadId );
if ( !NativeMethods.WaitForDebugEvent( ref m_DEventBuffer, 2500 ) )
throw new Win32Exception();
WriteProcessMemory( ar.Address, BreakCode );
GetThreadContext( hThread );
if ( SystemInfo.IsX64 )
m_X64ContextBuffer.EFlags &= ~0x100u; // End single step
else
m_ContextBuffer.EFlags &= ~0x100u; // End single step
SetThreadContext( hThread );
#endregion
NativeMethods.CloseHandle( hThread );
ContinueDebugEvent( threadId );
if ( data != null )
m_PacketHandler( data, send );
}
private byte[] ReadProcessMemory( uint address, uint length )
{
byte[] buffer = new byte[length];
IntPtr ptrAddr = new IntPtr( address );
uint read;
NativeMethods.ReadProcessMemory( m_hProcess, ptrAddr, buffer, length, out read );
if ( read != length )
throw new Win32Exception();
return buffer;
}
private void WriteProcessMemory( uint address, byte[] data )
{
uint length = (uint)data.Length;
IntPtr ptrAddr = new IntPtr( address );
uint written;
NativeMethods.WriteProcessMemory( m_hProcess, ptrAddr, data, length, out written );
if ( written != length )
throw new Win32Exception();
NativeMethods.FlushInstructionCache( m_hProcess, ptrAddr, length );
}
private void ContinueDebugEvent( uint threadId )
{
if ( !NativeMethods.ContinueDebugEvent( (uint)m_Process.Id, threadId, NativeMethods.ContinueStatus.DBG_CONTINUE ) )
throw new Win32Exception();
}
private void GetThreadContext( IntPtr hThread )
{
if ( SystemInfo.IsX64 )
{
if ( !NativeMethods.Wow64GetThreadContext( hThread, ref m_X64ContextBuffer ) )
throw new Win32Exception();
}
else
{
if ( !NativeMethods.GetThreadContext( hThread, ref m_ContextBuffer ) )
throw new Win32Exception();
}
}
private void SetThreadContext( IntPtr hThread )
{
if ( SystemInfo.IsX64 )
{
if ( !NativeMethods.Wow64SetThreadContext( hThread, ref m_X64ContextBuffer ) )
throw new Win32Exception();
}
else
{
if ( !NativeMethods.SetThreadContext( hThread, ref m_ContextBuffer ) )
throw new Win32Exception();
}
}
private uint GetContextRegister( Register register )
{
if ( SystemInfo.IsX64 )
{
switch ( register )
{
case Register.Eax: return m_X64ContextBuffer.Eax;
case Register.Ebp: return m_X64ContextBuffer.Ebp;
case Register.Ebx: return m_X64ContextBuffer.Ebx;
case Register.Ecx: return m_X64ContextBuffer.Ecx;
case Register.Edi: return m_X64ContextBuffer.Edi;
case Register.Edx: return m_X64ContextBuffer.Edx;
case Register.Esi: return m_X64ContextBuffer.Esi;
case Register.Esp: return m_X64ContextBuffer.Esp;
default: throw new ArgumentException();
}
}
else
{
switch ( register )
{
case Register.Eax: return m_ContextBuffer.Eax;
case Register.Ebp: return m_ContextBuffer.Ebp;
case Register.Ebx: return m_ContextBuffer.Ebx;
case Register.Ecx: return m_ContextBuffer.Ecx;
case Register.Edi: return m_ContextBuffer.Edi;
case Register.Edx: return m_ContextBuffer.Edx;
case Register.Esi: return m_ContextBuffer.Esi;
case Register.Esp: return m_ContextBuffer.Esp;
default: throw new ArgumentException();
}
}
}
public void Dispose()
{
if ( !SafeToStop )
{
SafeToStop = true;
m_Stopped.WaitOne();
m_Stopped.Close();
}
}
private void EndSpy()
{
try
{
RemoveBreakpoints();
NativeMethods.DebugActiveProcessStop( (uint)m_Process.Id );
NativeMethods.CloseHandle( m_hProcess );
}
catch { }
m_Stopped.Set();
}
}
}
| |
#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
#region Namespace Declarations
using System;
using Axiom.Core;
using Axiom.ParticleSystems;
using Axiom.Scripting;
#endregion
namespace Axiom.ParticleFX
{
/// <summary>
/// Summary description for ColorFaderAffector.
/// </summary>
public class ColorInterpolatorAffector : ParticleAffector {
protected const int MAX_STAGES = 6;
internal ColorEx[] colorAdj = new ColorEx[MAX_STAGES];
internal float[] timeAdj = new float[MAX_STAGES];
public ColorInterpolatorAffector() {
this.type = "ColourInterpolator";
for( int i = 0; i < MAX_STAGES; ++i ) {
colorAdj[i] = new ColorEx(0.5f, 0.5f, 0.5f, 0.0f);
timeAdj[i] = 1.0f;
}
}
public override void AffectParticles(ParticleSystem system, float timeElapsed) {
// loop through the particles
for(int i = 0; i < system.Particles.Count; i++) {
Particle p = (Particle)system.Particles[i];
float lifeTime = p.totalTimeToLive;
float particleTime = 1.0f - (p.timeToLive / lifeTime);
if (particleTime <= timeAdj[0]) {
p.Color = colorAdj[0];
}
else if (particleTime >= timeAdj[MAX_STAGES - 1]) {
p.Color = colorAdj[MAX_STAGES-1];
}
else {
for (int k = 0; k < MAX_STAGES - 1; k++) {
if (particleTime >= timeAdj[k] && particleTime < timeAdj[k + 1]) {
particleTime -= timeAdj[k];
particleTime /= (timeAdj[k+1] - timeAdj[k]);
p.Color.r = ((colorAdj[k+1].r * particleTime) + (colorAdj[k].r * (1.0f - particleTime)));
p.Color.g = ((colorAdj[k+1].g * particleTime) + (colorAdj[k].g * (1.0f - particleTime)));
p.Color.b = ((colorAdj[k+1].b * particleTime) + (colorAdj[k].b * (1.0f - particleTime)));
p.Color.a = ((colorAdj[k+1].a * particleTime) + (colorAdj[k].a * (1.0f - particleTime)));
break;
}
}
}
}
}
#region Command definition classes
[Command("colour0", "Initial 'keyframe' color.", typeof(ParticleAffector))]
class Color0Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.colorAdj[0]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.colorAdj[0] = StringConverter.ParseColor(val);
}
#endregion
}
[Command("colour1", "1st 'keyframe' color.", typeof(ParticleAffector))]
class Color1Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
// TODO: Common way for writing color.
return StringConverter.ToString(affector.colorAdj[1]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.colorAdj[1] = StringConverter.ParseColor(val);
}
#endregion
}
[Command("colour2", "2nd 'keyframe' color.", typeof(ParticleAffector))]
class Color2Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
// TODO: Common way for writing color.
return StringConverter.ToString(affector.colorAdj[2]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.colorAdj[2] = StringConverter.ParseColor(val);
}
#endregion
}
[Command("colour3", "3rd 'keyframe' color.", typeof(ParticleAffector))]
class Color3Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.colorAdj[3]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.colorAdj[3] = StringConverter.ParseColor(val);
}
#endregion
}
[Command("colour4", "4th 'keyframe' color.", typeof(ParticleAffector))]
class Color4Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.colorAdj[4]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.colorAdj[4] = StringConverter.ParseColor(val);
}
#endregion
}
[Command("colour5", "5th 'keyframe' color.", typeof(ParticleAffector))]
class Color5Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.colorAdj[5]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.colorAdj[5] = StringConverter.ParseColor(val);
}
#endregion
}
[Command("time0", "Initial 'keyframe' time.", typeof(ParticleAffector))]
class Time0Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.timeAdj[0]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.timeAdj[0] = StringConverter.ParseFloat(val);
}
#endregion
}
[Command("time1", "1st 'keyframe' time.", typeof(ParticleAffector))]
class Time1Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.timeAdj[1]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.timeAdj[1] = StringConverter.ParseFloat(val);
}
#endregion
}
[Command("time2", "2nd 'keyframe' time.", typeof(ParticleAffector))]
class Time2Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.timeAdj[2]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.timeAdj[2] = StringConverter.ParseFloat(val);
}
#endregion
}
[Command("time3", "3rd 'keyframe' time.", typeof(ParticleAffector))]
class Time3Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.timeAdj[3]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.timeAdj[3] = StringConverter.ParseFloat(val);
}
#endregion
}
[Command("time4", "4th 'keyframe' time.", typeof(ParticleAffector))]
class Time4Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.timeAdj[4]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.timeAdj[4] = StringConverter.ParseFloat(val);
}
#endregion
}
[Command("time5", "5th 'keyframe' time.", typeof(ParticleAffector))]
class Time5Command : ICommand {
#region ICommand Members
public string Get(object target) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
return StringConverter.ToString(affector.timeAdj[5]);
}
public void Set(object target, string val) {
ColorInterpolatorAffector affector = target as ColorInterpolatorAffector;
affector.timeAdj[5] = StringConverter.ParseFloat(val);
}
#endregion
}
#endregion Command definition classes
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuildConstruction = Microsoft.Build.Construction;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudioTools.Project {
[ComVisible(true)]
internal abstract class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject {
internal const string Debug = "Debug";
internal const string AnyCPU = "AnyCPU";
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private IVsProjectFlavorCfg flavoredCfg;
private List<OutputGroup> outputGroups;
private BuildableProjectConfig buildableCfg;
private string platformName;
#region properties
internal ProjectNode ProjectMgr {
get {
return this.project;
}
}
public string ConfigName {
get {
return this.configName;
}
set {
this.configName = value;
}
}
public string PlatformName {
get {
return platformName;
}
set {
platformName = value;
}
}
internal IList<OutputGroup> OutputGroups {
get {
if (null == this.outputGroups) {
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// If the project is not buildable (no CoreCompile target)
// then don't bother getting the output groups.
if (this.project.BuildProject != null && this.project.BuildProject.Targets.ContainsKey("CoreCompile")) {
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if (groupNames != null) {
// Populate the output array
foreach (KeyValuePair<string, string> group in groupNames) {
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
internal ProjectConfig(ProjectNode project, string configuration) {
this.project = project;
if (configuration.Contains("|")) { // If configuration is in the form "<Configuration>|<Platform>"
string[] configStrArray = configuration.Split('|');
if (2 == configStrArray.Length) {
this.configName = configStrArray[0];
this.platformName = configStrArray[1];
}
else {
throw new Exception(string.Format(CultureInfo.InvariantCulture, "Invalid configuration format: {0}", configuration));
}
}
else { // If configuration is in the form "<Configuration>"
this.configName = configuration;
}
var flavoredCfgProvider = ProjectMgr.GetOuterInterface<IVsProjectFlavorCfgProvider>();
Utilities.ArgumentNotNull("flavoredCfgProvider", flavoredCfgProvider);
ErrorHandler.ThrowOnFailure(flavoredCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
Utilities.ArgumentNotNull("flavoredCfg", flavoredCfg);
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if (null != persistXML) {
this.project.LoadXmlFragment(persistXML, configName, platformName);
}
}
#endregion
#region methods
internal virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group) {
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean) {
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache) {
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue) {
if (!this.project.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition) {
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0) {
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups) {
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase)) {
newGroup = group;
break;
}
}
if (newGroup == null) {
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0) {
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType) {
int isDirty = 0;
if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) {
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment) {
fragment = null;
int hr = VSConstants.S_OK;
if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) {
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages) {
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages) {
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name) {
if (!string.IsNullOrEmpty(PlatformName)) {
name = ConfigName + "|" + PlatformName;
} else {
name = DisplayName;
}
return VSConstants.S_OK;
}
private string DisplayName {
get {
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if (!string.IsNullOrEmpty(platform[0])) {
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug) {
fDebug = 0;
if (this.configName == "Debug") {
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease) {
fRelease = 0;
if (this.configName == "Release") {
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo) {
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb) {
if (project.BuildProject == null || !project.BuildProject.Targets.ContainsKey("CoreCompile")) {
// The project is not buildable, so don't return a config. This
// will hide the 'Build' commands from the VS UI.
pb = null;
return VSConstants.E_NOTIMPL;
}
if (buildableCfg == null) {
buildableCfg = new BuildableProjectConfig(this);
}
pb = buildableCfg;
return VSConstants.S_OK;
}
public virtual int get_CanonicalName(out string name) {
name = configName;
return VSConstants.S_OK;
}
public virtual int get_IsPackaged(out int pkgd) {
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f) {
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform) {
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p) {
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if (cfgProvider != null) {
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root) {
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target) {
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li) {
Utilities.ArgumentNotNull("li", li);
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output) {
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup) {
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach (OutputGroup group in OutputGroups) {
string groupName;
group.get_CanonicalName(out groupName);
if (String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0) {
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot) {
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) {
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate) {
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual) {
// Are they only asking for the number of groups?
if (celt == 0) {
if ((null == pcActual) || (0 == pcActual.Length)) {
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if ((null == rgpcfg) || (rgpcfg.Length == 0)) {
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach (OutputGroup group in OutputGroups) {
if (rgpcfg.Length > count && celt > count && group != null) {
rgpcfg[count] = group;
++count;
}
}
if (pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot) {
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public abstract int DebugLaunch(uint grfLaunch);
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch) {
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if (fCanLaunch == 0) {
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg) {
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) {
Utilities.CheckNotNull(this.project);
Utilities.CheckNotNull(this.project.NodeProperties);
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
private MSBuildExecution.ProjectInstance GetCurrentConfig(bool resetCache = false) {
if (resetCache || currentConfig == null) {
// Get properties for current configuration from project file and cache it
project.SetConfiguration(ConfigName);
project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
currentConfig = project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
return currentConfig;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache) {
var current = GetCurrentConfig(resetCache);
if (current == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return current.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages) {
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
Utilities.ArgumentNotNull("pages", pages);
if (pages.Length == 0) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = project.GetOuterInterface<IVsHierarchy>();
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if (guids == null || guids.Length == 0) {
pages[0] = new CAUUID();
pages[0].cElems = 0;
} else {
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
internal virtual bool IsInputGroup(string groupName) {
return groupName == "SourceFiles";
}
private static DateTime? TryGetLastWriteTimeUtc(string path, Redirector output = null) {
try {
return File.GetLastWriteTimeUtc(path);
} catch (UnauthorizedAccessException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
} catch (ArgumentException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
} catch (PathTooLongException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
} catch (NotSupportedException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
}
return null;
}
internal virtual bool IsUpToDate() {
var outputWindow = OutputWindowRedirector.GetGeneral(ProjectMgr.Site);
#if DEBUG
outputWindow.WriteLine(string.Format("Checking whether {0} needs to be rebuilt:", ProjectMgr.Caption));
#endif
var latestInput = DateTime.MinValue;
var earliestOutput = DateTime.MaxValue;
bool mustRebuild = false;
var allInputs = new HashSet<string>(OutputGroups
.Where(g => IsInputGroup(g.Name))
.SelectMany(x => x.EnumerateOutputs())
.Select(input => input.CanonicalName),
StringComparer.OrdinalIgnoreCase
);
foreach (var group in OutputGroups.Where(g => !IsInputGroup(g.Name))) {
foreach (var output in group.EnumerateOutputs()) {
var path = output.CanonicalName;
#if DEBUG
var dt = TryGetLastWriteTimeUtc(path);
outputWindow.WriteLine(string.Format(
" Out: {0}: {1} [{2}]",
group.Name,
path,
dt.HasValue ? dt.Value.ToString("s") : "err"
));
#endif
DateTime? modifiedTime;
if (!File.Exists(path) ||
!(modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow)).HasValue) {
mustRebuild = true;
break;
}
string inputPath;
if (File.Exists(inputPath = output.GetMetadata("SourceFile"))) {
var inputModifiedTime = TryGetLastWriteTimeUtc(inputPath, outputWindow);
if (inputModifiedTime.HasValue && inputModifiedTime.Value > modifiedTime.Value) {
mustRebuild = true;
break;
} else {
continue;
}
}
// output is an input, ignore it...
if (allInputs.Contains(path)) {
continue;
}
if (modifiedTime.Value < earliestOutput) {
earliestOutput = modifiedTime.Value;
}
}
if (mustRebuild) {
// Early exit if we know we're going to have to rebuild
break;
}
}
if (mustRebuild) {
#if DEBUG
outputWindow.WriteLine(string.Format(
"Rebuilding {0} because mustRebuild is true",
ProjectMgr.Caption
));
#endif
return false;
}
foreach (var group in OutputGroups.Where(g => IsInputGroup(g.Name))) {
foreach (var input in group.EnumerateOutputs()) {
var path = input.CanonicalName;
#if DEBUG
var dt = TryGetLastWriteTimeUtc(path);
outputWindow.WriteLine(string.Format(
" In: {0}: {1} [{2}]",
group.Name,
path,
dt.HasValue ? dt.Value.ToString("s") : "err"
));
#endif
if (!File.Exists(path)) {
continue;
}
var modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow);
if (modifiedTime.HasValue && modifiedTime.Value > latestInput) {
latestInput = modifiedTime.Value;
if (earliestOutput < latestInput) {
break;
}
}
}
if (earliestOutput < latestInput) {
// Early exit if we know we're going to have to rebuild
break;
}
}
if (earliestOutput < latestInput) {
#if DEBUG
outputWindow.WriteLine(string.Format(
"Rebuilding {0} because {1:s} < {2:s}",
ProjectMgr.Caption,
earliestOutput,
latestInput
));
#endif
return false;
} else {
#if DEBUG
outputWindow.WriteLine(string.Format(
"Not rebuilding {0} because {1:s} >= {2:s}",
ProjectMgr.Caption,
earliestOutput,
latestInput
));
#endif
return true;
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close() {
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) {
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID) {
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
} else if (iidCfg == typeof(IVsBuildableProjectCfg).GUID) {
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
//
//In some cases we've intentionally shutdown the build options
// If buildableConfig is null then don't try to get the BuildableProjectCfg interface
//
if (null != buildableConfig) {
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
}
// If not supported
if (ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
[ComVisible(true)]
internal class BuildableProjectConfig : IVsBuildableProjectCfg {
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config) {
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie) {
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p) {
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done) {
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options) {
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options) {
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options) {
return config.IsUpToDate() ?
VSConstants.S_OK :
VSConstants.E_FAIL;
}
public virtual int Stop(int fsync) {
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie) {
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty) {
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin() {
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks) {
try {
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0) {
return false;
}
} catch (Exception e) {
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(SR.GetString(SR.BuildEventError, e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget) {
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks) {
try {
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
} catch (Exception e) {
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(SR.GetString(SR.BuildEventError, e.Message));
} finally {
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful)) {
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target) {
if (!this.NotifyBuildBegin()) {
return;
}
try {
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
} catch (Exception e) {
if (e.IsCriticalException()) {
throw;
}
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
} finally {
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences() {
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
if (referenceContainer != null) {
foreach (ReferenceNode referenceNode in referenceContainer.EnumReferences()) {
referenceNode.RefreshReference();
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class SingleSingleOrDefaultTests
{
public static IEnumerable<object[]> SingleSpecificData(int[] counts)
{
foreach (int count in counts.DefaultIfEmpty(Sources.OuterLoopCount))
{
foreach (int position in new[] { 0, count / 2, Math.Max(0, count - 1) }.Distinct())
{
yield return new object[] { count, position };
}
}
}
//
// Single and SingleOrDefault
//
[Theory]
[InlineData(1)]
[InlineData("string")]
[InlineData((object)null)]
public static void Single<T>(T element)
{
Assert.Equal(element, ParallelEnumerable.Repeat(element, 1).Single());
Assert.Equal(element, ParallelEnumerable.Repeat(element, 1).Single(x => true));
}
[Theory]
[InlineData(1, 0)]
[InlineData("string", 0)]
[InlineData((object)null, 0)]
[InlineData(1, 1)]
[InlineData("string", 1)]
[InlineData((object)null, 1)]
public static void SingleOrDefault<T>(T element, int count)
{
Assert.Equal(count >= 1 ? element : default(T), ParallelEnumerable.Repeat(element, count).SingleOrDefault());
Assert.Equal(count >= 1 ? element : default(T), ParallelEnumerable.Repeat(element, count).SingleOrDefault(x => true));
}
[Fact]
public static void Single_Empty()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Single());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Single(x => true));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Single_NoMatch(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, count).Single(x => !seen.Add(x)));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Single_NoMatch_Longrunning()
{
Single_NoMatch(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void SingleOrDefault_NoMatch(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(default(int), ParallelEnumerable.Range(0, count).SingleOrDefault(x => !seen.Add(x)));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void SingleOrDefault_NoMatch_Longrunning()
{
SingleOrDefault_NoMatch(Sources.OuterLoopCount);
}
[Theory]
[InlineData(2)]
[InlineData(16)]
public static void Single_AllMatch(int count)
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, count).Single(x => true));
}
[Fact]
[OuterLoop]
public static void Single_AllMatch_Longrunning()
{
Single_AllMatch(Sources.OuterLoopCount);
}
[Theory]
[InlineData(2)]
[InlineData(16)]
public static void SingleOrDefault_AllMatch(int count)
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, count).SingleOrDefault(x => true));
}
[Fact]
[OuterLoop]
public static void SingleOrDefault_AllMatch_Longrunning()
{
SingleOrDefault_AllMatch(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(SingleSpecificData), new[] { 1, 2, 16 })]
public static void Single_OneMatch(int count, int element)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(element, ParallelEnumerable.Range(0, count).Single(x => seen.Add(x) && x == element));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleSpecificData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Single_OneMatch_Longrunning(int count, int element)
{
Single_OneMatch(count, element);
}
[Theory]
[MemberData(nameof(SingleSpecificData), new[] { 0, 1, 2, 16 })]
public static void SingleOrDefault_OneMatch(int count, int element)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(element, ParallelEnumerable.Range(0, count).SingleOrDefault(x => seen.Add(x) && x == element));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(SingleSpecificData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SingleOrDefault_OneMatch_Longrunning(int count, int element)
{
SingleOrDefault_OneMatch(count, element);
}
[Fact]
public static void Single_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.Single(x => { canceler(); return false; }));
}
[Fact]
public static void SingleOrDefault_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; }));
}
[Fact]
public static void Single_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.Single(x => { canceler(); return false; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Single(x => { canceler(); return false; }));
}
[Fact]
public static void SingleOrDefault_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; }));
}
[Fact]
public static void Single_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.Single());
AssertThrows.AlreadyCanceled(source => source.Single(x => true));
}
[Fact]
public static void SingleOrDefault_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.SingleOrDefault());
AssertThrows.AlreadyCanceled(source => source.SingleOrDefault(x => true));
}
[Fact]
public static void Single_AggregateException()
{
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Single(x => { throw new DeliberateTestException(); }));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).SingleOrDefault(x => { throw new DeliberateTestException(); }));
}
[Fact]
public static void Single_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Single());
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SingleOrDefault());
Assert.Throws<ArgumentNullException>("predicate", () => ParallelEnumerable.Empty<int>().Single(null));
Assert.Throws<ArgumentNullException>("predicate", () => ParallelEnumerable.Empty<int>().SingleOrDefault(null));
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Text;
using Assets.Scripts;
public class MainBehaviour : MonoBehaviour
{
// Read only
public static readonly int maxNoiseStrength = 30;
public readonly float fastAnimationSpeed = 3;
public readonly float normalAnimationSpeed = 1;
public readonly float slowAnimationSpeed = 0.333F;
// Fields
public int round = 1;
public int score = 0;
private Vector2 scrollVector1 = Vector2.zero;
private Vector2 scrollVector2 = Vector2.zero;
public bool quickConfirm = true;
bool affirmNextRound;
public bool insideControl;
public PlayerBehaviour watchingPlayer;
public WatchSelectedBehaviour guiObjectCam1;
public WatchSelectedBehaviour guiObjectCam2;
public AudioClip menuButton;
private Selectable _clickedObject;
public bool doubleClick;
public bool blockSelection;
public List<PlayerBehaviour> players;
public int currentPlayerIndex;
public List<Group> teams = new List<Group>();
public Group winnerTeam;
public List<HexTileBehaviour> hexTileTypes;
public bool gameOver;
private Order activeOrder;
public bool isAnimating;
public DateTime animationStart;
public TimeSpan animationDuration;
public TimeSpan normalDuration;
public Action animationFinalAction;
public GameObject animationTargetGO;
//public Vector3 animationStartLocation;
//public Vector3 animationEndLocation;
public AnimationInstruction[] animationInstructions;
public int activeAnimationInstructionIndex;
public bool delayedMonsterSpawning;
public float activeAnimationSpeed;
public GUISkin customSkin;
float animProgress = 0;
bool oldEscPressed = false;
bool oldReturnPressed = false;
private GUIStyle passiveRunningStyleOn;
public GUIStyle PassiveRunningStyleOn {
get {
if (passiveRunningStyleOn == null)
{
passiveRunningStyleOn = new GUIStyle(customSkin.button);
passiveRunningStyleOn.normal.textColor = Color.red;
}
return passiveRunningStyleOn;
}
set {
passiveRunningStyleOn = value;
}
}
private GUIStyle passiveRunningStyleOff;
public GUIStyle PassiveRunningStyleOff {
get {
if (passiveRunningStyleOff == null)
{
passiveRunningStyleOff = new GUIStyle(customSkin.button);
}
return passiveRunningStyleOff;
}
set {
passiveRunningStyleOff = value;
}
}
// Properties
public Selectable clickedSelectable
{
get { return _clickedObject; }
set
{
if (_clickedObject == value)
{
doubleClick = true;
}
else
{
_clickedObject = value;
}
}
}
public Selectable _selectedGOSBH;
public Selectable selectedGOSBH
{
get { return _selectedGOSBH; }
set
{
if (_selectedGOSBH != null)
{
// _selectedGOSBH.deSelectMarker();
deSelectUnit(_selectedGOSBH);
}
_selectedGOSBH = value;
if (_selectedGOSBH != null)
{
//_selectedGOSBH.selectMarker();
selectUnit(_selectedGOSBH);
}
}
}
public Selectable _orderTarget;
public Selectable orderTarget
{
get { return _orderTarget; }
set
{
if (_orderTarget != null)
{
//_orderTarget.deSelectMarker();
deSelectUnit(_orderTarget);
}
_orderTarget = value;
if (_orderTarget != null)
{
//_orderTarget.selectMarker();
selectUnit(_orderTarget);
}
}
}
public bool touchOptions;
public Rect rightUnitTileInfoRect;
public bool toggleTest;
public string someText = "start";
public Vector2 scrollTest = Vector2.zero;
public Rect topScoreRect;
public Rect bottomScrollRect;
//Vector2 scrollVector = Vector2.zero;
float scrollFloat;
//GameObject model1;
//GameObject model2;
public int marginDistance;
public void ScaleToScreen()
{
marginDistance = 10;
//y position is last
topScoreRect = new Rect (5,0, Screen.width - 10, Screen.height / 7);
rightUnitTileInfoRect = new Rect (Screen.width - Screen.width / 5, 0, Screen.width / 5 - 5, 0);
bottomScrollRect = new Rect( 0, 0 , Screen.width ,Screen.height/6 );
// if (!touchOptions) {
// marginDistance /=2;
// topScoreRect.height /= 2;
// bottomScrollRect.height /= 2;
// }
//rightUnitTileInfoRect.y = topScoreRect.height ;
rightUnitTileInfoRect.y = 0 ;
rightUnitTileInfoRect.height = Screen.height - topScoreRect.height - bottomScrollRect.height ;
bottomScrollRect.y = rightUnitTileInfoRect.height + topScoreRect.height ;
}
private void aiActions()
{
// Final actions before the ai finishes
if (delayedMonsterSpawning && animationFinalAction == null)
{
delayedMonsterSpawning = false;
foreach (Selectable inTileSBH in players[currentPlayerIndex].land) {
HexTileBehaviour inTileHTB = inTileSBH.GetComponent<HexTileBehaviour>();
if (inTileHTB.hexTileDefintion == HextTileDefinitions.factory) {
if (players[currentPlayerIndex].graphene >= players[currentPlayerIndex].unitType.resourcePrice) {
createUnit(players[currentPlayerIndex],inTileHTB);
players[currentPlayerIndex].graphene -= players[currentPlayerIndex].unitType.resourcePrice;
}
else {
break;
}
}
}
foreach (Selectable inUnitSBH in players[currentPlayerIndex].units) {
inUnitSBH.GetComponent<AiUnitBehaviour>().unableToActCount = 0;
}
nextPlayer();
return;
}
//ai actions depending on available orders;
if (sortedEnemyList != null && sortedEnemyList.Count() > 0)
{
Selectable aiUnitToActSB = sortedEnemyList.LastOrDefault();
sortedEnemyList.Remove(aiUnitToActSB);
if (
(!aiUnitToActSB.availableOrders.SameFlags(OrderLevel.B | OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F))
)
{
singleMonsterCapture(aiUnitToActSB);
}
// check if the current ai can act.
if ((aiUnitToActSB.availableOrders & OrderLevel.B) != OrderLevel.B)
{
singleMonsterMoving(aiUnitToActSB);
}
if (!aiUnitToActSB.availableOrders.SameFlags(OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F))
{
singleMonsterAttacking(aiUnitToActSB);
}
if (
!aiUnitToActSB.availableOrders.SameFlags(OrderLevel.B)
||
!aiUnitToActSB.availableOrders.SameFlags(OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F)
)
{
AiUnitBehaviour aiUnitToActAUB = aiUnitToActSB.GetComponent<AiUnitBehaviour>();
aiUnitToActAUB.unableToActCount +=1;
if (aiUnitToActAUB.unableToActCount < aiUnitToActAUB.unableToActCountMax) {
sortedEnemyList.Insert(0,aiUnitToActSB);
}
}
}
if (sortedEnemyList.Count <= 0)
{
delayedMonsterSpawning = true;
}
}
public static void setTeam(Selectable selectableToSwitchSB, PlayerBehaviour newTeam)
{
selectableToSwitchSB.team = newTeam;
Transform modelChild = selectableToSwitchSB.transform.FindChild ("Model");
modelChild.renderer.material.color = newTeam.teamColor;
Renderer[] childTransormRendererCollection = modelChild.GetComponentsInChildren<Renderer>(true);
foreach (Renderer inChildRenderer in childTransormRendererCollection) {
inChildRenderer.material.color = newTeam.teamColor;
}
}
private void animateTarget( GameObject targetGO)
{
if (activeAnimationInstructionIndex < animationInstructions.Count()) {
//Check what kind of animation the instruction is.
if ((animationInstructions[activeAnimationInstructionIndex].instructionDef & InstructionDef.Position) == InstructionDef.Position) {
targetGO.transform.position = Vector3.Lerp (animationInstructions[activeAnimationInstructionIndex].startPosition, animationInstructions[activeAnimationInstructionIndex].endPosition, animProgress);
}
if ((animationInstructions[activeAnimationInstructionIndex].instructionDef & InstructionDef.Rotation) == InstructionDef.Rotation) {
targetGO.transform.FindChild("Model").transform.eulerAngles = Vector3.Lerp (animationInstructions[activeAnimationInstructionIndex].startRotation, animationInstructions[activeAnimationInstructionIndex].endRotation, animProgress);
}
if ((animationInstructions[activeAnimationInstructionIndex].instructionDef & InstructionDef.Scaling) == InstructionDef.Scaling) {
targetGO.transform.localScale = Vector3.Lerp (animationInstructions[activeAnimationInstructionIndex].startScale, animationInstructions[activeAnimationInstructionIndex].endScale, animProgress);
}
if (animProgress > 1) {
animProgress = 0;
activeAnimationInstructionIndex += 1;
}
}
if (activeAnimationInstructionIndex < animationInstructions.Count()) {
normalDuration = animationInstructions[activeAnimationInstructionIndex].duration;
animationDuration = TimeSpan.FromMilliseconds(normalDuration.TotalMilliseconds * (1/ activeAnimationSpeed));
animationStart = DateTime.Now;
}
else {
isAnimating = false;
}
}
public void initiateAnimation(Action animationFinal, GameObject targetGO, AnimationInstruction[] instructions)
{
isAnimating = true;
animationFinalAction = animationFinal;
activeAnimationInstructionIndex = 0;
animationInstructions = instructions;
normalDuration = animationInstructions[activeAnimationInstructionIndex].duration;
animationDuration = TimeSpan.FromMilliseconds(normalDuration.TotalMilliseconds * (1/ activeAnimationSpeed));
animationStart = DateTime.Now;
animationTargetGO = targetGO;
}
// Use this for initialization
public void StartByCall()
{
Time.timeScale = 1;
Camera.main.enabled = true;
activeAnimationSpeed = normalAnimationSpeed;
//Add Players to teams
Group men = new Group ("Men");
men.players.Add (GameObject.Find ("Human").GetComponent<PlayerBehaviour> ());
teams.Add( men);
// Group zero = new Group ("Zero");
// zero.players.Add (GameObject.Find ("Neutral").GetComponent<PlayerBehaviour> ());
// teams.Add( zero);
Group malice = new Group ("Malice");
malice.players.Add (GameObject.Find ("Ai").GetComponent<PlayerBehaviour> ());
teams.Add( malice);
//preparing gui
touchOptions = (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.WP8Player || Application.platform == RuntimePlatform.MetroPlayerX86 || Application.platform == RuntimePlatform.MetroPlayerX64 || Application.platform == RuntimePlatform.MetroPlayerARM);
ScaleToScreen ();
nextPlayerSetup ();
roundSetup ();
}
void LateUpdate()
{
//Tab through available units
if (Input.GetButtonDown("TabThroughUnits")) {
selectedGOSBH = lookForAvailableUnits();
}
//Showing pause menu
bool newEscPressed = Input.GetKey (KeyCode.Escape);
bool newReturnPressed = Input.GetKey (KeyCode.Return);
if(newEscPressed && !oldEscPressed){
if(Time.timeScale == 0){
Time.timeScale = 1;
}
else {
Time.timeScale = 0;
}
}
// start next round by keypress
if ((players [currentPlayerIndex].name == "Human")) {
if (newReturnPressed && !oldReturnPressed) {
//nextPlayer ();
affirmNextRound = true;
audio.PlayOneShot (menuButton, 0.3F);
}
}
oldReturnPressed = newReturnPressed;
oldEscPressed = newEscPressed;
//TODO: Needs wayyyy more testing, and code calling improvements
Touch touchRes = Input.touches.FirstOrDefault (t => t.phase == TouchPhase.Moved);
if (IsTouchInsideList (touchRes.position, bottomScrollRect)) {
scrollFloat = Mathf.Clamp(scrollFloat - touchRes.deltaPosition.x *3 ,0,Screen.width);
insideControl = true;
} else {
insideControl = false;
//Testing
}
}
// Update is called once per frame
void Update()
{
//sets the nextround logic bool for ongui
//affirmNextRound = setAffirmNextRoundInUpdate;
if (Time.timeScale == 0) {
return;
}
if (isAnimating)
{
animProgress += (float)(1 / animationDuration.TotalSeconds) * Time.deltaTime;
animateTarget(animationTargetGO);
//isAnimating = (animationStart + animationDuration > DateTime.Now);
if (!isAnimating)
{
selectUnit(selectedGOSBH);
animationFinalAction();
animationFinalAction = null;
animProgress = 0;
activeAnimationInstructionIndex = 0;
}
return;
}
//Check if a group has lost
var losingTeam = from lTeam in this.teams
where lTeam.players.All (p => p.lost)
select lTeam;
//TODO: may unnecessarily hit perfomance
if (losingTeam != null && losingTeam.Count() > 0) {
foreach (var inLosingTeam in losingTeam) {
inLosingTeam.teamLost = true;
}
}
if (teams.Count(lastP => !lastP.teamLost) <= 1) {
winnerTeam = teams.First(lastP => !lastP.teamLost);
gameOver = true;
return;
}
// check if current player lost.
if (players[currentPlayerIndex].lost) {
nextPlayer();
return;
}
// Ai code
if (players[currentPlayerIndex].name == "Ai")
{
aiActions();
}
if (activeOrder != null)
{
switch (activeOrder.Targeting)
{
case TargetType.Global:
case TargetType.Self:
if (activeOrder.ValidTarget(selectedGOSBH, selectedGOSBH))
{
orderTarget = selectedGOSBH;
}
break;
// case TargetType.Target:
// case TargetType.TargetFriendly:
// //The player selected the target
// if (activeOrder.ValidTarget(selectedUnit, clickedObject.gameObject))
// {
// orderTarget = clickedSelectable;
// }
// break;
default:
break;
}
}
if (clickedSelectable != null) {
Selectable clickedSelectableUpdateLocked = clickedSelectable;
if (selectedGOSBH != null && selectedGOSBH.GetComponent<UnitBehaviour>() != null && selectedGOSBH.team == players [currentPlayerIndex]) {
UnitBehaviour selectedGOUB = selectedGOSBH.GetComponent<UnitBehaviour>();
//begin with action targeting.
if (activeOrder != null) {
switch (activeOrder.Targeting) {
case TargetType.Target:
case TargetType.TargetFriendly:
//The player selected the target
if (activeOrder.ValidTarget (selectedGOSBH, clickedSelectableUpdateLocked)) {
orderTarget = clickedSelectableUpdateLocked;
}
else {
activeOrder = null;
selectedGOSBH = clickedSelectableUpdateLocked;
}
break;
case TargetType.Self:
case TargetType.Global:
break;
default:
throw new Exception ();
}
}
if (selectedGOSBH.GetComponent<UnitBehaviour> () != null) {
//the unit default actions like move and attack;
if (doubleClick && orderTarget == clickedSelectableUpdateLocked) {
activeOrder.ActiveAction (selectedGOSBH, orderTarget);
audio.PlayOneShot(menuButton,0.3F);
resetSelection ();
} else {
if (activeOrder == null) {
HexTileBehaviour clickedSelectableHTB = clickedSelectableUpdateLocked.GetComponent<HexTileBehaviour> ();
if (clickedSelectableHTB != null) {
activeOrder = selectedGOSBH.orderCollection.FirstOrDefault ((Order su) => su.Title == "Move");
if (!activeOrder.Usable (selectedGOSBH, clickedSelectableUpdateLocked) || !activeOrder.ValidTarget (selectedGOSBH, clickedSelectable))
{
activeOrder = null;
orderTarget = null;
clickedSelectable = null;
selectedGOSBH = clickedSelectableUpdateLocked;
}
}
UnitBehaviour clickedSelectableUB = clickedSelectableUpdateLocked.GetComponent<UnitBehaviour> ();
if (clickedSelectableUB != null) {
activeOrder = selectedGOSBH.orderCollection.FirstOrDefault ((Order su) => su.Title == "Attack");
if (!activeOrder.Usable (selectedGOSBH, clickedSelectableUpdateLocked) || !activeOrder.ValidTarget (selectedGOSBH, clickedSelectableUpdateLocked))
{
activeOrder = null;
orderTarget = null;
clickedSelectable = null;
selectedGOSBH = clickedSelectableUpdateLocked;
}
}
}
}
}
} else {
selectedGOSBH = clickedSelectableUpdateLocked;
clickedSelectable = null;
}
//to fast switch between the unit and tile
if (selectedGOSBH != null) {
UnitBehaviour selUBH = selectedGOSBH.GetComponent<UnitBehaviour>();
if (selUBH != null && selUBH.hexPosition.GetComponent<Selectable>() == clickedSelectableUpdateLocked )
{
selectedGOSBH = clickedSelectableUpdateLocked;
}
}
}
if (Input.GetMouseButtonDown(1))
{
resetSelection();
}
// //TODO: Needs wayyyy more testing.
// Touch touchRes = Input.touches.FirstOrDefault (t => t.phase == TouchPhase.Moved);
//
// if (IsTouchInsideList (touchRes.position, bottomScrollRect)) {
// scrollFloat -= touchRes.deltaPosition.x;
// wasDragging = true;
// } else {
// wasDragging = false;
// //Testing
// GameObject.Find ("WorldCam").GetComponent<WorldCamera>().
// }
}
bool IsTouchInsideList(Vector2 touchPos, Rect targetBounds)
{
Vector2 screenPos = new Vector2(touchPos.x, Screen.height - touchPos.y); // invert y coordinate
return targetBounds.Contains(screenPos);
}
public static int damageCalculation(UnitBehaviour attackerUnit, UnitBehaviour targetUnit)
{
return targetUnit.energy - (attackerUnit.currentAttackStrength) / (int)targetUnit.hexPosition.cover;
}
private void nextPlayer()
{
foreach (Selectable inUnit in players[currentPlayerIndex].units)
{
//inUnit.GetComponent<UnitBehaviour>().hexPosition.noise = inUnit.currentLoudness;
inUnit.availableOrders = OrderLevel.None;
}
currentPlayerIndex += 1;
if (currentPlayerIndex == players.Count)
{
newRound();
currentPlayerIndex = 0;
}
nextPlayerSetup ();
if (players[currentPlayerIndex].name == "Ai")
{
aiMoves(players[currentPlayerIndex]);
}
}
private void nextPlayerSetup()
{
foreach (Selectable inUnit in players[currentPlayerIndex].units)
{
//Iterating through each units passives
foreach (Order inOrder in inUnit.orderCollection)
{
//reset loudness from earlier round
inUnit.currentLoudness = inUnit.baseLoudness;
inOrder.PassiveAction(inUnit);
}
}
foreach (Selectable inLand in players[currentPlayerIndex].land)
{
//Iterating through each units passives
foreach (Order inOrder in inLand.orderCollection)
{
inOrder.PassiveAction(inLand);
}
}
}
private void roundSetup()
{
foreach (var inHextileEntry in GameFieldBehaviour.hexTiles)
{
if (inHextileEntry.Value != null)
{
HexTileBehaviour tileHTB = ((HexTileBehaviour)inHextileEntry.Value);
Selectable resetSelectable = tileHTB.gameObject.GetComponent<Selectable>();
resetSelectable.GetComponent<HexTileBehaviour>().noise = resetSelectable.currentLoudness;
if (tileHTB.containedUnit != null)
{
resetSelectable.GetComponent<HexTileBehaviour>().noise += tileHTB.containedUnit.currentLoudness;
}
// Collecting Silicon
if (tileHTB.hexTileDefintion == HextTileDefinitions.mine) {
resetSelectable.team.graphene +=tileHTB.GetComponent<MineBehaviour >().amountPerRound;
}
}
}
}
//TODO: Clean up
Selectable noisiestSB;
List<Selectable> sortedEnemyList;
private void aiMoves(PlayerBehaviour theAiGo)
{
noisiestSB = GetTheNoisiestTile().GetComponent<Selectable>();
sortedEnemyList = new List<Selectable>(players[currentPlayerIndex].units.OrderByDescending((Selectable sel) =>
{
return GameFieldBehaviour.NavigationBuddy.hexDistance(sel.positionQ, sel.positionR, noisiestSB.positionQ, noisiestSB.positionR);
}));
}
private bool enemyNeighbourExists(int[][] neighbours, Selectable source)
{
//try
{
HexKey key;
foreach (var inNeighbour in neighbours)
{
key = new HexKey(inNeighbour[0], inNeighbour[1]);
if (
GameFieldBehaviour.GetMapCost(key) >= 0 &&
GameFieldBehaviour.hexTiles[key] != null
)
{
HexTileBehaviour targetTile = GameFieldBehaviour.hexTiles[key] as HexTileBehaviour;
if (targetTile.GetComponent<HexTileBehaviour>().containedUnit != null &&
targetTile.GetComponent<HexTileBehaviour>().containedUnit.GetComponent<Selectable>().team != source.team)
{
return true;
}
}
}
return false;
}
// catch (Exception ex)
// {
// Debug.LogWarning(ex);
// throw;
// }
}
private HexTileBehaviour GetTheNoisiestTile()
{
HexTileBehaviour loudestHB = null;
//foreach (DictionaryEntry inHextileEntry in GameFieldBehaviour.hexTiles)
foreach (var inHextileEntry in GameFieldBehaviour.hexTiles)
{
if (loudestHB == null)
{
loudestHB = ((HexTileBehaviour)inHextileEntry.Value);
}
else if (((HexTileBehaviour)inHextileEntry.Value) != null && ((HexTileBehaviour)inHextileEntry.Value).noise > loudestHB.noise)
{
loudestHB = ((HexTileBehaviour)inHextileEntry.Value);
}
}
return loudestHB;
}
//TODO: Write even better code to walk around other units.
private void moveMonsters(PlayerBehaviour theAiGo)
{
bool hasMovableUnits;
Selectable movingMonsterSB = null;
while (true)
{
hasMovableUnits = false;
foreach (Selectable inMonsterSB in theAiGo.GetComponent<PlayerBehaviour>().units)
{
//Checking if the monster moved already, which has an orderLevel of B
if (!((inMonsterSB.availableOrders & OrderLevel.B) == OrderLevel.B))
{
hasMovableUnits = true;
movingMonsterSB = inMonsterSB;
break;
}
}
if (!hasMovableUnits)
{
break;
}
//check if neighbours with enemy units.
if (enemyNeighbourExists(GameFieldBehaviour.NavigationBuddy.getNeighbours(movingMonsterSB.positionQ, movingMonsterSB.positionR), movingMonsterSB))
{
movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
continue;
}
//else
UnitBehaviour startUnitBehaviour = movingMonsterSB.GetComponent<UnitBehaviour>();
//TODO: insert noisiest check in here and assign as targets.
Selectable GoalTargetTile = null;
foreach (Selectable inNeighbours in movingMonsterSB.Neighbours)
{
if (GoalTargetTile == null)
{
GoalTargetTile = inNeighbours;
}
else if (inNeighbours != null && inNeighbours.GetComponent<HexTileBehaviour>().noise > GoalTargetTile.GetComponent<HexTileBehaviour>().noise)
{
GoalTargetTile = inNeighbours;
}
}
if (GoalTargetTile == null)
{
movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
continue;
}
if (GoalTargetTile.GetComponent<HexTileBehaviour>().noise < movingMonsterSB.GetComponent<UnitBehaviour>().hexPosition.noise || GoalTargetTile.GetComponent<HexTileBehaviour>().noise < 0.01)
{
GoalTargetTile = GetTheNoisiestTile().GetComponent<Selectable>();
}
var res = NavigationHelper.FindPath<Selectable>(startUnitBehaviour.hexPosition.GetComponent<Selectable>(), GoalTargetTile, 1,
(Selectable su, Selectable gu) =>
{
return GameFieldBehaviour.NavigationBuddy.hexDistance(su.positionQ, su.positionR, gu.positionQ, gu.positionR);
}
, (Selectable u) =>
{
return GameFieldBehaviour.NavigationBuddy.hexDistance(u.positionQ, u.positionR, GoalTargetTile.positionQ, GoalTargetTile.positionR);
});
if (res == null)
{
movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
continue;
}
var test = res.ToArray();
//begin Navigation
HexKey key = new HexKey(test[test.Length - 2].positionQ, test[test.Length - 2].positionR);
HexTileBehaviour tile = (HexTileBehaviour)GameFieldBehaviour.hexTiles[key];
movingMonsterSB.orderCollection.First((order) => order.Title == "Move").ActiveAction(movingMonsterSB, tile.GetComponent<Selectable>());
movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
}
}
private void singleMonsterCapture(Selectable capturingMonsterSB)
{
HexTileBehaviour aiHexHTB = capturingMonsterSB.GetComponent<UnitBehaviour>().hexPosition;
if (aiHexHTB.hexTileDefintion != HextTileDefinitions.classic &&aiHexHTB.GetComponent<Selectable>().team != capturingMonsterSB.team )
{
capturingMonsterSB.orderCollection.First((order) => order.Title == "Capture").ActiveAction(capturingMonsterSB, capturingMonsterSB);
//capturingMonsterSB.availableOrders = capturingMonsterSB.availableOrders | OrderLevel.B | OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F;
}
}
private void singleMonsterAttacking(Selectable attackingMonsterSB)
{
HexKey key;
foreach (var inNeighbour in GameFieldBehaviour.NavigationBuddy.getNeighbours(attackingMonsterSB.positionQ, attackingMonsterSB.positionR))
{
key = new HexKey(inNeighbour[0], inNeighbour[1]);
if (GameFieldBehaviour.GetMapCost(key) < 0 || GameFieldBehaviour.hexTiles[key] == null)
{
continue;
}
Selectable possibleTarget = (GameFieldBehaviour.hexTiles[key] as HexTileBehaviour).containedUnit;
if (possibleTarget != null)
{
Selectable possibleTargetSB = possibleTarget.GetComponent<Selectable>();
if (possibleTargetSB.team != attackingMonsterSB.team) {
attackingMonsterSB.orderCollection.First((order) => order.Title == "Attack").ActiveAction(attackingMonsterSB, possibleTargetSB);
break;
}
}
}
//attackingMonsterSB.availableOrders = attackingMonsterSB.availableOrders | OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F;
}
private void singleMonsterMoving(Selectable movingMonsterSB)
{
if (enemyNeighbourExists(GameFieldBehaviour.NavigationBuddy.getNeighbours(movingMonsterSB.positionQ, movingMonsterSB.positionR), movingMonsterSB))
{
//movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
return;
}
UnitBehaviour startUnitBehaviour = movingMonsterSB.GetComponent<UnitBehaviour>();
//TODO: insert noisiest check in here and assign as targets.
Selectable GoalTargetTile = null;
foreach (Selectable inNeighbours in movingMonsterSB.Neighbours)
{
if (GoalTargetTile == null)
{
GoalTargetTile = inNeighbours;
}
else if (inNeighbours != null && inNeighbours.GetComponent<HexTileBehaviour>().noise > GoalTargetTile.GetComponent<HexTileBehaviour>().noise)
{
GoalTargetTile = inNeighbours;
}
}
if (GoalTargetTile == null)
{
//movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
return;
}
if (GoalTargetTile.GetComponent<HexTileBehaviour>().noise < 0.01)
{
GoalTargetTile = GetTheNoisiestTile().GetComponent<Selectable>();
}
var res = NavigationHelper.FindPath<Selectable>(startUnitBehaviour.hexPosition.GetComponent<Selectable>(), GoalTargetTile, 1,
(Selectable su, Selectable gu) =>
{
return GameFieldBehaviour.NavigationBuddy.hexDistance(su.positionQ, su.positionR, gu.positionQ, gu.positionR);
}
, (Selectable u) =>
{
return GameFieldBehaviour.NavigationBuddy.hexDistance(u.positionQ, u.positionR, GoalTargetTile.positionQ, GoalTargetTile.positionR);
});
if (res == null)
{
// movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
return;
}
var test = res.ToArray();
//begin Navigation
HexKey key = new HexKey(test[test.Length - 2].positionQ, test[test.Length - 2].positionR);
HexTileBehaviour tile = (HexTileBehaviour)GameFieldBehaviour.hexTiles[key];
Selectable tileSB = tile.GetComponent<Selectable>();
movingMonsterSB.orderCollection.First((order) => order.Title == "Move").ActiveAction(movingMonsterSB, tileSB);
//movingMonsterSB.availableOrders = movingMonsterSB.availableOrders | OrderLevel.B;
}
public static List<double[]> MakeNoise(Selectable epicenter, int strength)
{
List<double[]> hexagonCollection = new List<double[]>();
int noiseRange = strength; //* 1/ 10;
for (int idx = -noiseRange; idx <= noiseRange; idx += 1)
{
for (int idy = Math.Max(-noiseRange, -idx - noiseRange); idy <= Math.Min(noiseRange, -idx + noiseRange); idy += 1)
{
double dz = idx - idy;
hexagonCollection.Add(new double[] { epicenter.positionQ + Convert.ToInt32(idx), epicenter.positionR + Convert.ToInt32(idy),
noiseRange - (Math.Abs(0 - idx) + Math.Abs(0 - idy) + Math.Abs(0 + 0 - idx - idy)) / 2});
}
}
return hexagonCollection;
}
private void monstersAttack(PlayerBehaviour theAiGo)
{
bool hasActableUnits;
Selectable actingMonsterSB = null;
while (true)
{
hasActableUnits = false;
foreach (Selectable inMonsterSB in theAiGo.GetComponent<PlayerBehaviour>().units)
{
if (!(inMonsterSB.availableOrders.SameFlags(OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F)))
{
hasActableUnits = true;
actingMonsterSB = inMonsterSB;
break;
}
}
if (!hasActableUnits)
{
break;
}
HexKey key;
foreach (var inNeighbour in GameFieldBehaviour.NavigationBuddy.getNeighbours(actingMonsterSB.positionQ, actingMonsterSB.positionR))
{
key = new HexKey(inNeighbour[0], inNeighbour[1]);
if (GameFieldBehaviour.GetMapCost(key) < 0 || GameFieldBehaviour.hexTiles[key] == null)
{
continue;
}
Selectable possibleTarget = (GameFieldBehaviour.hexTiles[key] as HexTileBehaviour).containedUnit;
if (possibleTarget != null)
{
Selectable possibleTargetSB = possibleTarget.GetComponent<Selectable>();
if (possibleTarget.GetComponent<Selectable>().team != actingMonsterSB.team) {
actingMonsterSB.orderCollection.First((order) => order.Title == "Attack").ActiveAction(actingMonsterSB, possibleTargetSB);
actingMonsterSB.availableOrders = actingMonsterSB.availableOrders | OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F;
break;
}
}
}
actingMonsterSB.availableOrders = actingMonsterSB.availableOrders | OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F;
}
}
// private void killUnit(Selectable unitToDie)
// {
// unitToDie.GetComponent<UnitBehaviour>().hexPosition.containedUnit = null;
// PlayerBehaviour unitTeam = unitToDie.team.GetComponent<PlayerBehaviour>();
// unitTeam.units.Remove(unitToDie);
// UnityEngine.Object.Destroy(unitToDie);
//
// if (unitTeam.units.Count <= 0)
// {
// unitTeam.lost();
// }
// }
// private void killUnit(UnitBehaviour unitToDie)
// {
// killUnit(unitToDie.GetComponent<Selectable>());
// }
//spawning Monsters
private void createUnit(PlayerBehaviour player,HexTileBehaviour inTileHTB)
{
Selectable inHexSelectBehav = inTileHTB.GetComponent<Selectable>();
if (inTileHTB.containedUnit == null)
{
GameObject unitGO = (GameObject)Instantiate(player.GetComponent<PlayerBehaviour>().unitType.gameObject);
unitGO.transform.parent = player.transform;
unitGO.transform.localScale = new Vector3(Mathf.Sqrt(3f) / 2f * GameFieldBehaviour.size * 1f, 1f, Mathf.Sqrt(3f) / 2f * GameFieldBehaviour.size * 1f);
unitGO.name = "unit:" + Guid.NewGuid().ToString();
Selectable selec = unitGO.GetComponent<Selectable>();
selec.orderCollection.Add(OrderStatic.Attack());
selec.orderCollection.Add(OrderStatic.Move());
selec.orderCollection.Add(OrderStatic.Capture());
selec.availableOrders = OrderLevel.A| OrderLevel.B | OrderLevel.C |OrderLevel.D| OrderLevel.E |OrderLevel.F;
MainBehaviour.positionUnit(selec, inTileHTB);
unitGO.transform.position = GameFieldBehaviour.placeHexagon(selec.positionQ, selec.positionR, 1);
unitGO.transform.localScale = GameFieldBehaviour.scaleHexagon();
setTeam(selec,player);
//unitGO.GetComponent<UnitBehaviour>().updateInfo();
player.GetComponent<PlayerBehaviour>().units.Add(selec);
}
}
private void selectUnit(Selectable aSelec)
{
if (aSelec == null) {
guiObjectCam1.setSelected (null);
guiObjectCam2.setSelected (null);
return;
}
aSelec.selectMarker();
UnitBehaviour selectedUB = aSelec.GetComponent<UnitBehaviour> ();
if (selectedUB != null) {
guiObjectCam2.setSelected (aSelec.gameObject);
guiObjectCam1.setSelected (selectedUB.hexPosition.gameObject);
} else {
//it is a hextile
guiObjectCam1.setSelected (aSelec.gameObject);
//Does the tile have a unit on it?
Selectable containedSB = aSelec.GetComponent<HexTileBehaviour> ().containedUnit;
if (containedSB != null) {
guiObjectCam2.setSelected (aSelec.GetComponent<HexTileBehaviour> ().containedUnit.gameObject);
} else {
guiObjectCam2.setSelected (null);
}
}
}
private void deSelectUnit(Selectable aSelec)
{
aSelec.deSelectMarker();
}
private void newRound()
{
round++;
roundSetup ();
}
//looks for the next unit which can move.
private Selectable lookForAvailableUnits()
{
return watchingPlayer.units.FirstOrDefault (u => {
return (
!u.availableOrders.SameFlags (OrderLevel.B)
&&
!u.availableOrders.SameFlags (OrderLevel.C | OrderLevel.D | OrderLevel.E | OrderLevel.F)
);
});
}
private void resetSelection()
{
guiObjectCam1.setSelected (null);
guiObjectCam2.setSelected (null);
if (selectedGOSBH != null)
{
//selectedGOSBH.deSelectMarker();
deSelectUnit(selectedGOSBH);
}
if (orderTarget != null)
{
//orderTarget.deSelectMarker();
deSelectUnit(orderTarget);
}
if (clickedSelectable != null)
{
//clickedSelectable.GetComponent<Selectable>().deSelectMarker();
deSelectUnit(clickedSelectable);
}
activeOrder = null;
selectedGOSBH = null;
orderTarget = null;
clickedSelectable = null;
doubleClick = false;
}
private void beginAct()
{activeOrder.ActiveAction(selectedGOSBH, orderTarget);
audio.PlayOneShot(menuButton,0.3F);
resetSelection();
}
//bool setAffirmNextRoundInUpdate;
private void showGreyBlend()
{
guiObjectCam1.camera.enabled = false;
guiObjectCam2.camera.enabled = false;
GameObject.Find("CameraBlend").GetComponent<MeshRenderer>().enabled = true;
GameObject.Find("CameraBlend").GetComponent<MeshCollider>().enabled = true;
}
private void hideGreyBlend()
{
guiObjectCam1.camera.enabled = true;
guiObjectCam2.camera.enabled = true;
GameObject.Find("CameraBlend").GetComponent<MeshRenderer>().enabled = false;
GameObject.Find("CameraBlend").GetComponent<MeshCollider>().enabled = false;
}
void OnGUI()
{
GUI.skin = customSkin;
//unnecessary if not debugging gui
//ScaleToScreen ();
if(Time.timeScale == 0){
showGreyBlend();
GUILayout.BeginArea(new Rect(Screen.width/4,0,Screen.width/2,Screen.height));
GUILayout.Box( "PAUSE");
GUILayout.EndArea();
GUILayout.BeginArea(new Rect(Screen.width/4,0,Screen.width/2,Screen.height));
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
//Speed Options
GUILayout.Label( "Animation Speed:");
GUILayout.BeginHorizontal();
if (GUILayout.Button( "Slow"))
{
activeAnimationSpeed = slowAnimationSpeed;
audio.PlayOneShot(menuButton,0.3F);
}
if (GUILayout.Button( "Normal"))
{
activeAnimationSpeed = normalAnimationSpeed;
audio.PlayOneShot(menuButton,0.3F);
}
if (GUILayout.Button("Fast"))
{
activeAnimationSpeed = fastAnimationSpeed;
audio.PlayOneShot(menuButton,0.3F);
}
GUILayout.EndHorizontal();
GUILayout.Label( "Toggle Fast Confirm");
//fast confirm
quickConfirm = GUILayout.Toggle(quickConfirm, quickConfirm.ToString());
//quit
if (GUILayout.Button("Return to game"))
{
Time.timeScale = 1;
}
if (GUILayout.Button("Quit"))
{
Application.LoadLevel(0);
audio.PlayOneShot(menuButton,0.3F);
}
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndArea();
return;
}
else {
hideGreyBlend();
}
if (gameOver) {
GUIText winDisplay = GameObject.Find ("WinBillboard").GetComponent<GUIText> ();
winDisplay.text = "TEAM \"" + winnerTeam.title + "\" WON!";
winDisplay.enabled = true;
if (GUI.Button (new Rect (Screen.width / 3, Screen.height / 3, Screen.width / 3, Screen.height / 3), "Game Over!" + Environment.NewLine +
"Rounds: " + round + Environment.NewLine +
"Final Score: " + this.watchingPlayer.score + Environment.NewLine +
"Click to return to menu.")) {
Application.LoadLevel (0);
}
return;
}
if (affirmNextRound) {
Selectable resUnitSB = lookForAvailableUnits ();
if ( resUnitSB != null) {
showGreyBlend();
GUILayout.BeginArea(new Rect( Screen.width * 2/8, Screen.height/4, Screen.width /2, Screen.height/4));
GUILayout.BeginVertical();
//GUILayout.FlexibleSpace();
GUILayout.Box("There are still some units that can move, already end round?", GUILayout.ExpandHeight(false));
GUILayout.BeginHorizontal();
if (GUILayout.Button("Yes", GUILayout.ExpandHeight(true))) {
affirmNextRound = false;
nextPlayer();
audio.PlayOneShot (menuButton, 0.3F);
}
if (GUILayout.Button("No", GUILayout.ExpandHeight(true))) {
affirmNextRound = false;
selectedGOSBH = resUnitSB;
audio.PlayOneShot (menuButton, 0.3F);
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
//GUILayout.FlexibleSpace();
GUILayout.EndArea();
}
else {
hideGreyBlend();
if (Event.current.type == EventType.Repaint)
{
affirmNextRound = false;
nextPlayer();
return;
}
}
return;
}
//Display Round, Silicon and Next Round Button
GUILayout.BeginArea (topScoreRect);
GUILayout.BeginHorizontal (GUILayout.ExpandHeight (true));
GUILayout.Label ("Round: " + round);
GUILayout.Label ("Graphene: " + watchingPlayer.graphene );
if (players [currentPlayerIndex].lost) {
return;
}
GUI.enabled = (players [currentPlayerIndex].name == "Human");
if (GUILayout.Button ("End Round", GUILayout.ExpandHeight (true), GUILayout.ExpandWidth (false))) {
//nextPlayer ();
affirmNextRound = true;
audio.PlayOneShot (menuButton, 0.3F);
}
GUI.enabled = true;
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
if (players[currentPlayerIndex].name != "Human")
{
return;
}
if (selectedGOSBH != null) {
UnitBehaviour selectedGOUB = selectedGOSBH.GetComponent<UnitBehaviour> ();
HexTileBehaviour selectedGOHTB;
if (selectedGOUB == null) {
selectedGOHTB = selectedGOSBH.GetComponent<HexTileBehaviour> ();
if (selectedGOHTB.containedUnit != null) {
selectedGOUB = selectedGOHTB.containedUnit.GetComponent<UnitBehaviour> ();
}
} else {
selectedGOHTB = selectedGOUB.hexPosition;
}
//Display Unit and Tile information
GUILayout.BeginArea (rightUnitTileInfoRect);
GUILayout.BeginVertical (GUILayout.ExpandWidth (true));
if (selectedGOUB != null) {
GUILayout.FlexibleSpace ();
string unitContent = "Unit: " + selectedGOUB.name + Environment.NewLine +
"En:" + selectedGOUB.energy + Environment.NewLine +
"ATK:" + selectedGOUB.currentAttackStrength;
// if (GUILayout.Button (unitContent, GUILayout.ExpandHeight (false), GUILayout.ExpandWidth (true))) {
// selectedGOSBH = selectedGOUB.GetComponent<Selectable>();
// return;
// }
bool unitRes = GUILayout.Toggle ((selectedGOSBH == selectedGOUB.GetComponent<Selectable>()), unitContent, GUILayout.ExpandHeight (false), GUILayout.ExpandWidth (true));
if (unitRes && selectedGOSBH != selectedGOUB.GetComponent<Selectable>()) {
selectedGOSBH = selectedGOUB.GetComponent<Selectable>();
}
}
GUILayout.FlexibleSpace ();
string tileContent = "Tile: " + selectedGOHTB.name + Environment.NewLine +
"Cover:" + selectedGOHTB.cover.ToString () + Environment.NewLine +
"Noise:" + selectedGOHTB.noise;
// if (GUILayout.Button (tileContent, GUILayout.ExpandHeight (false), GUILayout.ExpandWidth (true))) {
// selectedGOSBH = selectedGOHTB.GetComponent<Selectable>();
// return;
// }
bool tileRes = GUILayout.Toggle ((selectedGOSBH == selectedGOHTB.GetComponent<Selectable>()),tileContent, GUILayout.ExpandHeight (false), GUILayout.ExpandWidth (true));
if (tileRes && selectedGOSBH != selectedGOHTB.GetComponent<Selectable>()){
selectedGOSBH = selectedGOHTB.GetComponent<Selectable>();
}
GUILayout.EndVertical ();
GUILayout.EndArea ();
//Display Unit Orders and Tile Constructions
int buttonWidth = Screen.width / 5;
int buttonHeight = Screen.height / 5;
if (!touchOptions) {
buttonWidth /= 2;
}
if (selectedGOSBH.team == watchingPlayer) {
//TODO: touch - need to make sure it snaps on limits
GUI.BeginGroup (new Rect (-scrollFloat, bottomScrollRect.y, bottomScrollRect.width, bottomScrollRect.height));
for (int i = 0; i < selectedGOSBH.orderCollection.Count; i++) {
GUI.enabled = selectedGOSBH.orderCollection[i].Usable(selectedGOSBH, null);
GUIStyle currentStyle;
if (selectedGOSBH.orderCollection[i].PassiveRunning)
{
currentStyle = PassiveRunningStyleOn;
}
else
{
currentStyle = PassiveRunningStyleOff;
}
if (GUI.Toggle (new Rect (i * (marginDistance + buttonWidth), marginDistance, buttonWidth, buttonHeight), (activeOrder == selectedGOSBH.orderCollection[i]) , selectedGOSBH.orderCollection[i].Title ,currentStyle)) {
activeOrder = selectedGOSBH.orderCollection[i];
}
}
GUI.EndGroup ();
//if (touchOptions) {
// GUI.HorizontalScrollbar (new Rect (0, Screen.height - (marginDistance * 2), Screen.width, (marginDistance * 2)), scrollFloat, buttonWidth + marginDistance, 0, selectedGOSBH.orderCollection.Count * (marginDistance + buttonWidth) - Screen.width + buttonWidth + marginDistance);
// }
}
FactoryBehaviour selectedFB = selectedGOHTB.GetComponent<FactoryBehaviour> ();
if (selectedFB != null && selectedGOSBH == selectedFB.GetComponent<Selectable>() && selectedFB.GetComponent<Selectable>().team == watchingPlayer) {
HexTileBehaviour selectedHTB = selectedFB.GetComponent<HexTileBehaviour>();
GUI.enabled = (selectedHTB.containedUnit == null && selectedGOSBH.team.graphene >= selectedGOSBH.team.unitType.resourcePrice);
GUILayout.BeginArea(bottomScrollRect);
GUILayout.BeginHorizontal(GUI.skin.box, GUILayout.Width(Screen.width / 2));
// Showing all Equipment on the tile
GUILayout.BeginScrollView(scrollVector1);
GUILayout.Label("Produce Unit");
if (GUILayout.Button( selectedGOSBH.team.unitType.name ))
{
createUnit(selectedGOSBH.team,selectedHTB);
selectedGOSBH.team.graphene -= selectedGOSBH.team.unitType.resourcePrice;
audio.PlayOneShot(menuButton,0.3F);
}
GUILayout.EndScrollView();
GUILayout.EndHorizontal();
GUILayout.EndArea();
GUI.enabled = true;
return;
}
if (activeOrder != null && orderTarget != null)
{
if (quickConfirm) {
beginAct();
}
else {
String buttonMessage = "Confirm?";
UnitBehaviour targetUB = orderTarget.GetComponent<UnitBehaviour>();
if (activeOrder.Targeting.SameFlags(TargetType.Target | TargetType.TargetFriendly) && targetUB != null)
{
buttonMessage += String.Format("\nPrognosis:\nTeam: {0},\nUnit: {1}\nenergy = {2}", orderTarget.team.name, orderTarget.name, damageCalculation(selectedGOUB, targetUB).ToString());
}
if (GUI.Button(new Rect(10, 10, 200, 100), buttonMessage))
{
beginAct();
}
}
return;
}
return;
}
//
//
// if (GUI.Button(new Rect(10, Screen.height - 110, 150, 100), "Quit"))
// {
// Application.LoadLevel(0);
// audio.PlayOneShot(menuButton,0.3F);
// }
//
// if (GUI.Button(new Rect(220 , Screen.height - 110, 100, 50), "Slow"))
// {
// activeAnimationSpeed = slowAnimationSpeed;
// audio.PlayOneShot(menuButton,0.3F);
// }
//
// if (GUI.Button(new Rect(330 , Screen.height - 110, 100, 50), "Normal"))
// {
// activeAnimationSpeed = normalAnimationSpeed;
// audio.PlayOneShot(menuButton,0.3F);
// }
//
// if (GUI.Button(new Rect(440 , Screen.height - 110, 100, 50), "Fast"))
// {
// activeAnimationSpeed = fastAnimationSpeed;
// audio.PlayOneShot(menuButton,0.3F);
// }
//
// PlayerBehaviour currentPB = players[currentPlayerIndex];
//
// if (currentPB.name != "Human")
// {
// return;
// }
//
// if (players[currentPlayerIndex].lost) {
// return;
// }
//
// if (selectedGOSBH == null)
// {
// if (GUI.Button(new Rect(Screen.width - 160, 10, 150, 100), "End Round"))
// {nextPlayer();
// audio.PlayOneShot(menuButton,0.3F);
// }
// return;
// }
//
//
// showGuiInfo(selectedGOSBH);
//
// //FactoryBehaviour selectedFB = selectedGOSBH.GetComponent<FactoryBehaviour> ();
// // UnitBehaviour selectedunitUB = selectedGOSBH.GetComponent<UnitBehaviour>();
//
// //if (selectedunitUB == null && selectedFB == null)
// {
// return;
// }
//
// if (activeOrder != null && orderTarget != null)
// {
// if (quickConfirm) {
// beginAct();
// }
// else {
// String buttonMessage = "Confirm?";
// UnitBehaviour targetUB = orderTarget.GetComponent<UnitBehaviour>();
//
// if (activeOrder.Targeting.SameFlags(TargetType.Target | TargetType.TargetFriendly) && targetUB != null)
// {
// buttonMessage += String.Format("\nPrognosis:\nTeam: {0},\nUnit: {1}\nenergy = {2}", orderTarget.team.name, orderTarget.name, damageCalculation(selectedunitUB, targetUB).ToString());
// }
//
// if (GUI.Button(new Rect(10, 10, 200, 100), buttonMessage))
// {
// beginAct();
// }
// }
//
// return;
// }
//
// if (selectedGOSBH.team != players[currentPlayerIndex])
// {
// return;
// }
//
// if (selectedFB != null) {
//
// HexTileBehaviour selectedHTB = selectedFB.GetComponent<HexTileBehaviour>();
// GUI.enabled = (selectedHTB.containedUnit == null && selectedGOSBH.team.silicon >= selectedGOSBH.team.unitType.resourcePrice);
// GUILayout.BeginHorizontal(GUI.skin.box, GUILayout.Width(Screen.width / 2));
//
// // Showing all Equipment on the tile
// GUILayout.BeginScrollView(scrollVector1);
// GUILayout.Label("Produce Unit");
//
// if (GUILayout.Button( selectedGOSBH.team.unitType.name ))
// {
// createUnit(selectedGOSBH.team,selectedHTB);
// selectedGOSBH.team.silicon -= selectedGOSBH.team.unitType.resourcePrice;
// audio.PlayOneShot(menuButton,0.3F);
// }
//
// GUILayout.EndScrollView();
// GUILayout.EndHorizontal();
//
// GUI.enabled = true;
// return;
// }
//
// GUILayout.BeginHorizontal(GUI.skin.box, GUILayout.Width(Screen.width / 2));
//
// // Showing all Equipment on the tile
// GUILayout.BeginScrollView(scrollVector1);
// GUILayout.Label("Order on Tile");
// Selectable hexSelectable = selectedunitUB.hexPosition.GetComponent<Selectable>();
//
// foreach (Order inOrder in hexSelectable.orderCollection)
// {
// //Check if the tiles options can be used
//
// GUI.enabled = inOrder.Usable(selectedunitUB.hexPosition.GetComponent<Selectable>(), null);
//
// GUIStyle currentStyle;
//
// if (inOrder.PassiveRunning)
// {
// currentStyle = PassiveRunningStyleOn;
// }
// else
// {
// currentStyle = PassiveRunningStyleOff;
// }
//
// if (GUILayout.Toggle((activeOrder == inOrder), inOrder.Title + "x " + inOrder.Uses.ToString(), currentStyle))
// {
// //audio.PlayOneShot(menuButton,0.3F);
// activeOrder = inOrder;
// }
//
// GUI.enabled = true;
// }
// GUILayout.EndScrollView();
//
// // Showing all Equipment on the unit itself
//
// GUILayout.BeginScrollView(scrollVector2);
// GUILayout.Label("Order on Unit");
// foreach (Order inOrder in selectedGOSBH.orderCollection)
// {
//
// GUI.enabled = inOrder.Usable(selectedGOSBH, null);
//
// GUIStyle currentStyle;
//
// if (inOrder.PassiveRunning)
// {
// currentStyle = PassiveRunningStyleOn;
// }
// else
// {
// currentStyle = PassiveRunningStyleOff;
// }
//
// if (GUILayout.Toggle((activeOrder == inOrder), inOrder.Title + " x " + inOrder.Uses.ToString(), currentStyle))
// {
// //audio.PlayOneShot(menuButton,0.3F);
// activeOrder = inOrder;
// }
//
// GUI.enabled = true;
// }
//
// //Usability is decided by the order itself, and can still be carried even if "empty"
// GUILayout.EndScrollView();
// GUILayout.EndHorizontal();
// return;
//
}
// shows information for uncommandable selectables
private void showGuiInfo(String message)
{
GUI.Label(new Rect(10, 130, 150, 100), "Info:" + message);
}
private void showGuiInfo(Selectable goInfoSB)
{
StringBuilder messageBuild = new StringBuilder("\nname: " + goInfoSB.name);
messageBuild.Append("\nteam: " + goInfoSB.team.name);
HexTileBehaviour hexTile = goInfoSB.GetComponent<HexTileBehaviour>();
if (hexTile != null)
{
messageBuild.Append("\ncover: " + hexTile.cover.ToString());
}
else
{
UnitBehaviour unit = goInfoSB.GetComponent<UnitBehaviour>();
if (unit != null)
{
messageBuild.Append("\nenergy: " + unit.energy + "/" + unit.energyLimit);
}
}
showGuiInfo(messageBuild.ToString());
}
public static void positionUnit(Selectable currentSelected, HexTileBehaviour clickedHexField)
{
UnitBehaviour currentSelUnitBehav = currentSelected.GetComponent<UnitBehaviour>();
Selectable clickedSelectable = clickedHexField.gameObject.GetComponent<Selectable>();
if (currentSelUnitBehav.hexPosition != null)
{
currentSelUnitBehav.hexPosition.containedUnit = null;
}
currentSelUnitBehav.hexPosition = clickedHexField;
currentSelUnitBehav.hexPosition.containedUnit = currentSelected ;
//turning
//rotateUnit(currentSelected, clickedSelectable);
//moving
currentSelected.positionQ = clickedSelectable.positionQ;
currentSelected.positionR = clickedSelectable.positionR;
currentSelected.transform.position = GameFieldBehaviour.placeHexagon(clickedSelectable.positionQ, clickedSelectable.positionR, 1);
}
public static void rotateUnit(Selectable toRotateSelectable, Selectable targetSelectable)
{
toRotateSelectable.transform.FindChild("Model").transform.eulerAngles =
new Vector3(toRotateSelectable.transform.FindChild("Model").transform.eulerAngles.x, rotateEul(toRotateSelectable, targetSelectable).y, toRotateSelectable.transform.FindChild("Model").transform.eulerAngles.z);
}
public static Vector3 rotateEul(Selectable currentSelectable, Selectable targetSelectable)
{
float rotation = 0;
for (int i = 0; i < Selectable.PossibleNeighbour.Count; i++)
{
if (Selectable.PossibleNeighbour[i][0] + currentSelectable.positionQ == targetSelectable.positionQ &&
Selectable.PossibleNeighbour[i][1] + currentSelectable.positionR == targetSelectable.positionR)
{
rotation = i * 60f;
break;
}
}
return new Vector3(currentSelectable.transform.eulerAngles.x, rotation, currentSelectable.transform.eulerAngles.z);
}
public static int rotateEulDegrees(Selectable currentSelectable, Selectable targetSelectable)
{
byte rotationTarget = 0;
for (byte i = 0; i < Selectable.PossibleNeighbour.Count; i++)
{
if (Selectable.PossibleNeighbour[i][0] + currentSelectable.positionQ == targetSelectable.positionQ &&
Selectable.PossibleNeighbour[i][1] + currentSelectable.positionR == targetSelectable.positionR)
{
rotationTarget = i;
break;
}
}
int finalRotation = 0;
finalRotation = (rotationTarget) * 60;;
currentSelectable.rotationIndex = rotationTarget;
return finalRotation;
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace Microsoft.Scripting.Actions.Calls {
using Ast = Expression;
/// <summary>
/// MethodCandidate represents the different possible ways of calling a method or a set of method overloads.
/// A single method can result in multiple MethodCandidates. Some reasons include:
/// - Every optional parameter or parameter with a default value will result in a candidate
/// - The presence of ref and out parameters will add a candidate for languages which want to return the updated values as return values.
/// - ArgumentKind.List and ArgumentKind.Dictionary can result in a new candidate per invocation since the list might be different every time.
///
/// Each MethodCandidate represents the parameter type for the candidate using ParameterWrapper.
/// </summary>
public sealed class MethodCandidate {
private readonly OverloadResolver _resolver;
private readonly OverloadInfo _overload;
private readonly List<ParameterWrapper> _parameters;
private readonly ParameterWrapper _paramsDict;
private readonly int _paramsArrayIndex;
private readonly IList<ArgBuilder> _argBuilders;
private readonly InstanceBuilder _instanceBuilder;
private readonly ReturnBuilder _returnBuilder;
private readonly Dictionary<DynamicMetaObject, BindingRestrictions> _restrictions;
internal MethodCandidate(OverloadResolver resolver, OverloadInfo method, List<ParameterWrapper> parameters, ParameterWrapper paramsDict,
ReturnBuilder returnBuilder, InstanceBuilder instanceBuilder, IList<ArgBuilder> argBuilders, Dictionary<DynamicMetaObject, BindingRestrictions> restrictions) {
Assert.NotNull(resolver, method, instanceBuilder, returnBuilder);
Assert.NotNullItems(parameters);
Assert.NotNullItems(argBuilders);
_resolver = resolver;
_overload = method;
_instanceBuilder = instanceBuilder;
_argBuilders = argBuilders;
_returnBuilder = returnBuilder;
_parameters = parameters;
_paramsDict = paramsDict;
_restrictions = restrictions;
_paramsArrayIndex = ParameterWrapper.IndexOfParamsArray(parameters);
parameters.TrimExcess();
}
internal MethodCandidate ReplaceMethod(OverloadInfo newMethod, List<ParameterWrapper> parameters, IList<ArgBuilder> argBuilders, Dictionary<DynamicMetaObject, BindingRestrictions> restrictions) {
return new MethodCandidate(_resolver, newMethod, parameters, _paramsDict, _returnBuilder, _instanceBuilder, argBuilders, restrictions);
}
internal ReturnBuilder ReturnBuilder {
get { return _returnBuilder; }
}
internal IList<ArgBuilder> ArgBuilders {
get { return _argBuilders; }
}
public OverloadResolver Resolver {
get { return _resolver; }
}
[Obsolete("Use Overload instead")]
public MethodBase Method {
get { return _overload.ReflectionInfo; }
}
public OverloadInfo Overload {
get { return _overload; }
}
internal Dictionary<DynamicMetaObject, BindingRestrictions> Restrictions {
get { return _restrictions; }
}
public Type ReturnType {
get { return _returnBuilder.ReturnType; }
}
public int ParamsArrayIndex {
get { return _paramsArrayIndex; }
}
public bool HasParamsArray {
get { return _paramsArrayIndex != -1; }
}
public bool HasParamsDictionary {
get { return _paramsDict != null; }
}
public ActionBinder Binder {
get { return _resolver.Binder; }
}
internal ParameterWrapper GetParameter(int argumentIndex, ArgumentBinding namesBinding) {
return _parameters[namesBinding.ArgumentToParameter(argumentIndex)];
}
internal ParameterWrapper GetParameter(int parameterIndex) {
return _parameters[parameterIndex];
}
internal int ParameterCount {
get { return _parameters.Count; }
}
internal int IndexOfParameter(string name) {
for (int i = 0; i < _parameters.Count; i++) {
if (_parameters[i].Name == name) {
return i;
}
}
return -1;
}
public int GetVisibleParameterCount() {
int result = 0;
foreach (var parameter in _parameters) {
if (!parameter.IsHidden) {
result++;
}
}
return result;
}
public IList<ParameterWrapper> GetParameters() {
return new ReadOnlyCollection<ParameterWrapper>(_parameters);
}
/// <summary>
/// Builds a new MethodCandidate which takes count arguments and the provided list of keyword arguments.
///
/// The basic idea here is to figure out which parameters map to params or a dictionary params and
/// fill in those spots w/ extra ParameterWrapper's.
/// </summary>
internal MethodCandidate MakeParamsExtended(int count, IList<string> names) {
Debug.Assert(_overload.IsVariadic);
List<ParameterWrapper> newParameters = new List<ParameterWrapper>(count);
// keep track of which named args map to a real argument, and which ones
// map to the params dictionary.
List<string> unusedNames = new List<string>(names);
List<int> unusedNameIndexes = new List<int>();
for (int i = 0; i < unusedNames.Count; i++) {
unusedNameIndexes.Add(i);
}
// if we don't have a param array we'll have a param dict which is type object
ParameterWrapper paramsArrayParameter = null;
int paramsArrayIndex = -1;
for (int i = 0; i < _parameters.Count; i++) {
ParameterWrapper parameter = _parameters[i];
if (parameter.IsParamsArray) {
paramsArrayParameter = parameter;
paramsArrayIndex = i;
} else {
int j = unusedNames.IndexOf(parameter.Name);
if (j != -1) {
unusedNames.RemoveAt(j);
unusedNameIndexes.RemoveAt(j);
}
newParameters.Add(parameter);
}
}
if (paramsArrayIndex != -1) {
ParameterWrapper expanded = paramsArrayParameter.Expand();
while (newParameters.Count < (count - unusedNames.Count)) {
newParameters.Insert(System.Math.Min(paramsArrayIndex, newParameters.Count), expanded);
}
}
if (_paramsDict != null) {
var flags = (_overload.ProhibitsNullItems(_paramsDict.ParameterInfo.Position) ? ParameterBindingFlags.ProhibitNull : 0) |
(_paramsDict.IsHidden ? ParameterBindingFlags.IsHidden : 0);
foreach (string name in unusedNames) {
newParameters.Add(new ParameterWrapper(_paramsDict.ParameterInfo, typeof(object), name, flags));
}
} else if (unusedNames.Count != 0) {
// unbound kw args and no where to put them, can't call...
// TODO: We could do better here because this results in an incorrect arg # error message.
return null;
}
// if we have too many or too few args we also can't call
if (count != newParameters.Count) {
return null;
}
return MakeParamsExtended(unusedNames.ToArray(), unusedNameIndexes.ToArray(), newParameters);
}
private MethodCandidate MakeParamsExtended(string[] names, int[] nameIndices, List<ParameterWrapper> parameters) {
Debug.Assert(Overload.IsVariadic);
List<ArgBuilder> newArgBuilders = new List<ArgBuilder>(_argBuilders.Count);
// current argument that we consume, initially skip this if we have it.
int curArg = _overload.IsStatic ? 0 : 1;
int kwIndex = -1;
ArgBuilder paramsDictBuilder = null;
foreach (ArgBuilder ab in _argBuilders) {
// TODO: define a virtual method on ArgBuilder implementing this functionality:
SimpleArgBuilder sab = ab as SimpleArgBuilder;
if (sab != null) {
// we consume one or more incoming argument(s)
if (sab.IsParamsArray) {
// consume all the extra arguments
int paramsUsed = parameters.Count -
GetConsumedArguments() -
names.Length +
(_overload.IsStatic ? 1 : 0);
newArgBuilders.Add(new ParamsArgBuilder(
sab.ParameterInfo,
sab.Type.GetElementType(),
curArg,
paramsUsed
));
curArg += paramsUsed;
} else if (sab.IsParamsDict) {
// consume all the kw arguments
kwIndex = newArgBuilders.Count;
paramsDictBuilder = sab;
} else {
// consume the argument, adjust its position:
newArgBuilders.Add(sab.MakeCopy(curArg++));
}
} else if (ab is KeywordArgBuilder) {
newArgBuilders.Add(ab);
curArg++;
} else {
// CodeContext, null, default, etc... we don't consume an
// actual incoming argument.
newArgBuilders.Add(ab);
}
}
if (kwIndex != -1) {
newArgBuilders.Insert(kwIndex, new ParamsDictArgBuilder(paramsDictBuilder.ParameterInfo, curArg, names, nameIndices));
}
return new MethodCandidate(_resolver, _overload, parameters, null, _returnBuilder, _instanceBuilder, newArgBuilders, null);
}
private int GetConsumedArguments() {
int consuming = 0;
foreach (ArgBuilder argb in _argBuilders) {
SimpleArgBuilder sab = argb as SimpleArgBuilder;
if (sab != null && !sab.IsParamsDict || argb is KeywordArgBuilder) {
consuming++;
}
}
return consuming;
}
public Type[] GetParameterTypes() {
List<Type> res = new List<Type>(_argBuilders.Count);
for (int i = 0; i < _argBuilders.Count; i++) {
Type t = _argBuilders[i].Type;
if (t != null) {
res.Add(t);
}
}
return res.ToArray();
}
#region MakeExpression
internal Expression MakeExpression(RestrictedArguments restrictedArgs) {
bool[] usageMarkers;
Expression[] spilledArgs;
Expression[] callArgs = GetArgumentExpressions(restrictedArgs, out usageMarkers, out spilledArgs);
Expression call;
MethodBase mb = _overload.ReflectionInfo;
// TODO: make MakeExpression virtual on OverloadInfo?
if (mb == null) {
throw new InvalidOperationException("Cannot generate an expression for an overload w/o MethodBase");
}
MethodInfo mi = mb as MethodInfo;
if (mi != null) {
Expression instance;
if (mi.IsStatic) {
instance = null;
} else {
Debug.Assert(mi != null);
instance = _instanceBuilder.ToExpression(ref mi, _resolver, restrictedArgs, usageMarkers);
Debug.Assert(instance != null, "Can't skip instance expression");
}
if (CompilerHelpers.IsVisible(mi)) {
call = AstUtils.SimpleCallHelper(instance, mi, callArgs);
} else {
call = Ast.Call(
typeof(BinderOps).GetMethod("InvokeMethod"),
AstUtils.Constant(mi),
instance != null ? AstUtils.Convert(instance, typeof(object)) : AstUtils.Constant(null),
AstUtils.NewArrayHelper(typeof(object), callArgs)
);
}
} else {
ConstructorInfo ci = (ConstructorInfo)mb;
if (CompilerHelpers.IsVisible(ci)) {
call = AstUtils.SimpleNewHelper(ci, callArgs);
} else {
call = Ast.Call(
typeof(BinderOps).GetMethod("InvokeConstructor"),
AstUtils.Constant(ci),
AstUtils.NewArrayHelper(typeof(object), callArgs)
);
}
}
if (spilledArgs != null) {
call = Expression.Block(spilledArgs.AddLast(call));
}
Expression ret = _returnBuilder.ToExpression(_resolver, _argBuilders, restrictedArgs, call);
List<Expression> updates = null;
for (int i = 0; i < _argBuilders.Count; i++) {
Expression next = _argBuilders[i].UpdateFromReturn(_resolver, restrictedArgs);
if (next != null) {
if (updates == null) {
updates = new List<Expression>();
}
updates.Add(next);
}
}
if (updates != null) {
if (ret.Type != typeof(void)) {
ParameterExpression temp = Ast.Variable(ret.Type, "$ret");
updates.Insert(0, Ast.Assign(temp, ret));
updates.Add(temp);
ret = Ast.Block(new[] { temp }, updates.ToArray());
} else {
updates.Insert(0, ret);
ret = Ast.Block(typeof(void), updates.ToArray());
}
}
if (_resolver.Temps != null) {
ret = Ast.Block(_resolver.Temps, ret);
}
return ret;
}
private Expression[] GetArgumentExpressions(RestrictedArguments restrictedArgs, out bool[] usageMarkers, out Expression[] spilledArgs) {
int minPriority = Int32.MaxValue;
int maxPriority = Int32.MinValue;
foreach (ArgBuilder ab in _argBuilders) {
minPriority = System.Math.Min(minPriority, ab.Priority);
maxPriority = System.Math.Max(maxPriority, ab.Priority);
}
var args = new Expression[_argBuilders.Count];
Expression[] actualArgs = null;
usageMarkers = new bool[restrictedArgs.Length];
for (int priority = minPriority; priority <= maxPriority; priority++) {
for (int i = 0; i < _argBuilders.Count; i++) {
if (_argBuilders[i].Priority == priority) {
args[i] = _argBuilders[i].ToExpression(_resolver, restrictedArgs, usageMarkers);
// see if this has a temp that needs to be passed as the actual argument
Expression byref = _argBuilders[i].ByRefArgument;
if (byref != null) {
if (actualArgs == null) {
actualArgs = new Expression[_argBuilders.Count];
}
actualArgs[i] = byref;
}
}
}
}
if (actualArgs != null) {
for (int i = 0; i < args.Length; i++) {
if (args[i] != null && actualArgs[i] == null) {
actualArgs[i] = _resolver.GetTemporary(args[i].Type, null);
args[i] = Expression.Assign(actualArgs[i], args[i]);
}
}
spilledArgs = RemoveNulls(args);
return RemoveNulls(actualArgs);
}
spilledArgs = null;
return RemoveNulls(args);
}
private static Expression[] RemoveNulls(Expression[] args) {
int newLength = args.Length;
for (int i = 0; i < args.Length; i++) {
if (args[i] == null) {
newLength--;
}
}
var result = new Expression[newLength];
for (int i = 0, j = 0; i < args.Length; i++) {
if (args[i] != null) {
result[j++] = args[i];
}
}
return result;
}
#endregion
public override string ToString() {
return string.Format("MethodCandidate({0} on {1})", Overload.ReflectionInfo, Overload.DeclaringType.FullName);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Microsoft.Azure.Management.Sql.LegacySdk.Responses;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for determining the set of capabilites
/// available in a specified region.
/// </summary>
internal partial class CapabilitiesOperations : IServiceOperations<SqlManagementClient>, ICapabilitiesOperations
{
/// <summary>
/// Initializes a new instance of the CapabilitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CapabilitiesOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Returns information about the Azure SQL capabilities available for
/// the specified region.
/// </summary>
/// <param name='locationName'>
/// Required. The name of the region for which the Azure SQL
/// capabilities are retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql capabilities request
/// </returns>
public async Task<LocationCapabilitiesGetResponse> GetAsync(string locationName, CancellationToken cancellationToken)
{
// Validate
if (locationName == null)
{
throw new ArgumentNullException("locationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("locationName", locationName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/locations/";
url = url + Uri.EscapeDataString(locationName);
url = url + "/capabilities";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LocationCapabilitiesGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LocationCapabilitiesGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LocationCapability capabilitiesInstance = new LocationCapability();
result.Capabilities = capabilitiesInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
capabilitiesInstance.Name = nameInstance;
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
capabilitiesInstance.Status = statusInstance;
}
JToken supportedServerVersionsArray = responseDoc["supportedServerVersions"];
if (supportedServerVersionsArray != null && supportedServerVersionsArray.Type != JTokenType.Null)
{
foreach (JToken supportedServerVersionsValue in ((JArray)supportedServerVersionsArray))
{
ServerVersionCapability serverVersionCapabilityInstance = new ServerVersionCapability();
capabilitiesInstance.SupportedServerVersions.Add(serverVersionCapabilityInstance);
JToken nameValue2 = supportedServerVersionsValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
serverVersionCapabilityInstance.Name = nameInstance2;
}
JToken statusValue2 = supportedServerVersionsValue["status"];
if (statusValue2 != null && statusValue2.Type != JTokenType.Null)
{
string statusInstance2 = ((string)statusValue2);
serverVersionCapabilityInstance.Status = statusInstance2;
}
JToken supportedEditionsArray = supportedServerVersionsValue["supportedEditions"];
if (supportedEditionsArray != null && supportedEditionsArray.Type != JTokenType.Null)
{
foreach (JToken supportedEditionsValue in ((JArray)supportedEditionsArray))
{
EditionCapability editionCapabilityInstance = new EditionCapability();
serverVersionCapabilityInstance.SupportedEditions.Add(editionCapabilityInstance);
JToken nameValue3 = supportedEditionsValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
editionCapabilityInstance.Name = nameInstance3;
}
JToken statusValue3 = supportedEditionsValue["status"];
if (statusValue3 != null && statusValue3.Type != JTokenType.Null)
{
string statusInstance3 = ((string)statusValue3);
editionCapabilityInstance.Status = statusInstance3;
}
JToken supportedServiceLevelObjectivesArray = supportedEditionsValue["supportedServiceLevelObjectives"];
if (supportedServiceLevelObjectivesArray != null && supportedServiceLevelObjectivesArray.Type != JTokenType.Null)
{
foreach (JToken supportedServiceLevelObjectivesValue in ((JArray)supportedServiceLevelObjectivesArray))
{
ServiceObjectiveCapability serviceObjectiveCapabilityInstance = new ServiceObjectiveCapability();
editionCapabilityInstance.SupportedServiceObjectives.Add(serviceObjectiveCapabilityInstance);
JToken nameValue4 = supportedServiceLevelObjectivesValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
serviceObjectiveCapabilityInstance.Name = nameInstance4;
}
JToken statusValue4 = supportedServiceLevelObjectivesValue["status"];
if (statusValue4 != null && statusValue4.Type != JTokenType.Null)
{
string statusInstance4 = ((string)statusValue4);
serviceObjectiveCapabilityInstance.Status = statusInstance4;
}
JToken idValue = supportedServiceLevelObjectivesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
Guid idInstance = Guid.Parse(((string)idValue));
serviceObjectiveCapabilityInstance.Id = idInstance;
}
JToken supportedMaxSizesArray = supportedServiceLevelObjectivesValue["supportedMaxSizes"];
if (supportedMaxSizesArray != null && supportedMaxSizesArray.Type != JTokenType.Null)
{
foreach (JToken supportedMaxSizesValue in ((JArray)supportedMaxSizesArray))
{
MaxSizeCapability maxSizeCapabilityInstance = new MaxSizeCapability();
serviceObjectiveCapabilityInstance.SupportedMaxSizes.Add(maxSizeCapabilityInstance);
JToken limitValue = supportedMaxSizesValue["limit"];
if (limitValue != null && limitValue.Type != JTokenType.Null)
{
int limitInstance = ((int)limitValue);
maxSizeCapabilityInstance.Limit = limitInstance;
}
JToken unitValue = supportedMaxSizesValue["unit"];
if (unitValue != null && unitValue.Type != JTokenType.Null)
{
string unitInstance = ((string)unitValue);
maxSizeCapabilityInstance.Unit = unitInstance;
}
JToken statusValue5 = supportedMaxSizesValue["status"];
if (statusValue5 != null && statusValue5.Type != JTokenType.Null)
{
string statusInstance5 = ((string)statusValue5);
maxSizeCapabilityInstance.Status = statusInstance5;
}
}
}
}
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using Gum.Graphics.Animation;
using Microsoft.Xna.Framework.Graphics;
namespace Gum.Content.AnimationChain
{
#if !UWP
[Serializable]
#endif
public class AnimationFrameSave
{
#region XML Docs
/// <summary>
/// Whether the texture should be flipped horizontally.
/// </summary>
#endregion
public bool FlipHorizontal;
public bool ShouldSerializeFlipHorizontal()
{
return FlipHorizontal == true;
}
#region XML Docs
/// <summary>
/// Whether the texture should be flipped on the vertidally.
/// </summary>
#endregion
public bool FlipVertical;
public bool ShouldSerializeFlipVertical()
{
return FlipVertical == true;
}
#region XML Docs
/// <summary>
/// Used in XML Serialization of AnimationChains - this should
/// not explicitly be set by the user.
/// </summary>
#endregion
public string TextureName;
#region XML Docs
/// <summary>
/// The amount of time in seconds the AnimationFrame should be shown for.
/// </summary>
#endregion
public float FrameLength;
/// <summary>
/// The left coordinate in texture coordinates of the AnimationFrame. Default is 0.
/// This may be in UV coordinates or pixel coordinates.
/// </summary>
public float LeftCoordinate;
/// <summary>
/// The right coordinate in texture coordinates of the AnimationFrame. Default is 1.
/// This may be in UV coordinates or pixel coordinates.
/// </summary>
public float RightCoordinate = 1;
/// <summary>
/// The top coordinate in texture coordinates of the AnimationFrame. Default is 0.
/// This may be in UV coordinates or pixel coordinates.
/// </summary>
public float TopCoordinate;
/// <summary>
/// The bottom coordinate in texture coordinates of the AnimationFrame. Default is 1.
/// This may be in UV coordinates or pixel coordinates.
/// </summary>
public float BottomCoordinate = 1;
#region XML Docs
/// <summary>
/// The relative X position of the object that is using this AnimationFrame. This
/// is only applied if the IAnimationChainAnimatable's UseAnimationRelativePosition is
/// set to true.
/// </summary>
#endregion
public float RelativeX;
public bool ShouldSerializeRelativeX()
{
return RelativeX != 0;
}
#region XML Docs
/// <summary>
/// The relative Y position of the object that is using this AnimationFrame. This
/// is only applied if the IAnimationChainAnimatable's UseAnimationRelativePosition is
/// set to true.
/// </summary>
#endregion
public float RelativeY;
public bool ShouldSerializeRelativeY()
{
return RelativeY != 0;
}
[XmlIgnore]
#if !UWP
[NonSerialized]
#endif
internal Texture2D mTextureInstance;
public AnimationFrameSave() { }
public AnimationFrameSave(AnimationFrame template)
{
FrameLength = template.FrameLength;
TextureName = template.TextureName;
FlipVertical = template.FlipVertical;
FlipHorizontal = template.FlipHorizontal;
LeftCoordinate = template.LeftCoordinate;
RightCoordinate = template.RightCoordinate;
TopCoordinate = template.TopCoordinate;
BottomCoordinate = template.BottomCoordinate;
RelativeX = template.RelativeX;
RelativeY = template.RelativeY;
TextureName = template.Texture.Name;
}
public AnimationFrame ToAnimationFrame(string contentManagerName)
{
return ToAnimationFrame(contentManagerName, true);
}
public AnimationFrame ToAnimationFrame(string contentManagerName, bool loadTexture)
{
return ToAnimationFrame(contentManagerName, loadTexture, TextureCoordinateType.UV);
}
public AnimationFrame ToAnimationFrame(string contentManagerName, bool loadTexture, TextureCoordinateType coordinateType)
{
AnimationFrame frame = new AnimationFrame();
#region Set basic variables
frame.TextureName = TextureName;
frame.FrameLength = FrameLength;
if (loadTexture)
{
if (mTextureInstance != null)
{
frame.Texture = mTextureInstance;
}
// I think we should tolarte frames with a null Texture
else if (!string.IsNullOrEmpty(TextureName))
{
//throw new NotImplementedException();
//frame.Texture = FlatRedBallServices.Load<Texture2D>(TextureName, contentManagerName);
try
{
var fileName = ToolsUtilities.FileManager.RemoveDotDotSlash(ToolsUtilities.FileManager.RelativeDirectory + TextureName);
frame.Texture = global::RenderingLibrary.Content.LoaderManager.Self.LoadContent<Microsoft.Xna.Framework.Graphics.Texture2D>(
fileName);
}
catch (System.IO.FileNotFoundException)
{
if (Wireframe.GraphicalUiElement.MissingFileBehavior == Wireframe.MissingFileBehavior.ThrowException)
{
string message = $"Error loading texture in animation :\n{TextureName}";
throw new System.IO.FileNotFoundException(message);
}
frame.Texture = null;
}
}
//frame.Texture = FlatRedBallServices.Load<Texture2D>(TextureName, contentManagerName);
}
frame.FlipHorizontal = FlipHorizontal;
frame.FlipVertical = FlipVertical;
if (coordinateType == TextureCoordinateType.UV)
{
frame.LeftCoordinate = LeftCoordinate;
frame.RightCoordinate = RightCoordinate;
frame.TopCoordinate = TopCoordinate;
frame.BottomCoordinate = BottomCoordinate;
}
else if (coordinateType == TextureCoordinateType.Pixel)
{
// April 16, 2015
// Victor Chelaru
// We used to throw this exception, but I don't know why we should, because
// the Sprite won't show up, and the problem should be discoverable in tools
// without a crash
//if (frame.Texture == null)
//{
// throw new Exception("The frame must have its texture loaded to use the Pixel coordinate type");
//}
if (frame.Texture != null)
{
frame.LeftCoordinate = LeftCoordinate / frame.Texture.Width;
frame.RightCoordinate = RightCoordinate / frame.Texture.Width;
frame.TopCoordinate = TopCoordinate / frame.Texture.Height;
frame.BottomCoordinate = BottomCoordinate / frame.Texture.Height;
}
}
frame.RelativeX = RelativeX;
frame.RelativeY = RelativeY;
#endregion
return frame;
}
//public AnimationFrame ToAnimationFrame(TextureAtlas textureAtlas)
//{
// AnimationFrame toReturn = ToAnimationFrame(null, false);
// var entry = textureAtlas.GetEntryFor(this.TextureName);
// if (entry != null)
// {
// float left;
// float right;
// float top;
// float bottom;
// entry.FullToReduced(toReturn.LeftCoordinate, toReturn.RightCoordinate,
// toReturn.TopCoordinate, toReturn.BottomCoordinate,
// out left, out right, out top, out bottom);
// toReturn.LeftCoordinate = left;
// toReturn.RightCoordinate = right;
// toReturn.TopCoordinate = top;
// toReturn.BottomCoordinate = bottom;
// }
// return toReturn;
//}
//internal static AnimationFrameSave FromXElement(System.Xml.Linq.XElement element)
//{
// AnimationFrameSave toReturn = new AnimationFrameSave();
// foreach (var subElement in element.Elements())
// {
// switch (subElement.Name.LocalName)
// {
// case "FlipHorizontal":
// toReturn.FlipHorizontal = SceneSave.AsBool(subElement);
// break;
// case "FlipVertical":
// toReturn.FlipVertical = SceneSave.AsBool(subElement);
// break;
// case "TextureName":
// toReturn.TextureName = subElement.Value;
// break;
// case "FrameLength":
// toReturn.FrameLength = SceneSave.AsFloat(subElement);
// break;
// case "LeftCoordinate":
// toReturn.LeftCoordinate = SceneSave.AsFloat(subElement);
// break;
// case "RightCoordinate":
// toReturn.RightCoordinate = SceneSave.AsFloat(subElement);
// break;
// case "TopCoordinate":
// toReturn.TopCoordinate = SceneSave.AsFloat(subElement);
// break;
// case "BottomCoordinate":
// toReturn.BottomCoordinate = SceneSave.AsFloat(subElement);
// break;
// case "RelativeX":
// toReturn.RelativeX = SceneSave.AsFloat(subElement);
// break;
// case "RelativeY":
// toReturn.RelativeY = SceneSave.AsFloat(subElement);
// break;
// }
// }
// return toReturn;
//}
}
}
| |
/*
* Copyright (c) 2007, Second Life Reverse Engineering Team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using libsecondlife.StructuredData;
namespace libsecondlife.Capabilities
{
public class CapsClient
{
public delegate void ProgressCallback(CapsClient client, long bytesReceived, long bytesSent,
long totalBytesToReceive, long totalBytesToSend);
public delegate void CompleteCallback(CapsClient client, LLSD result, Exception error);
public ProgressCallback OnProgress;
public CompleteCallback OnComplete;
public IWebProxy Proxy;
public object UserData;
protected CapsBase _Client;
protected byte[] _PostData;
protected string _ContentType;
public CapsClient(Uri capability)
{
_Client = new CapsBase(capability);
_Client.DownloadProgressChanged += new CapsBase.DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
_Client.UploadProgressChanged += new CapsBase.UploadProgressChangedEventHandler(Client_UploadProgressChanged);
_Client.UploadDataCompleted += new CapsBase.UploadDataCompletedEventHandler(Client_UploadDataCompleted);
_Client.DownloadStringCompleted += new CapsBase.DownloadStringCompletedEventHandler(Client_DownloadStringCompleted);
}
public void StartRequest()
{
StartRequest(null, null);
}
public void StartRequest(LLSD llsd)
{
byte[] postData = LLSDParser.SerializeXmlBytes(llsd);
StartRequest(postData, null);
}
public void StartRequest(byte[] postData)
{
StartRequest(postData, null);
}
public void StartRequest(byte[] postData, string contentType)
{
_PostData = postData;
_ContentType = contentType;
if (_Client.IsBusy)
{
Logger.Log("New CAPS request to " + _Client.Location +
" initiated, closing previous request", Helpers.LogLevel.Warning);
_Client.CancelAsync();
}
else
{
Logger.DebugLog("New CAPS request to " + _Client.Location + " initiated");
}
// Proxy
if (Proxy != null)
_Client.Proxy = Proxy;
// Content-Type
_Client.Headers.Clear();
if (!String.IsNullOrEmpty(contentType))
_Client.Headers.Add(HttpRequestHeader.ContentType, contentType);
else
_Client.Headers.Add(HttpRequestHeader.ContentType, "application/xml");
if (postData == null)
_Client.DownloadStringAsync(_Client.Location);
else
_Client.UploadDataAsync(_Client.Location, postData);
}
public void Cancel()
{
if (_Client.IsBusy)
_Client.CancelAsync();
}
#region Callback Handlers
private void Client_DownloadProgressChanged(object sender, CapsBase.DownloadProgressChangedEventArgs e)
{
if (OnProgress != null)
{
try { OnProgress(this, e.BytesReceived, 0, e.TotalBytesToReceive, 0); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
private void Client_UploadProgressChanged(object sender, CapsBase.UploadProgressChangedEventArgs e)
{
if (OnProgress != null)
{
try { OnProgress(this, e.BytesReceived, e.BytesSent, e.TotalBytesToReceive, e.TotalBytesToSend); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
private void Client_UploadDataCompleted(object sender, CapsBase.UploadDataCompletedEventArgs e)
{
if (OnComplete != null && !e.Cancelled)
{
if (e.Error == null)
{
LLSD result = LLSDParser.DeserializeXml(e.Result);
try { OnComplete(this, result, e.Error); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
else
{
if (Helpers.StringContains(e.Error.Message, "502"))
{
// These are normal, retry the request automatically
Logger.DebugLog("502 error from capability " + _Client.Location);
StartRequest(_PostData, _ContentType);
}
else
{
Logger.DebugLog(String.Format("Caps error at {0}: {1}", _Client.Location, e.Error.Message));
try { OnComplete(this, null, e.Error); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
}
else if (e.Cancelled)
{
Logger.DebugLog("Capability action at " + _Client.Location + " cancelled");
}
}
private void Client_DownloadStringCompleted(object sender, CapsBase.DownloadStringCompletedEventArgs e)
{
if (OnComplete != null && !e.Cancelled)
{
if (e.Error == null)
{
LLSD result = LLSDParser.DeserializeXml(e.Result);
try { OnComplete(this, result, e.Error); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
else
{
if (Helpers.StringContains(e.Error.Message, "502"))
{
// These are normal, retry the request automatically
Logger.DebugLog("502 error from capability " + _Client.Location);
StartRequest(_PostData, _ContentType);
}
else
{
try { OnComplete(this, null, e.Error); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
}
else if (e.Cancelled)
{
Logger.DebugLog("Capability action at " + _Client.Location + " cancelled");
}
}
#endregion Callback Handlers
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractInt32129()
{
var test = new SimpleUnaryOpTest__ExtractInt32129();
try
{
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
}
catch (PlatformNotSupportedException)
{
test.Succeeded = true;
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ExtractInt32129
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static SimpleUnaryOpTest__ExtractInt32129()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ExtractInt32129()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.Extract(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.Extract(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.Extract(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.Extract(
_clsVar,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ExtractInt32129();
var result = Sse41.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.Extract(_fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
if ((result[0] != firstOp[1]))
{
Succeeded = false;
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Int32>(Vector128<Int32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// SynchronizedCollection.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
namespace System.Collections.Generic
{
[ComVisibleAttribute (false)]
internal class SynchronizedCollection<T> : IList<T>, ICollection<T>,
IEnumerable<T>, IList, ICollection, IEnumerable
{
object root;
List<T> list;
public SynchronizedCollection ()
: this (new object (), null, false)
{
}
public SynchronizedCollection (object syncRoot)
: this (syncRoot, null, false)
{
}
public SynchronizedCollection (object syncRoot,
IEnumerable<T> list)
: this (syncRoot, new List<T> (list), false)
{
}
public SynchronizedCollection (object syncRoot,
params T [] list)
: this (syncRoot, new List<T> (list), false)
{
}
public SynchronizedCollection (object syncRoot,
List<T> list, bool makeCopy)
{
if (syncRoot == null)
syncRoot = new object ();
root = syncRoot;
if (list == null)
this.list = new List<T> ();
else if (makeCopy)
this.list = new List<T> (list);
else
this.list = list;
}
public int Count {
get {
lock (root) {
return list.Count;
}
}
}
public T this [int index] {
get {
lock (root) {
return list [index];
}
}
set {
SetItem (index, value);
}
}
public object SyncRoot {
get { return root; }
}
protected List<T> Items {
get { return list; }
}
public void Add (T item)
{
InsertItem (list.Count, item);
}
public void Clear ()
{
ClearItems ();
}
public bool Contains (T item)
{
lock (root) {
return list.Contains (item);
}
}
public void CopyTo (T [] array, int index)
{
lock (root) {
list.CopyTo (array, index);
}
}
public IEnumerator<T> GetEnumerator ()
{
lock (root) {
return list.GetEnumerator ();
}
}
public int IndexOf (T item)
{
lock (root) {
return list.IndexOf (item);
}
}
public void Insert (int index, T item)
{
InsertItem (index, item);
}
public bool Remove (T item)
{
int index = IndexOf (item);
if (index < 0)
return false;
RemoveAt (index);
return true;
}
public void RemoveAt (int index)
{
RemoveItem (index);
}
protected virtual void ClearItems ()
{
lock (root) {
list.Clear ();
}
}
protected virtual void InsertItem (int index, T item)
{
lock (root) {
list.Insert (index, item);
}
}
protected virtual void RemoveItem (int index)
{
lock (root) {
list.RemoveAt (index);
}
}
protected virtual void SetItem (int index, T item)
{
lock (root) {
list [index] = item;
}
}
#region Explicit interface implementations
void ICollection.CopyTo (Array array, int index)
{
CopyTo ((T []) array, index);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
int IList.Add (object value)
{
lock (root) {
Add ((T) value);
return list.Count - 1;
}
}
bool IList.Contains (object value)
{
return Contains ((T) value);
}
int IList.IndexOf (object value)
{
return IndexOf ((T) value);
}
void IList.Insert (int index, object value)
{
Insert (index, (T) value);
}
void IList.Remove (object value)
{
Remove ((T) value);
}
bool ICollection<T>.IsReadOnly {
get { return false; }
}
bool ICollection.IsSynchronized {
get { return true; }
}
object ICollection.SyncRoot {
get { return root; }
}
bool IList.IsFixedSize {
get { return false; }
}
bool IList.IsReadOnly {
get { return false; }
}
object IList.this [int index] {
get { return this [index]; }
set { this [index] = (T) value; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class Node
{
public static PersonNode Person { get { return new PersonNode(); } }
}
public partial class PersonNode : Blueprint41.Query.Node
{
protected override string GetNeo4jLabel()
{
return "Person";
}
internal PersonNode() { }
internal PersonNode(PersonAlias alias, bool isReference = false)
{
NodeAlias = alias;
IsReference = isReference;
}
internal PersonNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { }
public PersonNode Alias(out PersonAlias alias)
{
alias = new PersonAlias(this);
NodeAlias = alias;
return this;
}
public PersonNode UseExistingAlias(AliasResult alias)
{
NodeAlias = alias;
return this;
}
public PersonIn In { get { return new PersonIn(this); } }
public class PersonIn
{
private PersonNode Parent;
internal PersonIn(PersonNode parent)
{
Parent = parent;
}
public IFromIn_PERSON_BECOMES_EMPLOYEE_REL PERSON_BECOMES_EMPLOYEE { get { return new PERSON_BECOMES_EMPLOYEE_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_HAS_ADDRESS_REL PERSON_HAS_ADDRESS { get { return new PERSON_HAS_ADDRESS_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_HAS_CONTACTTYPE_REL PERSON_HAS_CONTACTTYPE { get { return new PERSON_HAS_CONTACTTYPE_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_HAS_EMAILADDRESS_REL PERSON_HAS_EMAILADDRESS { get { return new PERSON_HAS_EMAILADDRESS_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_HAS_PASSWORD_REL PERSON_HAS_PASSWORD { get { return new PERSON_HAS_PASSWORD_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_HAS_PHONENUMBERTYPE_REL PERSON_HAS_PHONENUMBERTYPE { get { return new PERSON_HAS_PHONENUMBERTYPE_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_VALID_FOR_CREDITCARD_REL PERSON_VALID_FOR_CREDITCARD { get { return new PERSON_VALID_FOR_CREDITCARD_REL(Parent, DirectionEnum.In); } }
public IFromIn_PERSON_VALID_FOR_DOCUMENT_REL PERSON_VALID_FOR_DOCUMENT { get { return new PERSON_VALID_FOR_DOCUMENT_REL(Parent, DirectionEnum.In); } }
}
public PersonOut Out { get { return new PersonOut(this); } }
public class PersonOut
{
private PersonNode Parent;
internal PersonOut(PersonNode parent)
{
Parent = parent;
}
public IFromOut_CUSTOMER_HAS_PERSON_REL CUSTOMER_HAS_PERSON { get { return new CUSTOMER_HAS_PERSON_REL(Parent, DirectionEnum.Out); } }
public IFromOut_SALESPERSON_IS_PERSON_REL SALESPERSON_IS_PERSON { get { return new SALESPERSON_IS_PERSON_REL(Parent, DirectionEnum.Out); } }
}
}
public class PersonAlias : AliasResult
{
internal PersonAlias(PersonNode parent)
{
Node = parent;
}
public override IReadOnlyDictionary<string, FieldResult> AliasFields
{
get
{
if (m_AliasFields == null)
{
m_AliasFields = new Dictionary<string, FieldResult>()
{
{ "PersonType", new NumericResult(this, "PersonType", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["PersonType"]) },
{ "NameStyle", new StringResult(this, "NameStyle", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["NameStyle"]) },
{ "Title", new StringResult(this, "Title", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["Title"]) },
{ "FirstName", new StringResult(this, "FirstName", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["FirstName"]) },
{ "MiddleName", new StringResult(this, "MiddleName", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["MiddleName"]) },
{ "LastName", new StringResult(this, "LastName", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["LastName"]) },
{ "Suffix", new StringResult(this, "Suffix", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["Suffix"]) },
{ "EmailPromotion", new StringResult(this, "EmailPromotion", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["EmailPromotion"]) },
{ "AdditionalContactInfo", new StringResult(this, "AdditionalContactInfo", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["AdditionalContactInfo"]) },
{ "Demographics", new StringResult(this, "Demographics", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["Demographics"]) },
{ "rowguid", new StringResult(this, "rowguid", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Person"].Properties["rowguid"]) },
{ "ModifiedDate", new DateTimeResult(this, "ModifiedDate", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]) },
{ "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["Person"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) },
};
}
return m_AliasFields;
}
}
private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null;
public PersonNode.PersonIn In { get { return new PersonNode.PersonIn(new PersonNode(this, true)); } }
public PersonNode.PersonOut Out { get { return new PersonNode.PersonOut(new PersonNode(this, true)); } }
public NumericResult PersonType
{
get
{
if ((object)m_PersonType == null)
m_PersonType = (NumericResult)AliasFields["PersonType"];
return m_PersonType;
}
}
private NumericResult m_PersonType = null;
public StringResult NameStyle
{
get
{
if ((object)m_NameStyle == null)
m_NameStyle = (StringResult)AliasFields["NameStyle"];
return m_NameStyle;
}
}
private StringResult m_NameStyle = null;
public StringResult Title
{
get
{
if ((object)m_Title == null)
m_Title = (StringResult)AliasFields["Title"];
return m_Title;
}
}
private StringResult m_Title = null;
public StringResult FirstName
{
get
{
if ((object)m_FirstName == null)
m_FirstName = (StringResult)AliasFields["FirstName"];
return m_FirstName;
}
}
private StringResult m_FirstName = null;
public StringResult MiddleName
{
get
{
if ((object)m_MiddleName == null)
m_MiddleName = (StringResult)AliasFields["MiddleName"];
return m_MiddleName;
}
}
private StringResult m_MiddleName = null;
public StringResult LastName
{
get
{
if ((object)m_LastName == null)
m_LastName = (StringResult)AliasFields["LastName"];
return m_LastName;
}
}
private StringResult m_LastName = null;
public StringResult Suffix
{
get
{
if ((object)m_Suffix == null)
m_Suffix = (StringResult)AliasFields["Suffix"];
return m_Suffix;
}
}
private StringResult m_Suffix = null;
public StringResult EmailPromotion
{
get
{
if ((object)m_EmailPromotion == null)
m_EmailPromotion = (StringResult)AliasFields["EmailPromotion"];
return m_EmailPromotion;
}
}
private StringResult m_EmailPromotion = null;
public StringResult AdditionalContactInfo
{
get
{
if ((object)m_AdditionalContactInfo == null)
m_AdditionalContactInfo = (StringResult)AliasFields["AdditionalContactInfo"];
return m_AdditionalContactInfo;
}
}
private StringResult m_AdditionalContactInfo = null;
public StringResult Demographics
{
get
{
if ((object)m_Demographics == null)
m_Demographics = (StringResult)AliasFields["Demographics"];
return m_Demographics;
}
}
private StringResult m_Demographics = null;
public StringResult rowguid
{
get
{
if ((object)m_rowguid == null)
m_rowguid = (StringResult)AliasFields["rowguid"];
return m_rowguid;
}
}
private StringResult m_rowguid = null;
public DateTimeResult ModifiedDate
{
get
{
if ((object)m_ModifiedDate == null)
m_ModifiedDate = (DateTimeResult)AliasFields["ModifiedDate"];
return m_ModifiedDate;
}
}
private DateTimeResult m_ModifiedDate = null;
public StringResult Uid
{
get
{
if ((object)m_Uid == null)
m_Uid = (StringResult)AliasFields["Uid"];
return m_Uid;
}
}
private StringResult m_Uid = null;
}
}
| |
//
// PlaybackControllerService.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Hyena;
using Hyena.Collections;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.MediaEngine;
namespace Banshee.PlaybackController
{
public class PlaybackControllerService : IRequiredService, ICanonicalPlaybackController,
IPlaybackController, IPlaybackControllerService
{
private enum Direction
{
Next,
Previous
}
private IStackProvider<TrackInfo> previous_stack;
private IStackProvider<TrackInfo> next_stack;
private TrackInfo current_track;
private TrackInfo prior_track;
private TrackInfo changing_to_track;
private bool raise_started_after_transition = false;
private bool transition_track_started = false;
private bool last_was_skipped = true;
private int consecutive_errors;
private uint error_transition_id;
private DateTime source_auto_set_at = DateTime.MinValue;
private string shuffle_mode;
private PlaybackRepeatMode repeat_mode;
private bool stop_when_finished = false;
private PlayerEngineService player_engine;
private ITrackModelSource source;
private ITrackModelSource next_source;
private event PlaybackControllerStoppedHandler dbus_stopped;
event PlaybackControllerStoppedHandler IPlaybackControllerService.Stopped {
add { dbus_stopped += value; }
remove { dbus_stopped -= value; }
}
public event EventHandler Stopped;
public event EventHandler SourceChanged;
public event EventHandler NextSourceChanged;
public event EventHandler TrackStarted;
public event EventHandler Transition;
public event EventHandler<EventArgs<string>> ShuffleModeChanged;
public event EventHandler<EventArgs<PlaybackRepeatMode>> RepeatModeChanged;
public PlaybackControllerService ()
{
InstantiateStacks ();
player_engine = ServiceManager.PlayerEngine;
player_engine.PlayWhenIdleRequest += OnPlayerEnginePlayWhenIdleRequest;
player_engine.ConnectEvent (OnPlayerEvent,
PlayerEvent.RequestNextTrack |
PlayerEvent.EndOfStream |
PlayerEvent.StartOfStream |
PlayerEvent.StateChange |
PlayerEvent.Error,
true);
ServiceManager.SourceManager.ActiveSourceChanged += delegate {
ITrackModelSource active_source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource;
if (active_source != null && source_auto_set_at == source_set_at && !player_engine.IsPlaying ()) {
Source = active_source;
source_auto_set_at = source_set_at;
}
};
}
protected virtual void InstantiateStacks ()
{
previous_stack = new PlaybackControllerDatabaseStack ();
next_stack = new PlaybackControllerDatabaseStack ();
}
private void OnPlayerEnginePlayWhenIdleRequest (object o, EventArgs args)
{
ITrackModelSource next_source = NextSource;
if (next_source != null && next_source.TrackModel.Selection.Count > 0) {
Source = NextSource;
CancelErrorTransition ();
CurrentTrack = next_source.TrackModel[next_source.TrackModel.Selection.FirstIndex];
QueuePlayTrack ();
} else {
Next ();
}
}
private void OnPlayerEvent (PlayerEventArgs args)
{
switch (args.Event) {
case PlayerEvent.StartOfStream:
CurrentTrack = player_engine.CurrentTrack;
consecutive_errors = 0;
break;
case PlayerEvent.EndOfStream:
EosTransition ();
break;
case PlayerEvent.Error:
if (++consecutive_errors >= 5) {
consecutive_errors = 0;
player_engine.Close (false);
OnStopped ();
break;
}
CancelErrorTransition ();
// TODO why is this so long? any reason not to be instantaneous?
error_transition_id = Application.RunTimeout (250, delegate {
EosTransition ();
RequestTrackHandler ();
return true;
});
break;
case PlayerEvent.StateChange:
if (((PlayerEventStateChangeArgs)args).Current != PlayerState.Loading) {
break;
}
TrackInfo track = player_engine.CurrentTrack;
if (changing_to_track != track && track != null) {
CurrentTrack = track;
}
changing_to_track = null;
if (!raise_started_after_transition) {
transition_track_started = false;
OnTrackStarted ();
} else {
transition_track_started = true;
}
break;
case PlayerEvent.RequestNextTrack:
RequestTrackHandler ();
break;
}
}
private void CancelErrorTransition ()
{
if (error_transition_id > 0) {
Application.IdleTimeoutRemove (error_transition_id);
error_transition_id = 0;
}
}
private bool EosTransition ()
{
player_engine.IncrementLastPlayed ();
return true;
}
private bool RequestTrackHandler ()
{
if (!StopWhenFinished) {
if (RepeatMode == PlaybackRepeatMode.RepeatSingle) {
RepeatCurrentAsNext ();
} else {
last_was_skipped = false;
Next (RepeatMode == PlaybackRepeatMode.RepeatAll, false);
}
} else {
OnStopped ();
}
StopWhenFinished = false;
return false;
}
private void RepeatCurrentAsNext ()
{
raise_started_after_transition = true;
player_engine.SetNextTrack (CurrentTrack);
OnTransition ();
}
public void First ()
{
CancelErrorTransition ();
Source = NextSource;
// This and OnTransition() below commented out b/c of BGO #524556
//raise_started_after_transition = true;
if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).First ()) {
} else {
((IBasicPlaybackController)this).First ();
}
//OnTransition ();
}
public void Next ()
{
Next (RepeatMode == PlaybackRepeatMode.RepeatAll, true);
}
public void Next (bool restart)
{
Next (restart, true);
}
public void Next (bool restart, bool changeImmediately)
{
CancelErrorTransition ();
Source = NextSource;
raise_started_after_transition = true;
if (changeImmediately) {
player_engine.IncrementLastPlayed ();
}
if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).Next (restart, changeImmediately)) {
} else {
((IBasicPlaybackController)this).Next (restart, changeImmediately);
}
OnTransition ();
}
public void Previous ()
{
Previous (RepeatMode == PlaybackRepeatMode.RepeatAll);
}
public void Previous (bool restart)
{
CancelErrorTransition ();
Source = NextSource;
raise_started_after_transition = true;
player_engine.IncrementLastPlayed ();
if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).Previous (restart)) {
} else {
((IBasicPlaybackController)this).Previous (restart);
}
OnTransition ();
}
public void RestartOrPrevious ()
{
RestartOrPrevious (RepeatMode == PlaybackRepeatMode.RepeatAll);
}
public void RestartOrPrevious (bool restart)
{
const int delay = 4000; // ms
if (player_engine.CanSeek && player_engine.Position > delay) {
Restart ();
} else {
Previous ();
}
}
public void Restart ()
{
player_engine.RestartCurrentTrack ();
}
bool IBasicPlaybackController.First ()
{
if (Source.Count > 0) {
if (ShuffleMode == "off") {
CurrentTrack = Source.TrackModel[0];
player_engine.OpenPlay (CurrentTrack);
} else {
((IBasicPlaybackController)this).Next (false, true);
}
}
return true;
}
bool IBasicPlaybackController.Next (bool restart, bool changeImmediately)
{
if (CurrentTrack != null) {
previous_stack.Push (CurrentTrack);
}
CurrentTrack = CalcNextTrack (Direction.Next, restart);
if (!changeImmediately) {
// A RequestNextTrack event should always result in SetNextTrack being called. null is acceptable.
player_engine.SetNextTrack (CurrentTrack);
} else if (CurrentTrack != null) {
QueuePlayTrack ();
}
return true;
}
bool IBasicPlaybackController.Previous (bool restart)
{
if (CurrentTrack != null && previous_stack.Count > 0) {
next_stack.Push (current_track);
}
CurrentTrack = CalcNextTrack (Direction.Previous, restart);
if (CurrentTrack != null) {
QueuePlayTrack ();
}
return true;
}
private TrackInfo CalcNextTrack (Direction direction, bool restart)
{
if (direction == Direction.Previous) {
if (previous_stack.Count > 0) {
return previous_stack.Pop ();
}
} else if (direction == Direction.Next) {
if (next_stack.Count > 0) {
return next_stack.Pop ();
}
}
return QueryTrack (direction, restart);
}
private TrackInfo QueryTrack (Direction direction, bool restart)
{
Log.DebugFormat ("Querying model for track to play in {0}:{1} mode", ShuffleMode, direction);
return ShuffleMode == "off"
? QueryTrackLinear (direction, restart)
: QueryTrackRandom (ShuffleMode, restart);
}
private TrackInfo QueryTrackLinear (Direction direction, bool restart)
{
if (Source.TrackModel.Count == 0)
return null;
int index = Source.TrackModel.IndexOf (PriorTrack);
// Clear the PriorTrack after using it, it's only meant to be used for a single Query
PriorTrack = null;
if (index == -1) {
return Source.TrackModel[0];
} else {
index += (direction == Direction.Next ? 1 : -1);
if (index >= 0 && index < Source.TrackModel.Count) {
return Source.TrackModel[index];
} else if (!restart) {
return null;
} else if (index < 0) {
return Source.TrackModel[Source.TrackModel.Count - 1];
} else {
return Source.TrackModel[0];
}
}
}
private TrackInfo QueryTrackRandom (string shuffle_mode, bool restart)
{
var track_shuffler = Source.TrackModel as Banshee.Collection.Database.DatabaseTrackListModel;
TrackInfo track = track_shuffler == null
? Source.TrackModel.GetRandom (source_set_at)
: track_shuffler.GetRandom (source_set_at, shuffle_mode, restart, last_was_skipped, Banshee.Collection.Database.Shuffler.Playback);
// Reset to default of true, only ever set to false by EosTransition
last_was_skipped = true;
return track;
}
private void QueuePlayTrack ()
{
changing_to_track = CurrentTrack;
player_engine.OpenPlay (CurrentTrack);
}
protected virtual void OnStopped ()
{
player_engine.IncrementLastPlayed ();
EventHandler handler = Stopped;
if (handler != null) {
handler (this, EventArgs.Empty);
}
PlaybackControllerStoppedHandler dbus_handler = dbus_stopped;
if (dbus_handler != null) {
dbus_handler ();
}
}
protected virtual void OnTransition ()
{
EventHandler handler = Transition;
if (handler != null) {
handler (this, EventArgs.Empty);
}
if (raise_started_after_transition && transition_track_started) {
OnTrackStarted ();
}
raise_started_after_transition = false;
transition_track_started = false;
}
protected virtual void OnSourceChanged ()
{
EventHandler handler = SourceChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected void OnNextSourceChanged ()
{
EventHandler handler = NextSourceChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnTrackStarted ()
{
EventHandler handler = TrackStarted;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
public TrackInfo CurrentTrack {
get { return current_track; }
protected set { current_track = value; }
}
public TrackInfo PriorTrack {
get { return prior_track ?? CurrentTrack; }
set { prior_track = value; }
}
protected DateTime source_set_at = DateTime.MinValue;
public ITrackModelSource Source {
get {
if (source == null && ServiceManager.SourceManager.DefaultSource is ITrackModelSource) {
return (ITrackModelSource)ServiceManager.SourceManager.DefaultSource;
}
return source;
}
set {
if (source != value) {
NextSource = value;
source = value;
source_set_at = DateTime.Now;
OnSourceChanged ();
}
}
}
public ITrackModelSource NextSource {
get { return next_source ?? Source; }
set {
if (next_source != value) {
next_source = value;
OnNextSourceChanged ();
if (!player_engine.IsPlaying ()) {
Source = next_source;
}
}
}
}
public string ShuffleMode {
get { return shuffle_mode; }
set {
shuffle_mode = value;
// If the user changes the shuffle mode, she expects the "Next"
// button to behave according to the new selection. See bgo#528809
next_stack.Clear ();
var handler = ShuffleModeChanged;
if (handler != null) {
handler (this, new EventArgs<string> (shuffle_mode));
}
}
}
string prev_shuffle;
public void ToggleShuffle ()
{
if (ShuffleMode == "off") {
ShuffleMode = prev_shuffle ?? "song";
} else {
prev_shuffle = ShuffleMode;
ShuffleMode = "off";
}
}
public PlaybackRepeatMode RepeatMode {
get { return repeat_mode; }
set {
repeat_mode = value;
EventHandler<EventArgs<PlaybackRepeatMode>> handler = RepeatModeChanged;
if (handler != null) {
handler (this, new EventArgs<PlaybackRepeatMode> (repeat_mode));
}
}
}
PlaybackRepeatMode? prev_repeat;
public void ToggleRepeat ()
{
if (RepeatMode == PlaybackRepeatMode.None) {
RepeatMode = prev_repeat != null ? prev_repeat.Value : PlaybackRepeatMode.RepeatAll;
} else {
prev_repeat = RepeatMode;
RepeatMode = PlaybackRepeatMode.None;
}
}
public bool StopWhenFinished {
get { return stop_when_finished; }
set { stop_when_finished = value; }
}
string IService.ServiceName {
get { return "PlaybackController"; }
}
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
}
}
| |
using System.Text.RegularExpressions;
namespace Sharpen
{
using System;
using System.Globalization;
public class SimpleDateFormat : DateFormat
{
private const string FIELD_YEAR = "year";
private const string FIELD_MONTH = "month";
private const string FIELD_DAY = "day";
private const string FIELD_HOUR = "hour";
private const string FIELD_MINUTE = "minute";
private const string FIELD_SECOND = "second";
string format;
CultureInfo Culture {
get; set;
}
public SimpleDateFormat (): this ("g")
{
}
public SimpleDateFormat (string format): this (format, CultureInfo.CurrentCulture)
{
}
public SimpleDateFormat (string format, CultureInfo c)
{
Culture = c;
this.format = format.Replace ("EEE", "ddd");
this.format = this.format.Replace ("Z", "zzz");
SetTimeZone (TimeZoneInfo.Local);
}
public override DateTime Parse (string value)
{
DateTime? result;
if (TryDateTimeParse(value, out result))
{
return result.Value;
}
try
{
return DateTime.ParseExact(value, format, Culture);
}
catch (Exception ex)
{
throw new ParseException();
}
}
public override string Format (DateTime date)
{
date += GetTimeZone().BaseUtcOffset;
return date.ToString (format);
}
public string Format (long date)
{
return Extensions.MillisToDateTimeOffset (date, (int)GetTimeZone ().BaseUtcOffset.TotalMinutes).DateTime.ToString (format);
}
private bool TryDateTimeParse(string value, out DateTime? result)
{
var formatParts = GetParsedFormat();
if (formatParts.Length == 0)
{
result = null;
return false;
}
var parser = BuildDateTimeParser(formatParts);
try
{
var parseResult = parser.Matches(value);
if (parseResult.Count == 0)
{
result = null;
return false;
}
result = ConvertResult(parseResult[0]);
return true;
}
catch
{
}
result = null;
return false;
}
private string[] GetParsedFormat()
{
var r = new Regex("(yyyy|MM|dd|HH|mm|ss)");
return r.Split(format);
}
private Regex BuildDateTimeParser(string[] formatParts)
{
string pattern = "";
foreach (var formatPart in formatParts)
{
if (string.IsNullOrEmpty(formatPart))
{
continue;
}
if (formatPart.Equals("yyyy"))
{
pattern += string.Format("(?<{0}>\\d{{4}})", FIELD_YEAR);
continue;
}
if (formatPart.Equals("MM"))
{
pattern += string.Format("(?<{0}>\\d{{2}})", FIELD_MONTH);
continue;
}
if (formatPart.Equals("dd"))
{
pattern += string.Format("(?<{0}>\\d{{2}})", FIELD_DAY);
continue;
}
if (formatPart.Equals("HH"))
{
pattern += string.Format("(?<{0}>\\d{{2}})", FIELD_HOUR);
continue;
}
if (formatPart.Equals("mm"))
{
pattern += string.Format("(?<{0}>\\d{{2}})", FIELD_MINUTE);
continue;
}
if (formatPart.Equals("ss"))
{
pattern += string.Format("(?<{0}>\\d{{2}})", FIELD_SECOND);
continue;
}
if (string.IsNullOrWhiteSpace(formatPart))
{
pattern += string.Format("\\s{{{0}}}", formatPart.Length);
continue;
}
pattern += formatPart;
}
return new Regex(pattern);
}
private DateTime ConvertResult(Match data)
{
Calendar result = Calendar.GetInstance(Culture);
if (data.Groups[FIELD_YEAR].Success)
{
result.Set(CalendarEnum.Year, int.Parse(data.Groups[FIELD_YEAR].Value));
}
else
{
result.Set(CalendarEnum.Year, 1);
}
if (data.Groups[FIELD_MONTH].Success)
{
result.Set(CalendarEnum.MonthOneBased, int.Parse(data.Groups[FIELD_MONTH].Value));
}
else
{
result.Set(CalendarEnum.MonthOneBased, 1);
}
if (data.Groups[FIELD_DAY].Success)
{
result.Set(CalendarEnum.DayOfMonth, int.Parse(data.Groups[FIELD_DAY].Value));
}
else
{
result.Set(CalendarEnum.DayOfMonth, 0);
}
if (data.Groups[FIELD_HOUR].Success)
{
result.Set(CalendarEnum.HourOfDay, int.Parse(data.Groups[FIELD_HOUR].Value));
}
else
{
result.Set(CalendarEnum.HourOfDay, 0);
}
if (data.Groups[FIELD_MINUTE].Success)
{
result.Set(CalendarEnum.Minute, int.Parse(data.Groups[FIELD_MINUTE].Value));
}
else
{
result.Set(CalendarEnum.Minute, 0);
}
if (data.Groups[FIELD_SECOND].Success)
{
result.Set(CalendarEnum.Second, int.Parse(data.Groups[FIELD_SECOND].Value));
}
else
{
result.Set(CalendarEnum.Second, 0);
}
result.Set(CalendarEnum.Millisecond, 0);
return result.GetTime();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.