context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A user of the system
/// First published in XenServer 4.0.
/// </summary>
public partial class User : XenObject<User>
{
public User()
{
}
public User(string uuid,
string short_name,
string fullname,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.short_name = short_name;
this.fullname = fullname;
this.other_config = other_config;
}
/// <summary>
/// Creates a new User from a Proxy_User.
/// </summary>
/// <param name="proxy"></param>
public User(Proxy_User proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given User.
/// </summary>
public override void UpdateFrom(User update)
{
uuid = update.uuid;
short_name = update.short_name;
fullname = update.fullname;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_User proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
short_name = proxy.short_name == null ? null : (string)proxy.short_name;
fullname = proxy.fullname == null ? null : (string)proxy.fullname;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_User ToProxy()
{
Proxy_User result_ = new Proxy_User();
result_.uuid = uuid ?? "";
result_.short_name = short_name ?? "";
result_.fullname = fullname ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new User from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public User(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this User
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("short_name"))
short_name = Marshalling.ParseString(table, "short_name");
if (table.ContainsKey("fullname"))
fullname = Marshalling.ParseString(table, "fullname");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._short_name, other._short_name) &&
Helper.AreEqual2(this._fullname, other._fullname) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<User> ProxyArrayToObjectList(Proxy_User[] input)
{
var result = new List<User>();
foreach (var item in input)
result.Add(new User(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, User server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_fullname, server._fullname))
{
User.set_fullname(session, opaqueRef, _fullname);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
User.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given user.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static User get_record(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_record(session.opaque_ref, _user);
else
return new User((Proxy_User)session.proxy.user_get_record(session.opaque_ref, _user ?? "").parse());
}
/// <summary>
/// Get a reference to the user instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<User>.Create(session.proxy.user_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> create(Session session, User _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_create(session.opaque_ref, _record);
else
return XenRef<User>.Create(session.proxy.user_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_create(Session session, User _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_user_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_user_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static void destroy(Session session, string _user)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_destroy(session.opaque_ref, _user);
else
session.proxy.user_destroy(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_destroy(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_user_destroy(session.opaque_ref, _user);
else
return XenRef<Task>.Create(session.proxy.async_user_destroy(session.opaque_ref, _user ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_uuid(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_uuid(session.opaque_ref, _user);
else
return (string)session.proxy.user_get_uuid(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Get the short_name field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_short_name(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_short_name(session.opaque_ref, _user);
else
return (string)session.proxy.user_get_short_name(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Get the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_fullname(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_fullname(session.opaque_ref, _user);
else
return (string)session.proxy.user_get_fullname(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static Dictionary<string, string> get_other_config(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_other_config(session.opaque_ref, _user);
else
return Maps.convert_from_proxy_string_string(session.proxy.user_get_other_config(session.opaque_ref, _user ?? "").parse());
}
/// <summary>
/// Set the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_fullname">New value to set</param>
public static void set_fullname(Session session, string _user, string _fullname)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_set_fullname(session.opaque_ref, _user, _fullname);
else
session.proxy.user_set_fullname(session.opaque_ref, _user ?? "", _fullname ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _user, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_set_other_config(session.opaque_ref, _user, _other_config);
else
session.proxy.user_set_other_config(session.opaque_ref, _user ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _user, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_add_to_other_config(session.opaque_ref, _user, _key, _value);
else
session.proxy.user_add_to_other_config(session.opaque_ref, _user ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given user. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _user, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_remove_from_other_config(session.opaque_ref, _user, _key);
else
session.proxy.user_remove_from_other_config(session.opaque_ref, _user ?? "", _key ?? "").parse();
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// short name (e.g. userid)
/// </summary>
public virtual string short_name
{
get { return _short_name; }
set
{
if (!Helper.AreEqual(value, _short_name))
{
_short_name = value;
Changed = true;
NotifyPropertyChanged("short_name");
}
}
}
private string _short_name = "";
/// <summary>
/// full name
/// </summary>
public virtual string fullname
{
get { return _fullname; }
set
{
if (!Helper.AreEqual(value, _fullname))
{
_fullname = value;
Changed = true;
NotifyPropertyChanged("fullname");
}
}
}
private string _fullname = "";
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
/* Recording.cs
* Copyright Eddie Cameron 2012 (See readme for licence)
* ----------------------------
* Class for transferring and parsing InputVCR Recordings. Think of it as a VHS cassete, but fancier
*
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using LitJson;
public class Recording
{
public int frameRate;
public List<RecordingFrame> frames = new List<RecordingFrame>();
public int totalFrames{ get{ return frames.Count; } }
public float recordingLength{ get{ return totalFrames / frameRate; } }
public Recording()
{
this.frameRate = 60;
frames = new List<RecordingFrame>();
}
public Recording( int frameRate )
{
this.frameRate = Mathf.Max ( 1, frameRate );
frames = new List<RecordingFrame>();
}
/// <summary>
/// Copies the data in oldRecoding to a new instance of the <see cref="Recording"/> class.
/// </summary>
/// <param name='oldRecording'>
/// Recording to be copied
/// </param>
public Recording( Recording oldRecording )
{
frameRate = oldRecording.frameRate;
frames = new List<RecordingFrame>( oldRecording.frames );
}
/// <summary>
/// Parses a Recording from saved JSON string
/// </summary>
/// <returns>
/// The recording.
/// </returns>
/// <param name='jsonRecording'>
/// JSON recording
/// </param>
public static Recording ParseRecording( string jsonRecording )
{
ImporterFunc<double, float> importer = delegate( double input) {
return (float)input;
};
JsonMapper.RegisterImporter<double, float>( importer ); // let float values be parsed
Recording rec = JsonMapper.ToObject<Recording>( jsonRecording );
JsonMapper.UnregisterImporters ();
return rec;
}
/// <summary>
/// Gets the closest frame index to a provided time
/// </summary>
/// <returns>
/// The closest frame.
/// </returns>
/// <param name='toTime'>
/// To time.
/// </param>/
public int GetClosestFrame( float toTime )
{
return (int)( toTime * frameRate );
}
/// <summary>
/// Adds the supplied input info to given frame
/// </summary>
/// <param name='atFrame'>
/// At frame.
/// </param>
/// <param name='inputInfo'>
/// Input info.
/// </param>
public void AddInput( int atFrame, InputInfo inputInfo )
{
CheckFrame ( atFrame );
for( int i = 0; i < frames[atFrame].inputs.Count; i++ )
{
// no duplicate properties
if ( frames[atFrame].inputs[i].inputName == inputInfo.inputName )
{
frames[atFrame].inputs[i] = new InputInfo( inputInfo );
return;
}
}
frames[atFrame].inputs.Add ( new InputInfo( inputInfo ) );
}
/// <summary>
/// Adds a custom property to a given frame
/// </summary>
/// <param name='atFrame'>
/// At frame.
/// </param>
/// <param name='propertyInfo'>
/// Property info.
/// </param>
public void AddProperty( int atFrame, FrameProperty propertyInfo )
{
CheckFrame( atFrame );
for( int i = 0; i < frames[atFrame].syncedProperties.Count; i++ )
{
// no duplicate properties
if ( frames[atFrame].syncedProperties[i].name == propertyInfo.name )
{
frames[atFrame].syncedProperties[i] = propertyInfo;
return;
}
}
frames[atFrame].syncedProperties.Add ( propertyInfo );
}
/// <summary>
/// Gets the given input at given frame.
/// </summary>
/// <returns>
/// InputInfo
/// </returns>
/// <param name='atFrame'>
/// At frame.
/// </param>
/// <param name='inputName'>
/// Input name.
/// </param>
public InputInfo GetInput( int atFrame, string inputName )
{
if ( atFrame < 0 || atFrame >= frames.Count )
{
Debug.LogWarning ( "Frame " + atFrame + " out of bounds" );
return null;
}
else
{
// iterating to find. Could avoid repeat access time with pre-processing, but would be a waste of memory/GC slowdown? & list is small anyway
foreach( InputInfo input in frames[atFrame].inputs )
if ( input.inputName == inputName )
return input;
}
Debug.LogWarning ( "Input " + inputName + " not found in frame " + atFrame );
return null;
}
/// <summary>
/// Gets all inputs in a given frame.
/// </summary>
/// <returns>
/// The inputs.
/// </returns>
/// <param name='atFrame'>
/// At frame.
/// </param>
public InputInfo[] GetInputs( int atFrame )
{
if ( atFrame < 0 || atFrame >= frames.Count )
{
Debug.LogWarning ( "Frame " + atFrame + " out of bounds" );
return null;
}
else
return frames[atFrame].inputs.ToArray ();
}
/// <summary>
/// Gets the given custom property if recorded in given frame
/// </summary>
/// <returns>
/// The property.
/// </returns>
/// <param name='atFrame'>
/// At frame.
/// </param>
/// <param name='propertyName'>
/// Property name.
/// </param>
public string GetProperty( int atFrame, string propertyName )
{
if ( atFrame < 0 || atFrame >= frames.Count )
{
Debug.LogWarning ( "Frame " + atFrame + " out of bounds" );
return null;
}
else
{
// iterating to find. Could avoid repeat access time with pre-processing, but would be a waste of memory/GC slowdown? & list is small anyway
foreach( FrameProperty prop in frames[atFrame].syncedProperties )
if ( prop.name == propertyName )
return prop.property;
}
return null;
}
// Make sure this frame has an entry
void CheckFrame( int frame )
{
while ( frame >= frames.Count )
frames.Add ( new RecordingFrame() );
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Recording"/> using JSON
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents the current <see cref="Recording"/>.
/// </returns>
public override string ToString()
{
StringBuilder jsonB = new StringBuilder();
JsonWriter writer = new JsonWriter( jsonB );
writer.WriteObjectStart();
//{
writer.WritePropertyName ( "frameRate" );
writer.Write ( frameRate );
writer.WritePropertyName ( "frames" );
writer.WriteArrayStart();
//[
foreach( RecordingFrame frame in frames )
{
writer.WriteObjectStart();
//{
writer.WritePropertyName ( "recordTime" );
writer.Write ( (double)frame.recordTime );
writer.WritePropertyName ( "inputs" );
writer.WriteArrayStart();
//[
foreach( InputInfo input in frame.inputs )
{
writer.WriteObjectStart();
//{
writer.WritePropertyName ( "inputName" );
writer.Write ( input.inputName );
writer.WritePropertyName ( "isAxis" );
writer.Write ( input.isAxis );
writer.WritePropertyName ( "mouseButtonNum" );
writer.Write ( input.mouseButtonNum );
writer.WritePropertyName ( "buttonState" );
writer.Write ( input.buttonState );
writer.WritePropertyName ( "axisValue" );
writer.Write ( input.axisValue );
//}
writer.WriteObjectEnd();
}
//]
writer.WriteArrayEnd ();
writer.WritePropertyName ( "syncedProperties" );
writer.WriteArrayStart ();
//[
foreach( FrameProperty prop in frame.syncedProperties )
{
writer.WriteObjectStart();
//{
writer.WritePropertyName ( "name" );
writer.Write ( prop.name );
writer.WritePropertyName ( "property" );
writer.Write ( prop.property );
//}
writer.WriteObjectEnd ();
}
//]
writer.WriteArrayEnd ();
//}
writer.WriteObjectEnd ();
}
//]
writer.WriteArrayEnd ();
//}
writer.WriteObjectEnd();
return jsonB.ToString();
}
}
public class RecordingFrame
{
public float recordTime;
public List<InputInfo> inputs = new List<InputInfo>();
public List<FrameProperty> syncedProperties = new List<FrameProperty>();
}
[System.Serializable]
public class InputInfo // represents state of certain input in one frame. Has to be class for inspector to serialize
{
public string inputName; // from InputManager
public bool isAxis;
[HideInInspector]
public int mouseButtonNum = -1; // only positive if is mouse button
[HideInInspector]
public bool buttonState;
[HideInInspector]
public float axisValue; // not raw value
public InputInfo()
{
inputName = "";
mouseButtonNum = -1;
isAxis = false;
buttonState = false;
axisValue = 0f;
}
public InputInfo( InputInfo toCopy )
{
inputName = toCopy.inputName;
isAxis = toCopy.isAxis;
mouseButtonNum = toCopy.mouseButtonNum;
buttonState = toCopy.buttonState;
axisValue = toCopy.axisValue;
}
public override bool Equals (object obj)
{
InputInfo other = obj as InputInfo;
return Equals ( other );
}
public bool Equals( InputInfo other )
{
if ( other == null )
return false;
if ( inputName != other.inputName || isAxis != other.isAxis || mouseButtonNum != other.mouseButtonNum )
return false;
if ( isAxis )
return axisValue == other.axisValue;
else
return buttonState == other.buttonState;
}
public override int GetHashCode ()
{
return base.GetHashCode ();
}
}
public struct FrameProperty
{
public string name;
public string property;
public FrameProperty( string name, string property )
{
this.name = name;
this.property = property;
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using System.Linq;
// this assembly attribute allows the dynamic assembly generated for shared and delta
// settings for IDE projects to see the internal classes of the master package assembly
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("IDESharedSettings")]
namespace C
{
/// <summary>
/// Base class for all concrete settings classes. This is tuned towards compilation settings
/// which can be delta'd in project generation.
/// </summary>
abstract class SettingsBase :
Bam.Core.Settings
{
/// <summary>
/// Default constructor
/// </summary>
protected SettingsBase()
{ }
/// <summary>
/// Construct an instance with the given layout
/// </summary>
/// <param name="layout">Layout of switches, inputs and outputs</param>
protected SettingsBase(
Bam.Core.Settings.ELayout layout)
:
base(layout)
{ }
/// <summary>
/// Create a delta settings collection
/// </summary>
/// <param name="sharedSettings">Settings to compare</param>
/// <param name="module">For this module</param>
/// <returns>Delta settings</returns>
public SettingsBase
CreateDeltaSettings(
Bam.Core.Settings sharedSettings,
Bam.Core.Module module)
{
var attributeType = typeof(Bam.Core.SettingsExtensionsAttribute);
var moduleSpecificSettings = System.Activator.CreateInstance(module.Settings.GetType()) as SettingsBase;
moduleSpecificSettings.AssignModule(module);
var sharedInterfaces = sharedSettings.Interfaces();
foreach (var i in module.Settings.Interfaces())
{
var attributeArray = i.GetCustomAttributes(attributeType, false);
if (0 == attributeArray.Length)
{
throw new Bam.Core.Exception(
$"Settings interface {i.ToString()} is missing attribute {attributeType.ToString()}"
);
}
var attribute = attributeArray[0] as Bam.Core.SettingsExtensionsAttribute;
// if we match any of the shared interfaces, get a delta
// otherwise, just clone the interface
if (sharedInterfaces.Any(item => item == i))
{
var deltaMethod = attribute.GetMethod("Delta", new[] { i, i, i });
if (null != deltaMethod)
{
Bam.Core.Log.DebugMessage($"Executing {deltaMethod.Name}");
deltaMethod.Invoke(null, new[] { moduleSpecificSettings, this, sharedSettings });
}
else
{
throw new Bam.Core.Exception(
$"Unable to find method {attribute.ExtensionsClassName}.Delta(this {i.ToString()}, {i.ToString()}, {i.ToString()})"
);
}
}
else
{
var cloneMethod = attribute.GetMethod("Clone", new[] { i, i });
if (null != cloneMethod)
{
Bam.Core.Log.DebugMessage($"Executing {cloneMethod.Name}");
cloneMethod.Invoke(null, new[] { moduleSpecificSettings, this });
}
else
{
throw new Bam.Core.Exception(
$"Unable to find method {attribute.ExtensionsClassName}.Clone(this {i.ToString()}, {i.ToString()})"
);
}
}
}
return moduleSpecificSettings;
}
private static Bam.Core.TypeArray
SharedInterfaces(
System.Collections.Generic.IEnumerable<Bam.Core.Module> objectFiles)
{
System.Collections.Generic.IEnumerable<System.Type> sharedInterfaces = null;
foreach (var input in objectFiles)
{
var interfaces = input.Settings.GetType().GetInterfaces().Where(item => (item != typeof(Bam.Core.ISettingsBase)) && typeof(Bam.Core.ISettingsBase).IsAssignableFrom(item));
if (null == sharedInterfaces)
{
sharedInterfaces = interfaces;
}
else
{
sharedInterfaces = sharedInterfaces.Intersect(interfaces);
}
}
return new Bam.Core.TypeArray(sharedInterfaces.OrderByDescending(item =>
{
var precedenceAttribs = item.GetCustomAttributes(typeof(Bam.Core.SettingsPrecedenceAttribute), false);
if (precedenceAttribs.Length > 0)
{
return (precedenceAttribs[0] as Bam.Core.SettingsPrecedenceAttribute).Order;
}
return 0;
}));
}
/// <summary>
/// Create shared settings for all object files provided
/// </summary>
/// <param name="objectFiles">List of object files to consider</param>
/// <returns>Settings shared by all object files</returns>
public static SettingsBase
SharedSettings(
System.Collections.Generic.IEnumerable<Bam.Core.Module> objectFiles)
{
var sharedInterfaces = SharedInterfaces(objectFiles);
var implementedInterfaces = new Bam.Core.TypeArray(sharedInterfaces);
// define a new type, that contains just the shared interfaces between all object files
// (any interface not shared, must be cloned later)
var typeSignature = "IDESharedSettings";
var assemblyName = new System.Reflection.AssemblyName(typeSignature);
var assemblyBuilder = System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(
assemblyName,
System.Reflection.Emit.AssemblyBuilderAccess.Run
);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
var sharedSettingsTypeDefn = moduleBuilder.DefineType(typeSignature,
System.Reflection.TypeAttributes.Public |
System.Reflection.TypeAttributes.Class |
System.Reflection.TypeAttributes.AutoClass |
System.Reflection.TypeAttributes.AnsiClass |
System.Reflection.TypeAttributes.BeforeFieldInit |
System.Reflection.TypeAttributes.AutoLayout,
typeof(C.SettingsBase),
implementedInterfaces.ToArray());
// TODO: is this necessary?
#if false
sharedSettingsTypeDefn.DefineDefaultConstructor(
System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.RTSpecialName);
#endif
// implement 'automatic property' setter and getters for each property in each interface
foreach (var i in sharedInterfaces)
{
var properties = i.GetProperties();
foreach (var prop in properties)
{
var dynamicProperty = sharedSettingsTypeDefn.DefineProperty(
System.String.Join(".", new[] { i.FullName, prop.Name }),
System.Reflection.PropertyAttributes.None,
prop.PropertyType,
System.Type.EmptyTypes
);
var field = sharedSettingsTypeDefn.DefineField("m" + prop.Name,
prop.PropertyType,
System.Reflection.FieldAttributes.Private);
var methodAttrs = System.Reflection.MethodAttributes.Public |
System.Reflection.MethodAttributes.HideBySig |
System.Reflection.MethodAttributes.Virtual;
if (prop.IsSpecialName)
{
methodAttrs |= System.Reflection.MethodAttributes.SpecialName;
}
var getter = sharedSettingsTypeDefn.DefineMethod("get_" + prop.Name,
methodAttrs,
prop.PropertyType,
System.Type.EmptyTypes);
var setter = sharedSettingsTypeDefn.DefineMethod("set_" + prop.Name,
methodAttrs,
null,
new[] { prop.PropertyType });
var getIL = getter.GetILGenerator();
getIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
getIL.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
getIL.Emit(System.Reflection.Emit.OpCodes.Ret);
dynamicProperty.SetGetMethod(getter);
var setIL = setter.GetILGenerator();
setIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
setIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
setIL.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
setIL.Emit(System.Reflection.Emit.OpCodes.Ret);
dynamicProperty.SetSetMethod(setter);
}
}
var sharedSettingsType = sharedSettingsTypeDefn.CreateType();
var attributeType = typeof(Bam.Core.SettingsExtensionsAttribute);
// now that we have an instance of the shared settings type, calculate the values of the
// individual settings across all object files for all shared interfaces
var commonSettings = System.Activator.CreateInstance(sharedSettingsType) as SettingsBase;
// note: commonSettings have a null Module
foreach (var i in sharedInterfaces)
{
var attributeArray = i.GetCustomAttributes(attributeType, false);
if (0 == attributeArray.Length)
{
throw new Bam.Core.Exception(
$"Settings interface {i.ToString()} is missing attribute {attributeType.ToString()}"
);
}
var attribute = attributeArray[0] as Bam.Core.SettingsExtensionsAttribute;
var cloneSettingsMethod = attribute.GetMethod("Clone", new[] { i, i });
if (null == cloneSettingsMethod)
{
throw new Bam.Core.Exception(
$"Unable to find extension method {attribute.ExtensionsClassName}.Clone(this {i.ToString()}, {i.ToString()}, {i.ToString()}, {i.ToString()})"
);
}
var intersectSettingsMethod = attribute.GetMethod("Intersect", new[] { i, i });
if (null == intersectSettingsMethod)
{
throw new Bam.Core.Exception(
$"Unable to find extension method {attribute.ExtensionsClassName}.Intersect(this {i.ToString()}, {i.ToString()})"
);
}
var objectFileCount = objectFiles.Count();
cloneSettingsMethod.Invoke(null, new[] { commonSettings, objectFiles.First().Settings });
for (int objIndex = 1; objIndex < objectFileCount; ++objIndex)
{
intersectSettingsMethod.Invoke(null, new[] { commonSettings, objectFiles.ElementAt(objIndex).Settings });
}
}
return commonSettings;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
using Oculus.Avatar;
using System.Runtime.InteropServices;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if AVATAR_INTERNAL
using UnityEngine.Events;
#endif
[System.Serializable]
public class AvatarLayer
{
public int layerIndex;
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(AvatarLayer))]
public class AvatarLayerPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, GUIContent.none, property);
SerializedProperty layerIndex = property.FindPropertyRelative("layerIndex");
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
layerIndex.intValue = EditorGUI.LayerField(position, layerIndex.intValue);
EditorGUI.EndProperty();
}
}
#endif
[System.Serializable]
public class PacketRecordSettings
{
internal bool RecordingFrames = false;
public float UpdateRate = 1f / 30f; // 30 hz update of packets
internal float AccumulatedTime;
};
public class OvrAvatar : MonoBehaviour
{
[Header("Avatar")]
public IntPtr sdkAvatar = IntPtr.Zero;
public string oculusUserID;
public OvrAvatarDriver Driver;
[Header("Capabilities")]
public bool EnableBody = true;
public bool EnableHands = true;
public bool EnableBase = true;
public bool EnableExpressive = false;
[Header("Network")]
public bool RecordPackets;
public bool UseSDKPackets = true;
public PacketRecordSettings PacketSettings = new PacketRecordSettings();
[Header("Visibility")]
public bool StartWithControllers;
public AvatarLayer FirstPersonLayer;
public AvatarLayer ThirdPersonLayer;
public bool ShowFirstPerson = true;
public bool ShowThirdPerson;
internal ovrAvatarCapabilities Capabilities = ovrAvatarCapabilities.Body;
[Header("Performance")]
#if UNITY_ANDROID
[Tooltip(
"LOD mesh complexity and texture resolution. Highest LOD recommended on PC and simple mobile apps." +
" Medium LOD recommended on mobile devices or for background characters on PC." +
" Lowest LOD recommended for background characters on mobile.")]
[SerializeField]
internal ovrAvatarAssetLevelOfDetail LevelOfDetail = ovrAvatarAssetLevelOfDetail.Medium;
#else
[SerializeField]
internal ovrAvatarAssetLevelOfDetail LevelOfDetail = ovrAvatarAssetLevelOfDetail.Highest;
#endif
#if UNITY_ANDROID && UNITY_5_5_OR_NEWER
[Tooltip(
"Enable to use combined meshes to reduce draw calls. Currently only available on mobile devices. " +
"Will be forced to false on PC.")]
private bool CombineMeshes = true;
#else
private bool CombineMeshes = false;
#endif
[Tooltip(
"Enable to use transparent queue, disable to use geometry queue. Requires restart to take effect.")]
public bool UseTransparentRenderQueue = true;
[Header("Shaders")]
public Shader Monochrome_SurfaceShader;
public Shader Monochrome_SurfaceShader_SelfOccluding;
public Shader Monochrome_SurfaceShader_PBS;
public Shader Skinshaded_SurfaceShader_SingleComponent;
public Shader Skinshaded_VertFrag_SingleComponent;
public Shader Skinshaded_VertFrag_CombinedMesh;
public Shader Skinshaded_Expressive_SurfaceShader_SingleComponent;
public Shader Skinshaded_Expressive_VertFrag_SingleComponent;
public Shader Skinshaded_Expressive_VertFrag_CombinedMesh;
public Shader Loader_VertFrag_CombinedMesh;
public Shader EyeLens;
public Shader ControllerShader;
[Header("Other")]
public bool CanOwnMicrophone = true;
[Tooltip(
"Enable laughter detection and animation as part of OVRLipSync.")]
public bool EnableLaughter = true;
public GameObject MouthAnchor;
public Transform LeftHandCustomPose;
public Transform RightHandCustomPose;
// Avatar asset
private HashSet<UInt64> assetLoadingIds = new HashSet<UInt64>();
private bool assetsFinishedLoading = false;
private int renderPartCount = 0;
// Material manager
private OvrAvatarMaterialManager materialManager;
private bool waitingForCombinedMesh = false;
// Global expressive system initialization
private static bool doneExpressiveGlobalInit = false;
// Clothing offsets
private Vector4 clothingAlphaOffset = new Vector4(0f, 0f, 0f, 1f);
private UInt64 clothingAlphaTexture = 0;
// Lipsync
private OVRLipSyncMicInput micInput = null;
private OVRLipSyncContext lipsyncContext = null;
private OVRLipSync.Frame currentFrame = new OVRLipSync.Frame();
private float[] visemes = new float[VISEME_COUNT];
private AudioSource audioSource;
private ONSPAudioSource spatializedSource;
private List<float[]> voiceUpdates = new List<float[]>();
private static ovrAvatarVisemes RuntimeVisemes;
// Custom hand poses
private Transform cachedLeftHandCustomPose;
private Transform[] cachedCustomLeftHandJoints;
private ovrAvatarTransform[] cachedLeftHandTransforms;
private Transform cachedRightHandCustomPose;
private Transform[] cachedCustomRightHandJoints;
private ovrAvatarTransform[] cachedRightHandTransforms;
private bool showLeftController;
private bool showRightController;
// Consts
#if UNITY_ANDROID
private const bool USE_MOBILE_TEXTURE_FORMAT = true;
#else
private const bool USE_MOBILE_TEXTURE_FORMAT = false;
#endif
private static readonly Vector3 MOUTH_HEAD_OFFSET = new Vector3(0, -0.085f, 0.09f);
private const string MOUTH_HELPER_NAME = "MouthAnchor";
// Initial 'silence' score, 14 viseme scores and 1 laughter score as last element
private const int VISEME_COUNT = 16;
// Lipsync animation speeds
private const float ACTION_UNIT_ONSET_SPEED = 30f;
private const float ACTION_UNIT_FALLOFF_SPEED = 20f;
private const float VISEME_LEVEL_MULTIPLIER = 1.5f;
// Internals
internal UInt64 oculusUserIDInternal;
internal OvrAvatarBase Base = null;
internal OvrAvatarTouchController ControllerLeft = null;
internal OvrAvatarTouchController ControllerRight = null;
internal OvrAvatarBody Body = null;
internal OvrAvatarHand HandLeft = null;
internal OvrAvatarHand HandRight = null;
internal ovrAvatarLookAndFeelVersion LookAndFeelVersion = ovrAvatarLookAndFeelVersion.Two;
internal ovrAvatarLookAndFeelVersion FallbackLookAndFeelVersion = ovrAvatarLookAndFeelVersion.Two;
#if AVATAR_INTERNAL
public AvatarControllerBlend BlendController;
public UnityEvent AssetsDoneLoading = new UnityEvent();
#endif
// Avatar packets
public class PacketEventArgs : EventArgs
{
public readonly OvrAvatarPacket Packet;
public PacketEventArgs(OvrAvatarPacket packet)
{
Packet = packet;
}
}
private OvrAvatarPacket CurrentUnityPacket;
public EventHandler<PacketEventArgs> PacketRecorded;
public enum HandType
{
Right,
Left,
Max
};
public enum HandJoint
{
HandBase,
IndexBase,
IndexTip,
ThumbBase,
ThumbTip,
Max,
}
private static string[,] HandJoints = new string[(int)HandType.Max, (int)HandJoint.Max]
{
{
"hands:r_hand_world",
"hands:r_hand_world/hands:b_r_hand/hands:b_r_index1",
"hands:r_hand_world/hands:b_r_hand/hands:b_r_index1/hands:b_r_index2/hands:b_r_index3/hands:b_r_index_ignore",
"hands:r_hand_world/hands:b_r_hand/hands:b_r_thumb1/hands:b_r_thumb2",
"hands:r_hand_world/hands:b_r_hand/hands:b_r_thumb1/hands:b_r_thumb2/hands:b_r_thumb3/hands:b_r_thumb_ignore"
},
{
"hands:l_hand_world",
"hands:l_hand_world/hands:b_l_hand/hands:b_l_index1",
"hands:l_hand_world/hands:b_l_hand/hands:b_l_index1/hands:b_l_index2/hands:b_l_index3/hands:b_l_index_ignore",
"hands:l_hand_world/hands:b_l_hand/hands:b_l_thumb1/hands:b_l_thumb2",
"hands:l_hand_world/hands:b_l_hand/hands:b_l_thumb1/hands:b_l_thumb2/hands:b_l_thumb3/hands:b_l_thumb_ignore"
}
};
static OvrAvatar()
{
// This size has to match the 'MarshalAs' attribute in the ovrAvatarVisemes declaration.
RuntimeVisemes.visemeParams = new float[32];
RuntimeVisemes.visemeParamCount = VISEME_COUNT;
}
void OnDestroy()
{
if (sdkAvatar != IntPtr.Zero)
{
CAPI.ovrAvatar_Destroy(sdkAvatar);
}
}
public void AssetLoadedCallback(OvrAvatarAsset asset)
{
assetLoadingIds.Remove(asset.assetID);
}
public void CombinedMeshLoadedCallback(IntPtr assetPtr)
{
if (!waitingForCombinedMesh)
{
return;
}
var meshIDs = CAPI.ovrAvatarAsset_GetCombinedMeshIDs(assetPtr);
foreach (var id in meshIDs)
{
assetLoadingIds.Remove(id);
}
CAPI.ovrAvatar_GetCombinedMeshAlphaData(sdkAvatar, ref clothingAlphaTexture, ref clothingAlphaOffset);
waitingForCombinedMesh = false;
}
private OvrAvatarSkinnedMeshRenderComponent AddSkinnedMeshRenderComponent(GameObject gameObject, ovrAvatarRenderPart_SkinnedMeshRender skinnedMeshRender)
{
OvrAvatarSkinnedMeshRenderComponent skinnedMeshRenderer = gameObject.AddComponent<OvrAvatarSkinnedMeshRenderComponent>();
skinnedMeshRenderer.Initialize(skinnedMeshRender, Monochrome_SurfaceShader, Monochrome_SurfaceShader_SelfOccluding, ThirdPersonLayer.layerIndex, FirstPersonLayer.layerIndex);
return skinnedMeshRenderer;
}
private OvrAvatarSkinnedMeshRenderPBSComponent AddSkinnedMeshRenderPBSComponent(GameObject gameObject, ovrAvatarRenderPart_SkinnedMeshRenderPBS skinnedMeshRenderPBS)
{
OvrAvatarSkinnedMeshRenderPBSComponent skinnedMeshRenderer = gameObject.AddComponent<OvrAvatarSkinnedMeshRenderPBSComponent>();
skinnedMeshRenderer.Initialize(skinnedMeshRenderPBS, Monochrome_SurfaceShader_PBS, ThirdPersonLayer.layerIndex, FirstPersonLayer.layerIndex);
return skinnedMeshRenderer;
}
private OvrAvatarSkinnedMeshPBSV2RenderComponent AddSkinnedMeshRenderPBSV2Component(
IntPtr renderPart,
GameObject go,
ovrAvatarRenderPart_SkinnedMeshRenderPBS_V2 skinnedMeshRenderPBSV2,
bool isBodyPartZero,
bool isControllerModel)
{
OvrAvatarSkinnedMeshPBSV2RenderComponent skinnedMeshRenderer = go.AddComponent<OvrAvatarSkinnedMeshPBSV2RenderComponent>();
skinnedMeshRenderer.Initialize(
renderPart,
skinnedMeshRenderPBSV2,
materialManager,
ThirdPersonLayer.layerIndex,
FirstPersonLayer.layerIndex,
isBodyPartZero && CombineMeshes,
LevelOfDetail,
isBodyPartZero && EnableExpressive,
this,
isControllerModel);
return skinnedMeshRenderer;
}
static public IntPtr GetRenderPart(ovrAvatarComponent component, UInt32 renderPartIndex)
{
return Marshal.ReadIntPtr(component.renderParts, Marshal.SizeOf(typeof(IntPtr)) * (int)renderPartIndex);
}
private static string GetRenderPartName(ovrAvatarComponent component, uint renderPartIndex)
{
return component.name + "_renderPart_" + (int)renderPartIndex;
}
internal static void ConvertTransform(float[] transform, ref ovrAvatarTransform target)
{
target.position.x = transform[0];
target.position.y = transform[1];
target.position.z = transform[2];
target.orientation.x = transform[3];
target.orientation.y = transform[4];
target.orientation.z = transform[5];
target.orientation.w = transform[6];
target.scale.x = transform[7];
target.scale.y = transform[8];
target.scale.z = transform[9];
}
internal static void ConvertTransform(ovrAvatarTransform transform, Transform target)
{
Vector3 position = transform.position;
position.z = -position.z;
Quaternion orientation = transform.orientation;
orientation.x = -orientation.x;
orientation.y = -orientation.y;
target.localPosition = position;
target.localRotation = orientation;
target.localScale = transform.scale;
}
public static ovrAvatarTransform CreateOvrAvatarTransform(Vector3 position, Quaternion orientation)
{
return new ovrAvatarTransform
{
position = new Vector3(position.x, position.y, -position.z),
orientation = new Quaternion(-orientation.x, -orientation.y, orientation.z, orientation.w),
scale = Vector3.one
};
}
private static ovrAvatarGazeTarget CreateOvrGazeTarget(uint targetId, Vector3 targetPosition, ovrAvatarGazeTargetType targetType)
{
return new ovrAvatarGazeTarget
{
id = targetId,
// Do coordinate system switch.
worldPosition = new Vector3(targetPosition.x, targetPosition.y, -targetPosition.z),
type = targetType
};
}
private void BuildRenderComponents()
{
ovrAvatarBaseComponent baseComponnet = new ovrAvatarBaseComponent();
ovrAvatarHandComponent leftHandComponnet = new ovrAvatarHandComponent();
ovrAvatarHandComponent rightHandComponnet = new ovrAvatarHandComponent();
ovrAvatarControllerComponent leftControllerComponent = new ovrAvatarControllerComponent();
ovrAvatarControllerComponent rightControllerComponent = new ovrAvatarControllerComponent();
ovrAvatarBodyComponent bodyComponent = new ovrAvatarBodyComponent();
ovrAvatarComponent dummyComponent = new ovrAvatarComponent();
const bool FetchName = true;
if (CAPI.ovrAvatarPose_GetLeftHandComponent(sdkAvatar, ref leftHandComponnet))
{
CAPI.ovrAvatarComponent_Get(leftHandComponnet.renderComponent, FetchName, ref dummyComponent);
AddAvatarComponent(ref HandLeft, dummyComponent);
HandLeft.isLeftHand = true;
}
if (CAPI.ovrAvatarPose_GetRightHandComponent(sdkAvatar, ref rightHandComponnet))
{
CAPI.ovrAvatarComponent_Get(rightHandComponnet.renderComponent, FetchName, ref dummyComponent);
AddAvatarComponent(ref HandRight, dummyComponent);
HandRight.isLeftHand = false;
}
if (CAPI.ovrAvatarPose_GetBodyComponent(sdkAvatar, ref bodyComponent))
{
CAPI.ovrAvatarComponent_Get(bodyComponent.renderComponent, FetchName, ref dummyComponent);
AddAvatarComponent(ref Body, dummyComponent);
}
if (CAPI.ovrAvatarPose_GetLeftControllerComponent(sdkAvatar, ref leftControllerComponent))
{
CAPI.ovrAvatarComponent_Get(leftControllerComponent.renderComponent, FetchName, ref dummyComponent);
AddAvatarComponent(ref ControllerLeft, dummyComponent);
ControllerLeft.isLeftHand = true;
}
if (CAPI.ovrAvatarPose_GetRightControllerComponent(sdkAvatar, ref rightControllerComponent))
{
CAPI.ovrAvatarComponent_Get(rightControllerComponent.renderComponent, FetchName, ref dummyComponent);
AddAvatarComponent(ref ControllerRight, dummyComponent);
ControllerRight.isLeftHand = false;
}
if (CAPI.ovrAvatarPose_GetBaseComponent(sdkAvatar, ref baseComponnet))
{
CAPI.ovrAvatarComponent_Get(baseComponnet.renderComponent, FetchName, ref dummyComponent);
AddAvatarComponent(ref Base, dummyComponent);
}
}
private void AddAvatarComponent<T>(ref T root, ovrAvatarComponent nativeComponent) where T : OvrAvatarComponent
{
GameObject componentObject = new GameObject();
componentObject.name = nativeComponent.name;
componentObject.transform.SetParent(transform);
root = componentObject.AddComponent<T>();
root.SetOvrAvatarOwner(this);
AddRenderParts(root, nativeComponent, componentObject.transform);
}
void UpdateCustomPoses()
{
// Check to see if the pose roots changed
if (UpdatePoseRoot(LeftHandCustomPose, ref cachedLeftHandCustomPose, ref cachedCustomLeftHandJoints, ref cachedLeftHandTransforms))
{
if (cachedLeftHandCustomPose == null && sdkAvatar != IntPtr.Zero)
{
CAPI.ovrAvatar_SetLeftHandGesture(sdkAvatar, ovrAvatarHandGesture.Default);
}
}
if (UpdatePoseRoot(RightHandCustomPose, ref cachedRightHandCustomPose, ref cachedCustomRightHandJoints, ref cachedRightHandTransforms))
{
if (cachedRightHandCustomPose == null && sdkAvatar != IntPtr.Zero)
{
CAPI.ovrAvatar_SetRightHandGesture(sdkAvatar, ovrAvatarHandGesture.Default);
}
}
// Check to see if the custom gestures need to be updated
if (sdkAvatar != IntPtr.Zero)
{
if (cachedLeftHandCustomPose != null && UpdateTransforms(cachedCustomLeftHandJoints, cachedLeftHandTransforms))
{
CAPI.ovrAvatar_SetLeftHandCustomGesture(sdkAvatar, (uint)cachedLeftHandTransforms.Length, cachedLeftHandTransforms);
}
if (cachedRightHandCustomPose != null && UpdateTransforms(cachedCustomRightHandJoints, cachedRightHandTransforms))
{
CAPI.ovrAvatar_SetRightHandCustomGesture(sdkAvatar, (uint)cachedRightHandTransforms.Length, cachedRightHandTransforms);
}
}
}
static bool UpdatePoseRoot(Transform poseRoot, ref Transform cachedPoseRoot, ref Transform[] cachedPoseJoints, ref ovrAvatarTransform[] transforms)
{
if (poseRoot == cachedPoseRoot)
{
return false;
}
if (!poseRoot)
{
cachedPoseRoot = null;
cachedPoseJoints = null;
transforms = null;
}
else
{
List<Transform> joints = new List<Transform>();
OrderJoints(poseRoot, joints);
cachedPoseRoot = poseRoot;
cachedPoseJoints = joints.ToArray();
transforms = new ovrAvatarTransform[joints.Count];
}
return true;
}
static bool UpdateTransforms(Transform[] joints, ovrAvatarTransform[] transforms)
{
bool updated = false;
for (int i = 0; i < joints.Length; ++i)
{
Transform joint = joints[i];
ovrAvatarTransform transform = CreateOvrAvatarTransform(joint.localPosition, joint.localRotation);
if (transform.position != transforms[i].position || transform.orientation != transforms[i].orientation)
{
transforms[i] = transform;
updated = true;
}
}
return updated;
}
private static void OrderJoints(Transform transform, List<Transform> joints)
{
joints.Add(transform);
for (int i = 0; i < transform.childCount; ++i)
{
Transform child = transform.GetChild(i);
OrderJoints(child, joints);
}
}
void AvatarSpecificationCallback(IntPtr avatarSpecification)
{
sdkAvatar = CAPI.ovrAvatar_Create(avatarSpecification, Capabilities);
ShowLeftController(showLeftController);
ShowRightController(showRightController);
// Pump the Remote driver once to push the controller type through
if (Driver != null)
{
Driver.UpdateTransformsFromPose(sdkAvatar);
}
//Fetch all the assets that this avatar uses.
UInt32 assetCount = CAPI.ovrAvatar_GetReferencedAssetCount(sdkAvatar);
for (UInt32 i = 0; i < assetCount; ++i)
{
UInt64 id = CAPI.ovrAvatar_GetReferencedAsset(sdkAvatar, i);
if (OvrAvatarSDKManager.Instance.GetAsset(id) == null)
{
OvrAvatarSDKManager.Instance.BeginLoadingAsset(
id,
LevelOfDetail,
AssetLoadedCallback);
assetLoadingIds.Add(id);
}
}
if (CombineMeshes)
{
OvrAvatarSDKManager.Instance.RegisterCombinedMeshCallback(
sdkAvatar,
CombinedMeshLoadedCallback);
}
}
void Start()
{
if (OvrAvatarSDKManager.Instance == null)
{
return;
}
#if !UNITY_ANDROID
if (CombineMeshes)
{
CombineMeshes = false;
AvatarLogger.Log("Combined Meshes currently only supported on mobile");
}
#endif
#if !UNITY_5_5_OR_NEWER
if (CombineMeshes)
{
CombineMeshes = false;
AvatarLogger.LogWarning("Combined Meshes requires Unity 5.5.0+");
}
#endif
materialManager = gameObject.AddComponent<OvrAvatarMaterialManager>();
try
{
oculusUserIDInternal = UInt64.Parse(oculusUserID);
}
catch (Exception)
{
oculusUserIDInternal = 0;
AvatarLogger.LogWarning("Invalid Oculus User ID Format");
}
// If no oculus ID is supplied then turn off combine meshes to prevent the texture arrays
// being populated by invalid textures.
if (oculusUserIDInternal == 0)
{
AvatarLogger.LogWarning("Oculus User ID set to 0. Provide actual user ID: " + gameObject.name);
CombineMeshes = false;
}
AvatarLogger.Log("Starting OvrAvatar " + gameObject.name);
AvatarLogger.Log(AvatarLogger.Tab + "LOD: " + LevelOfDetail.ToString());
AvatarLogger.Log(AvatarLogger.Tab + "Combine Meshes: " + CombineMeshes);
AvatarLogger.Log(AvatarLogger.Tab + "Force Mobile Textures: " + USE_MOBILE_TEXTURE_FORMAT);
AvatarLogger.Log(AvatarLogger.Tab + "Oculus User ID: " + oculusUserIDInternal);
Capabilities = 0;
bool is3Dof = false;
var headsetType = OVRPlugin.GetSystemHeadsetType();
switch (headsetType)
{
case OVRPlugin.SystemHeadset.GearVR_R320:
case OVRPlugin.SystemHeadset.GearVR_R321:
case OVRPlugin.SystemHeadset.GearVR_R322:
case OVRPlugin.SystemHeadset.GearVR_R323:
case OVRPlugin.SystemHeadset.GearVR_R324:
case OVRPlugin.SystemHeadset.GearVR_R325:
case OVRPlugin.SystemHeadset.Oculus_Go:
is3Dof = true;
break;
case OVRPlugin.SystemHeadset.Oculus_Quest:
case OVRPlugin.SystemHeadset.Rift_S:
case OVRPlugin.SystemHeadset.Rift_DK1:
case OVRPlugin.SystemHeadset.Rift_DK2:
case OVRPlugin.SystemHeadset.Rift_CV1:
default:
break;
}
// The SDK 3 DOF Arm Model requires the body skeleton to pose itself. It will crash without it
// The likely use case here is trying to have an invisible body.
// T45010595
if (is3Dof && !EnableBody)
{
AvatarLogger.Log("Forcing the Body component for 3Dof hand tracking, and setting the visibility to 1st person");
EnableBody = true;
ShowFirstPerson = true;
ShowThirdPerson = false;
}
if (EnableBody) Capabilities |= ovrAvatarCapabilities.Body;
if (EnableHands) Capabilities |= ovrAvatarCapabilities.Hands;
if (EnableBase && EnableBody) Capabilities |= ovrAvatarCapabilities.Base;
if (EnableExpressive) Capabilities |= ovrAvatarCapabilities.Expressive;
// Enable body tilt on 6dof devices
if(OVRPlugin.positionSupported)
{
Capabilities |= ovrAvatarCapabilities.BodyTilt;
}
ShowLeftController(StartWithControllers);
ShowRightController(StartWithControllers);
OvrAvatarSDKManager.AvatarSpecRequestParams avatarSpecRequest = new OvrAvatarSDKManager.AvatarSpecRequestParams(
oculusUserIDInternal,
this.AvatarSpecificationCallback,
CombineMeshes,
LevelOfDetail,
USE_MOBILE_TEXTURE_FORMAT,
LookAndFeelVersion,
FallbackLookAndFeelVersion,
EnableExpressive);
OvrAvatarSDKManager.Instance.RequestAvatarSpecification(avatarSpecRequest);
OvrAvatarSDKManager.Instance.AddLoadingAvatar(GetInstanceID());
waitingForCombinedMesh = CombineMeshes;
if (Driver != null)
{
Driver.Mode = UseSDKPackets ? OvrAvatarDriver.PacketMode.SDK : OvrAvatarDriver.PacketMode.Unity;
}
}
void Update()
{
if (!OvrAvatarSDKManager.Instance || sdkAvatar == IntPtr.Zero || materialManager == null)
{
return;
}
if (Driver != null)
{
Driver.UpdateTransforms(sdkAvatar);
foreach (float[] voiceUpdate in voiceUpdates)
{
CAPI.ovrAvatarPose_UpdateVoiceVisualization(sdkAvatar, voiceUpdate);
}
voiceUpdates.Clear();
#if AVATAR_INTERNAL
if (BlendController != null)
{
BlendController.UpdateBlend(sdkAvatar);
}
#endif
CAPI.ovrAvatarPose_Finalize(sdkAvatar, Time.deltaTime);
}
if (RecordPackets)
{
RecordFrame();
}
if (assetLoadingIds.Count == 0)
{
if (!assetsFinishedLoading)
{
try
{
BuildRenderComponents();
}
catch (Exception e)
{
assetsFinishedLoading = true;
throw; // rethrow the original exception to preserve callstack
}
#if AVATAR_INTERNAL
AssetsDoneLoading.Invoke();
#endif
InitPostLoad();
assetsFinishedLoading = true;
OvrAvatarSDKManager.Instance.RemoveLoadingAvatar(GetInstanceID());
}
UpdateVoiceBehavior();
UpdateCustomPoses();
if (EnableExpressive)
{
UpdateExpressive();
}
}
}
public static ovrAvatarHandInputState CreateInputState(ovrAvatarTransform transform, OvrAvatarDriver.ControllerPose pose)
{
ovrAvatarHandInputState inputState = new ovrAvatarHandInputState();
inputState.transform = transform;
inputState.buttonMask = pose.buttons;
inputState.touchMask = pose.touches;
inputState.joystickX = pose.joystickPosition.x;
inputState.joystickY = pose.joystickPosition.y;
inputState.indexTrigger = pose.indexTrigger;
inputState.handTrigger = pose.handTrigger;
inputState.isActive = pose.isActive;
return inputState;
}
public void ShowControllers(bool show)
{
ShowLeftController(show);
ShowRightController(show);
}
public void ShowLeftController(bool show)
{
if (sdkAvatar != IntPtr.Zero)
{
CAPI.ovrAvatar_SetLeftControllerVisibility(sdkAvatar, show);
}
showLeftController = show;
}
public void ShowRightController(bool show)
{
if (sdkAvatar != IntPtr.Zero)
{
CAPI.ovrAvatar_SetRightControllerVisibility(sdkAvatar, show);
}
showRightController = show;
}
public void UpdateVoiceVisualization(float[] voiceSamples)
{
voiceUpdates.Add(voiceSamples);
}
void RecordFrame()
{
if(UseSDKPackets)
{
RecordSDKFrame();
}
else
{
RecordUnityFrame();
}
}
// Meant to be used mutually exclusively with RecordSDKFrame to give user more options to optimize or tweak packet data
private void RecordUnityFrame()
{
var deltaSeconds = Time.deltaTime;
var frame = Driver.GetCurrentPose();
// If this is our first packet, store the pose as the initial frame
if (CurrentUnityPacket == null)
{
CurrentUnityPacket = new OvrAvatarPacket(frame);
deltaSeconds = 0;
}
float recordedSeconds = 0;
while (recordedSeconds < deltaSeconds)
{
float remainingSeconds = deltaSeconds - recordedSeconds;
float remainingPacketSeconds = PacketSettings.UpdateRate - CurrentUnityPacket.Duration;
// If we're not going to fill the packet, just add the frame
if (remainingSeconds < remainingPacketSeconds)
{
CurrentUnityPacket.AddFrame(frame, remainingSeconds);
recordedSeconds += remainingSeconds;
}
// If we're going to fill the packet, interpolate the pose, send the packet,
// and open a new one
else
{
// Interpolate between the packet's last frame and our target pose
// to compute a pose at the end of the packet time.
OvrAvatarDriver.PoseFrame a = CurrentUnityPacket.FinalFrame;
OvrAvatarDriver.PoseFrame b = frame;
float t = remainingPacketSeconds / remainingSeconds;
OvrAvatarDriver.PoseFrame intermediatePose = OvrAvatarDriver.PoseFrame.Interpolate(a, b, t);
CurrentUnityPacket.AddFrame(intermediatePose, remainingPacketSeconds);
recordedSeconds += remainingPacketSeconds;
// Broadcast the recorded packet
if (PacketRecorded != null)
{
PacketRecorded(this, new PacketEventArgs(CurrentUnityPacket));
}
// Open a new packet
CurrentUnityPacket = new OvrAvatarPacket(intermediatePose);
}
}
}
private void RecordSDKFrame()
{
if (sdkAvatar == IntPtr.Zero)
{
return;
}
if (!PacketSettings.RecordingFrames)
{
CAPI.ovrAvatarPacket_BeginRecording(sdkAvatar);
PacketSettings.AccumulatedTime = 0.0f;
PacketSettings.RecordingFrames = true;
}
PacketSettings.AccumulatedTime += Time.deltaTime;
if (PacketSettings.AccumulatedTime >= PacketSettings.UpdateRate)
{
PacketSettings.AccumulatedTime = 0.0f;
var packet = CAPI.ovrAvatarPacket_EndRecording(sdkAvatar);
CAPI.ovrAvatarPacket_BeginRecording(sdkAvatar);
if (PacketRecorded != null)
{
PacketRecorded(this, new PacketEventArgs(new OvrAvatarPacket { ovrNativePacket = packet }));
}
CAPI.ovrAvatarPacket_Free(packet);
}
}
private void AddRenderParts(
OvrAvatarComponent ovrComponent,
ovrAvatarComponent component,
Transform parent)
{
bool isBody = ovrComponent.name == "body";
bool isLeftController = ovrComponent.name == "controller_left";
bool isReftController = ovrComponent.name == "controller_right";
for (UInt32 renderPartIndex = 0; renderPartIndex < component.renderPartCount; renderPartIndex++)
{
GameObject renderPartObject = new GameObject();
renderPartObject.name = GetRenderPartName(component, renderPartIndex);
renderPartObject.transform.SetParent(parent);
IntPtr renderPart = GetRenderPart(component, renderPartIndex);
ovrAvatarRenderPartType type = CAPI.ovrAvatarRenderPart_GetType(renderPart);
OvrAvatarRenderComponent ovrRenderPart = null;
switch (type)
{
case ovrAvatarRenderPartType.SkinnedMeshRender:
ovrRenderPart = AddSkinnedMeshRenderComponent(renderPartObject, CAPI.ovrAvatarRenderPart_GetSkinnedMeshRender(renderPart));
break;
case ovrAvatarRenderPartType.SkinnedMeshRenderPBS:
ovrRenderPart = AddSkinnedMeshRenderPBSComponent(renderPartObject, CAPI.ovrAvatarRenderPart_GetSkinnedMeshRenderPBS(renderPart));
break;
case ovrAvatarRenderPartType.SkinnedMeshRenderPBS_V2:
{
ovrRenderPart = AddSkinnedMeshRenderPBSV2Component(
renderPart,
renderPartObject,
CAPI.ovrAvatarRenderPart_GetSkinnedMeshRenderPBSV2(renderPart),
isBody && renderPartIndex == 0,
isLeftController || isReftController);
}
break;
default:
break;
}
if (ovrRenderPart != null)
{
ovrComponent.RenderParts.Add(ovrRenderPart);
}
}
}
public void RefreshBodyParts()
{
if (Body != null)
{
foreach (var part in Body.RenderParts)
{
Destroy(part.gameObject);
}
Body.RenderParts.Clear();
var nativeAvatarComponent = Body.GetNativeAvatarComponent();
if (nativeAvatarComponent.HasValue)
{
AddRenderParts(Body, nativeAvatarComponent.Value, Body.gameObject.transform);
}
}
}
public ovrAvatarBodyComponent? GetBodyComponent()
{
if (Body != null)
{
CAPI.ovrAvatarPose_GetBodyComponent(sdkAvatar, ref Body.component);
return Body.component;
}
return null;
}
public Transform GetHandTransform(HandType hand, HandJoint joint)
{
if (hand >= HandType.Max || joint >= HandJoint.Max)
{
return null;
}
var HandObject = hand == HandType.Left ? HandLeft : HandRight;
if (HandObject != null)
{
var AvatarComponent = HandObject.GetComponent<OvrAvatarComponent>();
if (AvatarComponent != null && AvatarComponent.RenderParts.Count > 0)
{
var SkinnedMesh = AvatarComponent.RenderParts[0];
return SkinnedMesh.transform.Find(HandJoints[(int)hand, (int)joint]);
}
}
return null;
}
public void GetPointingDirection(HandType hand, ref Vector3 forward, ref Vector3 up)
{
Transform handBase = GetHandTransform(hand, HandJoint.HandBase);
if (handBase != null)
{
forward = handBase.forward;
up = handBase.up;
}
}
static Vector3 MOUTH_POSITION_OFFSET = new Vector3(0, -0.018f, 0.1051f);
static string VOICE_PROPERTY = "_Voice";
static string MOUTH_POSITION_PROPERTY = "_MouthPosition";
static string MOUTH_DIRECTION_PROPERTY = "_MouthDirection";
static string MOUTH_SCALE_PROPERTY = "_MouthEffectScale";
static float MOUTH_SCALE_GLOBAL = 0.007f;
static float MOUTH_MAX_GLOBAL = 0.007f;
static string NECK_JONT = "root_JNT/body_JNT/chest_JNT/neckBase_JNT/neck_JNT";
public float VoiceAmplitude = 0f;
public bool EnableMouthVertexAnimation = false;
private void UpdateVoiceBehavior()
{
if (!EnableMouthVertexAnimation)
{
return;
}
if (Body != null)
{
OvrAvatarComponent component = Body.GetComponent<OvrAvatarComponent>();
VoiceAmplitude = Mathf.Clamp(VoiceAmplitude, 0f, 1f);
if (component.RenderParts.Count > 0)
{
var material = component.RenderParts[0].mesh.sharedMaterial;
var neckJoint = component.RenderParts[0].mesh.transform.Find(NECK_JONT);
var scaleDiff = neckJoint.TransformPoint(Vector3.up) - neckJoint.position;
material.SetFloat(MOUTH_SCALE_PROPERTY, scaleDiff.magnitude);
material.SetFloat(
VOICE_PROPERTY,
Mathf.Min(scaleDiff.magnitude * MOUTH_MAX_GLOBAL, scaleDiff.magnitude * VoiceAmplitude * MOUTH_SCALE_GLOBAL));
material.SetVector(
MOUTH_POSITION_PROPERTY,
neckJoint.TransformPoint(MOUTH_POSITION_OFFSET));
material.SetVector(MOUTH_DIRECTION_PROPERTY, neckJoint.up);
}
}
}
bool IsValidMic()
{
string[] devices = Microphone.devices;
if (devices.Length < 1)
{
return false;
}
int selectedDeviceIndex = 0;
#if UNITY_STANDALONE_WIN
for (int i = 1; i < devices.Length; i++)
{
if (devices[i].ToUpper().Contains("RIFT"))
{
selectedDeviceIndex = i;
break;
}
}
#endif
string selectedDevice = devices[selectedDeviceIndex];
int minFreq;
int maxFreq;
Microphone.GetDeviceCaps(selectedDevice, out minFreq, out maxFreq);
if (maxFreq == 0)
{
maxFreq = 44100;
}
AudioClip clip = Microphone.Start(selectedDevice, true, 1, maxFreq);
if (clip == null)
{
return false;
}
Microphone.End(selectedDevice);
return true;
}
void InitPostLoad()
{
ExpressiveGlobalInit();
ConfigureHelpers();
if (GetComponent<OvrAvatarLocalDriver>() != null)
{
// Use mic.
lipsyncContext.audioLoopback = false;
if (CanOwnMicrophone && IsValidMic())
{
micInput = MouthAnchor.gameObject.AddComponent<OVRLipSyncMicInput>();
micInput.enableMicSelectionGUI = false;
micInput.MicFrequency = 44100;
micInput.micControl = OVRLipSyncMicInput.micActivation.ConstantSpeak;
}
// Set lipsync animation parameters in SDK
CAPI.ovrAvatar_SetActionUnitOnsetSpeed(sdkAvatar, ACTION_UNIT_ONSET_SPEED);
CAPI.ovrAvatar_SetActionUnitFalloffSpeed(sdkAvatar, ACTION_UNIT_FALLOFF_SPEED);
CAPI.ovrAvatar_SetVisemeMultiplier(sdkAvatar, VISEME_LEVEL_MULTIPLIER);
}
}
static ovrAvatarLights ovrLights = new ovrAvatarLights();
static void ExpressiveGlobalInit()
{
if (doneExpressiveGlobalInit)
{
return;
}
doneExpressiveGlobalInit = true;
// This array size has to match the 'MarshalAs' attribute in the ovrAvatarLights declaration.
const int MAXSIZE = 16;
ovrLights.lights = new ovrAvatarLight[MAXSIZE];
InitializeLights();
}
static void InitializeLights()
{
// Set light info. Lights are shared across all avatar instances.
ovrLights.ambientIntensity = RenderSettings.ambientLight.grayscale * 0.5f;
Light[] sceneLights = FindObjectsOfType(typeof(Light)) as Light[];
int i = 0;
for (i = 0; i < sceneLights.Length && i < ovrLights.lights.Length; ++i)
{
Light sceneLight = sceneLights[i];
if (sceneLight && sceneLight.enabled)
{
uint instanceID = (uint)sceneLight.transform.GetInstanceID();
switch (sceneLight.type)
{
case LightType.Directional:
{
CreateLightDirectional(instanceID, sceneLight.transform.forward, sceneLight.intensity, ref ovrLights.lights[i]);
break;
}
case LightType.Point:
{
CreateLightPoint(instanceID, sceneLight.transform.position, sceneLight.range, sceneLight.intensity, ref ovrLights.lights[i]);
break;
}
case LightType.Spot:
{
CreateLightSpot(instanceID, sceneLight.transform.position, sceneLight.transform.forward, sceneLight.spotAngle, sceneLight.range, sceneLight.intensity, ref ovrLights.lights[i]);
break;
}
}
}
}
ovrLights.lightCount = (uint)i;
CAPI.ovrAvatar_UpdateLights(ovrLights);
}
static ovrAvatarLight CreateLightDirectional(uint id, Vector3 direction, float intensity, ref ovrAvatarLight light)
{
light.id = id;
light.type = ovrAvatarLightType.Direction;
light.worldDirection = new Vector3(direction.x, direction.y, -direction.z);
light.intensity = intensity;
return light;
}
static ovrAvatarLight CreateLightPoint(uint id, Vector3 position, float range, float intensity, ref ovrAvatarLight light)
{
light.id = id;
light.type = ovrAvatarLightType.Point;
light.worldPosition = new Vector3(position.x, position.y, -position.z);
light.range = range;
light.intensity = intensity;
return light;
}
static ovrAvatarLight CreateLightSpot(uint id, Vector3 position, Vector3 direction, float spotAngleDeg, float range, float intensity, ref ovrAvatarLight light)
{
light.id = id;
light.type = ovrAvatarLightType.Spot;
light.worldPosition = new Vector3(position.x, position.y, -position.z);
light.worldDirection = new Vector3(direction.x, direction.y, -direction.z);
light.spotAngleDeg = spotAngleDeg;
light.range = range;
light.intensity = intensity;
return light;
}
void UpdateExpressive()
{
ovrAvatarTransform baseTransform = OvrAvatar.CreateOvrAvatarTransform(transform.position, transform.rotation);
CAPI.ovrAvatar_UpdateWorldTransform(sdkAvatar, baseTransform);
UpdateFacewave();
}
private void ConfigureHelpers()
{
Transform head =
transform.Find("body/body_renderPart_0/root_JNT/body_JNT/chest_JNT/neckBase_JNT/neck_JNT/head_JNT");
if (head == null)
{
AvatarLogger.LogError("Avatar helper config failed. Cannot find head transform. All helpers spawning on root avatar transform");
head = transform;
}
if (MouthAnchor == null)
{
MouthAnchor = CreateHelperObject(head, MOUTH_HEAD_OFFSET, MOUTH_HELPER_NAME);
}
if (GetComponent<OvrAvatarLocalDriver>() != null)
{
if (audioSource == null)
{
audioSource = MouthAnchor.gameObject.AddComponent<AudioSource>();
}
spatializedSource = MouthAnchor.GetComponent<ONSPAudioSource>();
if (spatializedSource == null)
{
spatializedSource = MouthAnchor.gameObject.AddComponent<ONSPAudioSource>();
}
spatializedSource.UseInvSqr = true;
spatializedSource.EnableRfl = false;
spatializedSource.EnableSpatialization = true;
spatializedSource.Far = 100f;
spatializedSource.Near = 0.1f;
// Add phoneme context to the mouth anchor
lipsyncContext = MouthAnchor.GetComponent<OVRLipSyncContext>();
if (lipsyncContext == null)
{
lipsyncContext = MouthAnchor.gameObject.AddComponent<OVRLipSyncContext>();
}
lipsyncContext.provider = EnableLaughter
? OVRLipSync.ContextProviders.Enhanced_with_Laughter
: OVRLipSync.ContextProviders.Enhanced;
// Ignore audio callback if microphone is owned by VoIP
lipsyncContext.skipAudioSource = !CanOwnMicrophone;
StartCoroutine(WaitForMouthAudioSource());
}
if (GetComponent<OvrAvatarRemoteDriver>() != null)
{
GazeTarget headTarget = head.gameObject.AddComponent<GazeTarget>();
headTarget.Type = ovrAvatarGazeTargetType.AvatarHead;
AvatarLogger.Log("Added head as gaze target");
Transform hand = transform.Find("hand_left");
if (hand == null)
{
AvatarLogger.LogWarning("Gaze target helper config failed: Cannot find left hand transform");
}
else
{
GazeTarget handTarget = hand.gameObject.AddComponent<GazeTarget>();
handTarget.Type = ovrAvatarGazeTargetType.AvatarHand;
AvatarLogger.Log("Added left hand as gaze target");
}
hand = transform.Find("hand_right");
if (hand == null)
{
AvatarLogger.Log("Gaze target helper config failed: Cannot find right hand transform");
}
else
{
GazeTarget handTarget = hand.gameObject.AddComponent<GazeTarget>();
handTarget.Type = ovrAvatarGazeTargetType.AvatarHand;
AvatarLogger.Log("Added right hand as gaze target");
}
}
}
private IEnumerator WaitForMouthAudioSource()
{
while (MouthAnchor.GetComponent<AudioSource>() == null)
{
yield return new WaitForSeconds(0.1f);
}
AudioSource AS = MouthAnchor.GetComponent<AudioSource>();
AS.minDistance = 0.3f;
AS.maxDistance = 4f;
AS.rolloffMode = AudioRolloffMode.Logarithmic;
AS.loop = true;
AS.playOnAwake = true;
AS.spatialBlend = 1.0f;
AS.spatialize = true;
AS.spatializePostEffects = true;
}
public void DestroyHelperObjects()
{
if (MouthAnchor)
{
DestroyImmediate(MouthAnchor.gameObject);
}
}
public GameObject CreateHelperObject(Transform parent, Vector3 localPositionOffset, string helperName,
string helperTag = "")
{
GameObject helper = new GameObject();
helper.name = helperName;
if (helperTag != "")
{
helper.tag = helperTag;
}
helper.transform.SetParent(parent);
helper.transform.localRotation = Quaternion.identity;
helper.transform.localPosition = localPositionOffset;
return helper;
}
public void UpdateVoiceData(short[] pcmData, int numChannels)
{
if (lipsyncContext != null && micInput == null)
{
lipsyncContext.ProcessAudioSamplesRaw(pcmData, numChannels);
}
}
public void UpdateVoiceData(float[] pcmData, int numChannels)
{
if (lipsyncContext != null && micInput == null)
{
lipsyncContext.ProcessAudioSamplesRaw(pcmData, numChannels);
}
}
private void UpdateFacewave()
{
if (lipsyncContext != null && (micInput != null || CanOwnMicrophone == false))
{
// Get the current viseme frame
currentFrame = lipsyncContext.GetCurrentPhonemeFrame();
// Verify length (-1 for laughter)
if (currentFrame.Visemes.Length != (VISEME_COUNT - 1))
{
Debug.LogError("Unexpected number of visemes " + currentFrame.Visemes);
return;
}
// Copy to viseme array
currentFrame.Visemes.CopyTo(visemes, 0);
// Copy laughter as final element
visemes[VISEME_COUNT - 1] = EnableLaughter ? currentFrame.laughterScore : 0.0f;
// Send visemes to native implementation.
for (int i = 0; i < VISEME_COUNT; i++)
{
RuntimeVisemes.visemeParams[i] = visemes[i];
}
CAPI.ovrAvatar_SetVisemes(sdkAvatar, RuntimeVisemes);
}
}
}
| |
using Microsoft.Xna.Framework.Graphics;
namespace Cocos2D
{
internal struct CCV3F_T2F : IVertexType
{
internal static readonly VertexDeclaration VertexDeclaration;
/// <summary>
/// vertices (3F)
/// </summary>
internal CCVertex3F vertices; // 12 bytes
/// <summary>
/// tex coords (2F)
/// </summary>
internal CCTex2F texCoords; // 8 byts
static CCV3F_T2F()
{
var elements = new[]
{
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)
};
VertexDeclaration = new VertexDeclaration(elements);
}
#region IVertexType Members
VertexDeclaration IVertexType.VertexDeclaration
{
get { return VertexDeclaration; }
}
#endregion
}
/// <summary>
/// CCGrid3D is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z
/// </summary>
public class CCGrid3D : CCGridBase
{
private bool m_bDirty;
private CCIndexBuffer<ushort> m_pIndexBuffer;
protected ushort[] m_pIndices;
protected CCVertex3F[] m_pOriginalVertices;
private CCVertexBuffer<CCV3F_T2F> m_pVertexBuffer;
internal CCV3F_T2F[] m_pVertices;
//protected CCPoint[] m_pTexCoordinates;
//protected ccVertex3F[] m_pVertices;
/// <summary>
/// returns the vertex at a given position
/// </summary>
public CCVertex3F Vertex(CCGridSize pos)
{
return m_pVertices[pos.X * (m_sGridSize.Y + 1) + pos.Y].vertices;
}
/// <summary>
/// returns the original (non-transformed) vertex at a given position
/// </summary>
public CCVertex3F OriginalVertex(CCGridSize pos)
{
return m_pOriginalVertices[pos.X * (m_sGridSize.Y + 1) + pos.Y];
}
/// <summary>
/// sets a new vertex at a given position
/// </summary>
public void SetVertex(CCGridSize pos, ref CCVertex3F vertex)
{
m_pVertices[pos.X * (m_sGridSize.Y + 1) + pos.Y].vertices = vertex;
m_bDirty = true;
}
public override void Blit()
{
if (m_bDirty)
{
m_pVertexBuffer.UpdateBuffer();
}
bool save = CCDrawManager.VertexColorEnabled;
CCDrawManager.VertexColorEnabled = false;
CCDrawManager.DrawBuffer(m_pVertexBuffer, m_pIndexBuffer, 0, m_pIndices.Length / 3);
CCDrawManager.VertexColorEnabled = save;
}
public override void Reuse()
{
if (m_nReuseGrid > 0)
{
for (int i = 0, count = (m_sGridSize.X + 1) * (m_sGridSize.Y + 1); i < count; i++)
{
m_pOriginalVertices[i] = m_pVertices[i].vertices;
}
--m_nReuseGrid;
}
}
public override void CalculateVertexPoints()
{
float width = m_pTexture.PixelsWide;
float height = m_pTexture.PixelsHigh;
float imageH = m_pTexture.ContentSizeInPixels.Height;
int numOfPoints = (m_sGridSize.X + 1) * (m_sGridSize.Y + 1);
m_pVertexBuffer = new CCVertexBuffer<CCV3F_T2F>(numOfPoints, BufferUsage.WriteOnly);
m_pVertexBuffer.Count = numOfPoints;
m_pIndexBuffer = new CCIndexBuffer<ushort>(m_sGridSize.X * m_sGridSize.Y * 6, BufferUsage.WriteOnly);
m_pIndexBuffer.Count = m_sGridSize.X * m_sGridSize.Y * 6;
m_pVertices = m_pVertexBuffer.Data.Elements;
m_pIndices = m_pIndexBuffer.Data.Elements;
m_pOriginalVertices = new CCVertex3F[numOfPoints];
CCV3F_T2F[] vertArray = m_pVertices;
ushort[] idxArray = m_pIndices;
var l1 = new int[4];
var l2 = new CCVertex3F[4];
var tex1 = new int[4];
var tex2 = new CCPoint[4];
//int idx = -1;
for (int x = 0; x < m_sGridSize.X; ++x)
{
for (int y = 0; y < m_sGridSize.Y; ++y)
{
float x1 = x * m_obStep.X;
float x2 = x1 + m_obStep.X;
float y1 = y * m_obStep.Y;
float y2 = y1 + m_obStep.Y;
var a = (short) (x * (m_sGridSize.Y + 1) + y);
var b = (short) ((x + 1) * (m_sGridSize.Y + 1) + y);
var c = (short) ((x + 1) * (m_sGridSize.Y + 1) + (y + 1));
var d = (short) (x * (m_sGridSize.Y + 1) + (y + 1));
int idx = ((y * m_sGridSize.X) + x) * 6;
idxArray[idx + 0] = (ushort) a;
idxArray[idx + 1] = (ushort) b;
idxArray[idx + 2] = (ushort) d;
idxArray[idx + 3] = (ushort) b;
idxArray[idx + 4] = (ushort) c;
idxArray[idx + 5] = (ushort) d;
//var tempidx = new short[6] {a, d, b, b, d, c};
//Array.Copy(tempidx, 0, idxArray, 6 * idx, tempidx.Length);
l1[0] = a;
l1[1] = b;
l1[2] = c;
l1[3] = d;
//var e = new Vector3(x1, y1, 0);
//var f = new Vector3(x2, y1, 0);
//var g = new Vector3(x2, y2, 0);
//var h = new Vector3(x1, y2, 0);
l2[0] = new CCVertex3F(x1, y1, 0);
l2[1] = new CCVertex3F(x2, y1, 0);
l2[2] = new CCVertex3F(x2, y2, 0);
l2[3] = new CCVertex3F(x1, y2, 0);
tex1[0] = a;
tex1[1] = b;
tex1[2] = c;
tex1[3] = d;
tex2[0] = new CCPoint(x1, y1);
tex2[1] = new CCPoint(x2, y1);
tex2[2] = new CCPoint(x2, y2);
tex2[3] = new CCPoint(x1, y2);
for (int i = 0; i < 4; ++i)
{
vertArray[l1[i]].vertices = l2[i];
vertArray[tex1[i]].texCoords.U = tex2[i].X / width;
if (m_bIsTextureFlipped)
{
vertArray[tex1[i]].texCoords.V = tex2[i].Y / height;
}
else
{
vertArray[tex1[i]].texCoords.V = (imageH - tex2[i].Y) / height;
}
}
}
}
int n = (m_sGridSize.X + 1) * (m_sGridSize.Y + 1);
for (int i = 0; i < n; i++)
{
m_pOriginalVertices[i] = m_pVertices[i].vertices;
}
m_pIndexBuffer.UpdateBuffer();
m_bDirty = true;
}
public CCGrid3D(CCGridSize gridSize, CCTexture2D pTexture, bool bFlipped)
{
InitWithSize(gridSize, pTexture, bFlipped);
}
public CCGrid3D(CCGridSize gridSize)
{
InitWithSize(gridSize);
}
public CCGrid3D(CCGridSize gridSize, CCSize size)
{
InitWithSize(gridSize, size);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-2015 Charlie Poole, Rob Prouse
//
// 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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class ValueSourceTests : ValueSourceMayBeInherited
{
[Test]
public void ValueSourceCanBeStaticProperty(
[ValueSource(nameof(StaticProperty))] string source)
{
Assert.AreEqual("StaticProperty", source);
}
static IEnumerable StaticProperty
{
get
{
yield return "StaticProperty";
}
}
[Test]
public void ValueSourceCanBeInheritedStaticProperty(
[ValueSource(nameof(InheritedStaticProperty))] bool source)
{
Assert.AreEqual(true, source);
}
[Test]
public void ValueSourceMayNotBeInstanceProperty()
{
var result = TestBuilder.RunParameterizedMethodSuite(GetType(), "MethodWithValueSourceInstanceProperty");
Assert.That(result.Children.ToArray()[0].ResultState, Is.EqualTo(ResultState.NotRunnable));
}
public void MethodWithValueSourceInstanceProperty(
[ValueSource(nameof(InstanceProperty))] string source)
{
Assert.AreEqual("InstanceProperty", source);
}
IEnumerable InstanceProperty
{
get { return new object[] { "InstanceProperty" }; }
}
[Test]
public void ValueSourceCanBeStaticMethod(
[ValueSource(nameof(StaticMethod))] string source)
{
Assert.AreEqual("StaticMethod", source);
}
static IEnumerable StaticMethod()
{
return new object[] { "StaticMethod" };
}
[Test]
public void ValueSourceMayNotBeInstanceMethod()
{
var result = TestBuilder.RunParameterizedMethodSuite(GetType(), "MethodWithValueSourceInstanceMethod");
Assert.That(result.Children.ToArray()[0].ResultState, Is.EqualTo(ResultState.NotRunnable));
}
public void MethodWithValueSourceInstanceMethod(
[ValueSource(nameof(InstanceMethod))] string source)
{
Assert.AreEqual("InstanceMethod", source);
}
IEnumerable InstanceMethod()
{
return new object[] { "InstanceMethod" };
}
[Test]
public void ValueSourceCanBeStaticField(
[ValueSource(nameof(StaticField))] string source)
{
Assert.AreEqual("StaticField", source);
}
internal static object[] StaticField = { "StaticField" };
[Test]
public void ValueSourceMayNotBeInstanceField()
{
var result = TestBuilder.RunParameterizedMethodSuite(GetType(), "MethodWithValueSourceInstanceField");
Assert.That(result.Children.ToArray ()[0].ResultState, Is.EqualTo(ResultState.NotRunnable));
}
public void MethodWithValueSourceInstanceField(
[ValueSource(nameof(InstanceField))] string source)
{
Assert.AreEqual("InstanceField", source);
}
internal object[] InstanceField = { "InstanceField" };
[Test, Sequential]
public void MultipleArguments(
[ValueSource(nameof(Numerators))] int n,
[ValueSource(nameof(Denominators))] int d,
[ValueSource(nameof(Quotients))] int q)
{
Assert.AreEqual(q, n / d);
}
internal static int[] Numerators = new int[] { 12, 12, 12 };
internal static int[] Denominators = new int[] { 3, 4, 6 };
internal static int[] Quotients = new int[] { 4, 3, 2 };
[Test, Sequential]
public void ValueSourceMayBeInAnotherClass(
[ValueSource(typeof(DivideDataProvider), nameof(DivideDataProvider.Numerators))] int n,
[ValueSource(typeof(DivideDataProvider), nameof(DivideDataProvider.Denominators))] int d,
[ValueSource(typeof(DivideDataProvider), nameof(DivideDataProvider.Quotients))] int q)
{
Assert.AreEqual(q, n / d);
}
private class DivideDataProvider
{
internal static int[] Numerators = new int[] { 12, 12, 12 };
internal static int[] Denominators = new int[] { 3, 4, 6 };
internal static int[] Quotients = new int[] { 4, 3, 2 };
}
[Test]
public void ValueSourceMayBeGeneric(
[ValueSourceAttribute(typeof(ValueProvider), nameof(ValueProvider.IntegerProvider))] int val)
{
Assert.That(2 * val, Is.EqualTo(val + val));
}
public class ValueProvider
{
public static IEnumerable<int> IntegerProvider()
{
List<int> dataList = new List<int>();
dataList.Add(1);
dataList.Add(2);
dataList.Add(4);
dataList.Add(8);
return dataList;
}
public static IEnumerable<int> ForeignNullResultProvider()
{
return null;
}
}
public static string NullSource = null;
public static IEnumerable<int> NullDataSourceProvider()
{
return null;
}
public static IEnumerable<int> NullDataSourceProperty
{
get { return null; }
}
[Test, Explicit("Null or nonexistent data sources definitions should not prevent other tests from run #1121")]
public void ValueSourceMayNotBeNull(
[ValueSource(nameof(NullSource))] string nullSource,
[ValueSource(nameof(NullDataSourceProvider))] string nullDataSourceProvided,
[ValueSource(typeof(ValueProvider), nameof(ValueProvider.ForeignNullResultProvider))] string nullDataSourceProvider,
[ValueSource(nameof(NullDataSourceProperty))] int nullDataSourceProperty,
[ValueSource("SomeNonExistingMemberSource")] int nonExistingMember)
{
Assert.Fail();
}
[Test]
public void ValueSourceAttributeShouldThrowInsteadOfReturningNull()
{
var method = new MethodWrapper(GetType(), "ValueSourceMayNotBeNull");
var parameters = method.GetParameters();
foreach (var parameter in parameters)
{
var dataSource = parameter.GetCustomAttributes<IParameterDataSource>(false)[0];
Assert.Throws<InvalidDataSourceException>(() => dataSource.GetData(parameter));
}
}
[Test]
public void MethodWithArrayArguments([ValueSource(nameof(ComplexArrayBasedTestInput))] object o)
{
}
static object[] ComplexArrayBasedTestInput = new[]
{
new object[] { 1, "text", new object() },
new object[0],
new object[] { 1, new int[] { 2, 3 }, 4 },
new object[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
new object[] { new byte[,] { { 1, 2 }, { 2, 3 } } }
};
[Test]
public void TestNameIntrospectsArrayValues()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
GetType(), nameof(MethodWithArrayArguments));
Assert.That(suite.TestCaseCount, Is.EqualTo(5));
Assert.Multiple(() =>
{
Assert.That(suite.Tests[0].Name, Is.EqualTo(@"MethodWithArrayArguments([1, ""text"", System.Object])"));
Assert.That(suite.Tests[1].Name, Is.EqualTo(@"MethodWithArrayArguments([])"));
Assert.That(suite.Tests[2].Name, Is.EqualTo(@"MethodWithArrayArguments([1, Int32[], 4])"));
Assert.That(suite.Tests[3].Name, Is.EqualTo(@"MethodWithArrayArguments([1, 2, 3, 4, 5, ...])"));
Assert.That(suite.Tests[4].Name, Is.EqualTo(@"MethodWithArrayArguments([System.Byte[,]])"));
});
}
}
public class ValueSourceMayBeInherited
{
protected static IEnumerable<bool> InheritedStaticProperty
{
get { yield return true; }
}
}
}
| |
/*
* 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 MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.MySQL
{
public class MySQLEstateStore : IEstateDataStore
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string m_waitTimeoutSelect = "select @@wait_timeout";
private MySqlConnection m_connection;
private string m_connectionString;
private long m_waitTimeout;
private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond;
private long m_lastConnectionUse;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
try
{
m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString));
}
catch (Exception e)
{
m_log.Debug("Exception: password not found in connection string\n" + e.ToString());
}
m_connection = new MySqlConnection(m_connectionString);
m_connection.Open();
GetWaitTimeout();
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_connection, assem, "EstateStore");
m.Update();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
{
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
protected void GetWaitTimeout()
{
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect,
m_connection);
using (MySqlDataReader dbReader =
cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) *
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
dbReader.Close();
cmd.Dispose();
}
m_lastConnectionUse = DateTime.Now.Ticks;
m_log.DebugFormat(
"[REGION DB]: Connection wait timeout {0} seconds",
m_waitTimeout / TimeSpan.TicksPerSecond);
}
protected void CheckConnection()
{
long timeNow = DateTime.Now.Ticks;
if (timeNow - m_lastConnectionUse > m_waitTimeout ||
m_connection.State != ConnectionState.Open)
{
m_log.DebugFormat("[REGION DB]: Database connection has gone away - reconnecting");
lock (m_connection)
{
m_connection.Close();
m_connection = new MySqlConnection(m_connectionString);
m_connection.Open();
}
}
m_lastConnectionUse = timeNow;
}
public EstateSettings LoadEstateSettings(UUID regionID)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID";
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
IDataReader r = cmd.ExecuteReader();
if (r.Read())
{
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
m_FieldMap[name].SetValue(es, r[name]);
}
}
r.Close();
}
else
{
// Migration case
//
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")";
cmd.CommandText = sql;
cmd.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue("?" + name, "1");
else
cmd.Parameters.AddWithValue("?" + name, "0");
}
else
{
cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ID() as id";
cmd.Parameters.Clear();
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
r.Close();
cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
// Munge and transfer the ban list
//
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")";
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue("?" + name, "1");
else
cmd.Parameters.AddWithValue("?" + name, "0");
}
else
{
cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
// EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
r.Close();
return uuids.ToArray();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Threading;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
using System.Diagnostics;
using System.Reflection;
// All of these tests were created by Chris Mann and Jeff Callahan
namespace Microsoft.Build.UnitTests
{
#region EngineLoggingHelper
/// <summary>
/// This class is a basic implementation of EngineLoggingServices so that we can try and test the abstract EngineLoggingServices
/// class without a lot of other methods being added
/// </summary>
internal class EngineLoggingServicesHelper : EngineLoggingServices
{
/// <summary>
/// Reading queue
/// </summary>
DualQueue<BuildEventArgs> currentQueueBuildEvent;
/// <summary>
/// Reading queue
/// </summary>
DualQueue<NodeLoggingEvent> currentQueueNodeEvent;
internal EngineLoggingServicesHelper()
{
base.Initialize(new ManualResetEvent(false));
}
/// <summary>
/// We dont need to do anything to process events, we just want to get what events are in the queue
/// </summary>
internal override bool ProcessPostedLoggingEvents()
{
currentQueueBuildEvent = loggingQueueOfBuildEvents;
currentQueueNodeEvent = loggingQueueOfNodeEvents;
return true;
}
/// <summary>
/// Note that this "get" indirectly calls GetCurrentReadingQueue() which
/// returns references to distinct queues on sequential calls; in other
/// words this property has side effects on the internal data structures.
/// </summary>
internal DualQueue<BuildEventArgs> GetCurrentQueueBuildEvents()
{
ProcessPostedLoggingEvents();
return currentQueueBuildEvent;
}
/// <summary>
/// Note that this "get" indirectly calls GetCurrentReadingQueue() which
/// returns references to distinct queues on sequential calls; in other
/// words this property has side effects on the internal data structures.
/// </summary>
internal DualQueue<NodeLoggingEvent> GetCurrentQueueNodeEvents()
{
ProcessPostedLoggingEvents();
return loggingQueueOfNodeEvents;
}
}
#endregion
[TestFixture]
public class EngineLoggingServices_Tests
{
// A simple implementation of the abstract class EngineLoggingServices
EngineLoggingServicesHelper engineLoggingServicesHelper;
/// <summary>
/// Generate a generic BuildErrorEventArgs
/// </summary>
/// <param name="message">message to put in the event</param>
/// <returns>Event</returns>
private BuildErrorEventArgs GenerateBuildErrorEventArgs(string message)
{
return new BuildErrorEventArgs("SubCategory", "code", null, 0, 1, 2, 3, message, "Help", "EngineLoggingServicesTest");
}
/// <summary>
/// Generate a generic BuildWarningEventArgs
/// </summary>
/// <param name="message">message to put in the event</param>
/// <returns>Event</returns>
private BuildWarningEventArgs GenerateBuildWarningEventArgs(string message)
{
return new BuildWarningEventArgs("SubCategory", "code", null, 0, 1, 2, 3, message, "warning", "EngineLoggingServicesTest");
}
/// <summary>
/// Generate a generic BuildMessageEventArgs
/// </summary>
/// <param name="message">message to put in the event</param>
/// <param name="importance">importance for the message</param>
/// <returns>Event</returns>
private BuildMessageEventArgs GenerateBuildMessageEventArgs(string message, MessageImportance importance)
{
return new BuildMessageEventArgs(message, "HelpKeyword", "senderName", importance);
}
/// <summary>
/// A basic event derived from the abstract class CustomBuildEventArgs
/// </summary>
class MyCustomBuildEventArgs : CustomBuildEventArgs
{
public MyCustomBuildEventArgs() : base() { }
public MyCustomBuildEventArgs(string message) : base(message, "HelpKeyword", "SenderName") { }
}
/// <summary>
/// A custom BuildEventArgs derived from a CustomBuildEventArgs
/// </summary>
/// <param name="message">message to put in the event</param>
/// <returns></returns>
private MyCustomBuildEventArgs GenerateBuildCustomEventArgs(string message)
{
return new MyCustomBuildEventArgs("testCustomBuildEvent");
}
[SetUp]
public void SetUp()
{
engineLoggingServicesHelper = new EngineLoggingServicesHelper();
}
[TearDown]
public void TearDown()
{
engineLoggingServicesHelper = null;
}
#region TestEventBasedLoggingMethods
/// <summary>
/// Test the logging of and ErrorEvent
/// </summary>
[Test]
public void LogErrorEvent()
{
List<BuildEventArgs> eventList = new List<BuildEventArgs>();
// Log a number of events and then make sure that queue at the end contains all of those events
for (int i = 0; i < 10; i++)
{
BuildErrorEventArgs eventToAdd = GenerateBuildErrorEventArgs("ErrorMessage" + i);
eventList.Add(eventToAdd);
engineLoggingServicesHelper.LogErrorEvent(eventToAdd);
}
// Get the logging queue after we have logged a number of messages
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
// Assert that every event we sent to the logger exists in the queue
Assert.IsTrue(eventList.TrueForAll(delegate(BuildEventArgs args)
{
return currentQueue.Contains(args);
}), "Expected to find all events sent to LogErrorEvent");
// Assert that every event in the queue is of the correct type
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
/// <summary>
/// Test the case where null events are attempted to be logged
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void LogErrorEventNullEvent()
{
engineLoggingServicesHelper.LogErrorEvent(null);
}
/// <summary>
/// Test warning events
/// </summary>
[Test]
public void LogWarningEvent()
{
List<BuildEventArgs> eventList = new List<BuildEventArgs>();
// Log a number of events
for (int i = 0; i < 10; i++)
{
BuildWarningEventArgs eventToAdd = GenerateBuildWarningEventArgs("WarningMessage" + i);
eventList.Add(eventToAdd);
engineLoggingServicesHelper.LogWarningEvent(eventToAdd);
}
// Get the logged event queue from the "logger"
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
// Assert that every event we sent to the logger now exists in the queue
Assert.IsTrue(eventList.TrueForAll(delegate(BuildEventArgs args)
{
return currentQueue.Contains(args);
}), "Expected to find all events sent to LogWarningEvent");
// Assert that every event in the queue is of the correct type
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildWarningEventArgs>);
}
/// <summary>
/// Test the case where we attempt to log a null warning event
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void LogWarningEventNullEvent()
{
engineLoggingServicesHelper.LogWarningEvent(null);
}
/// <summary>
/// Test the case where we try and log a null message event
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void LogMessageEventNullEvent()
{
// Try and log a null when we are only going to log critical events
try
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogMessageEvent(null);
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
}
catch (Exception e)
{
Assert.Fail(e.Message + " Should not throw exception if OnlyLogCriticalEvents is true");
}
// Should throw an exception as OnlyLogCriticalEvents is false and the null check is performed
engineLoggingServicesHelper.LogMessageEvent(null);
}
/// <summary>
/// Test that we can log message events
/// </summary>
[Test]
public void LogMessageEvent()
{
List<BuildEventArgs> eventList = new List<BuildEventArgs>();
// Log a number of message events and keep track of the events we tried to log
for (int i = 0; i < 10; i++)
{
BuildMessageEventArgs eventToAdd = GenerateBuildMessageEventArgs("MessageMessage" + i, MessageImportance.Normal);
eventList.Add(eventToAdd);
engineLoggingServicesHelper.LogMessageEvent(eventToAdd);
}
// Get the queue of the events logged by the logger
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
// Assert that every event we sent to the logger exists in the logging queue
Assert.IsTrue(eventList.TrueForAll(delegate(BuildEventArgs args)
{
return currentQueue.Contains(args);
}), "Expected to find all events sent to LogMessageEvent");
// Assert that every event in the queue is of the correct type
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildMessageEventArgs>);
}
/// <summary>
/// Test the case where we try and log a null event
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void PostLoggingEventNullEvent()
{
BuildEventArgs nullEvent = null;
engineLoggingServicesHelper.PostLoggingEvent(nullEvent);
}
/// <summary>
/// Test the case where we try and log a null CustomEvent
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void LogCustomEventNullEvent()
{
engineLoggingServicesHelper.LogCustomEvent(null);
}
/// <summary>
/// Test that we can log CustomEvents
/// </summary>
[Test]
public void LogCustomEvent()
{
List<BuildEventArgs> eventList = new List<BuildEventArgs>();
// Log a number of events and keep track of which events we sent to the logger
for (int i = 0; i < 10; i++)
{
MyCustomBuildEventArgs eventToAdd = GenerateBuildCustomEventArgs("CustomMessage" + i);
eventList.Add(eventToAdd);
engineLoggingServicesHelper.LogCustomEvent(eventToAdd);
}
// Get the current queue of the logger
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
// Assert that every event we sent to the logger exists in the logging queue
Assert.IsTrue(eventList.TrueForAll(delegate(BuildEventArgs args)
{
return currentQueue.Contains(args);
}), "Expected to find all events sent to logcustomevent");
// Assert that every event in the queue is of the correct type
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<MyCustomBuildEventArgs>);
}
/// <summary>
/// Test that when we send an event to the logger we should see that same event in the queue
/// </summary>
[Test]
public void PostLoggingEventCustomEvent()
{
BuildEventArgs testBuildEventArgs = GenerateBuildCustomEventArgs("CustomMessage");
engineLoggingServicesHelper.PostLoggingEvent(testBuildEventArgs);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Contains(testBuildEventArgs), "Expected to find event sent to postloggingevent");
}
/// <summary>
/// Test that when we send an event to the logger we should see that same event in the queue
/// </summary>
[Test]
public void PostLoggingEventErrorEvent()
{
BuildEventArgs testBuildEventArgs = GenerateBuildErrorEventArgs("testErrorBuildEvent");
engineLoggingServicesHelper.PostLoggingEvent(testBuildEventArgs);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Contains(testBuildEventArgs), "Expected to find event we sent to postloggingevent");
}
/// <summary>
/// Test that when we send an event to the logger we should see that same event in the queue
/// </summary>
[Test]
public void PostLoggingEventWarningEvent()
{
BuildEventArgs testBuildEventArgs = GenerateBuildWarningEventArgs("testWarningBuildEvent");
engineLoggingServicesHelper.PostLoggingEvent(testBuildEventArgs);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Contains(testBuildEventArgs), "Expected to find event sent to postloggingevent");
}
/// <summary>
/// Test that when we send an event to the logger we should see that same event in the queue
/// </summary>
[Test]
public void PostLoggingEventMessageEvent()
{
BuildEventArgs testBuildEventArgs = GenerateBuildMessageEventArgs("testMessageBuildEvent", MessageImportance.Normal);
engineLoggingServicesHelper.PostLoggingEvent(testBuildEventArgs);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Contains(testBuildEventArgs), "Expected to find event sent to postloggingevent");
}
/// <summary>
/// Test that when we send an multiple event to the logger on multiple threads, we should everyone one of those event in the queue
/// </summary>
[Test]
public void PostLoggingEventMultiThreaded()
{
List<BuildEventArgs> eventsAdded = new List<BuildEventArgs>();
// Add a number of events on multiple threads
ManualResetEvent[] waitHandles = new ManualResetEvent[10];
for (int i = 0; i < waitHandles.Length; i++)
{
waitHandles[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
delegate(object state)
{
for (int j = 0; j < 4; j++)
{
BuildEventArgs testBuildEventArgs = GenerateBuildMessageEventArgs("testMessageBuildEvent" + i + "_" + j, MessageImportance.Normal);
lock (eventsAdded)
{
eventsAdded.Add(testBuildEventArgs);
}
engineLoggingServicesHelper.PostLoggingEvent(testBuildEventArgs);
}
((ManualResetEvent)state).Set();
}, waitHandles[i]);
}
// Wait for the threads to finish
foreach (ManualResetEvent resetEvent in waitHandles)
{
resetEvent.WaitOne();
}
// Get the current queue
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
// Assert that every event we sent to the logger on the multiple threads is in the queue at the end
Assert.IsTrue(eventsAdded.TrueForAll(delegate(BuildEventArgs args)
{
return currentQueue.Contains(args);
}), "Expected to find all events added to queue on multiple threads to be in the queue at the end");
}
#endregion
#region TestLogCommentMethods
/// <summary>
/// Test logging a null comment to the logger
/// </summary>
[Test]
public void LogCommentFromTextNullMessage()
{
// Test the case where we are trying to log a null and we are also trying to log only critical events
try
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogCommentFromText(null,MessageImportance.Low, null);
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
}
catch (Exception e)
{
Assert.Fail(e.Message + " Should not throw exception if OnlyLogCriticalEvents is true");
}
// Would have tested the case where null was passed and critical events is false, but this would cause an assertion window
// to popup thereby failing the test
}
/// <summary>
/// Test logging messages to the logger
/// </summary>
[Test]
public void LogCommentFromTextGoodMessages()
{
// Send a message, this message should be posted to the queue
engineLoggingServicesHelper.LogCommentFromText(null, MessageImportance.Low, "Message");
engineLoggingServicesHelper.LogCommentFromText(null, MessageImportance.Low, string.Empty);
// Make sure that the one message got posted to the queue
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 2, "Expected to find two events on the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildMessageEventArgs>);
}
/// <summary>
/// Test logging message comments to the logger
/// </summary>
[Test]
public void LogCommentGoodMessages()
{
// Send a message while not logging critical events, since comments are not considered critical they should
// not show up in the queue
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogComment((BuildEventContext)null, MessageImportance.Normal, "ErrorConvertedIntoWarning");
engineLoggingServicesHelper.LogComment((BuildEventContext)null, MessageImportance.Normal, "ErrorConvertedIntoWarning", 3);
engineLoggingServicesHelper.LogComment((BuildEventContext)null, "ErrorConvertedIntoWarning");
engineLoggingServicesHelper.LogComment((BuildEventContext)null, "ErrorCount", 3);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected to find no events on the queue");
// Sent the message while we are logging events, even non critical ones.
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogComment((BuildEventContext)null, MessageImportance.Normal, "ErrorConvertedIntoWarning");
engineLoggingServicesHelper.LogComment((BuildEventContext)null, MessageImportance.Normal, "ErrorConvertedIntoWarning", 3);
engineLoggingServicesHelper.LogComment((BuildEventContext)null, "ErrorConvertedIntoWarning");
engineLoggingServicesHelper.LogComment((BuildEventContext)null, "ErrorCount", 3);
// Get the queue from the logger
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
// Make sure we got all the events we sent to the logger
Assert.IsTrue(currentQueue.Count == 4, "Expected to find four events on the queue");
// Make sure that every event in the queue is of the correct type
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildMessageEventArgs>);
}
#endregion
#region TestStartedFinished
/// <summary>
/// Test logging the build started event
/// </summary>
[Test]
public void LogBuildStarted()
{
engineLoggingServicesHelper.LogBuildStarted();
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected to find one event in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildStartedEventArgs>);
}
/// <summary>
/// Test logging the build finished event
/// </summary>
[Test]
public void LogBuildFinished()
{
engineLoggingServicesHelper.LogBuildFinished(true);
engineLoggingServicesHelper.LogBuildFinished(false);
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 2, "Expected to find two events in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildFinishedEventArgs>);
}
/// <summary>
/// Checks to make sure that the event passed in is an instance of TType
/// </summary>
/// <typeparam name="TType">Type of event which should be found</typeparam>
/// <param name="e">Event to check against TType</param>
public void IsInstanceOfType<TType>(BuildEventArgs e)
{
Assert.IsTrue(typeof(TType).IsInstanceOfType(e), "Expected event to be a " + typeof(TType).Name);
}
/// <summary>
/// Check that every event in the queue is of the correct event type
/// </summary>
/// <param name="queue">queue to check</param>
/// <param name="action">An action which determines wheather or not a queue item is correct</param>
private void AssertForEachEventInQueue(DualQueue<BuildEventArgs> queue, Action<BuildEventArgs> action)
{
BuildEventArgs eventArgs;
while((eventArgs = queue.Dequeue())!=null)
{
action(eventArgs);
}
}
/// <summary>
/// Test logging of the task started event
/// </summary>
[Test]
public void LogTaskStarted()
{
// Test the logging while only logging critical events
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogTaskStarted(null, "taskName", "projectFile", "projectFileOfTaskNode");
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected to find no events in the queue");
// Test logging while logging all events
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogTaskStarted(null, "taskName", "projectFile", "projectFileOfTaskNode");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected to find one event in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<TaskStartedEventArgs>);
}
/// <summary>
/// Test that the TaskFinished event logs correctly
/// </summary>
[Test]
public void LogTaskFinished()
{
// Test the logging while only logging critical events
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogTaskFinished(null, "taskName", "projectFile", "projectFileOfTaskNode", true);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected to find no events in the queue");
// Test logging while logging all events
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogTaskFinished(null, "taskName", "projectFile", "projectFileOfTaskNode", true);
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected to find one event in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<TaskFinishedEventArgs>);
}
/// <summary>
/// Test that the TargetStarted event logs correctly
/// </summary>
[Test]
public void LogTargetStarted()
{
// Test logging while only logging critical events
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogTargetStarted(null, "TargetName", "projectFile", "projectFileOfTargetNode");
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected to find no events in the queue");
// Test logging while logging all events
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogTargetStarted(null, "targetName", "projectFile", "projectFileOfTargetNode");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected to find one event in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<TargetStartedEventArgs>);
}
/// <summary>
/// Test that TargetFinished logs correctly
/// </summary>
[Test]
public void LogTargetFinished()
{
// Test logging while only logging critical events
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogTargetFinished(null, "TargetName", "projectFile", "projectFileOfTargetNode", true);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected to find no events in the queue");
// Test logging while logging all events, even non critical ones
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogTargetFinished(null, "TargetName", "projectFile", "projectFileOfTargetNode", true);
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected to find one event in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<TargetFinishedEventArgs>);
}
/// <summary>
/// Test logging the ProjectStarted event
/// </summary>
[Test]
public void LogProjectStarted()
{
// Test logging while only logging critical events
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogProjectStarted(-1, null, null, "projectFile", "targetNames", null, null);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected to find no events in the queue");
// Test logging while logging all events, even non critical ones
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogProjectStarted(-1, null, null, "projectFile", "targetNames", null, null);
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected to find one event in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<ProjectStartedEventArgs>);
}
/// <summary>
/// Test logging the ProjectFinished event
/// </summary>
[Test]
public void LogProjectFinished()
{
// Test logging while only logging critical events
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogProjectFinished(null, "projectFile", true);
Assert.IsTrue(engineLoggingServicesHelper.GetCurrentQueueBuildEvents().Count == 0, "Expected no events in queue but found some");
//Test logging while logging all events, even non critical ones
engineLoggingServicesHelper.OnlyLogCriticalEvents = false;
engineLoggingServicesHelper.LogProjectFinished(null, "projectFile", true);
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected find one item in the queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<ProjectFinishedEventArgs>);
}
#endregion
#region LoggingMethodTests
[Test]
public void LogTaskWarningFromException()
{
engineLoggingServicesHelper.LogTaskWarningFromException(null, new Exception("testException"), new BuildEventFileInfo("noFile"), "taskName");
engineLoggingServicesHelper.LogTaskWarningFromException(null, null, new BuildEventFileInfo("noFile"), "taskName");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 2, "Expected two warnings in queue items");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildWarningEventArgs>);
}
[Test]
public void LogErrorWithoutSubcategoryResourceName()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogError(null, new BuildEventFileInfo("file"), "BuildTargetCompletely", "target");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected one event in queue!");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
[Test]
public void LogErrorWithSubcategoryResourceName()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogError(null, "SubCategoryForSchemaValidationErrors", new BuildEventFileInfo("file"), "BuildTargetCompletely", "target");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected one event in queue!");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
[Test]
public void LogErrorFromText()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogErrorFromText(null, "SubCategoryForSchemaValidationErrors", "MSB4000", "helpKeyword", new BuildEventFileInfo("file"), "error");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected one event in queue!");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
[Test]
public void LogWarningWithoutSubcategoryResourceName()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogWarning(null, new BuildEventFileInfo("file"), "BuildTargetCompletely", "target");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected one event in queue!");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildWarningEventArgs>);
}
[Test]
public void LogWarningWithSubcategoryResourceName()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogWarning(null, "SubCategoryForSchemaValidationErrors", new BuildEventFileInfo("file"), "BuildTargetCompletely", "target");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected one event in queue!");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildWarningEventArgs>);
}
[Test]
public void LogWarningFromText()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogWarningFromText(null, "SubCategoryForSchemaValidationErrors", "MSB4000", "helpKeyword", new BuildEventFileInfo("file"), "Warning");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 1, "Expected one event in queue!");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildWarningEventArgs>);
}
[Test]
public void LogInvalidProjectFileError()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogInvalidProjectFileError(null, new InvalidProjectFileException());
engineLoggingServicesHelper.LogInvalidProjectFileError(null, new InvalidProjectFileException("invalidProjectFile"));
InvalidProjectFileException invalidProjectFileException = new InvalidProjectFileException("anotherInvalidProjectFile");
invalidProjectFileException.HasBeenLogged = true;
engineLoggingServicesHelper.LogInvalidProjectFileError(null, invalidProjectFileException);
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 2, "Expected two errors in Queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
[Test]
public void LogFatalBuildError()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogFatalBuildError(null, new Exception("exception1!"), new BuildEventFileInfo("file1"));
engineLoggingServicesHelper.LogFatalBuildError(null, new Exception("exception2!"), new BuildEventFileInfo("file2"));
engineLoggingServicesHelper.LogFatalBuildError(null, new Exception("exception3!"), new BuildEventFileInfo("file3"));
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 3, "Expected three errors in Queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
[Test]
public void LogFatalError()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogFatalError(null, new Exception("exception1"), new BuildEventFileInfo("file1"), "BuildTargetCompletely", "target1");
engineLoggingServicesHelper.LogFatalError(null, new Exception("exception2"), new BuildEventFileInfo("file2"), "BuildTargetCompletely", "target2");
engineLoggingServicesHelper.LogFatalError(null, new Exception("exception3"), new BuildEventFileInfo("file3"), "BuildTargetCompletely", "target3");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 3, "Expected three errors in Queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
[Test]
public void LogFatalTaskError()
{
engineLoggingServicesHelper.OnlyLogCriticalEvents = true;
engineLoggingServicesHelper.LogFatalTaskError(null, new Exception("exception1"), new BuildEventFileInfo("file1"), "task1");
engineLoggingServicesHelper.LogFatalTaskError(null, new Exception("exception2"), new BuildEventFileInfo("file2"), "task2");
engineLoggingServicesHelper.LogFatalTaskError(null, new Exception("exception3"), new BuildEventFileInfo("file3"), "task3");
DualQueue<BuildEventArgs> currentQueue = engineLoggingServicesHelper.GetCurrentQueueBuildEvents();
Assert.IsTrue(currentQueue.Count == 3, "Expected three errors in Queue");
AssertForEachEventInQueue(currentQueue, IsInstanceOfType<BuildErrorEventArgs>);
}
#endregion
#region InProcLoggingTests
internal class VerifyEventSourceHelper
{
public VerifyEventSourceHelper()
{
sourceForEvents = new EventSource();
sourceForEvents.AnyEventRaised += new AnyEventHandler(this.AnyEventRaised);
sourceForEvents.BuildFinished += new BuildFinishedEventHandler(this.BuildFinished);
sourceForEvents.BuildStarted += new BuildStartedEventHandler(this.BuildStarted);
sourceForEvents.CustomEventRaised += new CustomBuildEventHandler(this.CustomEventRaised);
sourceForEvents.ErrorRaised += new BuildErrorEventHandler(this.ErrorRaised);
sourceForEvents.MessageRaised += new BuildMessageEventHandler(this.MessageRaised);
sourceForEvents.ProjectFinished += new ProjectFinishedEventHandler(this.ProjectFinished);
sourceForEvents.ProjectStarted += new ProjectStartedEventHandler(this.ProjectStarted);
sourceForEvents.TargetFinished += new TargetFinishedEventHandler(this.TargetFinished);
sourceForEvents.TargetStarted += new TargetStartedEventHandler(this.TargetStarted);
sourceForEvents.TaskFinished += new TaskFinishedEventHandler(this.TaskFinished);
sourceForEvents.TaskStarted += new TaskStartedEventHandler(this.TaskStarted);
sourceForEvents.WarningRaised += new BuildWarningEventHandler(this.WarningRaised);
sourceForEvents.StatusEventRaised += new BuildStatusEventHandler(this.StatusRaised);
ClearEvents();
}
public void ClearEvents()
{
eventsRaisedHash = new Hashtable();
eventsRaisedHash.Add("messageRaised", false);
eventsRaisedHash.Add("errorRaised", false);
eventsRaisedHash.Add("warningRaised", false);
eventsRaisedHash.Add("buildStarted", false);
eventsRaisedHash.Add("buildStatus", false);
eventsRaisedHash.Add("buildFinished", false);
eventsRaisedHash.Add("projectStarted", false);
eventsRaisedHash.Add("projectFinished", false);
eventsRaisedHash.Add("targetStarted", false);
eventsRaisedHash.Add("targetFinished", false);
eventsRaisedHash.Add("taskStarted", false);
eventsRaisedHash.Add("taskFinished", false);
eventsRaisedHash.Add("customEventRaised", false);
eventsRaisedHash.Add("anyEventRaised", false);
eventsRaisedHash.Add("statusRaised", false);
}
#region Fields
Hashtable eventsRaisedHash;
public EventSource sourceForEvents;
#endregion
#region EventHandlers
public void MessageRaised(object sender, BuildMessageEventArgs arg)
{
eventsRaisedHash["messageRaised"] = true;
}
public void StatusRaised(object sender, BuildStatusEventArgs arg)
{
eventsRaisedHash["statusRaised"] = true;
}
public void ErrorRaised(object sender, BuildErrorEventArgs arg)
{
eventsRaisedHash["errorRaised"] = true;
}
public void WarningRaised(object sender, BuildWarningEventArgs arg)
{
eventsRaisedHash["warningRaised"] = true;
}
public void BuildStarted(object sender, BuildStartedEventArgs arg)
{
eventsRaisedHash["buildStarted"] = true;
}
public void BuildFinished(object sender, BuildFinishedEventArgs arg)
{
eventsRaisedHash["buildFinished"] = true;
}
public void ProjectStarted(object sender, ProjectStartedEventArgs arg)
{
eventsRaisedHash["projectStarted"] = true;
}
public void ProjectFinished(object sender, ProjectFinishedEventArgs arg)
{
eventsRaisedHash["projectFinished"] = true;
}
public void TargetStarted(object sender, TargetStartedEventArgs arg)
{
eventsRaisedHash["targetStarted"] = true;
}
public void TargetFinished(object sender, TargetFinishedEventArgs arg)
{
eventsRaisedHash["targetFinished"] = true;
}
public void TaskStarted(object sender, TaskStartedEventArgs arg)
{
eventsRaisedHash["taskStarted"] = true;
}
public void TaskFinished(object sender, TaskFinishedEventArgs arg)
{
eventsRaisedHash["taskFinished"] = true;
}
public void CustomEventRaised(object sender, CustomBuildEventArgs arg)
{
eventsRaisedHash["customEventRaised"] = true;
}
public void AnyEventRaised(object sender, BuildEventArgs arg)
{
eventsRaisedHash["anyEventRaised"] = true;
}
#endregion
#region Assertions
public void AssertEventsAndNoOthers(params string[] eventList)
{
List<string> events = new List<string>(eventList);
foreach (string eventKey in eventList)
{
Assert.IsTrue(eventsRaisedHash[eventKey] != null, string.Format("Key {0} was not found in events list", eventKey));
}
foreach (string key in eventsRaisedHash.Keys)
{
if (events.Contains(key))
{
Assert.IsTrue((bool)(eventsRaisedHash[key]) == true, string.Format("Key {0} Should have been true", key));
continue;
}
Assert.IsFalse((bool)(eventsRaisedHash[key]) == true, string.Format("Key {0} Should not have been true", key));
}
}
#endregion
}
internal class MyCustomBuildErrorEventArgs : BuildErrorEventArgs
{
public MyCustomBuildErrorEventArgs()
: base()
{
}
}
internal class MyCustomBuildWarningEventArgs : BuildWarningEventArgs
{
public MyCustomBuildWarningEventArgs()
: base()
{
}
}
internal class MyCustomBuildMessageEventArgs : BuildMessageEventArgs
{
public MyCustomBuildMessageEventArgs()
: base()
{
}
}
internal class MyCustomBuildEventArg : BuildEventArgs
{
public MyCustomBuildEventArg()
: base()
{
}
}
internal class MyCustomStatusEventArg : BuildStatusEventArgs
{
public MyCustomStatusEventArg()
: base()
{
}
}
[Test]
public void InProcProcessPostedLoggingEvents()
{
VerifyEventSourceHelper eventSourceHelper = new VerifyEventSourceHelper();
List<EngineLoggingServicesInProc> engines = new List<EngineLoggingServicesInProc>();
EngineLoggingServicesInProc inProcLoggingServicesEventsAllEvents = new EngineLoggingServicesInProc(eventSourceHelper.sourceForEvents, false, new ManualResetEvent(false));
EngineLoggingServicesInProc inProcLoggingServicesEventsOnlyCriticalEvents = new EngineLoggingServicesInProc(eventSourceHelper.sourceForEvents, true, new ManualResetEvent(false));
engines.Add(inProcLoggingServicesEventsAllEvents);
engines.Add(inProcLoggingServicesEventsOnlyCriticalEvents);
foreach (EngineLoggingServicesInProc inProcLoggingServicesEvents in engines)
{
inProcLoggingServicesEvents.PostLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new TaskStartedEventArgs("message", "help", "projectFile", "taskFile", "taskName"));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "taskStarted", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new TaskFinishedEventArgs("message", "help", "projectFile", "taskFile", "taskName", true));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "taskFinished", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new TaskCommandLineEventArgs("commandLine", "taskName", MessageImportance.Low));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new BuildWarningEventArgs("SubCategoryForSchemaValidationErrors", "MSB4000", "file", 1, 2, 3, 4, "message", "help", "sender"));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "warningRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new BuildErrorEventArgs("SubCategoryForSchemaValidationErrors", "MSB4000", "file", 1, 2, 3, 4, "message", "help", "sender"));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "errorRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new TargetStartedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile"));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new ProjectStartedEventArgs(-1, "message", "help", "ProjectFile", "targetNames", null, null, null));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "projectStarted", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new ProjectFinishedEventArgs("message", "help", "ProjectFile", true));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "projectFinished", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new BuildStartedEventArgs("message", "help"));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "buildStarted", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new BuildFinishedEventArgs("message", "help", true));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "buildFinished", "statusRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new ExternalProjectStartedEventArgs("message", "help", "senderName", "projectFile", "targetNames"));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "customEventRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new ExternalProjectFinishedEventArgs("message", "help", "senderName", "projectFile", true));
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "customEventRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new MyCustomBuildEventArgs());
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "customEventRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new MyCustomBuildErrorEventArgs());
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "errorRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new MyCustomBuildWarningEventArgs());
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "warningRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new MyCustomBuildMessageEventArgs());
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
inProcLoggingServicesEvents.PostLoggingEvent(new MyCustomStatusEventArg());
inProcLoggingServicesEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "statusRaised");
eventSourceHelper.ClearEvents();
}
}
[Test]
public void TestCheckForFlushing()
{
VerifyEventSourceHelper eventSourceHelper = new VerifyEventSourceHelper();
ManualResetEvent flushEvent = new ManualResetEvent(false);
EngineLoggingServicesInProc inProcLoggingServicesEventsAllEvents = new EngineLoggingServicesInProc(eventSourceHelper.sourceForEvents, false, flushEvent);
Assert.IsFalse(inProcLoggingServicesEventsAllEvents.NeedsFlush(DateTime.Now.Ticks), "Didn't expect to need a flush because of time passed");
Assert.IsTrue(inProcLoggingServicesEventsAllEvents.NeedsFlush(DateTime.Now.Ticks + EngineLoggingServices.flushTimeoutInTicks + 1), "Expect to need a flush because of time passed");
for (int i = 0; i < 1001; i++)
{
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low));
}
Assert.IsTrue(inProcLoggingServicesEventsAllEvents.NeedsFlush(0), "Expect to need a flush because of number of events");
// Expect the handle to be signaled
long currentTicks = DateTime.Now.Ticks;
flushEvent.WaitOne(5000, false);
Assert.IsTrue((DateTime.Now.Ticks - currentTicks) / TimeSpan.TicksPerMillisecond < 4900, "Expected the handle to be signaled");
}
[Test]
public void LocalForwardingOfLoggingEvents()
{
VerifyEventSourceHelper eventSourceHelper = new VerifyEventSourceHelper();
EngineLoggingServicesInProc inProcLoggingServicesEventsAllEvents = new EngineLoggingServicesInProc(eventSourceHelper.sourceForEvents, false, new ManualResetEvent(false));
VerifyEventSourceHelper localForwardingSourceHelper = new VerifyEventSourceHelper();
VerifyEventSourceHelper centralLoggerEventSource = new VerifyEventSourceHelper();
inProcLoggingServicesEventsAllEvents.RegisterEventSource(EngineLoggingServicesInProc.LOCAL_FORWARDING_EVENTSOURCE, localForwardingSourceHelper.sourceForEvents);
inProcLoggingServicesEventsAllEvents.RegisterEventSource(EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID, centralLoggerEventSource.sourceForEvents);
// Create a local forwarding logger and initialize it
ConfigurableForwardingLogger localForwardingLogger = new ConfigurableForwardingLogger();
EventRedirector newRedirector = new EventRedirector(EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID, inProcLoggingServicesEventsAllEvents);
localForwardingLogger.BuildEventRedirector = newRedirector;
localForwardingLogger.Parameters = "TARGETSTARTEDEVENT;TARGETFINISHEDEVENT";
localForwardingLogger.Initialize(localForwardingSourceHelper.sourceForEvents);
// Verify that BuildStarted event is delivered both to the forwarding logger and ILoggers and
// that the forwarding logger forwards it to the central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new TargetStartedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile"));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
localForwardingSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
centralLoggerEventSource.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
localForwardingSourceHelper.ClearEvents();
centralLoggerEventSource.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that BuildFinished event is delivered both to the forwarding logger and ILoggers and
// that the forwarding logger forwards it to the central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
localForwardingSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
centralLoggerEventSource.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
localForwardingSourceHelper.ClearEvents();
centralLoggerEventSource.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that events that are not forwarded are not delivered to the central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
localForwardingSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
centralLoggerEventSource.AssertEventsAndNoOthers();
localForwardingSourceHelper.ClearEvents();
centralLoggerEventSource.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that external events with no logger id are not delivered to the forwarding or central loggers
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new NodeLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low)));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
localForwardingSourceHelper.AssertEventsAndNoOthers();
centralLoggerEventSource.AssertEventsAndNoOthers();
localForwardingSourceHelper.ClearEvents();
centralLoggerEventSource.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that external events with logger id are only delivered to central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent
(new NodeLoggingEventWithLoggerId(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low), 2));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers();
localForwardingSourceHelper.AssertEventsAndNoOthers();
centralLoggerEventSource.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
localForwardingSourceHelper.ClearEvents();
centralLoggerEventSource.ClearEvents();
eventSourceHelper.ClearEvents();
}
[Test]
public void ConfigurationByEngine()
{
VerifyEventSourceHelper eventSourceHelper = new VerifyEventSourceHelper();
EngineLoggingServicesInProc inProcLoggingServicesEventsAllEvents = new EngineLoggingServicesInProc(eventSourceHelper.sourceForEvents, false, new ManualResetEvent(false));
VerifyEventSourceHelper eventSourcePrivateHelper = new VerifyEventSourceHelper();
EngineLoggingServicesInProc inProcLoggingServicesEventsAllEventsPrivate = new EngineLoggingServicesInProc(eventSourcePrivateHelper.sourceForEvents, false, new ManualResetEvent(false));
Engine buildEngine = new Engine();
buildEngine.LoggingServices = inProcLoggingServicesEventsAllEvents;
// Create a logger that points at the private engine service (we'll use that logger as the central logger)
ConfigurableForwardingLogger localLogger = new ConfigurableForwardingLogger();
EventRedirector newRedirector = new EventRedirector(EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID, inProcLoggingServicesEventsAllEventsPrivate);
localLogger.BuildEventRedirector = newRedirector;
localLogger.Parameters = "TARGETSTARTEDEVENT;TARGETFINISHEDEVENT";
inProcLoggingServicesEventsAllEventsPrivate.RegisterEventSource(EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID, eventSourcePrivateHelper.sourceForEvents);
string filename = null;
Assembly assembly = Assembly.Load("MICROSOFT.BUILD.ENGINE");
filename = assembly.Location;
Console.WriteLine("Using the following engine assembly: " + filename);
LoggerDescription description = new LoggerDescription("ConfigurableForwardingLogger", null, filename, "TARGETSTARTEDEVENT;TARGETFINISHEDEVENT", LoggerVerbosity.Normal);
buildEngine.RegisterDistributedLogger(localLogger, description);
// Verify that BuildStarted event is delivered both to the forwarding logger and ILoggers and
// that the forwarding logger forwards it to the central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new TargetStartedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile"));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEventsPrivate.ProcessPostedLoggingEvents();
eventSourcePrivateHelper.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
eventSourcePrivateHelper.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that BuildFinished event is delivered both to the forwarding logger and ILoggers and
// that the forwarding logger forwards it to the central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(
new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEventsPrivate.ProcessPostedLoggingEvents();
eventSourcePrivateHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
eventSourcePrivateHelper.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that events that are not forwarded are not delivered to the central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEventsPrivate.ProcessPostedLoggingEvents();
eventSourcePrivateHelper.AssertEventsAndNoOthers();
eventSourcePrivateHelper.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that external events with no logger id are not delivered to the forwarding or central loggers
inProcLoggingServicesEventsAllEvents.PostLoggingEvent(new NodeLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low)));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEventsPrivate.ProcessPostedLoggingEvents();
eventSourcePrivateHelper.AssertEventsAndNoOthers();
eventSourcePrivateHelper.ClearEvents();
eventSourceHelper.ClearEvents();
// Verify that external events with logger id are only delivered to central logger
inProcLoggingServicesEventsAllEvents.PostLoggingEvent
(new NodeLoggingEventWithLoggerId(
new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true), 2));
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEventsPrivate.ProcessPostedLoggingEvents();
eventSourcePrivateHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
eventSourcePrivateHelper.ClearEvents();
eventSourceHelper.ClearEvents();
}
#endregion
#region OutProcLoggingTest
/// <summary>
/// Test logging the out of proc logger by sending events to the logger and check
/// the inproc logger queue which is the eventual handler of the events
/// </summary>
[Test]
public void OutProcLoggingTest()
{
VerifyEventSourceHelper eventSourceHelper = new VerifyEventSourceHelper();
EngineLoggingServicesInProc inProcLoggingServicesEventsAllEvents = new EngineLoggingServicesInProc(eventSourceHelper.sourceForEvents, false, new ManualResetEvent(false));
Engine buildEngine = new Engine();
buildEngine.LoggingServices = inProcLoggingServicesEventsAllEvents;
EngineCallback outProcessorProxy = new EngineCallback(buildEngine);
int nodeId = buildEngine.GetNextNodeId();
Node parentNode = new Node(nodeId, new LoggerDescription[0], outProcessorProxy, null,
ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, String.Empty);
EngineLoggingServicesOutProc loggingServicesOutProc = new EngineLoggingServicesOutProc(parentNode, new ManualResetEvent(false));
loggingServicesOutProc.PostLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new TaskStartedEventArgs("message", "help", "projectFile", "taskFile", "taskName"));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "taskStarted", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new TaskFinishedEventArgs("message", "help", "projectFile", "taskFile", "taskName", true));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "taskFinished", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new TaskCommandLineEventArgs("commandLine", "taskName", MessageImportance.Low));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new BuildWarningEventArgs("SubCategoryForSchemaValidationErrors", "MSB4000", "file", 1, 2, 3, 4, "message", "help", "sender"));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "warningRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new BuildErrorEventArgs("SubCategoryForSchemaValidationErrors", "MSB4000", "file", 1, 2, 3, 4, "message", "help", "sender"));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "errorRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new TargetStartedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile"));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetStarted", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "targetFinished", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new ProjectStartedEventArgs(-1, "message", "help", "ProjectFile", "targetNames", null, null, null));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "projectStarted", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new ProjectFinishedEventArgs("message", "help", "ProjectFile", true));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "projectFinished", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new BuildStartedEventArgs("message", "help"));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "buildStarted", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new BuildFinishedEventArgs("message", "help", true));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "buildFinished", "statusRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new ExternalProjectStartedEventArgs("message", "help", "senderName", "projectFile", "targetNames"));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "customEventRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new ExternalProjectFinishedEventArgs("message", "help", "senderName", "projectFile", true));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "customEventRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildEventArgs());
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "customEventRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildErrorEventArgs());
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "errorRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildWarningEventArgs());
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "warningRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildMessageEventArgs());
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildMessageEventArgs());
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildWarningEventArgs());
loggingServicesOutProc.PostLoggingEvent(new MyCustomBuildErrorEventArgs());
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised", "warningRaised", "errorRaised");
eventSourceHelper.ClearEvents();
// Check that node logging events are forwarded correctly with Id
loggingServicesOutProc.PostLoggingEvent(new NodeLoggingEventWithLoggerId(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low), 0));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
// Check that node logging events are forwarded correctly with no Id
loggingServicesOutProc.PostLoggingEvent(new NodeLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low)));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
// Register another event source and test that events are delivered correctly
VerifyEventSourceHelper privateEventSourceHelper1 = new VerifyEventSourceHelper();
VerifyEventSourceHelper privateEventSourceHelper2 = new VerifyEventSourceHelper();
inProcLoggingServicesEventsAllEvents.RegisterEventSource(EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID, privateEventSourceHelper1.sourceForEvents);
inProcLoggingServicesEventsAllEvents.RegisterEventSource(EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID + 1, privateEventSourceHelper2.sourceForEvents);
// Check that node logging events are forwarded correctly with Id
loggingServicesOutProc.PostLoggingEvent(new NodeLoggingEventWithLoggerId(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low), 0));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
//send a lot of events to test the event batching
for (int i = 0; i < 600; i++)
{
loggingServicesOutProc.PostLoggingEvent(new NodeLoggingEventWithLoggerId(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low), 0));
}
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised");
eventSourceHelper.ClearEvents();
// Check that the events are correctly sorted when posted with different logger ids
loggingServicesOutProc.PostLoggingEvent(new BuildMessageEventArgs("Message", "help", "sender", MessageImportance.Low));
loggingServicesOutProc.PostLoggingEvent(new NodeLoggingEventWithLoggerId(new BuildStartedEventArgs("message", "help"), EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID));
loggingServicesOutProc.PostLoggingEvent(new NodeLoggingEventWithLoggerId(new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true),
EngineLoggingServicesInProc.FIRST_AVAILABLE_LOGGERID +1));
loggingServicesOutProc.ProcessPostedLoggingEvents();
inProcLoggingServicesEventsAllEvents.ProcessPostedLoggingEvents();
privateEventSourceHelper1.AssertEventsAndNoOthers("anyEventRaised", "statusRaised", "buildStarted");
privateEventSourceHelper2.AssertEventsAndNoOthers("anyEventRaised", "statusRaised", "targetFinished");
eventSourceHelper.AssertEventsAndNoOthers("anyEventRaised", "messageRaised" );
eventSourceHelper.ClearEvents();
}
#endregion
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages client side native call lifecycle.
/// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{
Channel channel;
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Set after status is received. Only used for streaming response calls.
Status? finishedStatus;
bool readObserverCompleted; // True if readObserver has already been completed.
public AsyncCall(Func<TRequest, byte[]> serializer, Func<byte[], TResponse> deserializer) : base(serializer, deserializer)
{
}
public void Initialize(Channel channel, CompletionQueueSafeHandle cq, string methodName)
{
this.channel = channel;
var call = CallSafeHandle.Create(channel.Handle, channel.CompletionRegistry, cq, methodName, channel.Target, Timespec.InfFuture);
channel.Environment.DebugStats.ActiveClientCalls.Increment();
InitializeInternal(call);
}
// TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
// it is reusing fair amount of code in this class, so we are leaving it here.
// TODO: for other calls, you need to call Initialize, this methods calls initialize
// on its own, so there's a usage inconsistency.
/// <summary>
/// Blocking unary request - unary response call.
/// </summary>
public TResponse UnaryCall(Channel channel, string methodName, TRequest msg, Metadata headers)
{
using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create())
{
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
Initialize(channel, cq, methodName);
started = true;
halfcloseRequested = true;
readingDone = true;
}
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
using (var ctx = BatchContextSafeHandle.Create())
{
call.StartUnary(payload, ctx, metadataArray);
var ev = cq.Pluck(ctx.Handle);
bool success = (ev.success != 0);
try
{
HandleUnaryResponse(success, ctx);
}
catch (Exception e)
{
Console.WriteLine("Exception occured while invoking completion delegate: " + e);
}
}
}
try
{
// Once the blocking call returns, the result should be available synchronously.
return unaryResponseTcs.Task.Result;
}
catch (AggregateException ae)
{
throw ExceptionHelper.UnwrapRpcException(ae);
}
}
}
/// <summary>
/// Starts a unary request - unary response call.
/// </summary>
public Task<TResponse> UnaryCallAsync(TRequest msg, Metadata headers)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartUnary(payload, HandleUnaryResponse, metadataArray);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync(Metadata headers)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartClientStreaming(HandleUnaryResponse, metadataArray);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg, Metadata headers)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
halfcloseRequested = true;
halfclosed = true; // halfclose not confirmed yet, but it will be once finishedHandler is called.
byte[] payload = UnsafeSerialize(msg);
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartServerStreaming(payload, HandleFinished, metadataArray);
}
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall(Metadata headers)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartDuplexStreaming(HandleFinished, metadataArray);
}
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendMessage(TRequest msg, AsyncCompletionDelegate<object> completionDelegate)
{
StartSendMessageInternal(msg, completionDelegate);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate)
{
StartReadMessageInternal(completionDelegate);
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate)
{
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
call.StartSendCloseFromClient(HandleHalfclosed);
halfcloseRequested = true;
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// On client-side, we only fire readCompletionDelegate once all messages have been read
/// and status has been received.
/// </summary>
protected override void ProcessLastRead(AsyncCompletionDelegate<TResponse> completionDelegate)
{
if (completionDelegate != null && readingDone && finishedStatus.HasValue)
{
bool shouldComplete;
lock (myLock)
{
shouldComplete = !readObserverCompleted;
readObserverCompleted = true;
}
if (shouldComplete)
{
var status = finishedStatus.Value;
if (status.StatusCode != StatusCode.OK)
{
FireCompletion(completionDelegate, default(TResponse), new RpcException(status));
}
else
{
FireCompletion(completionDelegate, default(TResponse), null);
}
}
}
}
protected override void OnReleaseResources()
{
channel.Environment.DebugStats.ActiveClientCalls.Decrement();
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, BatchContextSafeHandle ctx)
{
lock (myLock)
{
finished = true;
halfclosed = true;
ReleaseResourcesIfPossible();
}
if (!success)
{
unaryResponseTcs.SetException(new RpcException(new Status(StatusCode.Internal, "Internal error occured.")));
return;
}
var status = ctx.GetReceivedStatus();
if (status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status));
return;
}
// TODO: handle deserialization error
TResponse msg;
TryDeserialize(ctx.GetReceivedMessage(), out msg);
unaryResponseTcs.SetResult(msg);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, BatchContextSafeHandle ctx)
{
var status = ctx.GetReceivedStatus();
AsyncCompletionDelegate<TResponse> origReadCompletionDelegate = null;
lock (myLock)
{
finished = true;
finishedStatus = status;
origReadCompletionDelegate = readCompletionDelegate;
ReleaseResourcesIfPossible();
}
ProcessLastRead(origReadCompletionDelegate);
}
}
}
| |
// ************************ ParseSMDeclaration : char ************************
//
// Char1 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'S' = Char2, default = decline;
// Char2 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 't' = Char3, default = decline;
// Char3 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'a' = Char4, default = decline;
// Char4 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 't' = Char5, default = decline;
// Char5 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'e' = Char6, default = decline;
// Char6 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'M' = Char7, default = decline;
// Char7 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'a' = Char8, default = decline;
// Char8 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'c' = Char9, default = decline;
// Char9 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'h' = Char10, default = decline;
// Char10 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'i' = Char11, default = decline;
// Char11 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'n' = Char12, default = decline;
// Char12 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes,
// 'e' = accept, default = decline;
// ParseSingleQuotes : ParseSingleQuotes ? decline : decline;
// ParseDoubleQuotes : ParseDoubleQuotes ? decline : decline;
//
//
// This file was automatically generated from a tool that converted the
// above state machine definition into this state machine class.
// Any changes to this code will be replaced the next time the code is generated.
using System;
using System.Collections.Generic;
namespace StateMachineParser
{
public class ParseSMDeclaration
{
public enum States
{
Char1 = 0, Char2 = 1,
Char3 = 2, Char4 = 3,
Char5 = 4, Char6 = 5,
Char7 = 6, Char8 = 7,
Char9 = 8, Char10 = 9,
Char11 = 10, Char12 = 11,
ParseSingleQuotes = 12, ParseDoubleQuotes = 13,
}
private States? state = null;
public States? CurrentState { get { return state; } }
private char currentCommand;
public char CurrentCommand { get { return currentCommand; } }
private bool reset = false;
private Action<char> onChar1State = null;
private Action<char> onChar1Enter = null;
private Action<char> onChar1Exit = null;
private Action<char> onChar2State = null;
private Action<char> onChar2Enter = null;
private Action<char> onChar2Exit = null;
private Action<char> onChar3State = null;
private Action<char> onChar3Enter = null;
private Action<char> onChar3Exit = null;
private Action<char> onChar4State = null;
private Action<char> onChar4Enter = null;
private Action<char> onChar4Exit = null;
private Action<char> onChar5State = null;
private Action<char> onChar5Enter = null;
private Action<char> onChar5Exit = null;
private Action<char> onChar6State = null;
private Action<char> onChar6Enter = null;
private Action<char> onChar6Exit = null;
private Action<char> onChar7State = null;
private Action<char> onChar7Enter = null;
private Action<char> onChar7Exit = null;
private Action<char> onChar8State = null;
private Action<char> onChar8Enter = null;
private Action<char> onChar8Exit = null;
private Action<char> onChar9State = null;
private Action<char> onChar9Enter = null;
private Action<char> onChar9Exit = null;
private Action<char> onChar10State = null;
private Action<char> onChar10Enter = null;
private Action<char> onChar10Exit = null;
private Action<char> onChar11State = null;
private Action<char> onChar11Enter = null;
private Action<char> onChar11Exit = null;
private Action<char> onChar12State = null;
private Action<char> onChar12Enter = null;
private Action<char> onChar12Exit = null;
private Action<char> onParseSingleQuotesState = null;
private Action<char> onParseSingleQuotesEnter = null;
private Action<char> onParseSingleQuotesExit = null;
private Action<char> onParseDoubleQuotesState = null;
private Action<char> onParseDoubleQuotesEnter = null;
private Action<char> onParseDoubleQuotesExit = null;
private Action<char> onAccept = null;
private Action<char> onDecline = null;
private Action<char> onEnd = null;
public readonly ParseSingleQuotes ParseSingleQuotesMachine = new ParseSingleQuotes();
public readonly ParseDoubleQuotes ParseDoubleQuotesMachine = new ParseDoubleQuotes();
public bool? Input(Queue<char> data)
{
if (reset)
state = null;
bool? result = null;
if (data == null)
return null;
bool? nestResult;
Reset:
reset = false;
switch (state)
{
case null:
if (data.Count > 0)
{
state = States.Char1;
goto ResumeChar1;
}
else
goto End;
case States.Char1:
goto ResumeChar1;
case States.Char2:
goto ResumeChar2;
case States.Char3:
goto ResumeChar3;
case States.Char4:
goto ResumeChar4;
case States.Char5:
goto ResumeChar5;
case States.Char6:
goto ResumeChar6;
case States.Char7:
goto ResumeChar7;
case States.Char8:
goto ResumeChar8;
case States.Char9:
goto ResumeChar9;
case States.Char10:
goto ResumeChar10;
case States.Char11:
goto ResumeChar11;
case States.Char12:
goto ResumeChar12;
case States.ParseSingleQuotes:
goto ResumeParseSingleQuotes;
case States.ParseDoubleQuotes:
goto ResumeParseDoubleQuotes;
}
EnterChar1:
state = States.Char1;
if (onChar1Enter != null)
onChar1Enter(currentCommand);
if (onChar1State != null)
onChar1State(currentCommand);
ResumeChar1:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar1Exit != null)
onChar1Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar1Exit != null)
onChar1Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'S':
if (onChar1Exit != null)
onChar1Exit(currentCommand);
goto EnterChar2;
default:
if (onChar1Exit != null)
onChar1Exit(currentCommand);
goto Decline;
}
EnterChar2:
state = States.Char2;
if (onChar2Enter != null)
onChar2Enter(currentCommand);
if (onChar2State != null)
onChar2State(currentCommand);
ResumeChar2:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar2Exit != null)
onChar2Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar2Exit != null)
onChar2Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 't':
if (onChar2Exit != null)
onChar2Exit(currentCommand);
goto EnterChar3;
default:
if (onChar2Exit != null)
onChar2Exit(currentCommand);
goto Decline;
}
EnterChar3:
state = States.Char3;
if (onChar3Enter != null)
onChar3Enter(currentCommand);
if (onChar3State != null)
onChar3State(currentCommand);
ResumeChar3:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar3Exit != null)
onChar3Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar3Exit != null)
onChar3Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'a':
if (onChar3Exit != null)
onChar3Exit(currentCommand);
goto EnterChar4;
default:
if (onChar3Exit != null)
onChar3Exit(currentCommand);
goto Decline;
}
EnterChar4:
state = States.Char4;
if (onChar4Enter != null)
onChar4Enter(currentCommand);
if (onChar4State != null)
onChar4State(currentCommand);
ResumeChar4:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar4Exit != null)
onChar4Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar4Exit != null)
onChar4Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 't':
if (onChar4Exit != null)
onChar4Exit(currentCommand);
goto EnterChar5;
default:
if (onChar4Exit != null)
onChar4Exit(currentCommand);
goto Decline;
}
EnterChar5:
state = States.Char5;
if (onChar5Enter != null)
onChar5Enter(currentCommand);
if (onChar5State != null)
onChar5State(currentCommand);
ResumeChar5:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar5Exit != null)
onChar5Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar5Exit != null)
onChar5Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'e':
if (onChar5Exit != null)
onChar5Exit(currentCommand);
goto EnterChar6;
default:
if (onChar5Exit != null)
onChar5Exit(currentCommand);
goto Decline;
}
EnterChar6:
state = States.Char6;
if (onChar6Enter != null)
onChar6Enter(currentCommand);
if (onChar6State != null)
onChar6State(currentCommand);
ResumeChar6:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar6Exit != null)
onChar6Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar6Exit != null)
onChar6Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'M':
if (onChar6Exit != null)
onChar6Exit(currentCommand);
goto EnterChar7;
default:
if (onChar6Exit != null)
onChar6Exit(currentCommand);
goto Decline;
}
EnterChar7:
state = States.Char7;
if (onChar7Enter != null)
onChar7Enter(currentCommand);
if (onChar7State != null)
onChar7State(currentCommand);
ResumeChar7:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar7Exit != null)
onChar7Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar7Exit != null)
onChar7Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'a':
if (onChar7Exit != null)
onChar7Exit(currentCommand);
goto EnterChar8;
default:
if (onChar7Exit != null)
onChar7Exit(currentCommand);
goto Decline;
}
EnterChar8:
state = States.Char8;
if (onChar8Enter != null)
onChar8Enter(currentCommand);
if (onChar8State != null)
onChar8State(currentCommand);
ResumeChar8:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar8Exit != null)
onChar8Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar8Exit != null)
onChar8Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'c':
if (onChar8Exit != null)
onChar8Exit(currentCommand);
goto EnterChar9;
default:
if (onChar8Exit != null)
onChar8Exit(currentCommand);
goto Decline;
}
EnterChar9:
state = States.Char9;
if (onChar9Enter != null)
onChar9Enter(currentCommand);
if (onChar9State != null)
onChar9State(currentCommand);
ResumeChar9:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar9Exit != null)
onChar9Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar9Exit != null)
onChar9Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'h':
if (onChar9Exit != null)
onChar9Exit(currentCommand);
goto EnterChar10;
default:
if (onChar9Exit != null)
onChar9Exit(currentCommand);
goto Decline;
}
EnterChar10:
state = States.Char10;
if (onChar10Enter != null)
onChar10Enter(currentCommand);
if (onChar10State != null)
onChar10State(currentCommand);
ResumeChar10:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar10Exit != null)
onChar10Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar10Exit != null)
onChar10Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'i':
if (onChar10Exit != null)
onChar10Exit(currentCommand);
goto EnterChar11;
default:
if (onChar10Exit != null)
onChar10Exit(currentCommand);
goto Decline;
}
EnterChar11:
state = States.Char11;
if (onChar11Enter != null)
onChar11Enter(currentCommand);
if (onChar11State != null)
onChar11State(currentCommand);
ResumeChar11:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar11Exit != null)
onChar11Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar11Exit != null)
onChar11Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'n':
if (onChar11Exit != null)
onChar11Exit(currentCommand);
goto EnterChar12;
default:
if (onChar11Exit != null)
onChar11Exit(currentCommand);
goto Decline;
}
EnterChar12:
state = States.Char12;
if (onChar12Enter != null)
onChar12Enter(currentCommand);
if (onChar12State != null)
onChar12State(currentCommand);
ResumeChar12:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\'':
if (onChar12Exit != null)
onChar12Exit(currentCommand);
goto EnterParseSingleQuotes;
case '"':
if (onChar12Exit != null)
onChar12Exit(currentCommand);
goto EnterParseDoubleQuotes;
case 'e':
if (onChar12Exit != null)
onChar12Exit(currentCommand);
goto Accept;
default:
if (onChar12Exit != null)
onChar12Exit(currentCommand);
goto Decline;
}
EnterParseSingleQuotes:
state = States.ParseSingleQuotes;
if (onParseSingleQuotesEnter != null)
onParseSingleQuotesEnter(currentCommand);
if (onParseSingleQuotesState != null)
onParseSingleQuotesState(currentCommand);
ResumeParseSingleQuotes:
nestResult = ParseSingleQuotesMachine.Input(data);
switch (nestResult)
{
case null:
goto End;
case true:
if (onParseSingleQuotesExit != null)
onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand);
goto Decline;
case false:
if (onParseSingleQuotesExit != null)
onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand);
goto Decline;
}
EnterParseDoubleQuotes:
state = States.ParseDoubleQuotes;
if (onParseDoubleQuotesEnter != null)
onParseDoubleQuotesEnter(currentCommand);
if (onParseDoubleQuotesState != null)
onParseDoubleQuotesState(currentCommand);
ResumeParseDoubleQuotes:
nestResult = ParseDoubleQuotesMachine.Input(data);
switch (nestResult)
{
case null:
goto End;
case true:
if (onParseDoubleQuotesExit != null)
onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand);
goto Decline;
case false:
if (onParseDoubleQuotesExit != null)
onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand);
goto Decline;
}
Accept:
result = true;
state = null;
if (onAccept != null)
onAccept(currentCommand);
goto End;
Decline:
result = false;
state = null;
if (onDecline != null)
onDecline(currentCommand);
goto End;
End:
if (onEnd != null)
onEnd(currentCommand);
if (reset)
{
goto Reset;
}
return result;
}
public void AddOnChar1(Action<char> addedFunc)
{
onChar1State += addedFunc;
}
public void AddOnChar2(Action<char> addedFunc)
{
onChar2State += addedFunc;
}
public void AddOnChar3(Action<char> addedFunc)
{
onChar3State += addedFunc;
}
public void AddOnChar4(Action<char> addedFunc)
{
onChar4State += addedFunc;
}
public void AddOnChar5(Action<char> addedFunc)
{
onChar5State += addedFunc;
}
public void AddOnChar6(Action<char> addedFunc)
{
onChar6State += addedFunc;
}
public void AddOnChar7(Action<char> addedFunc)
{
onChar7State += addedFunc;
}
public void AddOnChar8(Action<char> addedFunc)
{
onChar8State += addedFunc;
}
public void AddOnChar9(Action<char> addedFunc)
{
onChar9State += addedFunc;
}
public void AddOnChar10(Action<char> addedFunc)
{
onChar10State += addedFunc;
}
public void AddOnChar11(Action<char> addedFunc)
{
onChar11State += addedFunc;
}
public void AddOnChar12(Action<char> addedFunc)
{
onChar12State += addedFunc;
}
public void AddOnParseSingleQuotes(Action<char> addedFunc)
{
AddOnParseSingleQuotesEnter(addedFunc);
ParseSingleQuotesMachine.addOnAllStates(addedFunc);
}
public void AddOnParseDoubleQuotes(Action<char> addedFunc)
{
AddOnParseDoubleQuotesEnter(addedFunc);
ParseDoubleQuotesMachine.addOnAllStates(addedFunc);
}
public void AddOnChar1Enter(Action<char> addedFunc)
{
onChar1Enter += addedFunc;
}
public void AddOnChar2Enter(Action<char> addedFunc)
{
onChar2Enter += addedFunc;
}
public void AddOnChar3Enter(Action<char> addedFunc)
{
onChar3Enter += addedFunc;
}
public void AddOnChar4Enter(Action<char> addedFunc)
{
onChar4Enter += addedFunc;
}
public void AddOnChar5Enter(Action<char> addedFunc)
{
onChar5Enter += addedFunc;
}
public void AddOnChar6Enter(Action<char> addedFunc)
{
onChar6Enter += addedFunc;
}
public void AddOnChar7Enter(Action<char> addedFunc)
{
onChar7Enter += addedFunc;
}
public void AddOnChar8Enter(Action<char> addedFunc)
{
onChar8Enter += addedFunc;
}
public void AddOnChar9Enter(Action<char> addedFunc)
{
onChar9Enter += addedFunc;
}
public void AddOnChar10Enter(Action<char> addedFunc)
{
onChar10Enter += addedFunc;
}
public void AddOnChar11Enter(Action<char> addedFunc)
{
onChar11Enter += addedFunc;
}
public void AddOnChar12Enter(Action<char> addedFunc)
{
onChar12Enter += addedFunc;
}
public void AddOnParseSingleQuotesEnter(Action<char> addedFunc)
{
onParseSingleQuotesEnter += addedFunc;
}
public void AddOnParseDoubleQuotesEnter(Action<char> addedFunc)
{
onParseDoubleQuotesEnter += addedFunc;
}
public void AddOnChar1Exit(Action<char> addedFunc)
{
onChar1Exit += addedFunc;
}
public void AddOnChar2Exit(Action<char> addedFunc)
{
onChar2Exit += addedFunc;
}
public void AddOnChar3Exit(Action<char> addedFunc)
{
onChar3Exit += addedFunc;
}
public void AddOnChar4Exit(Action<char> addedFunc)
{
onChar4Exit += addedFunc;
}
public void AddOnChar5Exit(Action<char> addedFunc)
{
onChar5Exit += addedFunc;
}
public void AddOnChar6Exit(Action<char> addedFunc)
{
onChar6Exit += addedFunc;
}
public void AddOnChar7Exit(Action<char> addedFunc)
{
onChar7Exit += addedFunc;
}
public void AddOnChar8Exit(Action<char> addedFunc)
{
onChar8Exit += addedFunc;
}
public void AddOnChar9Exit(Action<char> addedFunc)
{
onChar9Exit += addedFunc;
}
public void AddOnChar10Exit(Action<char> addedFunc)
{
onChar10Exit += addedFunc;
}
public void AddOnChar11Exit(Action<char> addedFunc)
{
onChar11Exit += addedFunc;
}
public void AddOnChar12Exit(Action<char> addedFunc)
{
onChar12Exit += addedFunc;
}
public void AddOnParseSingleQuotesExit(Action<char> addedFunc)
{
onParseSingleQuotesExit += addedFunc;
}
public void AddOnParseDoubleQuotesExit(Action<char> addedFunc)
{
onParseDoubleQuotesExit += addedFunc;
}
public void AddOnAccept(Action<char> addedFunc)
{
onAccept += addedFunc;
}
public void AddOnDecline(Action<char> addedFunc)
{
onDecline += addedFunc;
}
public void AddOnEnd(Action<char> addedFunc)
{
onEnd += addedFunc;
}
internal void addOnAllStates( Action<char> addedFunc )
{
onChar1State += addedFunc;
onChar2State += addedFunc;
onChar3State += addedFunc;
onChar4State += addedFunc;
onChar5State += addedFunc;
onChar6State += addedFunc;
onChar7State += addedFunc;
onChar8State += addedFunc;
onChar9State += addedFunc;
onChar10State += addedFunc;
onChar11State += addedFunc;
onChar12State += addedFunc;
AddOnParseSingleQuotes(addedFunc);
AddOnParseDoubleQuotes(addedFunc);
}
public void ResetStateOnEnd()
{
state = null;
reset = true;
ParseSingleQuotesMachine.ResetStateOnEnd();
ParseDoubleQuotesMachine.ResetStateOnEnd();
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Implements the Totals profile message.
/// </summary>
public class TotalsMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public TotalsMesg() : base(Profile.mesgs[Profile.TotalsIndex])
{
}
public TotalsMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Timestamp field
/// Units: s</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TimerTime field
/// Units: s
/// Comment: Excludes pauses</summary>
/// <returns>Returns nullable uint representing the TimerTime field</returns>
public uint? GetTimerTime()
{
return (uint?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TimerTime field
/// Units: s
/// Comment: Excludes pauses</summary>
/// <param name="timerTime_">Nullable field value to be set</param>
public void SetTimerTime(uint? timerTime_)
{
SetFieldValue(0, 0, timerTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance field
/// Units: m</summary>
/// <returns>Returns nullable uint representing the Distance field</returns>
public uint? GetDistance()
{
return (uint?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance field
/// Units: m</summary>
/// <param name="distance_">Nullable field value to be set</param>
public void SetDistance(uint? distance_)
{
SetFieldValue(1, 0, distance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Calories field
/// Units: kcal</summary>
/// <returns>Returns nullable uint representing the Calories field</returns>
public uint? GetCalories()
{
return (uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Calories field
/// Units: kcal</summary>
/// <param name="calories_">Nullable field value to be set</param>
public void SetCalories(uint? calories_)
{
SetFieldValue(2, 0, calories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sport field</summary>
/// <returns>Returns nullable Sport enum representing the Sport field</returns>
public Sport? GetSport()
{
object obj = GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
Sport? value = obj == null ? (Sport?)null : (Sport)obj;
return value;
}
/// <summary>
/// Set Sport field</summary>
/// <param name="sport_">Nullable field value to be set</param>
public void SetSport(Sport? sport_)
{
SetFieldValue(3, 0, sport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ElapsedTime field
/// Units: s
/// Comment: Includes pauses</summary>
/// <returns>Returns nullable uint representing the ElapsedTime field</returns>
public uint? GetElapsedTime()
{
return (uint?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ElapsedTime field
/// Units: s
/// Comment: Includes pauses</summary>
/// <param name="elapsedTime_">Nullable field value to be set</param>
public void SetElapsedTime(uint? elapsedTime_)
{
SetFieldValue(4, 0, elapsedTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sessions field</summary>
/// <returns>Returns nullable ushort representing the Sessions field</returns>
public ushort? GetSessions()
{
return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Sessions field</summary>
/// <param name="sessions_">Nullable field value to be set</param>
public void SetSessions(ushort? sessions_)
{
SetFieldValue(5, 0, sessions_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActiveTime field
/// Units: s</summary>
/// <returns>Returns nullable uint representing the ActiveTime field</returns>
public uint? GetActiveTime()
{
return (uint?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveTime field
/// Units: s</summary>
/// <param name="activeTime_">Nullable field value to be set</param>
public void SetActiveTime(uint? activeTime_)
{
SetFieldValue(6, 0, activeTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SportIndex field</summary>
/// <returns>Returns nullable byte representing the SportIndex field</returns>
public byte? GetSportIndex()
{
return (byte?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SportIndex field</summary>
/// <param name="sportIndex_">Nullable field value to be set</param>
public void SetSportIndex(byte? sportIndex_)
{
SetFieldValue(9, 0, sportIndex_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
/*!
@file
@author Generate utility by Albert Semenov
@date 01/2009
@module
*/
using System;
using System.Runtime.InteropServices;
namespace MyGUI.Sharp
{
public class Window :
TextBox
{
#region Window
protected override string GetWidgetType() { return "Window"; }
internal static BaseWidget RequestWrapWindow(BaseWidget _parent, IntPtr _widget)
{
Window widget = new Window();
widget.WrapWidget(_parent, _widget);
return widget;
}
internal static BaseWidget RequestCreateWindow(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name)
{
Window widget = new Window();
widget.CreateWidgetImpl(_parent, _style, _skin, _coord, _align, _layer, _name);
return widget;
}
#endregion
//InsertPoint
#region Event WindowChangeCoord
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindowEvent_AdviseWindowChangeCoord(IntPtr _native, bool _advise);
public delegate void HandleWindowChangeCoord(
Window _sender);
private HandleWindowChangeCoord mEventWindowChangeCoord;
public event HandleWindowChangeCoord EventWindowChangeCoord
{
add
{
if (ExportEventWindowChangeCoord.mDelegate == null)
{
ExportEventWindowChangeCoord.mDelegate = new ExportEventWindowChangeCoord.ExportHandle(OnExportWindowChangeCoord);
ExportEventWindowChangeCoord.ExportWindowEvent_DelegateWindowChangeCoord(ExportEventWindowChangeCoord.mDelegate);
}
if (mEventWindowChangeCoord == null)
ExportWindowEvent_AdviseWindowChangeCoord(Native, true);
mEventWindowChangeCoord += value;
}
remove
{
mEventWindowChangeCoord -= value;
if (mEventWindowChangeCoord == null)
ExportWindowEvent_AdviseWindowChangeCoord(Native, false);
}
}
private struct ExportEventWindowChangeCoord
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportWindowEvent_DelegateWindowChangeCoord(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender);
public static ExportHandle mDelegate;
}
private static void OnExportWindowChangeCoord(
IntPtr _sender)
{
Window sender = (Window)BaseWidget.GetByNative(_sender);
if (sender.mEventWindowChangeCoord != null)
sender.mEventWindowChangeCoord(
sender);
}
#endregion
#region Event WindowButtonPressed
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindowEvent_AdviseWindowButtonPressed(IntPtr _native, bool _advise);
public delegate void HandleWindowButtonPressed(
Window _sender,
string _name);
private HandleWindowButtonPressed mEventWindowButtonPressed;
public event HandleWindowButtonPressed EventWindowButtonPressed
{
add
{
if (ExportEventWindowButtonPressed.mDelegate == null)
{
ExportEventWindowButtonPressed.mDelegate = new ExportEventWindowButtonPressed.ExportHandle(OnExportWindowButtonPressed);
ExportEventWindowButtonPressed.ExportWindowEvent_DelegateWindowButtonPressed(ExportEventWindowButtonPressed.mDelegate);
}
if (mEventWindowButtonPressed == null)
ExportWindowEvent_AdviseWindowButtonPressed(Native, true);
mEventWindowButtonPressed += value;
}
remove
{
mEventWindowButtonPressed -= value;
if (mEventWindowButtonPressed == null)
ExportWindowEvent_AdviseWindowButtonPressed(Native, false);
}
}
private struct ExportEventWindowButtonPressed
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportWindowEvent_DelegateWindowButtonPressed(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
[MarshalAs(UnmanagedType.LPStr)] string _name);
public static ExportHandle mDelegate;
}
private static void OnExportWindowButtonPressed(
IntPtr _sender,
string _name)
{
Window sender = (Window)BaseWidget.GetByNative(_sender);
if (sender.mEventWindowButtonPressed != null)
sender.mEventWindowButtonPressed(
sender ,
_name);
}
#endregion
#region Method SetMaxSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetMaxSize__width__height(IntPtr _native,
int _width,
int _height);
public void SetMaxSize(
int _width,
int _height)
{
ExportWindow_SetMaxSize__width__height(Native,
_width,
_height);
}
#endregion
#region Method SetMinSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetMinSize__width__height(IntPtr _native,
int _width,
int _height);
public void SetMinSize(
int _width,
int _height)
{
ExportWindow_SetMinSize__width__height(Native,
_width,
_height);
}
#endregion
#region Method SetVisibleSmooth
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetVisibleSmooth__value(IntPtr _native,
[MarshalAs(UnmanagedType.U1)] bool _value);
public void SetVisibleSmooth(
bool _value)
{
ExportWindow_SetVisibleSmooth__value(Native,
_value);
}
#endregion
#region Property Movable
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWindow_GetMovable(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetMovable(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool Movable
{
get { return ExportWindow_GetMovable(Native); }
set { ExportWindow_SetMovable(Native, value); }
}
#endregion
#region Property ActionScale
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWindow_GetActionScale(IntPtr _native);
public IntCoord ActionScale
{
get { return (IntCoord)Marshal.PtrToStructure(ExportWindow_GetActionScale(Native), typeof(IntCoord)); }
}
#endregion
#region Property Snap
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWindow_GetSnap(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetSnap(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool Snap
{
get { return ExportWindow_GetSnap(Native); }
set { ExportWindow_SetSnap(Native, value); }
}
#endregion
#region Property MaxSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWindow_GetMaxSize(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetMaxSize(IntPtr _widget, [In] ref IntSize _value);
public IntSize MaxSize
{
get { return (IntSize)Marshal.PtrToStructure(ExportWindow_GetMaxSize(Native), typeof(IntSize)); }
set { ExportWindow_SetMaxSize(Native, ref value); }
}
#endregion
#region Property MinSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWindow_GetMinSize(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetMinSize(IntPtr _widget, [In] ref IntSize _value);
public IntSize MinSize
{
get { return (IntSize)Marshal.PtrToStructure(ExportWindow_GetMinSize(Native), typeof(IntSize)); }
set { ExportWindow_SetMinSize(Native, ref value); }
}
#endregion
#region Property CaptionWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportWindow_GetCaptionWidget(IntPtr _native);
public TextBox CaptionWidget
{
get { return (TextBox)BaseWidget.GetByNative(ExportWindow_GetCaptionWidget(Native)); }
}
#endregion
#region Property AutoAlpha
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportWindow_GetAutoAlpha(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportWindow_SetAutoAlpha(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool AutoAlpha
{
get { return ExportWindow_GetAutoAlpha(Native); }
set { ExportWindow_SetAutoAlpha(Native, value); }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpPcap;
using System.Net;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
using WMPLib;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using System.Collections.Specialized;
using System.Collections;
using System.Globalization;
namespace RustGPS
{
public partial class frmRGPS : Form
{
public string version = "2.4";
public CaptureDeviceList devices;
public ICaptureDevice device;
public string[] bootstrap;
public float _x, _y, _z;
public Double _direction;
public int min_update_time = 3;
public bool updated = false;
public bool died = false;
public bool shooting = false;
public WebClient httpClient;
public Thread updateQMAP;
public Thread dropThread;
public string key = ""; /* api key*/
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
public double last_updated = 0;
public string latest_version = "http://url.domain.com/latest_version_check.txt";
public string latest_download = "http://url.domain.com/latest_version.zip";
public Form splashScreen;
public Form self;
public dynamic waypoint_types;
public string waypoint_name = "";
public int waypoint_id = 0;
public Single _fx, _fy, _fz;
public Double _fd;
public string entity;
public bool updateEntity = false;
public OrderedDictionary players = new OrderedDictionary();
public Object player_lock = new Object();
public OrderedDictionary drops = new OrderedDictionary();
public Object drop_lock = new Object();
public string my_entity = "";
public Thread sendForeignEntityThread;
public string[] doorPasswords = {
""
};
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
public frmRGPS()
{
InitializeComponent();
}
public static bool winPcapIsInstalled()
{
RegistryKey winPcapKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\NPF", true);
if (winPcapKey == null)
{
return false;
}
string currentKey = winPcapKey.GetValue("DisplayName").ToString();
return (currentKey != null && currentKey != "");
}
private void frmRGPS_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void frmRGPS_Load(object sender, EventArgs e)
{
self = this;
splashScreen = new Splash();
splashScreen.Show();
new Thread(checkForClientUpdates).Start();
lblVersion.Text = String.Format("v{0}", version);
if (!winPcapIsInstalled())
{
if (MessageBox.Show("WinPCAP is not installed. You must install WinPCAP in order for QMAP to work. Would you like to install WinPCAP now?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Process.Start(String.Format("{0}\\Resources\\WinPcap_4_1_3.exe", AppDomain.CurrentDomain.BaseDirectory));
}
Application.Exit();
return;
}
txtBootstrap.Text = readTokenFile();
if (txtBootstrap.Text.Length > 0)
{
saveBootstrapToken.Checked = true;
}
devices = CaptureDeviceList.Instance;
if (devices.Count < 1)
{
MessageBox.Show("No devices were found on this machine");
return;
}
foreach (var dev in devices)
{
SharpPcap.WinPcap.WinPcapDevice WinPcapDev = (SharpPcap.WinPcap.WinPcapDevice)dev;
cboInterfaces.Items.Add(WinPcapDev.Interface.FriendlyName.ToString());
if (WinPcapDev.Interface.GatewayAddress != null)
{
cboInterfaces.Text = WinPcapDev.Interface.FriendlyName.ToString();
}
}
string netif = getSavedNetworkInterface();
if (netif != "")
{
cboInterfaces.Text = netif;
}
waypoint_types = JsonConvert.DeserializeObject(new WebClient().DownloadString("http://mysite.com/gps/?wptypes"));
foreach (var waypoint_type in waypoint_types)
{
if (waypoint_type != null)
{
if (waypoint_type.name != null)
{
cboType.Items.Add(waypoint_type.name);
}
}
}
}
public void checkForClientUpdates()
{
WebClient Client = new WebClient();
Client.Headers.Add("Cache-Control", "no-cache");
//double latest_v = Convert.ToDouble(Client.DownloadString(latest_version).ToString().Trim());
double latest_v = Double.Parse(Client.DownloadString(latest_version).ToString().Trim(), CultureInfo.InvariantCulture);
//double current_v = Convert.ToDouble(version);
double current_v = Double.Parse(version, CultureInfo.InvariantCulture);
if (latest_v > current_v)
{
Thread.Sleep(1000);
MessageBox.Show("An update has been downloaded. Press OK to download and install the latest version.", "Update Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
string savepath = String.Format("{0}\\gps_latest.zip", AppDomain.CurrentDomain.BaseDirectory);
System.IO.File.Delete(savepath);
Client.DownloadFile(latest_download, savepath);
Process.Start(String.Format("{0}\\GPSUpdater.exe", AppDomain.CurrentDomain.BaseDirectory));
}
try
{
self.Opacity = 1.0;
splashScreen.Close();
}
catch (Exception ex)
{
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtBootstrap.Text == "" || !txtBootstrap.Text.Contains(";"))
{
MessageBox.Show("Please enter your bootstrap token. This can be found at http://www.mysite.com/gps/", "Required Field Notification", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtBootstrap.Focus();
return;
}
bootstrap = txtBootstrap.Text.Split(';');
bootstrap[0] = bootstrap[0].Trim();
bootstrap[1] = bootstrap[1].Trim();
try
{
IPAddress.Parse(bootstrap[1]);
}
catch (Exception ex2)
{
MessageBox.Show("Invalid bootstrap token. The IP Address was not found. This can be found at http://www.mysite.com/gps/", "Required Field Notification", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtBootstrap.Focus();
return;
}
if (cboInterfaces.SelectedIndex < 0 || cboInterfaces.SelectedItem.ToString() == "")
{
MessageBox.Show("Please select a valid Network Interface.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
cboInterfaces.Focus();
return;
}
httpClient = new WebClient();
httpClient.Headers.Add("Connection: keep-alive");
device = this.devices[int.Parse(cboInterfaces.SelectedIndex.ToString())];
saveNetworkInterface();
device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
device.Open(DeviceMode.Promiscuous, 1000);
//device.Filter = String.Format("host {0} and less 84 and greater 82", bootstrap[1]);
device.Filter = String.Format("host {0} and greater 28", bootstrap[1]);
device.StartCapture();
lblStatus.Text = "Running";
lblStatus.ForeColor = System.Drawing.Color.ForestGreen;
updateQMAP = new Thread(checkUpdate);
updateQMAP.Start();
sendForeignEntityThread = new Thread(sendForeignEntities);
sendForeignEntityThread.Start();
dropThread = new Thread(sendDropCoordinates);
dropThread.Start();
}
public void sendDropCoordinates()
{
while (true)
{
lock (drop_lock)
{
if (drops.Count > 0)
{
foreach(DictionaryEntry dropEntry in drops)
{
string drop_name = dropEntry.Key.ToString();
Drop drop_data = (Drop)dropEntry.Value;
using (WebClient wc = new WebClient())
{
wc.DownloadString(String.Format("http://mysite.com/gps/?drop={0}&ip={1}&name={2}&x={3}&y={4}&z={5}",
bootstrap[0],
bootstrap[1],
drop_name,
drop_data.x.ToString("R"),
drop_data.y.ToString("R"),
drop_data.z.ToString("R")
));
Console.WriteLine("Sending Drop Coords: {0}, {1}, {2}", drop_data.x.ToString("N2"), drop_data.y.ToString("N2"), drop_data.z.ToString("N2"));
}
}
drops.Clear();
}
}
Thread.Sleep(20);
}
}
public void sendForeignEntities()
{
while (true)
{
/*
* Always update enemies
*/
lock (player_lock)
{
if (players.Count > 0)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string req = String.Format("http://mysite.com/gps/?ghost={0}&ip={1}",
bootstrap[0],
bootstrap[1]
);
try
{
wc.UploadString(req, String.Format("data={0}", JsonConvert.SerializeObject(players)));
}
catch (Exception ex1)
{
}
changeText(myPID, my_entity);
}
/*
foreach (DictionaryEntry d1 in players)
{
Player plyr = (Player)d1.Value;
Console.WriteLine("{0} = ({1}, {2}, {3}) {4}", d1.Key.ToString(), plyr.x, plyr.y, plyr.z, plyr.d);
}
*/
players.Clear();
}
}
Thread.Sleep(20);
}
}
public void checkUpdate()
{
while (true)
{
/*
* Always update enemies
*/
if (updated && my_entity != "")
{
updated = false;
changeText(lblCoords, String.Format("x: {0}, z: {1}, d: {2}", _x.ToString("N2"), _z.ToString("N2"), _direction.ToString("N2")));
try
{
httpClient.DownloadString(String.Format(
"http://mysite.com/gps/?me={0}&x={1}&z={2}&ip={3}&d={4}&death={5}&shooting={6}&v={7}&mark={8}&labelmark={9}&iam={10}",
bootstrap[0].ToString(),
_x.ToString("R"),
_z.ToString("R"),
bootstrap[1].ToString(),
_direction.ToString(),
(died ? "1" : "0"),
(shooting ? "1" : "0"),
version,
waypoint_id,
waypoint_name,
my_entity
));
died = false;
shooting = false;
waypoint_id = 0;
waypoint_name = "";
}
catch (Exception ex)
{
/* into the abyss... */
}
}
else
{
Thread.Sleep(20);
}
}
}
private void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
/*
* Set i = 28 because all UDP headers
* for IPv4 protocol will be 28 bytes in length.
* IPv4 Header = 20 bytes
* Datagram = 8 bytes
*/
double timenow = ConvertToTimestamp(DateTime.Now);
int j = 0, i = 0, s = 0, t = 0, c = 0, drop = 0;
int[] dropSignal = e.Packet.Data.Locate(Encoding.ASCII.GetBytes("GetNetworkUpdate"), 28);
if (dropSignal.Length > 0)
{
drop = dropSignal[0];
}
if (drop > 28 && e.Packet.Data.Count() >= (drop + 30))
{
Double _dx = BitConverter.ToSingle(e.Packet.Data, drop + 18);
Double _dy = BitConverter.ToSingle(e.Packet.Data, drop + 18 + 4);
Double _dz = BitConverter.ToSingle(e.Packet.Data, drop + 18 + 8);
string hexpacket = ByteArrayToString(e.Packet.Data);
string drop_entity = hexpacket.Substring((drop - 5) * 2, 8);
Drop _drop = new Drop
{
x = _dx,
y = _dy,
z = _dz,
entity = drop_entity
};
if (e.Packet.Data[0x27] != 0x3E)
{
return;
}
lock (drop_lock)
{
if (drops.Contains(drop_entity))
{
drops[drop_entity] = _drop;
}
else
{
drops.Add(drop_entity, _drop);
}
}
return;
}
/* yes, the dev is an idiot and misspelled receive */
int[] recvNet = e.Packet.Data.Locate(Encoding.ASCII.GetBytes("RecieveNetwork"), 28);
if (recvNet.Length > 0)
{
c = recvNet[0];
}
if (c > 28)
{
string hexpacket = ByteArrayToString(e.Packet.Data);
my_entity = hexpacket.Substring((c - 5) * 2, 8);
return;
}
int[] playerMove = e.Packet.Data.Locate(Encoding.ASCII.GetBytes("ReadClientMove"), 28);
if (playerMove.Length > 0)
{
t = playerMove[0];
}
if (t > 28)
{
_fx = BitConverter.ToSingle(e.Packet.Data, t + 16);
_fy = BitConverter.ToSingle(e.Packet.Data, t + 16 + 4);
_fz = BitConverter.ToSingle(e.Packet.Data, t + 16 + 8);
short tw = BitConverter.ToInt16(e.Packet.Data, t + 16 + 14);
_fd = tw / 180;
if (_fd < 0)
{
_fd = -1 * _fd;
}
else
{
_fd = 180 + (180 - _fd);
}
string hexpacket = ByteArrayToString(e.Packet.Data);
entity = hexpacket.Substring((t - 5) * 2, 8);
updateEntity = true;
Player p = new Player
{
x = _fx,
y = _fy,
z = _fz,
d = _fd
};
lock (player_lock)
{
if (players.Contains(entity))
{
players[entity] = p;
}
else
{
players.Add(entity, p);
}
}
return;
}
if (chkActionBlip.Checked)
{
int[] isShooting = e.Packet.Data.Locate(Encoding.ASCII.GetBytes("Action1B"), 28);
if (isShooting.Length > 0)
{
s = isShooting[0];
}
if (s > 28)
{
shooting = true;
updated = true;
return;
}
}
// Check for Death
int[] isDead = e.Packet.Data.Locate(Encoding.ASCII.GetBytes("deathscreen.reason"), 28);
if (isDead.Length > 0)
{
j = isDead[0];
}
if (j > 28)
{
died = true;
updated = true;
return;
}
// Check for Position
int[] clientMoved = e.Packet.Data.Locate(Encoding.ASCII.GetBytes("GetClientMove"), 28);
if (clientMoved.Length > 0)
{
i = clientMoved[0];
}
if (i > 28)
{
Single x = BitConverter.ToSingle(e.Packet.Data, i + 15);
Single y = BitConverter.ToSingle(e.Packet.Data, i + 15 + 4);
Single z = BitConverter.ToSingle(e.Packet.Data, i + 15 + 8);
//short f = BitConverter.ToInt16(e.Packet.Data, i + 15 + 12);
short w = BitConverter.ToInt16(e.Packet.Data, i + 15 + 14);
//Double deg = (Math.Sqrt(f * f + w * w) * Math.Cos(Math.Atan2(f, w))) / 182;
Double deg = w / 180;
if (deg < 0)
{
deg = -1 * deg;
}
else
{
deg = 180 + (180 - deg);
}
if (x == _x && y == _y && z == _z && deg == _direction && !died)
{
if (last_updated + min_update_time >= timenow)
{
return;
}
}
last_updated = timenow;
updated = true;
_x = x;
_y = y;
_z = z;
_direction = deg;
return;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
sendForeignEntityThread.Abort();
updateQMAP.Abort();
dropThread.Abort();
httpClient.CancelAsync();
httpClient.Dispose();
device.StopCapture();
device.Close();
}
catch (Exception ex)
{
}
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "Not Running";
}
private void changeText(Control obj, string value)
{
if (obj.InvokeRequired)
{
obj.Invoke(new MethodInvoker(delegate
{
obj.Text = value;
}));
}
}
private void saveBootstrapToken_CheckedChanged(object sender, EventArgs e)
{
string data = Crypto.EncryptStringAES(txtBootstrap.Text.Trim(), key);
System.IO.File.WriteAllText(String.Format("{0}\\token.dat", AppDomain.CurrentDomain.BaseDirectory), data);
}
private void saveNetworkInterface()
{
System.IO.File.WriteAllText(
String.Format("{0}\\if.dat", AppDomain.CurrentDomain.BaseDirectory),
((SharpPcap.WinPcap.WinPcapDevice)device).Interface.FriendlyName.ToString());
}
private string getSavedNetworkInterface()
{
try
{
string netif = System.IO.File.ReadAllText(String.Format("{0}\\if.dat", AppDomain.CurrentDomain.BaseDirectory));
if (netif == null)
{
return "";
}
return netif.Trim();
}
catch (Exception e)
{
}
return "";
}
public string readTokenFile()
{
try
{
string encrypted = System.IO.File.ReadAllText(String.Format("{0}\\token.dat", AppDomain.CurrentDomain.BaseDirectory));
if (encrypted == null)
{
return "0";
}
encrypted = encrypted.Trim();
string decrypted = Crypto.DecryptStringAES(encrypted, key);
if (decrypted == null)
{
return "";
}
return decrypted.ToString();
}
catch (Exception ex)
{
}
return "";
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Application.Exit();
}
private void ExitApp(object sender, EventArgs e)
{
Process[] runningProcesses = Process.GetProcesses();
foreach (var p in runningProcesses)
{
if (p.ProcessName.ToString().Equals("GPS"))
{
p.Kill();
}
}
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
private double ConvertToTimestamp(DateTime value)
{
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
return (double)span.TotalSeconds;
}
private void btnPinit_Click(object sender, EventArgs e)
{
if (cboType.Text == "")
{
MessageBox.Show("You must select a waypoint type before adding this waypoint to the map.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cboType.Focus();
return;
}
foreach (var waypoint_type in waypoint_types)
{
if (waypoint_type != null)
{
if (waypoint_type.id != null && waypoint_type.name != null)
{
if (cboType.Text == waypoint_type.name.ToString())
{
//waypoint_id = Convert.ToInt32(waypoint_type.id.ToString());
waypoint_id = int.Parse(waypoint_type.id.ToString(), CultureInfo.InvariantCulture);
if (txtName.Text != "")
{
waypoint_name = txtName.Text;
}
updated = true;
cboType.Text = "";
txtName.Text = "";
}
}
}
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmTopSelectGRV
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmTopSelectGRV() : base()
{
Load += frmTopSelectGRV_Load;
KeyPress += frmTopSelectGRV_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdGroup;
public System.Windows.Forms.Button cmdGroup {
get { return withEventsField_cmdGroup; }
set {
if (withEventsField_cmdGroup != null) {
withEventsField_cmdGroup.Click -= cmdGroup_Click;
}
withEventsField_cmdGroup = value;
if (withEventsField_cmdGroup != null) {
withEventsField_cmdGroup.Click += cmdGroup_Click;
}
}
}
public System.Windows.Forms.Label lblGroup;
public System.Windows.Forms.GroupBox _Frame1_2;
public System.Windows.Forms.ComboBox cmbSort;
public System.Windows.Forms.ComboBox cmbSortField;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.GroupBox _Frame1_1;
public System.Windows.Forms.CheckBox chkPageBreak;
public System.Windows.Forms.ComboBox cmbGroup;
public System.Windows.Forms.RadioButton _optType_0;
public System.Windows.Forms.RadioButton _optType_1;
public System.Windows.Forms.RadioButton _optType_2;
public System.Windows.Forms.Label _lbl_3;
public System.Windows.Forms.GroupBox _Frame1_0;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdLoad;
public System.Windows.Forms.Button cmdLoad {
get { return withEventsField_cmdLoad; }
set {
if (withEventsField_cmdLoad != null) {
withEventsField_cmdLoad.Click -= cmdLoad_Click;
}
withEventsField_cmdLoad = value;
if (withEventsField_cmdLoad != null) {
withEventsField_cmdLoad.Click += cmdLoad_Click;
}
}
}
//Public WithEvents Frame1 As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents optType As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmTopSelectGRV));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this._Frame1_2 = new System.Windows.Forms.GroupBox();
this.cmdGroup = new System.Windows.Forms.Button();
this.lblGroup = new System.Windows.Forms.Label();
this._Frame1_1 = new System.Windows.Forms.GroupBox();
this.cmbSort = new System.Windows.Forms.ComboBox();
this.cmbSortField = new System.Windows.Forms.ComboBox();
this._lbl_0 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this._Frame1_0 = new System.Windows.Forms.GroupBox();
this.chkPageBreak = new System.Windows.Forms.CheckBox();
this.cmbGroup = new System.Windows.Forms.ComboBox();
this._optType_0 = new System.Windows.Forms.RadioButton();
this._optType_1 = new System.Windows.Forms.RadioButton();
this._optType_2 = new System.Windows.Forms.RadioButton();
this._lbl_3 = new System.Windows.Forms.Label();
this.cmdExit = new System.Windows.Forms.Button();
this.cmdLoad = new System.Windows.Forms.Button();
//Me.Frame1 = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.optType = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components)
this._Frame1_2.SuspendLayout();
this._Frame1_1.SuspendLayout();
this._Frame1_0.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.Frame1, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.optType, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Purchase Performance";
this.ClientSize = new System.Drawing.Size(252, 465);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmTopSelectGRV";
this._Frame1_2.Text = "&3. Report Filter";
this._Frame1_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Frame1_2.Size = new System.Drawing.Size(232, 145);
this._Frame1_2.Location = new System.Drawing.Point(12, 249);
this._Frame1_2.TabIndex = 12;
this._Frame1_2.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_2.Enabled = true;
this._Frame1_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_2.Visible = true;
this._Frame1_2.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_2.Name = "_Frame1_2";
this.cmdGroup.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdGroup.Text = "&Filter";
this.cmdGroup.Size = new System.Drawing.Size(97, 31);
this.cmdGroup.Location = new System.Drawing.Point(129, 105);
this.cmdGroup.TabIndex = 14;
this.cmdGroup.BackColor = System.Drawing.SystemColors.Control;
this.cmdGroup.CausesValidation = true;
this.cmdGroup.Enabled = true;
this.cmdGroup.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdGroup.TabStop = true;
this.cmdGroup.Name = "cmdGroup";
this.lblGroup.BackColor = System.Drawing.Color.FromArgb(192, 192, 192);
this.lblGroup.Text = "lblGroup";
this.lblGroup.Size = new System.Drawing.Size(220, 76);
this.lblGroup.Location = new System.Drawing.Point(6, 21);
this.lblGroup.TabIndex = 13;
this.lblGroup.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblGroup.Enabled = true;
this.lblGroup.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.lblGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblGroup.UseMnemonic = true;
this.lblGroup.Visible = true;
this.lblGroup.AutoSize = false;
this.lblGroup.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblGroup.Name = "lblGroup";
this._Frame1_1.Text = "&2. Report Sort Order";
this._Frame1_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Frame1_1.Size = new System.Drawing.Size(232, 85);
this._Frame1_1.Location = new System.Drawing.Point(12, 156);
this._Frame1_1.TabIndex = 7;
this._Frame1_1.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_1.Enabled = true;
this._Frame1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_1.Visible = true;
this._Frame1_1.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_1.Name = "_Frame1_1";
this.cmbSort.Size = new System.Drawing.Size(115, 21);
this.cmbSort.Location = new System.Drawing.Point(63, 48);
this.cmbSort.Items.AddRange(new object[] {
"Ascending",
"Descending"
});
this.cmbSort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSort.TabIndex = 11;
this.cmbSort.BackColor = System.Drawing.SystemColors.Window;
this.cmbSort.CausesValidation = true;
this.cmbSort.Enabled = true;
this.cmbSort.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbSort.IntegralHeight = true;
this.cmbSort.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbSort.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbSort.Sorted = false;
this.cmbSort.TabStop = true;
this.cmbSort.Visible = true;
this.cmbSort.Name = "cmbSort";
this.cmbSortField.Size = new System.Drawing.Size(115, 21);
this.cmbSortField.Location = new System.Drawing.Point(63, 24);
this.cmbSortField.Items.AddRange(new object[] {
"Item Name",
"Cost",
"Selling",
"Gross Profit",
"Gross Profit %",
"Quantity Sold"
});
this.cmbSortField.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSortField.TabIndex = 9;
this.cmbSortField.BackColor = System.Drawing.SystemColors.Window;
this.cmbSortField.CausesValidation = true;
this.cmbSortField.Enabled = true;
this.cmbSortField.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbSortField.IntegralHeight = true;
this.cmbSortField.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbSortField.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbSortField.Sorted = false;
this.cmbSortField.TabStop = true;
this.cmbSortField.Visible = true;
this.cmbSortField.Name = "cmbSortField";
this._lbl_0.Text = "Sort Field:";
this._lbl_0.Size = new System.Drawing.Size(47, 13);
this._lbl_0.Location = new System.Drawing.Point(12, 30);
this._lbl_0.TabIndex = 8;
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = true;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this._lbl_2.Text = "Sort Order:";
this._lbl_2.Size = new System.Drawing.Size(51, 13);
this._lbl_2.Location = new System.Drawing.Point(9, 54);
this._lbl_2.TabIndex = 10;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this._Frame1_0.Text = "&1. Report Options";
this._Frame1_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Frame1_0.Size = new System.Drawing.Size(232, 139);
this._Frame1_0.Location = new System.Drawing.Point(12, 9);
this._Frame1_0.TabIndex = 0;
this._Frame1_0.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_0.Enabled = true;
this._Frame1_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_0.Visible = true;
this._Frame1_0.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_0.Name = "_Frame1_0";
this.chkPageBreak.Text = "Page Break after each Group.";
this.chkPageBreak.Enabled = false;
this.chkPageBreak.Size = new System.Drawing.Size(163, 13);
this.chkPageBreak.Location = new System.Drawing.Point(54, 114);
this.chkPageBreak.TabIndex = 6;
this.chkPageBreak.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkPageBreak.FlatStyle = System.Windows.Forms.FlatStyle.Standard;
this.chkPageBreak.BackColor = System.Drawing.SystemColors.Control;
this.chkPageBreak.CausesValidation = true;
this.chkPageBreak.ForeColor = System.Drawing.SystemColors.ControlText;
this.chkPageBreak.Cursor = System.Windows.Forms.Cursors.Default;
this.chkPageBreak.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkPageBreak.Appearance = System.Windows.Forms.Appearance.Normal;
this.chkPageBreak.TabStop = true;
this.chkPageBreak.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.chkPageBreak.Visible = true;
this.chkPageBreak.Name = "chkPageBreak";
this.cmbGroup.Enabled = false;
this.cmbGroup.Size = new System.Drawing.Size(106, 21);
this.cmbGroup.Location = new System.Drawing.Point(108, 93);
this.cmbGroup.Items.AddRange(new object[] {
"Pricing Group",
"Stock Group",
"Supplier",
"Report Group"
});
this.cmbGroup.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbGroup.TabIndex = 5;
this.cmbGroup.BackColor = System.Drawing.SystemColors.Window;
this.cmbGroup.CausesValidation = true;
this.cmbGroup.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbGroup.IntegralHeight = true;
this.cmbGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbGroup.Sorted = false;
this.cmbGroup.TabStop = true;
this.cmbGroup.Visible = true;
this.cmbGroup.Name = "cmbGroup";
this._optType_0.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optType_0.Text = "Normal Item Listing";
this._optType_0.Size = new System.Drawing.Size(115, 13);
this._optType_0.Location = new System.Drawing.Point(12, 21);
this._optType_0.TabIndex = 1;
this._optType_0.Checked = true;
this._optType_0.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optType_0.BackColor = System.Drawing.SystemColors.Control;
this._optType_0.CausesValidation = true;
this._optType_0.Enabled = true;
this._optType_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._optType_0.Cursor = System.Windows.Forms.Cursors.Default;
this._optType_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optType_0.Appearance = System.Windows.Forms.Appearance.Normal;
this._optType_0.TabStop = true;
this._optType_0.Visible = true;
this._optType_0.Name = "_optType_0";
this._optType_1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optType_1.Text = "Items Per Group";
this._optType_1.Size = new System.Drawing.Size(115, 13);
this._optType_1.Location = new System.Drawing.Point(12, 39);
this._optType_1.TabIndex = 2;
this._optType_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optType_1.BackColor = System.Drawing.SystemColors.Control;
this._optType_1.CausesValidation = true;
this._optType_1.Enabled = true;
this._optType_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._optType_1.Cursor = System.Windows.Forms.Cursors.Default;
this._optType_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optType_1.Appearance = System.Windows.Forms.Appearance.Normal;
this._optType_1.TabStop = true;
this._optType_1.Checked = false;
this._optType_1.Visible = true;
this._optType_1.Name = "_optType_1";
this._optType_2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optType_2.Text = "Group Totals";
this._optType_2.Size = new System.Drawing.Size(115, 13);
this._optType_2.Location = new System.Drawing.Point(12, 57);
this._optType_2.TabIndex = 3;
this._optType_2.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optType_2.BackColor = System.Drawing.SystemColors.Control;
this._optType_2.CausesValidation = true;
this._optType_2.Enabled = true;
this._optType_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._optType_2.Cursor = System.Windows.Forms.Cursors.Default;
this._optType_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optType_2.Appearance = System.Windows.Forms.Appearance.Normal;
this._optType_2.TabStop = true;
this._optType_2.Checked = false;
this._optType_2.Visible = true;
this._optType_2.Name = "_optType_2";
this._lbl_3.Text = "Group on:";
this._lbl_3.Size = new System.Drawing.Size(47, 13);
this._lbl_3.Location = new System.Drawing.Point(54, 96);
this._lbl_3.TabIndex = 4;
this._lbl_3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_3.BackColor = System.Drawing.Color.Transparent;
this._lbl_3.Enabled = true;
this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_3.UseMnemonic = true;
this._lbl_3.Visible = true;
this._lbl_3.AutoSize = true;
this._lbl_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_3.Name = "_lbl_3";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(79, 43);
this.cmdExit.Location = new System.Drawing.Point(12, 408);
this.cmdExit.TabIndex = 16;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.TabStop = true;
this.cmdExit.Name = "cmdExit";
this.cmdLoad.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdLoad.Text = "Show/&Print Report";
this.cmdLoad.Size = new System.Drawing.Size(79, 43);
this.cmdLoad.Location = new System.Drawing.Point(164, 408);
this.cmdLoad.TabIndex = 15;
this.cmdLoad.BackColor = System.Drawing.SystemColors.Control;
this.cmdLoad.CausesValidation = true;
this.cmdLoad.Enabled = true;
this.cmdLoad.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdLoad.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdLoad.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdLoad.TabStop = true;
this.cmdLoad.Name = "cmdLoad";
this.Controls.Add(_Frame1_2);
this.Controls.Add(_Frame1_1);
this.Controls.Add(_Frame1_0);
this.Controls.Add(cmdExit);
this.Controls.Add(cmdLoad);
this._Frame1_2.Controls.Add(cmdGroup);
this._Frame1_2.Controls.Add(lblGroup);
this._Frame1_1.Controls.Add(cmbSort);
this._Frame1_1.Controls.Add(cmbSortField);
this._Frame1_1.Controls.Add(_lbl_0);
this._Frame1_1.Controls.Add(_lbl_2);
this._Frame1_0.Controls.Add(chkPageBreak);
this._Frame1_0.Controls.Add(cmbGroup);
this._Frame1_0.Controls.Add(_optType_0);
this._Frame1_0.Controls.Add(_optType_1);
this._Frame1_0.Controls.Add(_optType_2);
this._Frame1_0.Controls.Add(_lbl_3);
//Me.Frame1.SetIndex(_Frame1_2, CType(2, Short))
//Me.Frame1.SetIndex(_Frame1_1, CType(1, Short))
//Me.Frame1.SetIndex(_Frame1_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lbl.SetIndex(_lbl_3, CType(3, Short))
//Me.optType.SetIndex(_optType_0, CType(0, Short))
//Me.optType.SetIndex(_optType_1, CType(1, Short))
//Me.optType.SetIndex(_optType_2, CType(2, Short))
//CType(Me.optType, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Frame1, System.ComponentModel.ISupportInitialize).EndInit()
this._Frame1_2.ResumeLayout(false);
this._Frame1_1.ResumeLayout(false);
this._Frame1_0.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.IoT;
using Amazon.IoT.Model;
using Amazon.IoT.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public partial class IoTMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("iot-2015-05-28.normal.json", "iot-2015-.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void AcceptCertificateTransferMarshallTest()
{
var operation = service_model.FindOperation("AcceptCertificateTransfer");
var request = InstantiateClassGenerator.Execute<AcceptCertificateTransferRequest>();
var marshaller = new AcceptCertificateTransferRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("AcceptCertificateTransfer", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void AttachPrincipalPolicyMarshallTest()
{
var operation = service_model.FindOperation("AttachPrincipalPolicy");
var request = InstantiateClassGenerator.Execute<AttachPrincipalPolicyRequest>();
var marshaller = new AttachPrincipalPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("AttachPrincipalPolicy", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void AttachThingPrincipalMarshallTest()
{
var operation = service_model.FindOperation("AttachThingPrincipal");
var request = InstantiateClassGenerator.Execute<AttachThingPrincipalRequest>();
var marshaller = new AttachThingPrincipalRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("AttachThingPrincipal", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = AttachThingPrincipalResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as AttachThingPrincipalResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CancelCertificateTransferMarshallTest()
{
var operation = service_model.FindOperation("CancelCertificateTransfer");
var request = InstantiateClassGenerator.Execute<CancelCertificateTransferRequest>();
var marshaller = new CancelCertificateTransferRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CancelCertificateTransfer", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CreateCertificateFromCsrMarshallTest()
{
var operation = service_model.FindOperation("CreateCertificateFromCsr");
var request = InstantiateClassGenerator.Execute<CreateCertificateFromCsrRequest>();
var marshaller = new CreateCertificateFromCsrRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateCertificateFromCsr", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateCertificateFromCsrResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateCertificateFromCsrResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CreateKeysAndCertificateMarshallTest()
{
var operation = service_model.FindOperation("CreateKeysAndCertificate");
var request = InstantiateClassGenerator.Execute<CreateKeysAndCertificateRequest>();
var marshaller = new CreateKeysAndCertificateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateKeysAndCertificate", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateKeysAndCertificateResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateKeysAndCertificateResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CreatePolicyMarshallTest()
{
var operation = service_model.FindOperation("CreatePolicy");
var request = InstantiateClassGenerator.Execute<CreatePolicyRequest>();
var marshaller = new CreatePolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreatePolicy", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreatePolicyResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreatePolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CreatePolicyVersionMarshallTest()
{
var operation = service_model.FindOperation("CreatePolicyVersion");
var request = InstantiateClassGenerator.Execute<CreatePolicyVersionRequest>();
var marshaller = new CreatePolicyVersionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreatePolicyVersion", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreatePolicyVersionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreatePolicyVersionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CreateThingMarshallTest()
{
var operation = service_model.FindOperation("CreateThing");
var request = InstantiateClassGenerator.Execute<CreateThingRequest>();
var marshaller = new CreateThingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateThing", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateThingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateThingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void CreateTopicRuleMarshallTest()
{
var operation = service_model.FindOperation("CreateTopicRule");
var request = InstantiateClassGenerator.Execute<CreateTopicRuleRequest>();
var marshaller = new CreateTopicRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateTopicRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DeleteCertificateMarshallTest()
{
var operation = service_model.FindOperation("DeleteCertificate");
var request = InstantiateClassGenerator.Execute<DeleteCertificateRequest>();
var marshaller = new DeleteCertificateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteCertificate", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DeletePolicyMarshallTest()
{
var operation = service_model.FindOperation("DeletePolicy");
var request = InstantiateClassGenerator.Execute<DeletePolicyRequest>();
var marshaller = new DeletePolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeletePolicy", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DeletePolicyVersionMarshallTest()
{
var operation = service_model.FindOperation("DeletePolicyVersion");
var request = InstantiateClassGenerator.Execute<DeletePolicyVersionRequest>();
var marshaller = new DeletePolicyVersionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeletePolicyVersion", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DeleteThingMarshallTest()
{
var operation = service_model.FindOperation("DeleteThing");
var request = InstantiateClassGenerator.Execute<DeleteThingRequest>();
var marshaller = new DeleteThingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteThing", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DeleteThingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as DeleteThingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DeleteTopicRuleMarshallTest()
{
var operation = service_model.FindOperation("DeleteTopicRule");
var request = InstantiateClassGenerator.Execute<DeleteTopicRuleRequest>();
var marshaller = new DeleteTopicRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteTopicRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DescribeCertificateMarshallTest()
{
var operation = service_model.FindOperation("DescribeCertificate");
var request = InstantiateClassGenerator.Execute<DescribeCertificateRequest>();
var marshaller = new DescribeCertificateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DescribeCertificate", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DescribeCertificateResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as DescribeCertificateResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DescribeEndpointMarshallTest()
{
var operation = service_model.FindOperation("DescribeEndpoint");
var request = InstantiateClassGenerator.Execute<DescribeEndpointRequest>();
var marshaller = new DescribeEndpointRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DescribeEndpoint", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DescribeEndpointResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as DescribeEndpointResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DescribeThingMarshallTest()
{
var operation = service_model.FindOperation("DescribeThing");
var request = InstantiateClassGenerator.Execute<DescribeThingRequest>();
var marshaller = new DescribeThingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DescribeThing", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DescribeThingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as DescribeThingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DetachPrincipalPolicyMarshallTest()
{
var operation = service_model.FindOperation("DetachPrincipalPolicy");
var request = InstantiateClassGenerator.Execute<DetachPrincipalPolicyRequest>();
var marshaller = new DetachPrincipalPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DetachPrincipalPolicy", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void DetachThingPrincipalMarshallTest()
{
var operation = service_model.FindOperation("DetachThingPrincipal");
var request = InstantiateClassGenerator.Execute<DetachThingPrincipalRequest>();
var marshaller = new DetachThingPrincipalRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DetachThingPrincipal", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DetachThingPrincipalResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as DetachThingPrincipalResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void GetLoggingOptionsMarshallTest()
{
var operation = service_model.FindOperation("GetLoggingOptions");
var request = InstantiateClassGenerator.Execute<GetLoggingOptionsRequest>();
var marshaller = new GetLoggingOptionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetLoggingOptions", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetLoggingOptionsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetLoggingOptionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void GetPolicyMarshallTest()
{
var operation = service_model.FindOperation("GetPolicy");
var request = InstantiateClassGenerator.Execute<GetPolicyRequest>();
var marshaller = new GetPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetPolicy", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetPolicyResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetPolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void GetPolicyVersionMarshallTest()
{
var operation = service_model.FindOperation("GetPolicyVersion");
var request = InstantiateClassGenerator.Execute<GetPolicyVersionRequest>();
var marshaller = new GetPolicyVersionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetPolicyVersion", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetPolicyVersionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetPolicyVersionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void GetTopicRuleMarshallTest()
{
var operation = service_model.FindOperation("GetTopicRule");
var request = InstantiateClassGenerator.Execute<GetTopicRuleRequest>();
var marshaller = new GetTopicRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetTopicRule", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetTopicRuleResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetTopicRuleResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListCertificatesMarshallTest()
{
var operation = service_model.FindOperation("ListCertificates");
var request = InstantiateClassGenerator.Execute<ListCertificatesRequest>();
var marshaller = new ListCertificatesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListCertificates", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListCertificatesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListCertificatesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListPoliciesMarshallTest()
{
var operation = service_model.FindOperation("ListPolicies");
var request = InstantiateClassGenerator.Execute<ListPoliciesRequest>();
var marshaller = new ListPoliciesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListPolicies", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListPoliciesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListPoliciesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListPolicyVersionsMarshallTest()
{
var operation = service_model.FindOperation("ListPolicyVersions");
var request = InstantiateClassGenerator.Execute<ListPolicyVersionsRequest>();
var marshaller = new ListPolicyVersionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListPolicyVersions", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListPolicyVersionsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListPolicyVersionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListPrincipalPoliciesMarshallTest()
{
var operation = service_model.FindOperation("ListPrincipalPolicies");
var request = InstantiateClassGenerator.Execute<ListPrincipalPoliciesRequest>();
var marshaller = new ListPrincipalPoliciesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListPrincipalPolicies", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListPrincipalPoliciesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListPrincipalPoliciesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListPrincipalThingsMarshallTest()
{
var operation = service_model.FindOperation("ListPrincipalThings");
var request = InstantiateClassGenerator.Execute<ListPrincipalThingsRequest>();
var marshaller = new ListPrincipalThingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListPrincipalThings", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListPrincipalThingsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListPrincipalThingsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListThingPrincipalsMarshallTest()
{
var operation = service_model.FindOperation("ListThingPrincipals");
var request = InstantiateClassGenerator.Execute<ListThingPrincipalsRequest>();
var marshaller = new ListThingPrincipalsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListThingPrincipals", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListThingPrincipalsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListThingPrincipalsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListThingsMarshallTest()
{
var operation = service_model.FindOperation("ListThings");
var request = InstantiateClassGenerator.Execute<ListThingsRequest>();
var marshaller = new ListThingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListThings", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListThingsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListThingsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ListTopicRulesMarshallTest()
{
var operation = service_model.FindOperation("ListTopicRules");
var request = InstantiateClassGenerator.Execute<ListTopicRulesRequest>();
var marshaller = new ListTopicRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListTopicRules", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListTopicRulesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListTopicRulesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void RejectCertificateTransferMarshallTest()
{
var operation = service_model.FindOperation("RejectCertificateTransfer");
var request = InstantiateClassGenerator.Execute<RejectCertificateTransferRequest>();
var marshaller = new RejectCertificateTransferRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("RejectCertificateTransfer", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void ReplaceTopicRuleMarshallTest()
{
var operation = service_model.FindOperation("ReplaceTopicRule");
var request = InstantiateClassGenerator.Execute<ReplaceTopicRuleRequest>();
var marshaller = new ReplaceTopicRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ReplaceTopicRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void SetDefaultPolicyVersionMarshallTest()
{
var operation = service_model.FindOperation("SetDefaultPolicyVersion");
var request = InstantiateClassGenerator.Execute<SetDefaultPolicyVersionRequest>();
var marshaller = new SetDefaultPolicyVersionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("SetDefaultPolicyVersion", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void SetLoggingOptionsMarshallTest()
{
var operation = service_model.FindOperation("SetLoggingOptions");
var request = InstantiateClassGenerator.Execute<SetLoggingOptionsRequest>();
var marshaller = new SetLoggingOptionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("SetLoggingOptions", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void TransferCertificateMarshallTest()
{
var operation = service_model.FindOperation("TransferCertificate");
var request = InstantiateClassGenerator.Execute<TransferCertificateRequest>();
var marshaller = new TransferCertificateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("TransferCertificate", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = TransferCertificateResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as TransferCertificateResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void UpdateCertificateMarshallTest()
{
var operation = service_model.FindOperation("UpdateCertificate");
var request = InstantiateClassGenerator.Execute<UpdateCertificateRequest>();
var marshaller = new UpdateCertificateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateCertificate", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("IoT")]
public void UpdateThingMarshallTest()
{
var operation = service_model.FindOperation("UpdateThing");
var request = InstantiateClassGenerator.Execute<UpdateThingRequest>();
var marshaller = new UpdateThingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateThing", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateThingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateThingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json;
using System;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Sensus.Probes.User.Scripts
{
/// <summary>
/// Represents a condition under which a scripted probe is run.
/// </summary>
public class Trigger
{
private object _conditionValue;
private Type _conditionValueEnumType;
public Probe Probe { get; set; }
public string DatumPropertyName { get; set; }
[JsonIgnore]
public PropertyInfo DatumProperty => Probe.DatumType.GetProperty(DatumPropertyName);
public TriggerValueCondition Condition { get; set; }
public object ConditionValue
{
get { return _conditionValue; }
set
{
_conditionValue = value;
// convert to enumerated type if we have the string type name
if (_conditionValueEnumType != null)
{
_conditionValue = Enum.ToObject(_conditionValueEnumType, _conditionValue);
}
}
}
/// <summary>
/// This is a workaround for an odd behavior of JSON.NET, which serializes enumerations as integers. We happen to be deserializing them as objects
/// into ConditionValue, which means they are stored as integers after deserialization. Integers are not comparable with the enumerated values
/// that come off the probes, so we need to jump through some hoops during deserization (i.e., below and above). Below, gettings and setting the
/// value works off of the enumerated type that should be used for the ConditionValue above. When either the below or above are set, they check
/// for the existence of the other and convert the number returned by JSON.NET to its appropriate enumerated type.
/// </summary>
public string ConditionValueEnumType
{
get { return _conditionValue is Enum ? _conditionValue.GetType().FullName : null; }
set
{
if (value != null)
{
_conditionValueEnumType = Assembly.GetExecutingAssembly().GetType(value);
// convert to enumerated type if we have the integer value
if (_conditionValue != null)
{
_conditionValue = Enum.ToObject(_conditionValueEnumType, _conditionValue);
}
}
}
}
public bool Change { get; set; }
public bool FireRepeatedly { get; set; }
public bool FireValueConditionMetOnPreviousCall { get; set; }
public string RegularExpressionText { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
private Trigger()
{
Reset();
}
public Trigger(Probe probe, PropertyInfo datumProperty, TriggerValueCondition condition, object conditionValue, bool change, bool fireRepeatedly, bool useRegularExpressions, TimeSpan startTime, TimeSpan endTime) : this()
{
if (probe == null) throw new Exception("Trigger is missing Probe selection.");
if (datumProperty == null) throw new Exception("Trigger is missing Property selection.");
if (conditionValue == null) throw new Exception("Trigger is missing Value selection.");
if (endTime <= startTime) throw new Exception("Trigger Start Time must precede End Time.");
Probe = probe;
DatumPropertyName = datumProperty.Name;
Condition = condition;
_conditionValue = conditionValue;
Change = change;
FireRepeatedly = fireRepeatedly;
StartTime = startTime;
EndTime = endTime;
if (useRegularExpressions)
{
RegularExpressionText = _conditionValue.ToString();
}
}
public void Reset()
{
FireValueConditionMetOnPreviousCall = false;
}
public bool FireFor(object value)
{
try
{
var fireValueConditionMet = FireValueConditionMet(value);
var fireRepeatConditionMet = FireRepeatConditionMet();
var fireWindowConditionMet = FireWindowConditionMet();
FireValueConditionMetOnPreviousCall = fireValueConditionMet;
return fireValueConditionMet && fireRepeatConditionMet && fireWindowConditionMet;
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log(ex.Message, LoggingLevel.Normal, GetType());
return false;
}
}
public override string ToString()
{
return $"{Probe.DisplayName} ({DatumPropertyName} {Condition} {_conditionValue})";
}
public override bool Equals(object obj)
{
var trigger = obj as Trigger;
return trigger != null && Probe == trigger.Probe && DatumPropertyName == trigger.DatumPropertyName && Condition == trigger.Condition && ConditionValue == trigger.ConditionValue && Change == trigger.Change;
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
#region Private Methods
private bool FireValueConditionMet(object value)
{
if (RegularExpressionText == null)
{
try
{
var compareTo = ((IComparable)value).CompareTo(_conditionValue);
if (Condition == TriggerValueCondition.EqualTo) return compareTo == 0;
if (Condition == TriggerValueCondition.GreaterThan) return compareTo > 0;
if (Condition == TriggerValueCondition.GreaterThanOrEqualTo) return compareTo >= 0;
if (Condition == TriggerValueCondition.LessThan) return compareTo < 0;
if (Condition == TriggerValueCondition.LessThanOrEqualTo) return compareTo <= 0;
if (Condition == TriggerValueCondition.NotEqualTo) return compareTo != 0;
throw new Exception($"Trigger failed recognize Condition: {Condition}");
}
catch (Exception ex)
{
throw new Exception($"Trigger failed to compare values: {ex.Message}", ex);
}
}
else
{
try
{
return Regex.IsMatch(value.ToString(), RegularExpressionText);
}
catch (Exception ex)
{
throw new Exception($"Trigger failed to run Regex.Match: {ex.Message}", ex);
}
}
}
private bool FireRepeatConditionMet()
{
return FireRepeatedly || !FireValueConditionMetOnPreviousCall;
}
private bool FireWindowConditionMet()
{
return StartTime <= DateTime.Now.TimeOfDay && DateTime.Now.TimeOfDay <= EndTime;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type float with 3 columns and 3 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct mat3 : IEnumerable<float>, IEquatable<mat3>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public float m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public float m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
public float m02;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public float m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public float m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
public float m12;
/// <summary>
/// Column 2, Rows 0
/// </summary>
public float m20;
/// <summary>
/// Column 2, Rows 1
/// </summary>
public float m21;
/// <summary>
/// Column 2, Rows 2
/// </summary>
public float m22;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public mat3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m20 = m20;
this.m21 = m21;
this.m22 = m22;
}
/// <summary>
/// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m20 = 0f;
this.m21 = 0f;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = 0f;
this.m21 = 0f;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = 0f;
this.m21 = 0f;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(mat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(vec2 c0, vec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0f;
this.m20 = 0f;
this.m21 = 0f;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(vec2 c0, vec2 c1, vec2 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0f;
this.m20 = c2.x;
this.m21 = c2.y;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(vec3 c0, vec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m20 = 0f;
this.m21 = 0f;
this.m22 = 1f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3(vec3 c0, vec3 c1, vec3 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m20 = c2.x;
this.m21 = c2.y;
this.m22 = c2.z;
}
/// <summary>
/// Creates a rotation matrix from a quat.
/// </summary>
public mat3(quat q)
: this(q.ToMat3)
{
}
#endregion
#region Explicit Operators
/// <summary>
/// Creates a rotation matrix from a quat.
/// </summary>
public static explicit operator mat3(quat q) => q.ToMat3;
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public float[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public float[] Values1D => new[] { m00, m01, m02, m10, m11, m12, m20, m21, m22 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public vec3 Column0
{
get
{
return new vec3(m00, m01, m02);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public vec3 Column1
{
get
{
return new vec3(m10, m11, m12);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 2
/// </summary>
public vec3 Column2
{
get
{
return new vec3(m20, m21, m22);
}
set
{
m20 = value.x;
m21 = value.y;
m22 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public vec3 Row0
{
get
{
return new vec3(m00, m10, m20);
}
set
{
m00 = value.x;
m10 = value.y;
m20 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public vec3 Row1
{
get
{
return new vec3(m01, m11, m21);
}
set
{
m01 = value.x;
m11 = value.y;
m21 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public vec3 Row2
{
get
{
return new vec3(m02, m12, m22);
}
set
{
m02 = value.x;
m12 = value.y;
m22 = value.z;
}
}
/// <summary>
/// Creates a quaternion from the rotational part of this matrix.
/// </summary>
public quat ToQuaternion => quat.FromMat3(this);
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static mat3 Zero { get; } = new mat3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static mat3 Ones { get; } = new mat3(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static mat3 Identity { get; } = new mat3(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static mat3 AllMaxValue { get; } = new mat3(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static mat3 DiagonalMaxValue { get; } = new mat3(float.MaxValue, 0f, 0f, 0f, float.MaxValue, 0f, 0f, 0f, float.MaxValue);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static mat3 AllMinValue { get; } = new mat3(float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static mat3 DiagonalMinValue { get; } = new mat3(float.MinValue, 0f, 0f, 0f, float.MinValue, 0f, 0f, 0f, float.MinValue);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static mat3 AllEpsilon { get; } = new mat3(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static mat3 DiagonalEpsilon { get; } = new mat3(float.Epsilon, 0f, 0f, 0f, float.Epsilon, 0f, 0f, 0f, float.Epsilon);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static mat3 AllNaN { get; } = new mat3(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static mat3 DiagonalNaN { get; } = new mat3(float.NaN, 0f, 0f, 0f, float.NaN, 0f, 0f, 0f, float.NaN);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static mat3 AllNegativeInfinity { get; } = new mat3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static mat3 DiagonalNegativeInfinity { get; } = new mat3(float.NegativeInfinity, 0f, 0f, 0f, float.NegativeInfinity, 0f, 0f, 0f, float.NegativeInfinity);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static mat3 AllPositiveInfinity { get; } = new mat3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static mat3 DiagonalPositiveInfinity { get; } = new mat3(float.PositiveInfinity, 0f, 0f, 0f, float.PositiveInfinity, 0f, 0f, 0f, float.PositiveInfinity);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<float> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m10;
yield return m11;
yield return m12;
yield return m20;
yield return m21;
yield return m22;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (3 x 3 = 9).
/// </summary>
public int Count => 9;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public float this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m10;
case 4: return m11;
case 5: return m12;
case 6: return m20;
case 7: return m21;
case 8: return m22;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m10 = value; break;
case 4: this.m11 = value; break;
case 5: this.m12 = value; break;
case 6: this.m20 = value; break;
case 7: this.m21 = value; break;
case 8: this.m22 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public float this[int col, int row]
{
get
{
return this[col * 3 + row];
}
set
{
this[col * 3 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(mat3 rhs) => ((((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m12.Equals(rhs.m12) && m20.Equals(rhs.m20)) && (m21.Equals(rhs.m21) && m22.Equals(rhs.m22))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is mat3 && Equals((mat3) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(mat3 lhs, mat3 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(mat3 lhs, mat3 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m22.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public mat3 Transposed => new mat3(m00, m10, m20, m01, m11, m21, m02, m12, m22);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public float MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m10), m11), m12), m20), m21), m22);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public float MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12), m20), m21), m22);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22))));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => ((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public float Sum => ((((m00 + m01) + m02) + (m10 + m11)) + ((m12 + m20) + (m21 + m22)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22))));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => ((((Math.Abs(m00) + Math.Abs(m01)) + Math.Abs(m02)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m12) + Math.Abs(m20)) + (Math.Abs(m21) + Math.Abs(m22))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22))));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public float NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m22));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow(((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + Math.Pow((double)Math.Abs(m02), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m20), p)) + (Math.Pow((double)Math.Abs(m21), p) + Math.Pow((double)Math.Abs(m22), p)))), 1 / p);
/// <summary>
/// Returns determinant of this matrix.
/// </summary>
public float Determinant => m00 * (m11 * m22 - m21 * m12) - m10 * (m01 * m22 - m21 * m02) + m20 * (m01 * m12 - m11 * m02);
/// <summary>
/// Returns the adjunct of this matrix.
/// </summary>
public mat3 Adjugate => new mat3(m11 * m22 - m21 * m12, -m01 * m22 + m21 * m02, m01 * m12 - m11 * m02, -m10 * m22 + m20 * m12, m00 * m22 - m20 * m02, -m00 * m12 + m10 * m02, m10 * m21 - m20 * m11, -m00 * m21 + m20 * m01, m00 * m11 - m10 * m01);
/// <summary>
/// Returns the inverse of this matrix (use with caution).
/// </summary>
public mat3 Inverse => Adjugate / Determinant;
/// <summary>
/// Executes a matrix-matrix-multiplication mat3 * mat2x3 -> mat2x3.
/// </summary>
public static mat2x3 operator*(mat3 lhs, mat2x3 rhs) => new mat2x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12));
/// <summary>
/// Executes a matrix-matrix-multiplication mat3 * mat3 -> mat3.
/// </summary>
public static mat3 operator*(mat3 lhs, mat3 rhs) => new mat3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22));
/// <summary>
/// Executes a matrix-matrix-multiplication mat3 * mat4x3 -> mat4x3.
/// </summary>
public static mat4x3 operator*(mat3 lhs, mat4x3 rhs) => new mat4x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32), ((lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31) + lhs.m22 * rhs.m32));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static vec3 operator*(mat3 m, vec3 v) => new vec3(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z), ((m.m02 * v.x + m.m12 * v.y) + m.m22 * v.z));
/// <summary>
/// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution).
/// </summary>
public static mat3 operator/(mat3 A, mat3 B) => A * B.Inverse;
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static mat3 CompMul(mat3 A, mat3 B) => new mat3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m20 * B.m20, A.m21 * B.m21, A.m22 * B.m22);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static mat3 CompDiv(mat3 A, mat3 B) => new mat3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m20 / B.m20, A.m21 / B.m21, A.m22 / B.m22);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat3 CompAdd(mat3 A, mat3 B) => new mat3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m20 + B.m20, A.m21 + B.m21, A.m22 + B.m22);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat3 CompSub(mat3 A, mat3 B) => new mat3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m20 - B.m20, A.m21 - B.m21, A.m22 - B.m22);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat3 operator+(mat3 lhs, mat3 rhs) => new mat3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m22 + rhs.m22);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat3 operator+(mat3 lhs, float rhs) => new mat3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m22 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat3 operator+(float lhs, mat3 rhs) => new mat3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m22);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat3 operator-(mat3 lhs, mat3 rhs) => new mat3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m22 - rhs.m22);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat3 operator-(mat3 lhs, float rhs) => new mat3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m22 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat3 operator-(float lhs, mat3 rhs) => new mat3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m22);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat3 operator/(mat3 lhs, float rhs) => new mat3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m22 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat3 operator/(float lhs, mat3 rhs) => new mat3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m22);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat3 operator*(mat3 lhs, float rhs) => new mat3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m22 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat3 operator*(float lhs, mat3 rhs) => new mat3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m22);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat3 operator<(mat3 lhs, mat3 rhs) => new bmat3(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m22 < rhs.m22);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3 operator<(mat3 lhs, float rhs) => new bmat3(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m22 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3 operator<(float lhs, mat3 rhs) => new bmat3(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m22);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat3 operator<=(mat3 lhs, mat3 rhs) => new bmat3(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m22 <= rhs.m22);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator<=(mat3 lhs, float rhs) => new bmat3(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m22 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator<=(float lhs, mat3 rhs) => new bmat3(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m22);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat3 operator>(mat3 lhs, mat3 rhs) => new bmat3(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m22 > rhs.m22);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3 operator>(mat3 lhs, float rhs) => new bmat3(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m22 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3 operator>(float lhs, mat3 rhs) => new bmat3(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m22);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat3 operator>=(mat3 lhs, mat3 rhs) => new bmat3(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m22 >= rhs.m22);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator>=(mat3 lhs, float rhs) => new bmat3(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m22 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator>=(float lhs, mat3 rhs) => new bmat3(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m22);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
{
#region Static Members
[System.Security.SecurityCritical] // auto-generated
internal static DelegateEntry GetDelegateSerializationInfo(
SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
{
// Used for MulticastDelegate
if (method == null)
throw new ArgumentNullException("method");
Contract.EndContractBlock();
if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
if (method.DeclaringType == null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
if (info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
info.AddValue("Delegate",de,typeof(DelegateEntry));
}
// target can be an object so it needs to be added to the info, or else a fixup is needed
// when deserializing, and the fixup will occur too late. If it is added directly to the
// info then the rules of deserialization will guarantee that it will be available when
// needed
if (target != null)
{
String targetName = "target" + targetIndex;
info.AddValue(targetName, de.target);
de.target = targetName;
}
// Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
// first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
// get this by serializing the target MethodInfo. We still need to send the same information as before though (the
// DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
// ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
// order of deserialization guarantee otherwise.
String methodInfoName = "method" + targetIndex;
info.AddValue(methodInfoName, method);
return de;
}
#endregion
#region Definitions
[Serializable]
internal class DelegateEntry
{
#region Internal Data Members
internal String type;
internal String assembly;
internal Object target;
internal String targetTypeAssembly;
internal String targetTypeName;
internal String methodName;
internal DelegateEntry delegateEntry;
#endregion
#region Constructor
internal DelegateEntry(
String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName)
{
this.type = type;
this.assembly = assembly;
this.target = target;
this.targetTypeAssembly = targetTypeAssembly;
this.targetTypeName = targetTypeName;
this.methodName = methodName;
}
#endregion
#region Internal Members
internal DelegateEntry Entry
{
get { return delegateEntry; }
set { delegateEntry = value; }
}
#endregion
}
#endregion
#region Private Data Members
private DelegateEntry m_delegateEntry;
private MethodInfo[] m_methods;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
bool bNewWire = true;
try
{
m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
}
catch
{
// Old wire format
m_delegateEntry = OldDelegateWireFormat(info, context);
bNewWire = false;
}
if (bNewWire)
{
// retrieve the targets
DelegateEntry deiter = m_delegateEntry;
int count = 0;
while (deiter != null)
{
if (deiter.target != null)
{
string stringTarget = deiter.target as string; //need test to pass older wire format
if (stringTarget != null)
deiter.target = info.GetValue(stringTarget, typeof(Object));
}
count++;
deiter = deiter.delegateEntry;
}
// If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
// them into an ordered array if present.
MethodInfo[] methods = new MethodInfo[count];
int i;
for (i = 0; i < count; i++)
{
String methodInfoName = "method" + i;
methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
if (methods[i] == null)
break;
}
// If we got the info then make the array available for deserialization.
if (i == count)
m_methods = methods;
}
}
#endregion
#region Private Members
private void ThrowInsufficientState(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
String delegateType = info.GetString("DelegateType");
String delegateAssembly = info.GetString("DelegateAssembly");
Object target = info.GetValue("Target", typeof(Object));
String targetTypeAssembly = info.GetString("TargetTypeAssembly");
String targetTypeName = info.GetString("TargetTypeName");
String methodName = info.GetString("MethodName");
return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
}
[System.Security.SecurityCritical]
private Delegate GetDelegate(DelegateEntry de, int index)
{
Delegate d;
try
{
if (de.methodName == null || de.methodName.Length == 0)
ThrowInsufficientState("MethodName");
if (de.assembly == null || de.assembly.Length == 0)
ThrowInsufficientState("DelegateAssembly");
if (de.targetTypeName == null || de.targetTypeName.Length == 0)
ThrowInsufficientState("TargetTypeName");
// We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
// If we received the new style delegate encoding we already have the target MethodInfo in hand.
if (m_methods != null)
{
#if FEATURE_REMOTING
Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
#else
if(!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
Object target=de.target;
#endif
d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
}
else
{
if (de.target != null)
#if FEATURE_REMOTING
d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
#else
{
if(!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
d = Delegate.CreateDelegate(type, de.target, de.methodName);
}
#endif
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
}
if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
catch (Exception e)
{
if (e is SerializationException)
throw e;
throw new SerializationException(e.Message, e);
}
return d;
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
int count = 0;
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
count++;
int maxindex = count - 1;
if (count == 1)
{
return GetDelegate(m_delegateEntry, 0);
}
else
{
object[] invocationList = new object[count];
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
{
// Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
// the order we process the entries: we're actually looking at them in reverse order.
--count;
invocationList[count] = GetDelegate(de, maxindex - count);
}
return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length);
}
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NGraphics
{
public interface ICanvas
{
void SaveState ();
void Transform (Transform transform);
void RestoreState ();
TextMetrics MeasureText (string text, Font font);
void DrawText (string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null);
void ClipRect (Rect frame);
void ClipPath (IEnumerable<PathOp> ops);
void DrawPath (IEnumerable<PathOp> ops, Pen pen = null, Brush brush = null);
void DrawRectangle (Rect frame, Size corner, Pen pen = null, Brush brush = null);
void DrawEllipse (Rect frame, Pen pen = null, Brush brush = null);
void DrawImage (IImage image, Rect frame, double alpha = 1.0);
}
public static class CanvasEx
{
public static void Translate (this ICanvas canvas, double dx, double dy)
{
canvas.Transform (Transform.Translate (dx, dy));
}
public static void Translate (this ICanvas canvas, Size translation)
{
canvas.Transform (Transform.Translate (translation));
}
public static void Translate (this ICanvas canvas, Point translation)
{
canvas.Transform (Transform.Translate (translation));
}
/// <summary>
/// Rotate the specified canvas by the given angle (in degrees).
/// </summary>
/// <param name="canvas">The canvas to rotate.</param>
/// <param name="angle">Angle in degrees.</param>
public static void Rotate (this ICanvas canvas, double angle)
{
if (angle != 0) {
canvas.Transform (Transform.Rotate (angle));
}
}
/// <param name="canvas">The canvas to rotate.</param>
/// <param name="angle">Angle in degrees.</param>
/// <param name="point">The translation point.</param>
public static void Rotate (this ICanvas canvas, double angle, Point point)
{
if (angle != 0) {
canvas.Translate (point);
canvas.Rotate (angle);
canvas.Translate (-point);
}
}
/// <param name="canvas">The canvas to rotate.</param>
/// <param name="angle">Angle in degrees.</param>
/// <param name="x">The x coordinate of the translation point.</param>
/// <param name="y">The y coordinate of the translation point.</param>
public static void Rotate (this ICanvas canvas, double angle, double x, double y)
{
if (angle != 0) {
canvas.Rotate (angle, new Point (x, y));
}
}
public static void Scale (this ICanvas canvas, double sx, double sy)
{
if (sx != 1 || sy != 1) {
canvas.Transform (Transform.Scale (sx, sy));
}
}
public static void Scale (this ICanvas canvas, double scale)
{
if (scale != 1) {
canvas.Transform (Transform.Scale (scale, scale));
}
}
public static void Scale (this ICanvas canvas, Size scale)
{
if (scale.Width != 1 || scale.Height != 1) {
canvas.Transform (Transform.Scale (scale));
}
}
public static void Scale (this ICanvas canvas, Size scale, Point point)
{
if (scale.Width != 1 || scale.Height != 1) {
canvas.Translate (point);
canvas.Scale (scale);
canvas.Translate (-point);
}
}
public static void Scale (this ICanvas canvas, double scale, Point point)
{
if (scale != 1) {
canvas.Scale (new Size (scale), point);
}
}
public static void Scale (this ICanvas canvas, double sx, double sy, double x, double y)
{
if (sx != 1 || sy != 1) {
canvas.Scale (new Size (sx, sy), new Point (x, y));
}
}
public static void Scale (this ICanvas canvas, double scale, double x, double y)
{
if (scale != 1) {
canvas.Scale (new Size (scale), new Point (x, y));
}
}
public static void DrawRectangle (this ICanvas canvas, Rect frame, Color color, double width = 1)
{
canvas.DrawRectangle (frame, Size.Zero, new Pen (color, width), null);
}
public static void DrawRectangle (this ICanvas canvas, Rect frame, Size corner, Color color, double width = 1)
{
canvas.DrawRectangle (frame, corner, new Pen (color, width), null);
}
public static void DrawRectangle (this ICanvas canvas, Rect frame, Pen pen = null, Brush brush = null)
{
canvas.DrawRectangle (frame, Size.Zero, pen, brush);
}
public static void DrawRectangle (this ICanvas canvas, double x, double y, double width, double height, Pen pen = null, Brush brush = null)
{
canvas.DrawRectangle (new Rect (x, y, width, height), Size.Zero, pen, brush);
}
public static void DrawRectangle (this ICanvas canvas, double x, double y, double width, double height, double rx, double ry, Pen pen = null, Brush brush = null)
{
canvas.DrawRectangle (new Rect (x, y, width, height), new Size (rx, ry), pen, brush);
}
public static void DrawRectangle (this ICanvas canvas, double x, double y, double width, double height, double rx, double ry, Color color, double penWidth = 1)
{
canvas.DrawRectangle (new Rect (x, y, width, height), new Size (rx, ry), pen: new Pen (color, penWidth));
}
public static void DrawRectangle (this ICanvas canvas, Point position, Size size, Pen pen = null, Brush brush = null)
{
canvas.DrawRectangle (new Rect (position, size), pen, brush);
}
public static void FillRectangle (this ICanvas canvas, Rect frame, Color color)
{
canvas.DrawRectangle (frame, brush: new SolidBrush (color));
}
public static void FillRectangle (this ICanvas canvas, Rect frame, Size corner, Color color)
{
canvas.DrawRectangle (frame, corner, brush: new SolidBrush (color));
}
public static void FillRectangle (this ICanvas canvas, double x, double y, double width, double height, Color color)
{
canvas.DrawRectangle (new Rect (x, y, width, height), brush: new SolidBrush (color));
}
public static void FillRectangle (this ICanvas canvas, double x, double y, double width, double height, double rx, double ry, Color color)
{
canvas.DrawRectangle (new Rect (x, y, width, height), new Size (rx, ry), brush: new SolidBrush (color));
}
public static void FillRectangle (this ICanvas canvas, double x, double y, double width, double height, Brush brush)
{
canvas.DrawRectangle (new Rect (x, y, width, height), brush: brush);
}
public static void FillRectangle (this ICanvas canvas, Rect frame, Brush brush)
{
canvas.DrawRectangle (frame, brush: brush);
}
public static void FillRectangle (this ICanvas canvas, Rect frame, Size corner, Brush brush)
{
canvas.DrawRectangle (frame, corner, brush: brush);
}
public static void DrawEllipse (this ICanvas canvas, Rect frame, Color color, double width = 1)
{
canvas.DrawEllipse (frame, new Pen (color, width), null);
}
public static void DrawEllipse (this ICanvas canvas, double x, double y, double width, double height, Pen pen = null, Brush brush = null)
{
canvas.DrawEllipse (new Rect (x, y, width, height), pen, brush);
}
public static void DrawEllipse (this ICanvas canvas, Point position, Size size, Pen pen = null, Brush brush = null)
{
canvas.DrawEllipse (new Rect (position, size), pen, brush);
}
public static void FillEllipse (this ICanvas canvas, Point position, Size size, Brush brush)
{
canvas.DrawEllipse (new Rect (position, size), null, brush);
}
public static void FillEllipse (this ICanvas canvas, Point position, Size size, Color color)
{
canvas.DrawEllipse (new Rect (position, size), null, new SolidBrush (color));
}
public static void FillEllipse (this ICanvas canvas, double x, double y, double width, double height, Color color)
{
canvas.DrawEllipse (new Rect (x, y, width, height), brush: new SolidBrush (color));
}
public static void FillEllipse (this ICanvas canvas, double x, double y, double width, double height, Brush brush)
{
canvas.DrawEllipse (new Rect (x, y, width, height), brush: brush);
}
public static void FillEllipse (this ICanvas canvas, Rect frame, Color color)
{
canvas.DrawEllipse (frame, brush: new SolidBrush (color));
}
public static void FillEllipse (this ICanvas canvas, Rect frame, Brush brush)
{
canvas.DrawEllipse (frame, brush: brush);
}
public static void StrokeEllipse (this ICanvas canvas, Rect frame, Color color, double width = 1.0)
{
canvas.DrawEllipse (frame, pen: new Pen (color, width));
}
public static void StrokeEllipse (this ICanvas canvas, Point position, Size size, Color color, double width = 1.0)
{
canvas.DrawEllipse (new Rect (position, size), new Pen (color, width), null);
}
public static void DrawPath (this ICanvas canvas, Action<Path> draw, Pen pen = null, Brush brush = null)
{
var p = new Path (pen, brush);
draw (p);
p.Draw (canvas);
}
public static void FillPath (this ICanvas canvas, IEnumerable<PathOp> ops, Brush brush)
{
canvas.DrawPath (ops, brush: brush);
}
public static void FillPath (this ICanvas canvas, IEnumerable<PathOp> ops, Color color)
{
canvas.DrawPath (ops, brush: new SolidBrush (color));
}
public static void FillPath (this ICanvas canvas, Action<Path> draw, Brush brush)
{
var p = new Path (null, brush);
draw (p);
p.Draw (canvas);
}
public static void FillPath (this ICanvas canvas, Action<Path> draw, Color color)
{
FillPath (canvas, draw, new SolidBrush (color));
}
public static void DrawLine (this ICanvas canvas, Point start, Point end, Pen pen)
{
var p = new Path { Pen = pen };
p.MoveTo (start);
p.LineTo (end);
p.Draw (canvas);
}
public static void DrawLine (this ICanvas canvas, Point start, Point end, Color color, double width = 1.0)
{
var p = new Path { Pen = new Pen (color, width) };
p.MoveTo (start);
p.LineTo (end);
p.Draw (canvas);
}
public static void DrawLine (this ICanvas canvas, double x1, double y1, double x2, double y2, Color color, double width = 1.0)
{
var p = new Path { Pen = new Pen (color, width) };
p.MoveTo (x1, y1);
p.LineTo (x2, y2);
p.Draw (canvas);
}
public static void DrawImage (this ICanvas canvas, IImage image)
{
canvas.DrawImage (image, new Rect (image.Size));
}
public static void DrawImage (this ICanvas canvas, IImage image, double x, double y, double width, double height, double alpha = 1.0)
{
canvas.DrawImage (image, new Rect (x, y, width, height), alpha);
}
public static void DrawText (this ICanvas canvas, string text, Point point, Font font, Brush brush)
{
canvas.DrawText (text, new Rect (point, Size.MaxValue), font, brush: brush);
}
public static void DrawText (this ICanvas canvas, string text, Point point, Font font, Color color)
{
canvas.DrawText (text, new Rect (point, Size.MaxValue), font, brush: new SolidBrush (color));
}
public static void DrawText (this ICanvas canvas, string text, Rect frame, Font font, TextAlignment alignment, Color color)
{
canvas.DrawText (text, frame, font, alignment, brush: new SolidBrush (color));
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Encoding.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 Java.Nio;
using Java.Nio.Charset;
namespace System.Text
{
/// <summary>
/// Represents a character encoding.
/// </summary>
public abstract class Encoding
{
private sealed class ForwardingDecoder : Decoder
{
private readonly Encoding encoding;
public ForwardingDecoder(Encoding enc)
{
encoding = enc;
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return encoding.GetCharCount(bytes, index, count);
}
public override int GetChars(byte[] bytes, int byteIndex,
int byteCount, char[] chars,
int charIndex)
{
return encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
}
private sealed class ForwardingEncoder : Encoder
{
private readonly Encoding encoding;
public ForwardingEncoder(Encoding enc)
{
encoding = enc;
}
public override int GetByteCount(char[] chars, int index, int count, bool flush)
{
return encoding.GetByteCount(chars, index, count);
}
public override int GetBytes(char[] chars, int charIndex,
int charCount, byte[] bytes,
int byteCount, bool flush)
{
return encoding.GetBytes(chars, charIndex, charCount, bytes, byteCount);
}
}
private static volatile ASCIIEncoding ascii;
private static volatile UnicodeEncoding unicode;
private static volatile UnicodeEncoding bigEndianUnicode;
private static volatile UTF8Encoding utf8;
private static volatile UTF32Encoding utf32;
private static volatile UTF32Encoding bigEndianUtf32;
internal readonly Charset charSet;
/// <summary>
/// Default ctor
/// </summary>
internal Encoding(Charset charSet)
{
this.charSet = charSet;
}
/// <summary>
/// Gets the default encoding
/// </summary>
public static Encoding Default
{
get { return utf8; }
}
public static Encoding GetEncoding(int codePage)
{
switch (codePage)
{
case 0: //default
//return Encoding.Default;
return UTF8;
case 1200:
return Unicode;
case 1201:
return BigEndianUnicode;
case 1252:
case 20127:
return ASCII;
case 12000:
return UTF32;
case 12001:
return BigEndianUTF32;
//case 65000:
// return UTF7;
case 65001:
return UTF8;
}
throw new NotSupportedException("CodePage is not supported");
}
public static Encoding GetEncoding(string name)
{
name = name.ToLower();
switch (name)
{
case "utf-16":
case "utf-16le":
return Unicode;
case "utf-16be":
case "unicodeFFFE":
return BigEndianUnicode;
case "windows-1252":
case "us-ascii":
return ASCII;
default: //additional switch, because C# compiler crashes with the case statements in a single switch
switch (name)
{
case "utf-32":
case "utf-32le":
return UTF32;
case "utf-32be":
return BigEndianUTF32;
//case "utf-7":
// return UTF7;
case "utf-8":
return UTF8;
}
break;
}
throw new ArgumentException("Encoding is not supported");
}
/// <summary>
/// Get a decoder.
/// </summary>
public virtual Decoder GetDecoder()
{
return new ForwardingDecoder(this);
}
/// <summary>
/// Get an encoder.
/// </summary>
public virtual Encoder GetEncoder()
{
return new ForwardingEncoder(this);
}
/// <summary>
/// Can this encoding be used by browser clients to display content?
/// </summary>
public virtual bool IsBrowserDisplay
{
get { return false; }
}
/// <summary>
/// Can this encoding be used by browser clients to save content?
/// </summary>
public virtual bool IsBrowserSave
{
get { return false; }
}
/// <summary>
/// Can this encoding be used by mail and news clients to display content?
/// </summary>
public virtual bool IsMailNewsDisplay
{
get { return false; }
}
/// <summary>
/// Can this encoding be used by mail and news clients to save content?
/// </summary>
public virtual bool IsMailNewsSave
{
get { return false; }
}
/// <summary>
/// Does this encoding use single-byte code points?
/// </summary>
public virtual bool IsSingleByte
{
get { return false; }
}
/// <summary>
/// Is this encoding readonly.
/// </summary>
public bool IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets byte sequence that identifies used encoding.
/// </summary>
public virtual byte[] GetPreamble()
{
return new byte[0];
}
/// <summary>
/// Gets the maximum number of bytes needed to encode the given number of characters.
/// </summary>
public virtual int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
return Math.JavaRound(charSet.NewEncoder().MaxBytesPerChar() * charCount);
}
/// <summary>
/// Gets the maximum number of characters needed to decode the given number of bytes.
/// </summary>
public virtual int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount");
return Math.JavaRound(charSet.NewDecoder().MaxCharsPerByte() * byteCount);
}
/// <summary>
/// Gets the number of bytes needed to encode the given character range.
/// </summary>
public virtual int GetByteCount(char[] chars)
{
if (chars == null)
throw new ArgumentNullException("chars");
return GetByteCount(chars, 0, chars.Length);
}
/// <summary>
/// Gets the number of bytes needed to encode the given character range.
/// </summary>
public virtual int GetByteCount(char[] chars, int charIndex, int charCount)
{
if (chars == null)
throw new ArgumentNullException("chars");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
if (charIndex + charCount > chars.Length)
throw new ArgumentOutOfRangeException("length");
var buffer = CharBuffer.Wrap(chars, charIndex, charCount);
return Encode(buffer).Remaining();
}
/// <summary>
/// Gets the number of bytes needed to encode the given character range.
/// </summary>
public virtual int GetByteCount(string value)
{
if (ReferenceEquals(value, null))
throw new ArgumentNullException("value");
var buffer = CharBuffer.Wrap(value);
return Encode(buffer).Remaining();
}
/// <summary>
/// Encodes a part of a string into a byte array.
/// </summary>
public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (ReferenceEquals(s, null))
throw new ArgumentNullException();
if (bytes == null)
throw new ArgumentNullException("bytes");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (byteIndex < 0)
throw new ArgumentOutOfRangeException("byteIndex");
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
if (charIndex + charCount > s.Length)
throw new ArgumentOutOfRangeException("length");
var buffer = CharBuffer.Wrap(s, charIndex, charIndex + charCount);
var encoded = Encode(buffer);
var length = encoded.Remaining();
if (byteIndex + length > bytes.Length)
throw new ArgumentException("bytes length");
encoded.Get(bytes, byteIndex, length);
return length;
}
/// <summary>
/// Encodes a part of a string into a byte array.
/// </summary>
public virtual byte[] GetBytes(string s)
{
if (ReferenceEquals(s, null))
throw new ArgumentNullException();
var buffer = CharBuffer.Wrap(s);
var encoded = Encode(buffer);
var length = encoded.Remaining();
var bytes = new byte[length];
encoded.Get(bytes, 0, length);
return bytes;
}
/// <summary>
/// Encodes a sequence of characters into a byte array.
/// </summary>
public virtual int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (chars == null)
throw new ArgumentNullException("chars");
if (bytes == null)
throw new ArgumentNullException("bytes");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (byteIndex < 0)
throw new ArgumentOutOfRangeException("byteIndex");
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
if (charIndex + charCount > chars.Length)
throw new ArgumentOutOfRangeException("chars length");
var buffer = CharBuffer.Wrap(chars, charIndex, charCount);
var encoded = Encode(buffer);
var length = encoded.Remaining();
if (byteIndex + length > bytes.Length)
throw new ArgumentException("bytes length");
encoded.Get(bytes, byteIndex, length);
return length;
}
/// <summary>
/// Encodes a sequence of characters into a byte array.
/// </summary>
public virtual byte[] GetBytes(char[] chars)
{
if (chars == null)
throw new ArgumentNullException("chars");
return GetBytes(chars, 0, chars.Length);
}
/// <summary>
/// Encodes a sequence of characters into a byte array.
/// </summary>
public virtual byte[] GetBytes(char[] chars, int charIndex, int charCount)
{
if (chars == null)
throw new ArgumentNullException("chars");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
if (charIndex + charCount > chars.Length)
throw new ArgumentOutOfRangeException("chars length");
var buffer = CharBuffer.Wrap(chars, charIndex, charCount);
var encoded = Encode(buffer);
var length = encoded.Remaining();
var bytes = new byte[length];
encoded.Get(bytes, 0, length);
return bytes;
}
/// <summary>
/// Gets the number of character needed to decode the given byte range.
/// </summary>
public virtual int GetCharCount(byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
return GetCharCount(bytes, 0, bytes.Length);
}
/// <summary>
/// Gets the number of character needed to decode the given byte range.
/// </summary>
public virtual int GetCharCount(byte[] bytes, int index, int count)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (index + count > bytes.Length)
throw new ArgumentOutOfRangeException("length");
var buffer = ByteBuffer.Wrap(bytes, index, count);
var decoded = Decode(buffer);
return decoded.Remaining();
}
/// <summary>
/// Decodes a sequence of bytes into a character array.
/// </summary>
public virtual char[] GetChars(byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
return GetChars(bytes, 0, bytes.Length);
}
/// <summary>
/// Decodes a sequence of bytes into a character array.
/// </summary>
public virtual char[] GetChars(byte[] bytes, int index, int count)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (index + count > bytes.Length)
throw new ArgumentOutOfRangeException("length");
var buffer = ByteBuffer.Wrap(bytes, index, count);
var decoded = Decode(buffer);
var length = decoded.Remaining();
var chars = new char[length];
decoded.Get(chars, 0, length);
return chars;
}
/// <summary>
/// Decodes a sequence of bytes into a character array.
/// </summary>
public virtual int GetChars(byte[] bytes, int index, int count, char[] chars, int charIndex)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (chars == null)
throw new ArgumentNullException("chars");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (index + count > bytes.Length)
throw new ArgumentOutOfRangeException("bytes length");
var buffer = ByteBuffer.Wrap(bytes, index, count);
var decoded = Decode(buffer);
var length = decoded.Remaining();
if (charIndex + length > chars.Length)
throw new ArgumentOutOfRangeException("chars length" + string.Format("[count={0} charIndex={1} length={2} chars.Length={3} charSet={4} GetMaxCharCount={5}]", count, charIndex, length, chars.Length, this.charSet.Name(), GetMaxCharCount(count)));
decoded.Get(chars, charIndex, length);
return length;
}
/// <summary>
/// Decodes a sequence of bytes into a string array.
/// </summary>
public virtual string GetString(byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
return GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Decodes a sequence of bytes into a string array.
/// </summary>
public virtual string GetString(byte[] bytes, int index, int count)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (index + count > bytes.Length)
throw new ArgumentOutOfRangeException("bytes length");
var buffer = ByteBuffer.Wrap(bytes, index, count);
var decoded = Decode(buffer);
return decoded.ToString();
}
/// <summary>
/// Encode the given source using the character set.
/// </summary>
protected virtual ByteBuffer Encode(CharBuffer source)
{
var replaceWith = new[] {(byte)'?'};
var encoder =
charSet.NewEncoder()
.OnMalformedInput(CodingErrorAction.REPLACE)
.OnUnmappableCharacter(CodingErrorAction.REPLACE)
.ReplaceWith(replaceWith);
return encoder.Encode(source);
}
/// <summary>
/// Decode the given source using the character set.
/// </summary>
protected virtual CharBuffer Decode(ByteBuffer source)
{
const string replaceWith = "?";
var encoder =
charSet.NewDecoder()
.OnMalformedInput(CodingErrorAction.REPLACE)
.OnUnmappableCharacter(CodingErrorAction.REPLACE)
.ReplaceWith(replaceWith);
return encoder.Decode(source);
}
/// <summary>
/// Gets an encoding for the ASCII (7-bit) character set.
/// </summary>
public static Encoding ASCII
{
get { return ascii ?? (ascii = new ASCIIEncoding()); }
}
/// <summary>
/// Gets an encoding for the UTF-16 character set.
/// </summary>
public static Encoding Unicode
{
get { return unicode ?? (unicode = new UnicodeEncoding()); }
}
/// <summary>
/// Gets an encoding for the UTF-16 character set with big endian byte order.
/// </summary>
public static Encoding BigEndianUnicode
{
get { return bigEndianUnicode ?? (bigEndianUnicode = new UnicodeEncoding(true, true)); }
}
/// <summary>
/// Gets an encoding for the UTF-8 character set.
/// </summary>
public static Encoding UTF8
{
get { return utf8 ?? (utf8 = new UTF8Encoding()); }
}
/// <summary>
/// Gets an encoding for the UTF-32 character set.
/// </summary>
public static Encoding UTF32
{
get { return utf32 ?? (utf32 = new UTF32Encoding()); }
}
/// <summary>
/// Gets an encoding for the UTF-32 character set.
/// </summary>
public static Encoding BigEndianUTF32
{
get { return bigEndianUtf32 ?? (bigEndianUtf32 = new UTF32Encoding(true, true)); }
}
}
}
| |
/*
*
* (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.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Web;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Billing;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Notify.Cron;
using ASC.Notify.Messages;
using ASC.Notify.Patterns;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain.Reports;
using ASC.Projects.Core.Services.NotifyService;
using ASC.Projects.Engine;
using ASC.Web.Core.Files;
using ASC.Web.Files.Services.DocumentService;
using ASC.Web.Projects.Core;
using ASC.Web.Studio.Core.Notify;
using ASC.Web.Studio.Utility;
using Autofac;
namespace ASC.Web.Projects.Classes
{
public class NotifyHelper
{
private static readonly ILog logger;
static NotifyHelper()
{
logger = LogManager.GetLogger("ASC.Web.Projects.Reports");
}
public static void SendAutoReminderAboutTask(DateTime state)
{
try
{
var now = DateTime.UtcNow;
List<object[]> tasks;
using (var scope = DIHelper.Resolve(Tenant.DEFAULT_TENANT))
{
var daoFactory = scope.Resolve<IDaoFactory>();
tasks = daoFactory.TaskDao.GetTasksForReminder(now);
}
foreach (var r in tasks)
{
var tenant = CoreContext.TenantManager.GetTenant((int)r[0]);
if (tenant == null ||
tenant.Status != TenantStatus.Active ||
TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenant.TenantId).State)
{
continue;
}
var localTime = TenantUtil.DateTimeFromUtc(tenant.TimeZone, now);
if (!TimeToSendReminderAboutTask(localTime)) continue;
var deadline = (DateTime)r[2];
if (deadline.Date != localTime.Date) continue;
try
{
CoreContext.TenantManager.SetCurrentTenant(tenant);
SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
using (var scope = DIHelper.Resolve())
{
var engineFactory = scope.Resolve<EngineFactory>();
var t = engineFactory.TaskEngine.GetByID((int)r[1]);
if (t == null) continue;
foreach (var responsible in t.Responsibles)
{
var user = CoreContext.UserManager.GetUsers(t.CreateBy);
if (!Constants.LostUser.Equals(user) && user.Status == EmployeeStatus.Active)
{
SecurityContext.AuthenticateMe(user.ID);
Thread.CurrentThread.CurrentCulture = user.GetCulture();
Thread.CurrentThread.CurrentUICulture = user.GetCulture();
NotifyClient.Instance.SendReminderAboutTaskDeadline(new List<Guid> { responsible }, t);
}
}
}
}
catch (Exception ex)
{
logger.Error("SendAutoReminderAboutTask", ex);
}
}
}
catch (Exception ex)
{
logger.Error("SendAutoReminderAboutTask", ex);
}
}
private static bool TimeToSendReminderAboutTask(DateTime currentTime)
{
var hourToSend = 7;
if (!string.IsNullOrEmpty(ConfigurationManagerExtension.AppSettings["remindertime"]))
{
int hour;
if (int.TryParse(ConfigurationManagerExtension.AppSettings["remindertime"], out hour))
{
hourToSend = hour;
}
}
return currentTime.Hour == hourToSend;
}
public static void SendAutoReports(DateTime datetime)
{
try
{
var now = DateTime.UtcNow.Date.AddHours(DateTime.UtcNow.Hour);
List<ReportTemplate> templates;
using (var scope = DIHelper.Resolve(Tenant.DEFAULT_TENANT))
{
var daoFactory = scope.Resolve<IDaoFactory>();
templates = daoFactory.ReportDao.GetAutoTemplates();
}
foreach (var tGrouped in templates.GroupBy(r => r.Tenant))
{
try
{
SendByTenant(now, tGrouped);
}
catch (Exception e)
{
LogManager.GetLogger("ASC").Error("SendByTenant", e);
}
}
}
catch (Exception ex)
{
logger.Error("SendAutoReports", ex);
}
}
public static void SendMsgMilestoneDeadline(DateTime scheduleDate)
{
var date = DateTime.UtcNow.AddDays(2);
List<object[]> milestones;
using (var scope = DIHelper.Resolve(Tenant.DEFAULT_TENANT))
{
var daoFactory = scope.Resolve<IDaoFactory>();
milestones = daoFactory.MilestoneDao.GetInfoForReminder(date);
}
foreach (var r in milestones)
{
var tenant = CoreContext.TenantManager.GetTenant((int)r[0]);
if (tenant == null ||
tenant.Status != TenantStatus.Active ||
TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenant.TenantId).State)
{
continue;
}
var localTime = TenantUtil.DateTimeFromUtc(tenant.TimeZone, date);
if (localTime.Date == ((DateTime)r[2]).Date)
{
try
{
CoreContext.TenantManager.SetCurrentTenant(tenant);
SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
using (var scope = DIHelper.Resolve())
{
var m = scope.Resolve<IDaoFactory>().MilestoneDao.GetById((int)r[1]);
if (m != null)
{
var sender = !m.Responsible.Equals(Guid.Empty) ? m.Responsible : m.Project.Responsible;
var user = CoreContext.UserManager.GetUsers(sender);
if (!Constants.LostUser.Equals(user) && user.Status == EmployeeStatus.Active)
{
SecurityContext.AuthenticateMe(user.ID);
Thread.CurrentThread.CurrentCulture = user.GetCulture();
Thread.CurrentThread.CurrentUICulture = user.GetCulture();
NotifyClient.Instance.SendMilestoneDeadline(sender, m);
}
}
}
}
catch (Exception ex)
{
logger.Error("SendMsgMilestoneDeadline, tenant: " + tenant.TenantDomain, ex);
}
}
}
}
private static void SendByTenant(DateTime now, IGrouping<int, ReportTemplate> tGrouped)
{
var tenant = CoreContext.TenantManager.GetTenant(tGrouped.Key);
if (tenant == null || tenant.Status != TenantStatus.Active || CoreContext.PaymentManager.GetTariff(tenant.TenantId).State >= TariffState.NotPaid) return;
CoreContext.TenantManager.SetCurrentTenant(tenant);
DocbuilderReportsUtility.Terminate(ReportOrigin.ProjectsAuto);
var timeZone = CoreContext.TenantManager.GetCurrentTenant().TimeZone;
foreach (var t in tGrouped)
{
try
{
SendReport(now, timeZone, t);
}
catch (System.Security.SecurityException se)
{
logger.Error("SendAutoReports", se);
}
catch (Exception ex)
{
logger.ErrorFormat("TemplateId: {0}, Temaplate: {1}\r\n{2}", t.Id, t.Filter.ToXml(), ex);
}
}
}
private static void SendReport(DateTime now, TimeZoneInfo timeZone, ReportTemplate t)
{
var cron = new CronExpression(t.Cron) { TimeZone = timeZone };
var date = cron.GetTimeAfter(now.AddTicks(-1));
LogManager.GetLogger("ASC.Web.Projects.Reports").DebugFormat("Find auto report: {0} - {1}, now: {2}, date: {3}", t.Name, t.Cron, now, date);
if (date != now) return;
var user = CoreContext.UserManager.GetUsers(t.CreateBy);
if (user.ID == Constants.LostUser.ID || user.Status != EmployeeStatus.Active) return;
SecurityContext.AuthenticateMe(user.ID);
Thread.CurrentThread.CurrentCulture = user.GetCulture();
Thread.CurrentThread.CurrentUICulture = user.GetCulture();
var message = new NoticeMessage(user, HttpUtility.HtmlDecode(t.Name), "", "html");
message.AddArgument(new TagValue(CommonTags.SendFrom, CoreContext.TenantManager.GetCurrentTenant().Name));
message.AddArgument(new TagValue(CommonTags.Priority, 1));
ReportState state;
var template = t;
var result = Report.TryCreateReportFromTemplate(t, (s, u) =>
{
try
{
if (string.IsNullOrEmpty(s.Exception))
{
template.SaveDocbuilderReport(s, u);
}
SendWhenGenerated(s, user);
}
catch (Exception e)
{
logger.Error(e);
}
}, message, out state, true);
if (!result)
{
SendWhenGenerated(state, user);
}
}
private static void SendWhenGenerated(ReportState state, UserInfo user)
{
try
{
Thread.CurrentThread.CurrentCulture = user.GetCulture();
Thread.CurrentThread.CurrentUICulture = user.GetCulture();
var message = (NoticeMessage)state.Obj;
message.Body = !string.IsNullOrEmpty(state.Exception) ? state.Exception : string.Format(Resources.ReportResource.AutoGeneratedReportMail, message.Subject, CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(state.FileId)));
WorkContext.NotifyContext.DispatchEngine.Dispatch(message, "email.sender");
logger.DebugFormat("Send auto report: {0} to {1}, tenant: {2}", message.Subject, SecurityContext.CurrentAccount.ID, TenantProvider.CurrentTenantID);
}
catch (Exception e)
{
logger.Error("SendWhenGenerated", e);
}
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using System.Text;
using Google.GData.Client;
namespace Google.GData.Contacts {
//////////////////////////////////////////////////////////////////////
/// <summary>
/// A subclass of FeedQuery, to create an Contacts query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The ContactsQuery supports the following GData parameters:
/// The Contacts Data API supports the following standard Google Data API query parameters:
/// Name Description
/// alt The type of feed to return, such as atom (the default), rss, or json.
/// max-results The maximum number of entries to return. If you want to receive all of
/// the contacts, rather than only the default maximum, you can specify a very
/// large number for max-results.
/// start-index The 1-based index of the first result to be retrieved (for paging).
/// updated-min The lower bound on entry update dates.
///
/// For more information about the standard parameters, see the Google Data APIs protocol reference document.
/// In addition to the standard query parameters, the Contacts Data API supports the following parameters:
///
/// Name Description
/// orderby Sorting criterion. The only supported value is lastmodified.
/// showdeleted Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but an
/// atom:id element and a gd:deleted element.
/// (Google retains placeholders for deleted contacts for 30 days after
/// deletion; during that time, you can request the placeholders
/// using the showdeleted query parameter.) Valid values are true or false.
/// sortorder Sorting order direction. Can be either ascending or descending.
/// group Constrains the results to only the contacts belonging to the group specified.
/// Value of this parameter specifies group ID (see also: gContact:groupMembershipInfo).
/// </summary>
//////////////////////////////////////////////////////////////////////
public class GroupsQuery : FeedQuery
{
/// <summary>
/// contacts group base URI
/// </summary>
public const string groupsBaseUri = "http://www.google.com/m8/feeds/groups/";
/// <summary>
/// sortoder value for sorting by lastmodified
/// </summary>
public const string OrderByLastModified = "lastmodified";
/// <summary>
/// sortoder value for sorting ascending
/// </summary>
public const string SortOrderAscending = "ascending";
/// <summary>
/// sortoder value for sorting descending
/// </summary>
public const string SortOrderDescending = "ascending";
/// <summary>
/// base projection value
/// </summary>
public const string baseProjection = "base";
/// <summary>
/// thin projection value
/// </summary>
public const string thinProjection = "thin";
/// <summary>
/// property-key projection value
/// </summary>
public const string propertyProjection = "property-";
/// <summary>
/// full projection value
/// </summary>
public const string fullProjection = "full";
private string orderBy;
private bool showDeleted;
private string sortOrder;
/// <summary>
/// base constructor
/// </summary>
public GroupsQuery()
: base()
{
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public GroupsQuery(string queryUri)
: base(queryUri)
{
}
/// <summary>
/// convienience method to create an URI based on a userID for a groups feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID"></param>
/// <returns>string</returns>
public static string CreateGroupsUri(string userID)
{
return CreateGroupsUri(userID, ContactsQuery.fullProjection);
}
/// <summary>
/// convienience method to create an URI based on a userID for a groups feed
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <param name="projection">the projection to use</param>
/// <returns>string</returns>
public static string CreateGroupsUri(string userID, string projection)
{
return ContactsQuery.groupsBaseUri + ContactsQuery.UserString(userID) + projection;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Sorting order direction. Can be either ascending or descending</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string SortOrder
{
get {return this.sortOrder;}
set {this.sortOrder = value;}
}
// end of accessor public string SortOder
//////////////////////////////////////////////////////////////////////
/// <summary>Sorting criterion. The only supported value is lastmodified</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string OrderBy
{
get {return this.orderBy;}
set {this.orderBy = value;}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but
/// an atom:id element and a gd:deleted element. (Google retains placeholders
/// for deleted contacts for 30 days after deletion; during that time,
/// you can request the placeholders using the showdeleted query
/// parameter.) Valid values are true or false.</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public bool ShowDeleted
{
get {return this.showDeleted;}
set {this.showDeleted = value;}
}
// end of accessor public bool ShowDeleted
/// <summary>
/// helper to create the userstring for a query
/// </summary>
/// <param name="user">the user to encode, or NULL if default</param>
/// <returns></returns>
protected static string UserString(string user)
{
if (user == null)
{
return "default/";
}
return Utilities.UriEncodeReserved(user)+ "/";
}
#if WindowsCE || PocketPC
#else
//////////////////////////////////////////////////////////////////////
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
//////////////////////////////////////////////////////////////////////
protected override Uri ParseUri(Uri targetUri)
{
base.ParseUri(targetUri);
if (targetUri != null)
{
char[] deli = { '?', '&' };
TokenCollection tokens = new TokenCollection(targetUri.Query, deli);
foreach (String token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = { '=' };
String[] parameters = token.Split(otherDeli, 2);
switch (parameters[0])
{
case "orderby":
this.OrderBy = parameters[1];
break;
case "sortorder":
this.SortOrder = parameters[1];
break;
case "showdeleted":
if (String.Compare("true", parameters[1], false, CultureInfo.InvariantCulture) == 0)
{
this.ShowDeleted = true;
}
break;
}
}
}
}
return this.Uri;
}
#endif
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> string => the query part of the URI </returns>
//////////////////////////////////////////////////////////////////////
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.OrderBy != null && this.OrderBy.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "orderby={0}", Utilities.UriEncodeReserved(this.OrderBy));
paramInsertion = '&';
}
if (this.SortOrder != null && this.SortOrder.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "sortorder={0}", Utilities.UriEncodeReserved(this.SortOrder));
paramInsertion = '&';
}
if (this.ShowDeleted == true)
{
newPath.Append(paramInsertion);
newPath.Append("showdeleted=true");
paramInsertion = '&';
}
return newPath.ToString();
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// A subclass of GroupsQuery, to create an Contacts query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The ContactsQuery supports the following GData parameters:
/// Name Description
/// alt The type of feed to return, such as atom (the default), rss, or json.
/// max-results The maximum number of entries to return. If you want to receive all of
/// the contacts, rather than only the default maximum, you can specify a very
/// large number for max-results.
/// start-index The 1-based index of the first result to be retrieved (for paging).
/// updated-min The lower bound on entry update dates.
///
/// For more information about the standard parameters, see the Google Data APIs protocol reference document.
/// In addition to the standard query parameters, the Contacts Data API supports the following parameters:
///
/// Name Description
/// orderby Sorting criterion. The only supported value is lastmodified.
/// showdeleted Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but an
/// atom:id element and a gd:deleted element.
/// (Google retains placeholders for deleted contacts for 30 days after
/// deletion; during that time, you can request the placeholders
/// using the showdeleted query parameter.) Valid values are true or false.
/// sortorder Sorting order direction. Can be either ascending or descending.
/// group Constrains the results to only the contacts belonging to the group specified.
/// Value of this parameter specifies group ID (see also: gContact:groupMembershipInfo).
/// </summary>
//////////////////////////////////////////////////////////////////////
public class ContactsQuery : GroupsQuery
{
/// <summary>
/// contacts base URI
/// </summary>
public const string contactsBaseUri = "http://www.google.com/m8/feeds/contacts/";
private string group;
/// <summary>
/// base constructor
/// </summary>
public ContactsQuery()
: base()
{
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public ContactsQuery(string queryUri)
: base(queryUri)
{
}
/// <summary>
/// convienience method to create an URI based on a userID for a contacts feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <returns>string</returns>
public static string CreateContactsUri(string userID)
{
return CreateContactsUri(userID, ContactsQuery.fullProjection);
}
/// <summary>
/// convienience method to create an URI based on a userID for a contacts feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <param name="projection">the projection to use</param>
/// <returns>string</returns>
public static string CreateContactsUri(string userID, string projection)
{
return ContactsQuery.contactsBaseUri + UserString(userID) + projection;
}
/////////////////////////////////////////////////////////////////////
/// <summary>Constrains the results to only the contacts belonging to the
/// group specified. Value of this parameter specifies group ID</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Group
{
get {return this.group;}
set {this.group = value;}
}
// end of accessor public string SortOder
#if WindowsCE || PocketPC
#else
//////////////////////////////////////////////////////////////////////
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
//////////////////////////////////////////////////////////////////////
protected override Uri ParseUri(Uri targetUri)
{
base.ParseUri(targetUri);
if (targetUri != null)
{
char[] deli = { '?', '&' };
TokenCollection tokens = new TokenCollection(targetUri.Query, deli);
foreach (String token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = { '=' };
String[] parameters = token.Split(otherDeli, 2);
switch (parameters[0])
{
case "group":
this.Group = parameters[1];
break;
}
}
}
}
return this.Uri;
}
#endif
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> string => the query part of the URI </returns>
//////////////////////////////////////////////////////////////////////
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.Group != null && this.Group.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "group={0}", Utilities.UriEncodeReserved(this.Group));
paramInsertion = '&';
}
return newPath.ToString();
}
}
}
| |
using System;
using NUnit.Framework;
using System.Drawing;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Environment;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Interactions
{
[TestFixture]
public class DragAndDropTest : DriverTestFixture
{
[SetUp]
public void SetupTest()
{
IActionExecutor actionExecutor = driver as IActionExecutor;
if (actionExecutor != null)
{
actionExecutor.ResetInputState();
}
}
[Test]
public void DragAndDropRelative()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test1"));
Point expectedLocation = drag(img, img.Location, 150, 200);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, -50, -25);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, 0, 0);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, 1, -1);
Assert.AreEqual(expectedLocation, img.Location);
}
[Test]
public void DragAndDropToElement()
{
driver.Url = dragAndDropPage;
IWebElement img1 = driver.FindElement(By.Id("test1"));
IWebElement img2 = driver.FindElement(By.Id("test2"));
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
[Test]
public void DragAndDropToElementInIframe()
{
driver.Url = iframePage;
IWebElement iframe = driver.FindElement(By.TagName("iframe"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].src = arguments[1]", iframe,
dragAndDropPage);
driver.SwitchTo().Frame(0);
IWebElement img1 = WaitFor<IWebElement>(() =>
{
try
{
IWebElement element1 = driver.FindElement(By.Id("test1"));
return element1;
}
catch (NoSuchElementException)
{
return null;
}
}, "Element with ID 'test1' not found");
IWebElement img2 = driver.FindElement(By.Id("test2"));
new Actions(driver).DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
[Test]
public void DragAndDropElementWithOffsetInIframeAtBottom()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("iframeAtBottom.html");
IWebElement iframe = driver.FindElement(By.TagName("iframe"));
driver.SwitchTo().Frame(iframe);
IWebElement img1 = driver.FindElement(By.Id("test1"));
Point initial = img1.Location;
new Actions(driver).DragAndDropToOffset(img1, 20, 20).Perform();
initial.Offset(20, 20);
Assert.AreEqual(initial, img1.Location);
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")]
public void DragAndDropElementWithOffsetInScrolledDiv()
{
if (TestUtilities.IsFirefox(driver) && TestUtilities.IsNativeEventsEnabled(driver))
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("dragAndDropInsideScrolledDiv.html");
IWebElement el = driver.FindElement(By.Id("test1"));
Point initial = el.Location;
new Actions(driver).DragAndDropToOffset(el, 3700, 3700).Perform();
initial.Offset(3700, 3700);
Assert.AreEqual(initial, el.Location);
}
[Test]
public void ElementInDiv()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test3"));
Point startLocation = img.Location;
Point expectedLocation = drag(img, startLocation, 100, 100);
Point endLocation = img.Location;
Assert.AreEqual(expectedLocation, endLocation);
}
[Test]
public void DragTooFar()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test1"));
// Dragging too far left and up does not move the element. It will be at
// its original location after the drag.
Point originalLocation = new Point(0, 0);
Actions actionProvider = new Actions(driver);
Assert.That(() => actionProvider.DragAndDropToOffset(img, 2147480000, 2147400000).Perform(), Throws.InstanceOf<WebDriverException>());
new Actions(driver).Release().Perform();
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")]
public void ShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort()
{
Size originalSize = driver.Manage().Window.Size;
Size testSize = new Size(300, 300);
driver.Url = dragAndDropPage;
driver.Manage().Window.Size = testSize;
try
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test3"));
Point expectedLocation = drag(img, img.Location, 100, 100);
Assert.AreEqual(expectedLocation, img.Location);
}
finally
{
driver.Manage().Window.Size = originalSize;
}
}
[Test]
public void DragAndDropOnJQueryItems()
{
driver.Url = droppableItems;
IWebElement toDrag = driver.FindElement(By.Id("draggable"));
IWebElement dropInto = driver.FindElement(By.Id("droppable"));
// Wait until all event handlers are installed.
System.Threading.Thread.Sleep(500);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDrop(toDrag, dropInto).Perform();
string text = dropInto.FindElement(By.TagName("p")).Text;
DateTime endTime = DateTime.Now.Add(TimeSpan.FromSeconds(15));
while (text != "Dropped!" && (DateTime.Now < endTime))
{
System.Threading.Thread.Sleep(200);
text = dropInto.FindElement(By.TagName("p")).Text;
}
Assert.AreEqual("Dropped!", text);
IWebElement reporter = driver.FindElement(By.Id("drop_reports"));
// Assert that only one mouse click took place and the mouse was moved
// during it.
string reporterText = reporter.Text;
Assert.That(reporterText, Does.Match("start( move)* down( move)+ up"));
Assert.AreEqual(1, Regex.Matches(reporterText, "down").Count, "Reporter text:" + reporterText);
Assert.AreEqual(1, Regex.Matches(reporterText, "up").Count, "Reporter text:" + reporterText);
Assert.That(reporterText, Does.Contain("move"));
}
[Test]
[IgnoreBrowser(Browser.Opera, "Untested")]
[IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")]
public void CanDragAnElementNotVisibleInTheCurrentViewportDueToAParentOverflow()
{
driver.Url = dragDropOverflowPage;
IWebElement toDrag = driver.FindElement(By.Id("time-marker"));
IWebElement dragTo = driver.FindElement(By.Id("11am"));
Point srcLocation = toDrag.Location;
Point targetLocation = dragTo.Location;
int yOffset = targetLocation.Y - srcLocation.Y;
Assert.AreNotEqual(0, yOffset);
new Actions(driver).DragAndDropToOffset(toDrag, 0, yOffset).Perform();
Assert.AreEqual(dragTo.Location, toDrag.Location);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void DragAndDropRelativeAndToElement()
{
driver.Url = dragAndDropPage;
IWebElement img1 = driver.FindElement(By.Id("test1"));
IWebElement img2 = driver.FindElement(By.Id("test2"));
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDropToOffset(img1, 100, 100).DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
private Point drag(IWebElement elem, Point initialLocation, int moveRightBy, int moveDownBy)
{
Point expectedLocation = new Point(initialLocation.X, initialLocation.Y);
expectedLocation.Offset(moveRightBy, moveDownBy);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDropToOffset(elem, moveRightBy, moveDownBy).Perform();
return expectedLocation;
}
}
}
| |
#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;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal static class JavaScriptUtils
{
internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] HtmlCharEscapeFlags = new bool[128];
static JavaScriptUtils()
{
IList<char> escapeChars = new List<char>
{
'\n', '\r', '\t', '\\', '\f', '\b',
};
for (int i = 0; i < ' '; i++)
{
escapeChars.Add((char)i);
}
foreach (var escapeChar in escapeChars.Union(new[] { '\'' }))
{
SingleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (var escapeChar in escapeChars.Union(new[] { '"' }))
{
DoubleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' }))
{
HtmlCharEscapeFlags[escapeChar] = true;
}
}
private const string EscapedUnicodeText = "!";
public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar)
{
if (stringEscapeHandling == StringEscapeHandling.EscapeHtml)
return HtmlCharEscapeFlags;
if (quoteChar == '"')
return DoubleQuoteCharEscapeFlags;
return SingleQuoteCharEscapeFlags;
}
public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags)
{
if (s == null)
return false;
foreach (char c in s)
{
if (c >= charEscapeFlags.Length || charEscapeFlags[c])
return true;
}
return false;
}
public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters,
bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, ref char[] writeBuffer)
{
// leading delimiter
if (appendDelimiters)
writer.Write(delimiter);
if (s != null)
{
int lastWritePosition = 0;
for (int i = 0; i < s.Length; i++)
{
var c = s[i];
if (c < charEscapeFlags.Length && !charEscapeFlags[c])
continue;
string escapedValue;
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
default:
if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
{
if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\'";
}
else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\""";
}
else
{
if (writeBuffer == null)
writeBuffer = new char[6];
StringUtils.ToCharAsUnicode(c, writeBuffer);
// slightly hacky but it saves multiple conditions in if test
escapedValue = EscapedUnicodeText;
}
}
else
{
escapedValue = null;
}
break;
}
if (escapedValue == null)
continue;
bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText);
if (i > lastWritePosition)
{
int length = i - lastWritePosition + ((isEscapedUnicodeText) ? 6 : 0);
int start = (isEscapedUnicodeText) ? 6 : 0;
if (writeBuffer == null || writeBuffer.Length < length)
{
char[] newBuffer = new char[length];
// the unicode text is already in the buffer
// copy it over when creating new buffer
if (isEscapedUnicodeText)
Array.Copy(writeBuffer, newBuffer, 6);
writeBuffer = newBuffer;
}
s.CopyTo(lastWritePosition, writeBuffer, start, length - start);
// write unchanged chars before writing escaped text
writer.Write(writeBuffer, start, length - start);
}
lastWritePosition = i + 1;
if (!isEscapedUnicodeText)
writer.Write(escapedValue);
else
writer.Write(writeBuffer, 0, 6);
}
if (lastWritePosition == 0)
{
// no escaped text, write entire string
writer.Write(s);
}
else
{
int length = s.Length - lastWritePosition;
if (writeBuffer == null || writeBuffer.Length < length)
writeBuffer = new char[length];
s.CopyTo(lastWritePosition, writeBuffer, 0, length);
// write remaining text
writer.Write(writeBuffer, 0, length);
}
}
// trailing delimiter
if (appendDelimiters)
writer.Write(delimiter);
}
public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters)
{
return ToEscapedJavaScriptString(value, delimiter, appendDelimiters, StringEscapeHandling.Default);
}
public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling)
{
bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter);
using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16))
{
char[] buffer = null;
WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, ref buffer);
return w.ToString();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.ServiceModel.Security;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using System.Threading;
using System.IO;
using Infrastructure.Common;
public partial class ExpectedExceptionTests : ConditionalWcfTest
{
[WcfFact]
[OuterLoop]
public static void NonExistentAction_Throws_ActionNotSupportedException()
{
string exceptionMsg = "The message with Action 'http://tempuri.org/IWcfService/NotExistOnServer' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).";
try
{
BasicHttpBinding binding = new BasicHttpBinding();
using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)))
{
IWcfService serviceProxy = factory.CreateChannel();
serviceProxy.NotExistOnServer();
}
}
catch (Exception e)
{
if (e.GetType() != typeof(System.ServiceModel.ActionNotSupportedException))
{
Assert.True(false, string.Format("Expected exception: {0}, actual: {1}", "ActionNotSupportedException", e.GetType()));
}
if (e.Message != exceptionMsg)
{
Assert.True(false, string.Format("Expected Fault Message: {0}, actual: {1}", exceptionMsg, e.Message));
}
return;
}
Assert.True(false, "Expected ActionNotSupportedException exception, but no exception thrown.");
}
// SendTimeout is set to 5 seconds, the service waits 10 seconds to respond.
// The client should throw a TimeoutException
[WcfFact]
[OuterLoop]
public static void SendTimeout_For_Long_Running_Operation_Throws_TimeoutException()
{
TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(10000);
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(5000);
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
Stopwatch watch = new Stopwatch();
try
{
var exception = Assert.Throws<TimeoutException>(() =>
{
IWcfService proxy = factory.CreateChannel();
watch.Start();
proxy.EchoWithTimeout("Hello", serviceOperationTimeout);
});
}
finally
{
watch.Stop();
}
// want to assert that this completed in > 5 s as an upper bound since the SendTimeout is 5 sec
// (usual case is around 5001-5005 ms)
Assert.InRange<long>(watch.ElapsedMilliseconds, 4985, 6000);
}
// SendTimeout is set to 0, this should trigger a TimeoutException before even attempting to call the service.
[WcfFact]
[OuterLoop]
public static void SendTimeout_Zero_Throws_TimeoutException_Immediately()
{
TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(5000);
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(0);
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
Stopwatch watch = new Stopwatch();
try
{
var exception = Assert.Throws<TimeoutException>(() =>
{
IWcfService proxy = factory.CreateChannel();
watch.Start();
proxy.EchoWithTimeout("Hello", serviceOperationTimeout);
});
}
finally
{
watch.Stop();
}
// want to assert that this completed in < 2 s as an upper bound since the SendTimeout is 0 sec
// (usual case is around 1 - 3 ms)
Assert.InRange<long>(watch.ElapsedMilliseconds, 0, 2000);
}
[WcfFact]
[OuterLoop]
public static void FaultException_Throws_WithFaultDetail()
{
string faultMsg = "Test Fault Exception";
StringBuilder errorBuilder = new StringBuilder();
try
{
BasicHttpBinding binding = new BasicHttpBinding();
using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)))
{
IWcfService serviceProxy = factory.CreateChannel();
serviceProxy.TestFault(faultMsg);
}
}
catch (Exception e)
{
if (e.GetType() != typeof(FaultException<FaultDetail>))
{
string error = string.Format("Expected exception: {0}, actual: {1}\r\n{2}",
"FaultException<FaultDetail>", e.GetType(), e.ToString());
if (e.InnerException != null)
error += String.Format("\r\nInnerException:\r\n{0}", e.InnerException.ToString());
errorBuilder.AppendLine(error);
}
else
{
FaultException<FaultDetail> faultException = (FaultException<FaultDetail>)(e);
string actualFaultMsg = ((FaultDetail)(faultException.Detail)).Message;
if (actualFaultMsg != faultMsg)
{
errorBuilder.AppendLine(string.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, actualFaultMsg));
}
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: FaultException_Throws_WithFaultDetail FAILED with the following errors: {0}", errorBuilder));
return;
}
Assert.True(false, "Expected FaultException<FaultDetail> exception, but no exception thrown.");
}
[WcfFact]
[OuterLoop]
public static void UnexpectedException_Throws_FaultException()
{
string faultMsg = "This is a test fault msg";
StringBuilder errorBuilder = new StringBuilder();
try
{
BasicHttpBinding binding = new BasicHttpBinding();
using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)))
{
IWcfService serviceProxy = factory.CreateChannel();
serviceProxy.ThrowInvalidOperationException(faultMsg);
}
}
catch (Exception e)
{
if (e.GetType() != typeof(FaultException<ExceptionDetail>))
{
errorBuilder.AppendLine(string.Format("Expected exception: {0}, actual: {1}", "FaultException<ExceptionDetail>", e.GetType()));
}
else
{
FaultException<ExceptionDetail> faultException = (FaultException<ExceptionDetail>)(e);
string actualFaultMsg = ((ExceptionDetail)(faultException.Detail)).Message;
if (actualFaultMsg != faultMsg)
{
errorBuilder.AppendLine(string.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, actualFaultMsg));
}
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: UnexpectedException_Throws_FaultException FAILED with the following errors: {0}", errorBuilder));
return;
}
Assert.True(false, "Expected FaultException<FaultDetail> exception, but no exception thrown.");
}
[WcfFact]
[OuterLoop]
public static void Abort_During_Implicit_Open_Closes_Async_Waiters()
{
// This test is a regression test of an issue with CallOnceManager.
// When a single proxy is used to make several service calls without
// explicitly opening it, the CallOnceManager queues up all the requests
// that happen while it is opening the channel (or handling previously
// queued service calls. If the channel was closed or faulted during
// the handling of any queued requests, it caused a pathological worst
// case where every queued request waited for its complete SendTimeout
// before failing.
//
// This test operates by making multiple concurrent asynchronous service
// calls, but stalls the Opening event to allow them to be queued before
// any of them are allowed to proceed. It then closes the channel when
// the first service operation is allowed to proceed. This causes the
// CallOnce manager to deal with all its queued operations and cause
// them to complete other than by timing out.
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
int timeoutMs = 20000;
long operationsQueued = 0;
int operationCount = 5;
Task<string>[] tasks = new Task<string>[operationCount];
Exception[] exceptions = new Exception[operationCount];
string[] results = new string[operationCount];
bool isClosed = false;
DateTime endOfOpeningStall = DateTime.Now;
int serverDelayMs = 100;
TimeSpan serverDelayTimeSpan = TimeSpan.FromMilliseconds(serverDelayMs);
string testMessage = "testMessage";
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
// SendTimeout is the timeout used for implicit opens
binding.SendTimeout = TimeSpan.FromMilliseconds(timeoutMs);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// Force the implicit open to stall until we have multiple concurrent calls pending.
// This forces the CallOnceManager to have a queue of waiters it will need to notify.
((ICommunicationObject)serviceProxy).Opening += (s, e) =>
{
// Wait until we see sync calls have been queued
DateTime startOfOpeningStall = DateTime.Now;
while (true)
{
endOfOpeningStall = DateTime.Now;
// Don't wait forever -- if we stall longer than the SendTimeout, it means something
// is wrong other than what we are testing, so just fail early.
if ((endOfOpeningStall - startOfOpeningStall).TotalMilliseconds > timeoutMs)
{
Assert.True(false, "The Opening event timed out waiting for operations to queue, which was not expected for this test.");
}
// As soon as we have all our Tasks at least running, wait a little
// longer to allow them finish queuing up their waiters, then stop stalling the Opening
if (Interlocked.Read(ref operationsQueued) >= operationCount)
{
Task.Delay(500).Wait();
endOfOpeningStall = DateTime.Now;
return;
}
Task.Delay(100).Wait();
}
};
// Each task will make a synchronous service call, which will cause all but the
// first to be queued for the implicit open. The first call to complete then closes
// the channel so that it is forced to deal with queued waiters.
Func<string> callFunc = () =>
{
// We increment the # ops queued before making the actual sync call, which is
// technically a short race condition in the test. But reversing the order would
// timeout the implicit open and fault the channel.
Interlocked.Increment(ref operationsQueued);
// The call of the operation is what creates the entry in the CallOnceManager queue.
// So as each Task below starts, it increments the count and adds a waiter to the
// queue. We ask for a small delay on the server side just to introduce a small
// stall after the sync request has been made before it can complete. Otherwise
// fast machines can finish all the requests before the first one finishes the Close().
Task<string> t = serviceProxy.EchoWithTimeoutAsync(testMessage, serverDelayTimeSpan);
lock (tasks)
{
if (!isClosed)
{
try
{
isClosed = true;
((ICommunicationObject)serviceProxy).Abort();
}
catch { }
}
}
return t.GetAwaiter().GetResult();
};
// *** EXECUTE *** \\
DateTime startTime = DateTime.Now;
for (int i = 0; i < operationCount; ++i)
{
tasks[i] = Task.Run(callFunc);
}
for (int i = 0; i < operationCount; ++i)
{
try
{
results[i] = tasks[i].GetAwaiter().GetResult();
}
catch (Exception ex)
{
exceptions[i] = ex;
}
}
// *** VALIDATE *** \\
double elapsedMs = (DateTime.Now - endOfOpeningStall).TotalMilliseconds;
// Before validating that the issue was fixed, first validate that we received the exceptions or the
// results we expected. This is to verify the fix did not introduce a behavioral change other than the
// elimination of the long unnecessary timeouts after the channel was closed.
int nFailures = 0;
for (int i = 0; i < operationCount; ++i)
{
if (exceptions[i] == null)
{
Assert.True((String.Equals("test", results[i])),
String.Format("Expected operation #{0} to return '{1}' but actual was '{2}'",
i, testMessage, results[i]));
}
else
{
++nFailures;
TimeoutException toe = exceptions[i] as TimeoutException;
Assert.True(toe == null, String.Format("Task [{0}] should not have failed with TimeoutException", i));
}
}
Assert.True(nFailures > 0,
String.Format("Expected at least one operation to throw an exception, but none did. Elapsed time = {0} ms.",
elapsedMs));
// --- Here is the test of the actual bug fix ---
// The original issue was that sync waiters in the CallOnceManager were not notified when
// the channel became unusable and therefore continued to time out for the full amount.
// Additionally, because they were executed sequentially, it was also possible for each one
// to time out for the full amount. Given that we closed the channel, we expect all the queued
// waiters to have been immediately waked up and detected failure.
int expectedElapsedMs = (operationCount * serverDelayMs) + timeoutMs / 2;
Assert.True(elapsedMs < expectedElapsedMs,
String.Format("The {0} operations took {1} ms to complete which exceeds the expected {2} ms",
operationCount, elapsedMs, expectedElapsedMs));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
public class MyCertificateValidator : X509CertificateValidator
{
public const string exceptionMsg = "Throwing exception from Validate method on purpose.";
public override void Validate(X509Certificate2 certificate)
{
// Always throw an exception.
// MSDN guidance also uses a simple Exception when an exception is thrown from this method.
throw new Exception(exceptionMsg);
}
}
| |
//
// Authors:
// Atsushi Enomoto
//
// Copyright 2007 Novell (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.
//
#if !MOONLIGHT
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using XPI = System.Xml.Linq.XProcessingInstruction;
namespace System.Xml.Linq
{
internal class XNodeNavigator : XPathNavigator
{
static readonly XAttribute attr_ns_xml = new XAttribute (XNamespace.Xmlns.GetName ("xml"), XNamespace.Xml.NamespaceName);
XNode node;
XAttribute attr;
XmlNameTable name_table;
public XNodeNavigator (XNode node, XmlNameTable nameTable)
{
this.node = node;
this.name_table = nameTable;
}
public XNodeNavigator (XNodeNavigator other)
{
this.node = other.node;
this.attr = other.attr;
this.name_table = other.name_table;
}
public override string BaseURI {
get { return node.BaseUri ?? String.Empty; }
}
public override bool CanEdit {
get { return true; }
}
public override bool HasAttributes {
get {
if (attr != null)
return false;
XElement el = node as XElement;
if (el == null)
return false;
foreach (var at in el.Attributes ())
if (!at.IsNamespaceDeclaration)
return true;
return false;
}
}
public override bool HasChildren {
get {
if (attr != null)
return false;
XContainer c = node as XContainer;
return c != null && c.FirstNode != null;
}
}
public override bool IsEmptyElement {
get {
if (attr != null)
return false;
XElement el = node as XElement;
return el != null && el.IsEmpty;
}
}
public override string LocalName {
get {
switch (NodeType) {
case XPathNodeType.Namespace:
return attr.Name.Namespace == XNamespace.None ? String.Empty : attr.Name.LocalName;
case XPathNodeType.Attribute:
return attr.Name.LocalName;
case XPathNodeType.Element:
return ((XElement) node).Name.LocalName;
case XPathNodeType.ProcessingInstruction:
return ((XPI) node).Target;
default:
return String.Empty;
}
}
}
public override string Name {
get {
XName name = null;
switch (NodeType) {
case XPathNodeType.Attribute:
name = attr.Name;
break;
case XPathNodeType.Element:
name = ((XElement) node).Name;
break;
default:
return LocalName;
}
if (name.Namespace == XNamespace.None)
return name.LocalName;
XElement el = (node as XElement) ?? node.Parent;
if (el == null)
return name.LocalName;
string prefix = el.GetPrefixOfNamespace (name.Namespace);
return prefix.Length > 0 ? String.Concat (prefix, ":", name.LocalName) : name.LocalName;
}
}
public override string NamespaceURI {
get {
switch (NodeType) {
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Namespace:
return String.Empty;
case XPathNodeType.Attribute:
return attr.Name.NamespaceName;
case XPathNodeType.Element:
return ((XElement) node).Name.NamespaceName;
default:
return String.Empty;
}
}
}
public override XmlNameTable NameTable {
get { return name_table; }
}
public override XPathNodeType NodeType {
get {
if (attr != null)
return attr.IsNamespaceDeclaration ?
XPathNodeType.Namespace :
XPathNodeType.Attribute;
switch (node.NodeType) {
case XmlNodeType.Element:
return XPathNodeType.Element;
case XmlNodeType.Document:
return XPathNodeType.Root;
case XmlNodeType.Comment:
return XPathNodeType.Comment;
case XmlNodeType.ProcessingInstruction:
return XPathNodeType.ProcessingInstruction;
default:
return XPathNodeType.Text;
}
}
}
public override string Prefix {
get {
XName name = null;
switch (NodeType) {
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Namespace:
return String.Empty;
case XPathNodeType.Attribute:
name = attr.Name;
break;
case XPathNodeType.Element:
name = ((XElement) node).Name;
break;
default:
return LocalName;
}
if (name.Namespace == XNamespace.None)
return String.Empty;
XElement el = (node as XElement) ?? node.Parent;
if (el == null)
return String.Empty;
return el.GetPrefixOfNamespace (name.Namespace);
}
}
public override IXmlSchemaInfo SchemaInfo {
get { return null; }
}
public override object UnderlyingObject {
get { return attr != null ? (object) attr : node; }
}
public override string Value {
get {
if (attr != null)
return attr.Value;
else
switch (NodeType) {
case XPathNodeType.Comment:
return ((XComment) node).Value;
case XPathNodeType.ProcessingInstruction:
return ((XPI) node).Data;
case XPathNodeType.Text:
string s = String.Empty;
for (var xn = node as XText; xn != null; xn = xn.NextNode as XText)
s += xn.Value;
return s;
case XPathNodeType.Element:
case XPathNodeType.Root:
return GetInnerText ((XContainer) node);
}
return String.Empty;
}
}
string GetInnerText (XContainer node)
{
StringBuilder sb = null;
foreach (XNode n in node.Nodes ())
GetInnerText (n, ref sb);
return sb != null ? sb.ToString () : String.Empty;
}
void GetInnerText (XNode n, ref StringBuilder sb)
{
switch (n.NodeType) {
case XmlNodeType.Element:
foreach (XNode c in ((XElement) n).Nodes ())
GetInnerText (c, ref sb);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
if (sb == null)
sb = new StringBuilder ();
sb.Append (((XText) n).Value);
break;
}
}
public override XPathNavigator Clone ()
{
return new XNodeNavigator (this);
}
public override bool IsSamePosition (XPathNavigator other)
{
XNodeNavigator nav = other as XNodeNavigator;
if (nav == null || nav.node.Owner != node.Owner)
return false;
return node == nav.node && attr == nav.attr;
}
public override bool MoveTo (XPathNavigator other)
{
XNodeNavigator nav = other as XNodeNavigator;
if (nav == null || nav.node.Document != node.Document)
return false;
node = nav.node;
attr = nav.attr;
return true;
}
public override bool MoveToFirstAttribute ()
{
if (attr != null)
return false;
XElement el = node as XElement;
if (el == null || !el.HasAttributes)
return false;
foreach (XAttribute a in el.Attributes ())
if (!a.IsNamespaceDeclaration) {
attr = a;
return true;
}
return false;
}
public override bool MoveToFirstChild ()
{
if (attr != null)
return false;
XContainer c = node as XContainer;
if (c == null || c.FirstNode == null)
return false;
node = c.FirstNode;
attr = null;
return true;
}
public override bool MoveToFirstNamespace (XPathNamespaceScope scope)
{
if (NodeType != XPathNodeType.Element)
return false;
for (XElement el = node as XElement; el != null; el = el.Parent) {
foreach (XAttribute a in el.Attributes ())
if (a.IsNamespaceDeclaration) {
attr = a;
return true;
}
if (scope == XPathNamespaceScope.Local)
return false;
}
if (scope != XPathNamespaceScope.All)
return false;
attr = attr_ns_xml;
return true;
}
public override bool MoveToId (string id)
{
throw new NotSupportedException ("This XPathNavigator does not support IDs");
}
public override bool MoveToNext ()
{
XNode xn = node.NextNode;
if (node is XText)
for (; xn != null; xn = xn.NextNode)
if (!(xn.NextNode is XText))
break;
if (xn == null)
return false;
node = xn;
attr = null;
return true;
}
public override bool MoveToNextAttribute ()
{
if (attr == null)
return false;
if (attr.NextAttribute == null)
return false;
for (XAttribute a = attr.NextAttribute; a != null; a = a.NextAttribute)
if (!a.IsNamespaceDeclaration) {
attr = a;
return true;
}
return false;
}
public override bool MoveToNextNamespace (XPathNamespaceScope scope)
{
if (attr == null)
return false;
for (XAttribute a = attr.NextAttribute; a != null; a = a.NextAttribute)
if (a.IsNamespaceDeclaration) {
attr = a;
return true;
}
if (scope == XPathNamespaceScope.Local)
return false;
if (attr == attr_ns_xml)
return false; // no next attribute
for (XElement el = ((XElement) attr.Parent).Parent; el != null; el = el.Parent) {
foreach (XAttribute a in el.Attributes ())
if (a.IsNamespaceDeclaration) {
attr = a;
return true;
}
}
if (scope != XPathNamespaceScope.All)
return false;
attr = attr_ns_xml;
return true;
}
public override bool MoveToParent ()
{
if (attr != null) {
attr = null;
return true;
}
if (node.Owner == null)
return false;
node = node.Owner;
return true;
}
public override bool MoveToPrevious ()
{
if (node.PreviousNode == null)
return false;
node = node.PreviousNode;
attr = null;
return true;
}
public override void MoveToRoot ()
{
node = node.Document ?? node;
attr = null;
}
}
}
#endif
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.InvokeDelegateWithConditionalAccess
{
public class InvokeDelegateWithConditionalAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new InvokeDelegateWithConditionalAccessAnalyzer(),
new InvokeDelegateWithConditionalAccessCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task Test1()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestInvertedIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (null != v)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestIfWithNoBraces()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (null != v)
v();
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestWithComplexExpression()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
bool b = true;
[||]var v = b ? a : null;
if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
bool b = true;
(b ? a : null)?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingWithElseClause()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
else {}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnDeclarationWithMultipleVariables()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a, x = a;
if (v != null)
{
v();
}
}
}");
}
/// <remarks>
/// With multiple variables in the same declaration, the fix _is not_ offered on the declaration
/// itself, but _is_ offered on the invocation pattern.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocationWhereOfferedWithMultipleVariables()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a, x = a;
[||]if (v != null)
{
v();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
var v = a, x = a;
v?.Invoke();
}
}");
}
/// <remarks>
/// If we have a variable declaration and if it is read/written outside the delegate
/// invocation pattern, the fix is not offered on the declaration.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnDeclarationIfUsedOutside()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
if (v != null)
{
v();
}
v = null;
}
}");
}
/// <remarks>
/// If we have a variable declaration and if it is read/written outside the delegate
/// invocation pattern, the fix is not offered on the declaration but is offered on
/// the invocation pattern itself.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocationWhereOfferedIfUsedOutside()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]if (v != null)
{
v();
}
v = null;
}
}",
@"class C
{
System.Action a;
void Foo()
{
var v = a;
v?.Invoke();
v = null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestSimpleForm1()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
[||]if (this.E != null)
{
this.E(this, EventArgs.Empty);
}
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
this.E?.Invoke(this, EventArgs.Empty);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestInElseClause1()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else [||]if (this.E != null)
{
this.E(this, EventArgs.Empty);
}
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else
{
this.E?.Invoke(this, EventArgs.Empty);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestInElseClause2()
{
await TestAsync(
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else [||]if (this.E != null)
this.E(this, EventArgs.Empty);
}
}",
@"
using System;
class C
{
public event EventHandler E;
void M()
{
if (true != true)
{
}
else this.E?.Invoke(this, EventArgs.Empty);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestTrivia1()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
// Comment
[||]var v = a;
if (v != null)
{
v();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
// Comment
a?.Invoke();
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestTrivia2()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
// Comment
[||]if (a != null)
{
a();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
// Comment
a?.Invoke();
}
}", compareTokens: false);
}
/// <remarks>
/// tests locations where the fix is offered.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestFixOfferedOnIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]if (v != null)
{
v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
/// <remarks>
/// tests locations where the fix is offered.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestFixOfferedInsideIf()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v != null)
{
[||]v();
}
}
}",
@"
class C
{
System.Action a;
void Foo()
{
a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnConditionalInvocation()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
v?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnConditionalInvocation2()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
[||]v?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnConditionalInvocation3()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]a?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnNonNullCheckExpressions()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v == a)
{
[||]v();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnNonNullCheckExpressions2()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
if (v == null)
{
[||]v();
}
}
}");
}
/// <remarks>
/// if local declaration is not immediately preceding the invocation pattern,
/// the fix is not offered on the declaration.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocalNotImmediatelyPrecedingNullCheckAndInvokePattern()
{
await TestMissingAsync(
@"class C
{
System.Action a;
void Foo()
{
[||]var v = a;
int x;
if (v != null)
{
v();
}
}
}");
}
/// <remarks>
/// if local declaration is not immediately preceding the invocation pattern,
/// the fix is not offered on the declaration but is offered on the invocation pattern itself.
/// </remarks>
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestLocalDNotImmediatelyPrecedingNullCheckAndInvokePattern2()
{
await TestAsync(
@"class C
{
System.Action a;
void Foo()
{
var v = a;
int x;
[||]if (v != null)
{
v();
}
}
}",
@"class C
{
System.Action a;
void Foo()
{
var v = a;
int x;
v?.Invoke();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public async Task TestMissingOnFunc()
{
await TestMissingAsync(
@"class C
{
System.Func<int> a;
int Foo()
{
var v = a;
[||]if (v != null)
{
return v();
}
}
}");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Cassandra;
using Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using KillrVideo.Cassandra;
using KillrVideo.MessageBus;
using KillrVideo.Protobuf;
using KillrVideo.Protobuf.Services;
using KillrVideo.VideoCatalog.Events;
namespace KillrVideo.VideoCatalog
{
/// <summary>
/// An implementation of the video catalog service that stores catalog data in Cassandra and publishes events on a message bus.
/// </summary>
[Export(typeof(IGrpcServerService))]
public class VideoCatalogServiceImpl : VideoCatalogService.VideoCatalogServiceBase, IGrpcServerService
{
public static readonly int LatestVideosTtlSeconds = Convert.ToInt32(TimeSpan.FromDays(MaxDaysInPastForLatestVideos).TotalSeconds);
private const int MaxDaysInPastForLatestVideos = 7;
private static readonly Regex ParseLatestPagingState = new Regex("([0-9]{8}){8}([0-9]{1})(.*)", RegexOptions.Compiled | RegexOptions.Singleline);
private readonly ISession _session;
private readonly IBus _bus;
private readonly PreparedStatementCache _statementCache;
public ServiceDescriptor Descriptor => VideoCatalogService.Descriptor;
public VideoCatalogServiceImpl(ISession session, PreparedStatementCache statementCache, IBus bus)
{
if (session == null) throw new ArgumentNullException(nameof(session));
if (statementCache == null) throw new ArgumentNullException(nameof(statementCache));
if (bus == null) throw new ArgumentNullException(nameof(bus));
_session = session;
_statementCache = statementCache;
_bus = bus;
}
/// <summary>
/// Convert this instance to a ServerServiceDefinition that can be run on a Grpc server.
/// </summary>
public ServerServiceDefinition ToServerServiceDefinition()
{
return VideoCatalogService.BindService(this);
}
/// <summary>
/// Submits an uploaded video to the catalog.
/// </summary>
public override async Task<SubmitUploadedVideoResponse> SubmitUploadedVideo(SubmitUploadedVideoRequest request, ServerCallContext context)
{
var timestamp = DateTimeOffset.UtcNow;
// Store the information we have now in Cassandra
PreparedStatement[] prepared = await _statementCache.GetOrAddAllAsync(
"INSERT INTO videos (videoid, userid, name, description, tags, location_type, added_date) VALUES (?, ?, ?, ?, ?, ?, ?)",
"INSERT INTO user_videos (userid, added_date, videoid, name) VALUES (?, ?, ?, ?)"
);
var batch = new BatchStatement();
batch.Add(prepared[0].Bind(request.VideoId.ToGuid(), request.UserId.ToGuid(), request.Name, request.Description,
request.Tags.ToArray(), (int) VideoLocationType.Upload, timestamp))
.Add(prepared[1].Bind(request.UserId.ToGuid(), timestamp, request.VideoId.ToGuid(), request.Name))
.SetTimestamp(timestamp);
await _session.ExecuteAsync(batch).ConfigureAwait(false);
// Tell the world we've accepted an uploaded video (it hasn't officially been added until we get a location for the
// video playback and thumbnail)
await _bus.Publish(new UploadedVideoAccepted
{
VideoId = request.VideoId,
UploadUrl = request.UploadUrl,
Timestamp = timestamp.ToTimestamp()
}).ConfigureAwait(false);
return new SubmitUploadedVideoResponse();
}
/// <summary>
/// Submits a YouTube video to the catalog.
/// </summary>
public override async Task<SubmitYouTubeVideoResponse> SubmitYouTubeVideo(SubmitYouTubeVideoRequest request, ServerCallContext context)
{
// Use a batch to insert the YouTube video into multiple tables
PreparedStatement[] prepared = await _statementCache.GetOrAddAllAsync(
"INSERT INTO videos (videoid, userid, name, description, location, preview_image_location, tags, added_date, location_type) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
"INSERT INTO user_videos (userid, added_date, videoid, name, preview_image_location) VALUES (?, ?, ?, ?, ?)",
"INSERT INTO latest_videos (yyyymmdd, added_date, videoid, userid, name, preview_image_location) VALUES (?, ?, ?, ?, ?, ?) USING TTL ?");
// Calculate date-related info and location/thumbnail for YouTube video
var addDate = DateTimeOffset.UtcNow;
string yyyymmdd = addDate.ToString("yyyyMMdd");
string location = request.YouTubeVideoId; // TODO: Store URL instead of ID?
string previewImageLocation = $"//img.youtube.com/vi/{request.YouTubeVideoId}/hqdefault.jpg";
var batch = new BatchStatement();
batch.Add(prepared[0].Bind(request.VideoId.ToGuid(), request.UserId.ToGuid(), request.Name, request.Description, location,
previewImageLocation, request.Tags.ToArray(), addDate, (int) VideoLocationType.Youtube))
.Add(prepared[1].Bind(request.UserId.ToGuid(), addDate, request.VideoId.ToGuid(), request.Name, previewImageLocation))
.Add(prepared[2].Bind(yyyymmdd, addDate, request.VideoId.ToGuid(), request.UserId.ToGuid(), request.Name, previewImageLocation, LatestVideosTtlSeconds))
.SetTimestamp(addDate);
// Send the batch to Cassandra
await _session.ExecuteAsync(batch).ConfigureAwait(false);
// Tell the world about the new YouTube video
var message = new YouTubeVideoAdded
{
VideoId = request.VideoId,
UserId = request.UserId,
Name = request.Name,
Description = request.Description,
Location = location,
PreviewImageLocation = previewImageLocation,
AddedDate = addDate.ToTimestamp(),
Timestamp = addDate.ToTimestamp()
};
message.Tags.Add(request.Tags);
await _bus.Publish(message).ConfigureAwait(false);
return new SubmitYouTubeVideoResponse();
}
/// <summary>
/// Gets the details of a specific video.
/// </summary>
public override async Task<GetVideoResponse> GetVideo(GetVideoRequest request, ServerCallContext context)
{
PreparedStatement preparedStatement = await _statementCache.GetOrAddAsync("SELECT * FROM videos WHERE videoid = ?");
RowSet rows = await _session.ExecuteAsync(preparedStatement.Bind(request.VideoId.ToGuid())).ConfigureAwait(false);
Row row = rows.SingleOrDefault();
if (row == null)
{
var status = new Status(StatusCode.NotFound, $"Video with id {request.VideoId.Value} was not found");
throw new RpcException(status);
}
var response = new GetVideoResponse
{
VideoId = row.GetValue<Guid>("videoid").ToUuid(),
UserId = row.GetValue<Guid>("userid").ToUuid(),
Name = row.GetValue<string>("name"),
Description = row.GetValue<string>("description"),
Location = row.GetValue<string>("location"),
LocationType = (VideoLocationType) row.GetValue<int>("location_type"),
AddedDate = row.GetValue<DateTimeOffset>("added_date").ToTimestamp()
};
var tags = row.GetValue<IEnumerable<string>>("tags");
if (tags != null)
response.Tags.Add(tags);
return response;
}
/// <summary>
/// Gets a limited number of video preview data by video id.
/// </summary>
public override async Task<GetVideoPreviewsResponse> GetVideoPreviews(GetVideoPreviewsRequest request, ServerCallContext context)
{
var response = new GetVideoPreviewsResponse();
if (request.VideoIds == null || request.VideoIds.Count == 0)
return response;
// Since we're doing a multi-get here, limit the number of previews to 20 to try and enforce some
// performance sanity. If we ever needed to do more than that, we might think about a different
// data model that doesn't involve a multi-get.
if (request.VideoIds.Count > 20)
{
var status = new Status(StatusCode.InvalidArgument, "Cannot fetch more than 20 videos at once");
throw new RpcException(status);
}
// As an example, let's do the multi-get using multiple statements at the driver level. For an example of doing this at
// the CQL level with an IN() clause, see UserManagement's GetUserProfiles
PreparedStatement prepared = await _statementCache.GetOrAddAsync(
"SELECT videoid, userid, added_date, name, preview_image_location FROM videos WHERE videoid = ?");
// Bind multiple times to the prepared statement with each video id and execute all the gets in parallel, then await
// the completion of all the gets
RowSet[] rowSets = await Task.WhenAll(request.VideoIds.Select(id => _session.ExecuteAsync(prepared.Bind(id.ToGuid())))).ConfigureAwait(false);
// Flatten the rows in the rowsets to VideoPreview objects
response.VideoPreviews.Add(rowSets.SelectMany(rowSet => rowSet, (_, row) => MapRowToVideoPreview(row)));
return response;
}
/// <summary>
/// Gets the latest videos added to the site.
/// </summary>
public override async Task<GetLatestVideoPreviewsResponse> GetLatestVideoPreviews(GetLatestVideoPreviewsRequest request, ServerCallContext context)
{
string[] buckets;
int bucketIndex;
string rowPagingState;
// See if we have paging state from a previous page of videos
if (TryParsePagingState(request.PagingState, out buckets, out bucketIndex, out rowPagingState) == false)
{
// Generate a list of all the possibly bucket dates by truncating now to the day, then subtracting days from that day
// going back as many days as we're allowed to query back
DateTimeOffset nowToTheDay = DateTimeOffset.UtcNow.Truncate(TimeSpan.TicksPerDay);
buckets = Enumerable.Range(0, MaxDaysInPastForLatestVideos + 1)
.Select(day => nowToTheDay.Subtract(TimeSpan.FromDays(day)).ToString("yyyyMMdd"))
.ToArray();
bucketIndex = 0;
rowPagingState = null;
}
// We may need multiple queries to fill the quota so build up a list of results
var results = new List<VideoPreview>();
string nextPageState = string.Empty;
DateTimeOffset? startingAddedDate = request.StartingAddedDate?.ToDateTimeOffset();
Guid? startingVideoId = request.StartingVideoId?.ToGuid();
PreparedStatement preparedStatement;
if (startingVideoId == null)
{
preparedStatement = await _statementCache.GetOrAddAsync("SELECT * FROM latest_videos WHERE yyyymmdd = ?");
}
else
{
preparedStatement = await _statementCache.GetOrAddAsync("SELECT * FROM latest_videos WHERE yyyymmdd = ? AND (added_date, videoid) <= (?, ?)");
}
// TODO: Run queries in parallel?
while (bucketIndex < buckets.Length)
{
int recordsStillNeeded = request.PageSize - results.Count;
string bucket = buckets[bucketIndex];
// Get a page of records but don't automatically load more pages when enumerating the RowSet
IStatement boundStatement = startingVideoId == null
? preparedStatement.Bind(bucket)
: preparedStatement.Bind(bucket, startingAddedDate, startingVideoId);
boundStatement.SetAutoPage(false)
.SetPageSize(recordsStillNeeded);
// Start from where we left off in this bucket
if (string.IsNullOrEmpty(rowPagingState) == false)
boundStatement.SetPagingState(Convert.FromBase64String(rowPagingState));
RowSet rows = await _session.ExecuteAsync(boundStatement).ConfigureAwait(false);
results.AddRange(rows.Select(MapRowToVideoPreview));
// See if we can stop querying
if (results.Count == request.PageSize)
{
// Are there more rows in the current bucket?
if (rows.PagingState != null && rows.PagingState.Length > 0)
{
// Start from where we left off in this bucket if we get the next page
nextPageState = CreatePagingState(buckets, bucketIndex, Convert.ToBase64String(rows.PagingState));
}
else if (bucketIndex != buckets.Length - 1)
{
// Start from the beginning of the next bucket since we're out of rows in this one
nextPageState = CreatePagingState(buckets, bucketIndex + 1, string.Empty);
}
break;
}
bucketIndex++;
}
var response = new GetLatestVideoPreviewsResponse { PagingState = nextPageState };
response.VideoPreviews.Add(results);
return response;
}
/// <summary>
/// Gets a page of videos for a particular user.
/// </summary>
public override async Task<GetUserVideoPreviewsResponse> GetUserVideoPreviews(GetUserVideoPreviewsRequest request, ServerCallContext context)
{
// Figure out if we're getting first page or subsequent page
PreparedStatement prepared;
IStatement bound;
DateTimeOffset? startingAddedDate = request.StartingAddedDate?.ToDateTimeOffset();
Guid? startingVideoId = request.StartingVideoId?.ToGuid();
Guid userId = request.UserId.ToGuid();
if (startingVideoId == null)
{
prepared = await _statementCache.GetOrAddAsync("SELECT * FROM user_videos WHERE userid = ?");
bound = prepared.Bind(userId);
}
else
{
prepared = await _statementCache.GetOrAddAsync("SELECT * FROM user_videos WHERE userid = ? AND (added_date, videoid) <= (?, ?)");
bound = prepared.Bind(userId, startingAddedDate, startingVideoId);
}
bound.SetAutoPage(false)
.SetPageSize(request.PageSize);
// The initial query won't have a paging state, but subsequent calls should if there are more pages
if (string.IsNullOrEmpty(request.PagingState) == false)
bound.SetPagingState(Convert.FromBase64String(request.PagingState));
RowSet rows = await _session.ExecuteAsync(bound).ConfigureAwait(false);
var response = new GetUserVideoPreviewsResponse
{
UserId = request.UserId,
PagingState = rows.PagingState != null && rows.PagingState.Length > 0 ? Convert.ToBase64String(rows.PagingState) : string.Empty
};
response.VideoPreviews.Add(rows.Select(MapRowToVideoPreview));
return response;
}
/// <summary>
/// Maps a row to a VideoPreview object.
/// </summary>
private static VideoPreview MapRowToVideoPreview(Row row)
{
return new VideoPreview
{
VideoId = row.GetValue<Guid>("videoid").ToUuid(),
AddedDate = row.GetValue<DateTimeOffset>("added_date").ToTimestamp(),
Name = row.GetValue<string>("name"),
PreviewImageLocation = row.GetValue<string>("preview_image_location"),
UserId = row.GetValue<Guid>("userid").ToUuid()
};
}
/// <summary>
/// Creates a string representation of the paging state for the GetLatestVideos query from the inputs provided.
/// </summary>
private static string CreatePagingState(string[] buckets, int bucketIndex, string rowsPagingState)
{
return $"{string.Join(string.Empty, buckets)}{bucketIndex}{rowsPagingState}";
}
/// <summary>
/// Tries to parse a paging state string created by the CreatePagingState method into the constituent parts.
/// </summary>
private static bool TryParsePagingState(string pagingState, out string[] buckets, out int bucketIndex, out string rowsPagingState)
{
buckets = new string[] { };
bucketIndex = 0;
rowsPagingState = null;
if (string.IsNullOrEmpty(pagingState))
return false;
// Use Regex to parse string (should be 8 buckets in yyyyMMdd format, followed by 1 bucket index, followed by 0 or 1 paging state string)
Match match = ParseLatestPagingState.Match(pagingState);
if (match.Success == false)
return false;
// Match group 0 will be the entire string that matched, so start at index 1
buckets = match.Groups[1].Captures.Cast<Capture>().Select(c => c.Value).ToArray();
bucketIndex = int.Parse(match.Groups[2].Value);
rowsPagingState = match.Groups.Count == 4 ? match.Groups[3].Value : null;
return true;
}
}
}
| |
using De.Osthus.Ambeth.Bytecode.Util;
using De.Osthus.Ambeth.Cache;
using De.Osthus.Ambeth.Collections;
using De.Osthus.Ambeth.Collections.Specialized;
using De.Osthus.Ambeth.Ioc.Annotation;
using De.Osthus.Ambeth.Merge;
using De.Osthus.Ambeth.Merge.Model;
using De.Osthus.Ambeth.Model;
using De.Osthus.Ambeth.Proxy;
using De.Osthus.Ambeth.Mixin;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Reflection.Emit;
namespace De.Osthus.Ambeth.Bytecode.Visitor
{
/**
* NotifyPropertyChangedMethodVisitor implements {@link IPropertyChanged} and invokes {@link PropertyChangeListener#propertyChanged} when a property is changed.
* If the enhanced object implements {@link PropertyChangeListener} it is registered using
* {@link IPropertyChanged#addPropertyChangeListener(PropertyChangeListener)}
*/
public class NotifyPropertyChangedClassVisitor : ClassVisitor
{
public class MethodHandleValueResolver : IValueResolveDelegate
{
private readonly String propertyName;
private readonly IPropertyInfoProvider propertyInfoProvider;
public MethodHandleValueResolver(IPropertyInfoProvider propertyInfoProvider, String propertyName)
{
this.propertyInfoProvider = propertyInfoProvider;
this.propertyName = propertyName;
}
public Type ValueType
{
get { return typeof(IPropertyInfo); }
}
public Object Invoke(string fieldName, Type enhancedType)
{
return propertyInfoProvider.GetProperty(enhancedType, propertyName);
}
}
public static readonly Type templateType = typeof(PropertyChangeMixin);
protected static readonly String templatePropertyName = "__" + templateType.Name;
public static readonly MethodInstance template_m_collectionChanged = new MethodInstance(null, typeof(INotifyCollectionChangedListener),
typeof(void), "CollectionChanged", typeof(Object), typeof(NotifyCollectionChangedEventArgs));
public static readonly MethodInstance template_m_PropertyChanged = new MethodInstance(null, typeof(IPropertyChangedEventHandler), typeof(void), "PropertyChanged", typeof(Object), typeof(PropertyChangedEventArgs));
public static readonly MethodInstance template_m_onPropertyChanged = new MethodInstance(null, typeof(INotifyPropertyChangedSource),
typeof(void), "OnPropertyChanged", typeof(String));
public static readonly MethodInstance template_m_onPropertyChanged_Values = new MethodInstance(null, typeof(INotifyPropertyChangedSource),
typeof(void), "OnPropertyChanged", typeof(String), typeof(Object), typeof(Object));
public static readonly MethodInstance template_m_isPropertyChangeActive = new MethodInstance(null, typeof(IPropertyChangeConfigurable), typeof(bool),
"Is__PropertyChangeActive");
public static readonly MethodInstance template_m_setPropertyChangeActive = new MethodInstance(null, typeof(IPropertyChangeConfigurable), typeof(void),
"Set__PropertyChangeActive", typeof(bool));
public static readonly MethodInstance m_handlePropertyChange = new MethodInstance(null, templateType, typeof(void), "HandleParentChildPropertyChange", typeof(INotifyPropertyChangedSource), typeof(Object), typeof(PropertyChangedEventArgs));
public static readonly MethodInstance m_handleCollectionChange = new MethodInstance(null, templateType, typeof(void), "HandleCollectionChange", typeof(INotifyPropertyChangedSource), typeof(Object), typeof(NotifyCollectionChangedEventArgs));
protected static readonly MethodInstance m_newPropertyChangeSupport = new MethodInstance(null, templateType,
typeof(PropertyChangeSupport), "NewPropertyChangeSupport", typeof(Object));
protected static readonly MethodInstance m_getMethodHandle = new MethodInstance(null, templateType, typeof(IPropertyInfo), "GetMethodHandle", typeof(INotifyPropertyChangedSource),
typeof(String));
protected static readonly MethodInstance m_firePropertyChange = new MethodInstance(null, templateType, typeof(void), "FirePropertyChange",
typeof(INotifyPropertyChangedSource), typeof(PropertyChangeSupport), typeof(IPropertyInfo), typeof(Object), typeof(Object));
protected static readonly MethodInstance m_addPropertyChangeListener = new MethodInstance(null, templateType,
typeof(void), "AddPropertyChangeListener", typeof(PropertyChangeSupport), typeof(PropertyChangedEventHandler));
protected static readonly MethodInstance m_removePropertyChangeListener = new MethodInstance(null, templateType,
typeof(void), "RemovePropertyChangeListener", typeof(PropertyChangeSupport), typeof(PropertyChangedEventHandler));
public static readonly MethodInstance template_m_firePropertyChange = new MethodInstance(null, MethodAttributes.HideBySig | MethodAttributes.Family, typeof(void), "FirePropertyChange",
typeof(PropertyChangeSupport), typeof(IPropertyInfo), typeof(Object), typeof(Object));
protected static readonly MethodInstance template_m_usePropertyChangeSupport = new MethodInstance(null, MethodAttributes.HideBySig | MethodAttributes.Public, typeof(PropertyChangeSupport), "Use$PropertyChangeSupport");
public static readonly PropertyInstance p_propertyChangeSupport = new PropertyInstance(typeof(INotifyPropertyChangedSource).GetProperty("PropertyChangeSupport"));
public static readonly PropertyInstance p_parentChildEventHandler = new PropertyInstance(typeof(INotifyPropertyChangedSource).GetProperty("ParentChildEventHandler"));
public static readonly PropertyInstance p_collectionEventHandler = new PropertyInstance(typeof(INotifyPropertyChangedSource).GetProperty("CollectionEventHandler"));
public static readonly MethodInstance sm_hasPropertyChangedDefault = new MethodInstance(null, templateType, typeof(bool), "HasPropertyChangedDefault", typeof(Object), typeof(String), typeof(Object), typeof(Object));
public static readonly MethodInstance sm_hasPropertyChangedValueType = new MethodInstance(null, templateType, typeof(bool), "HasPropertyChangedValueType", typeof(Object), typeof(String), typeof(Object), typeof(Object));
public static readonly HashMap<Type, MethodInstance> propertyTypeToHasPropertyChangeMI = new HashMap<Type, MethodInstance>();
static NotifyPropertyChangedClassVisitor()
{
propertyTypeToHasPropertyChangeMI.Put(typeof(int), LookupHasPropertyChangeMI(typeof(int)));
propertyTypeToHasPropertyChangeMI.Put(typeof(long), LookupHasPropertyChangeMI(typeof(long)));
propertyTypeToHasPropertyChangeMI.Put(typeof(double), LookupHasPropertyChangeMI(typeof(double)));
propertyTypeToHasPropertyChangeMI.Put(typeof(float), LookupHasPropertyChangeMI(typeof(float)));
propertyTypeToHasPropertyChangeMI.Put(typeof(short), LookupHasPropertyChangeMI(typeof(short)));
propertyTypeToHasPropertyChangeMI.Put(typeof(byte), LookupHasPropertyChangeMI(typeof(byte)));
propertyTypeToHasPropertyChangeMI.Put(typeof(sbyte), LookupHasPropertyChangeMI(typeof(sbyte)));
propertyTypeToHasPropertyChangeMI.Put(typeof(char), LookupHasPropertyChangeMI(typeof(char)));
propertyTypeToHasPropertyChangeMI.Put(typeof(bool), LookupHasPropertyChangeMI(typeof(bool)));
propertyTypeToHasPropertyChangeMI.Put(typeof(String), LookupHasPropertyChangeMI(typeof(String)));
}
public static PropertyInstance GetPropertyChangeTemplatePI(IClassVisitor cv)
{
Object bean = State.BeanContext.GetService(templateType);
PropertyInstance pi = State.GetProperty(templatePropertyName, NewType.GetType(bean.GetType()));
if (pi != null)
{
return pi;
}
return cv.ImplementAssignedReadonlyProperty(templatePropertyName, bean);
}
public static MethodInstance GetApplicableHasPropertyChangedOverload(Type propertyType)
{
MethodInstance method = propertyTypeToHasPropertyChangeMI.Get(propertyType);
if (method != null)
{
return method;
}
if (propertyType.IsValueType)
{
return sm_hasPropertyChangedValueType;
}
return sm_hasPropertyChangedDefault;
}
public static bool IsBoxingNeededForHasPropertyChangedOverload(MethodInstance method, Type propertyType)
{
return propertyType.IsValueType && !method.Parameters[method.Parameters.Length - 1].Type.IsValueType;
}
protected static MethodInstance LookupHasPropertyChangeMI(Type propertyType)
{
return new MethodInstance(null, templateType, typeof(bool), "HasPropertyChanged", typeof(Object), typeof(String), propertyType, propertyType);
}
/** property infos of enhanced type */
protected readonly String[] properties;
protected IEntityMetaData metaData;
[Autowired]
public IPropertyInfoProvider PropertyInfoProvider { protected get; set; }
public NotifyPropertyChangedClassVisitor(IClassVisitor cv, IEntityMetaData metaData, String[] properties)
: base(cv)
{
this.metaData = metaData;
this.properties = properties;
}
/**
* {@inheritDoc}
*/
public override void VisitEnd()
{
FieldInstance f_propertyChangeSupport = GetPropertyChangeSupportField();
PropertyInstance p_propertyChangeTemplate = GetPropertyChangeTemplatePI(this);
ImplementPropertyChangeConfigurable();
MethodInstance m_getPropertyChangeSupport = ImplementUsePropertyChangeSupport(p_propertyChangeTemplate, f_propertyChangeSupport);
f_propertyChangeSupport = State.GetAlreadyImplementedField(f_propertyChangeSupport.Name);
ImplementNotifyPropertyChanged(p_propertyChangeTemplate, m_getPropertyChangeSupport);
MethodInstance m_firePropertyChange = ImplementFirePropertyChange(p_propertyChangeTemplate);
ImplementNotifyPropertyChangedSource(p_propertyChangeTemplate, f_propertyChangeSupport);
if (properties == null)
{
ImplementCollectionChanged(p_propertyChangeTemplate);
ImplementPropertyChanged(p_propertyChangeTemplate);
// handle all properties found
IPropertyInfo[] props = PropertyInfoProvider.GetProperties(State.CurrentType);
foreach (IPropertyInfo prop in props)
{
if (prop.Name.EndsWith(ValueHolderIEC.GetNoInitSuffix()))
{
continue;
}
PropertyInstance propInfo = PropertyInstance.FindByTemplate(prop.Name, prop.PropertyType, true);
if (propInfo == null)
{
continue;
}
ImplementPropertyChangeOnProperty(propInfo, p_propertyChangeTemplate, m_firePropertyChange, f_propertyChangeSupport);
}
}
else
{
foreach (String propertyName in properties)
{
PropertyInstance propInfo = PropertyInstance.FindByTemplate(propertyName, (NewType)null, false);
ImplementPropertyChangeOnProperty(propInfo, p_propertyChangeTemplate, m_firePropertyChange, f_propertyChangeSupport);
}
}
base.VisitEnd();
}
protected void ImplementPropertyChangeOnProperty(PropertyInstance propertyInfo,
PropertyInstance p_propertyChangeTemplate, MethodInstance m_firePropertyChange, FieldInstance f_propertyChangeSupport)
{
// add property change detection and notification
if (propertyInfo.Getter == null || propertyInfo.Setter == null)
{
return;
}
if (InitializeEmbeddedMemberVisitor.IsEmbeddedMember(metaData, propertyInfo.Name))
{
return;
}
PropertyInstance p_getterMethodHandle = ImplementAssignedReadonlyProperty(propertyInfo.Name + "$MethodHandle",
new MethodHandleValueResolver(PropertyInfoProvider, propertyInfo.Name));
Type propertyType = propertyInfo.PropertyType.Type;
MethodInstance m_hasPropertyChanged = GetApplicableHasPropertyChangedOverload(propertyType);
// check value type of last parameter
bool isBoxingNeededForHasPropertyChanged = IsBoxingNeededForHasPropertyChangedOverload(m_hasPropertyChanged, propertyType);
IMethodVisitor mg = VisitMethod(propertyInfo.Setter);
Label l_finish = mg.NewLabel();
Label l_noOldValue = mg.NewLabel();
Label l_noChangeCheck = mg.NewLabel();
LocalVariableInfo loc_oldValue;
if (isBoxingNeededForHasPropertyChanged)
{
loc_oldValue = mg.NewLocal(typeof(Object));
}
else
{
loc_oldValue = mg.NewLocal(propertyType);
}
LocalVariableInfo loc_valueChanged = mg.NewLocal<bool>();
MethodInstance m_getSuper = EnhancerUtil.GetSuperGetter(propertyInfo);
bool relationProperty = m_getSuper.Name.EndsWith(ValueHolderIEC.GetNoInitSuffix());
// initialize flag with false
mg.Push(false);
mg.StoreLocal(loc_valueChanged);
// initialize oldValue with null
mg.PushNullOrZero(loc_oldValue.LocalType);
mg.StoreLocal(loc_oldValue);
if (relationProperty)
{
// check if a setter call to an UNINITIALIZED relation occured with value null
// if it the case there would be no PCE because oldValue & newValue are both null
// but we need a PCE in this special case
Label l_noSpecialHandling = mg.NewLabel();
FieldInstance f_state = State.GetAlreadyImplementedField(ValueHolderIEC.GetInitializedFieldName(propertyInfo.Name));
mg.GetThisField(f_state);
mg.PushEnum(ValueHolderState.INIT);
mg.IfCmp(typeof(ValueHolderState), CompareOperator.EQ, l_noSpecialHandling);
mg.Push(true);
mg.StoreLocal(loc_valueChanged);
mg.Mark(l_noSpecialHandling);
}
// check if value should be checked to decide for a PCE
mg.LoadLocal(loc_valueChanged);
mg.IfZCmp(CompareOperator.NE, l_noOldValue);
// get old field value calling super property getter
mg.LoadThis();
mg.InvokeOnExactOwner(m_getSuper);
if (isBoxingNeededForHasPropertyChanged)
{
mg.Box(propertyType);
}
mg.StoreLocal(loc_oldValue);
mg.Mark(l_noOldValue);
// set new field value calling super property setter
mg.LoadThis();
mg.LoadArg(0);
mg.InvokeOnExactOwner(EnhancerUtil.GetSuperSetter(propertyInfo));
mg.PopIfReturnValue(EnhancerUtil.GetSuperSetter(propertyInfo));
// check if value should be checked to decide for a PCE
mg.LoadLocal(loc_valueChanged);
mg.IfZCmp(CompareOperator.NE, l_noChangeCheck);
LocalVariableInfo loc_newValue = null;
if (isBoxingNeededForHasPropertyChanged)
{
loc_newValue = mg.NewLocal(typeof(Object)); // loc_1 Object newValue
// Object loc_1 = (Object)value;
mg.LoadArg(0);
mg.Box(propertyType);
mg.StoreLocal(loc_newValue);
}
mg.CallThisGetter(p_propertyChangeTemplate);
// call HasPropertyChanged (static)
mg.LoadThis(); // "this" as Object obj
mg.Push(propertyInfo.Name); // String propertyName
mg.LoadLocal(loc_oldValue);
if (loc_newValue != null)
{
mg.LoadLocal(loc_newValue);
}
else
{
mg.LoadArg(0);
}
mg.InvokeVirtual(m_hasPropertyChanged);
//// if (!result)
//// { return; }
mg.IfZCmp(CompareOperator.EQ, l_finish);
mg.Mark(l_noChangeCheck);
// call firePropertyChange on this
mg.LoadThis();
// propertyChangeSupport
mg.GetThisField(f_propertyChangeSupport);
// property
mg.CallThisGetter(p_getterMethodHandle);
// oldValue
mg.LoadLocal(loc_oldValue);
if (!isBoxingNeededForHasPropertyChanged && propertyType.IsValueType)
{
// old value has not already been boxed but it is now necessary
mg.ValueOf(propertyType);
}
// newValue
if (loc_newValue != null)
{
mg.LoadLocal(loc_newValue);
}
else
{
mg.LoadArg(0);
if (propertyType.IsValueType)
{
mg.ValueOf(propertyType);
}
}
// firePropertyChange(propertyChangeSupport, property, oldValue, newValue)
mg.InvokeVirtual(m_firePropertyChange);
// return
mg.Mark(l_finish);
mg.ReturnVoidOrThis();
mg.EndMethod();
}
protected void ImplementCollectionChanged(PropertyInstance p_propertyChangeTemplate)
{
MethodInstance m_collectionChanged_super = MethodInstance.FindByTemplate(template_m_collectionChanged,
true);
IMethodVisitor mv = VisitMethod(template_m_collectionChanged);
if (m_collectionChanged_super != null)
{
mv.LoadThis();
mv.LoadArgs();
mv.InvokeSuperOfCurrentMethod();
}
mv.CallThisGetter(p_propertyChangeTemplate);
mv.LoadThis();
mv.LoadArgs();
// call PCT.HandleCollectionChange(this, sender, arg)
mv.InvokeVirtual(m_handleCollectionChange);
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementPropertyChanged(PropertyInstance p_propertyChangeTemplate)
{
MethodInstance m_propertyChanged_super = MethodInstance.FindByTemplate(template_m_PropertyChanged, true);
IMethodVisitor mv = VisitMethod(template_m_PropertyChanged);
if (m_propertyChanged_super != null)
{
mv.LoadThis();
mv.LoadArgs();
mv.InvokeSuperOfCurrentMethod();
}
mv.CallThisGetter(p_propertyChangeTemplate);
mv.LoadThis();
mv.LoadArgs();
// call PCT.HandlePropertyChange(this, sender, arg)
mv.InvokeVirtual(m_handlePropertyChange);
mv.ReturnValue();
mv.EndMethod();
}
/**
* Almost empty implementation (just calling the static method) to be able to override and act on the property change
*/
protected MethodInstance ImplementFirePropertyChange(PropertyInstance p_propertyChangeTemplate)
{
MethodInstance m_firePropertyChange_super = MethodInstance.FindByTemplate(template_m_firePropertyChange, true);
IMethodVisitor mg;
if (m_firePropertyChange_super == null)
{
// implement new
mg = VisitMethod(template_m_firePropertyChange);
}
else
{
// override existing
mg = VisitMethod(m_firePropertyChange_super);
}
Label l_propertyChangeIsInactive = mg.NewLabel();
MethodInstance m_isPropertyChangeActive = MethodInstance.FindByTemplate(template_m_isPropertyChangeActive, false);
mg.CallThisGetter(m_isPropertyChangeActive);
mg.IfZCmp(CompareOperator.EQ, l_propertyChangeIsInactive);
mg.CallThisGetter(p_propertyChangeTemplate);
mg.LoadThis();
mg.LoadArgs();
// firePropertyChange(thisPointer, propertyChangeSupport, property, oldValue, newValue)
mg.InvokeVirtual(m_firePropertyChange);
mg.PopIfReturnValue(m_firePropertyChange);
mg.Mark(l_propertyChangeIsInactive);
mg.ReturnVoidOrThis();
mg.EndMethod();
return mg.Method;
}
protected FieldInstance GetPropertyChangeSupportField()
{
FieldInstance f_propertyChangeSupport = State.GetAlreadyImplementedField("f_propertyChangeSupport");
if (f_propertyChangeSupport == null)
{
f_propertyChangeSupport = new FieldInstance(FieldAttributes.Family, "f_propertyChangeSupport", typeof(PropertyChangeSupport));
}
return f_propertyChangeSupport;
}
protected MethodInstance ImplementUsePropertyChangeSupport(PropertyInstance p_propertyChangeTemplate, FieldInstance f_propertyChangeSupport)
{
MethodInstance m_getPropertyChangeSupport = MethodInstance.FindByTemplate(template_m_usePropertyChangeSupport, true);
if (m_getPropertyChangeSupport == null)
{
// create field that holds propertyChangeSupport
f_propertyChangeSupport = ImplementField(f_propertyChangeSupport);
IMethodVisitor mg = VisitMethod(template_m_usePropertyChangeSupport);
HideFromDebug(mg.Method);
Label l_pcsValid = mg.NewLabel();
mg.GetThisField(f_propertyChangeSupport);
mg.Dup();
mg.IfNonNull(l_pcsValid);
mg.Pop(); // remove 2nd null instance from stack caused by previous dup
mg.PutThisField(f_propertyChangeSupport, delegate(IMethodVisitor mg2)
{
mg.CallThisGetter(p_propertyChangeTemplate);
mg.LoadThis();
mg.InvokeVirtual(m_newPropertyChangeSupport);
});
mg.GetThisField(f_propertyChangeSupport);
mg.Mark(l_pcsValid);
mg.ReturnValue(); // return instance already on the stack by both branches
mg.EndMethod();
m_getPropertyChangeSupport = mg.Method;
}
return m_getPropertyChangeSupport;
}
protected PropertyInstance ImplementNotifyPropertyChangedSource(PropertyInstance p_propertyChangeTemplate,
FieldInstance f_propertyChangeSupport)
{
MethodInstance m_onPropertyChanged_Values = MethodInstance.FindByTemplate(template_m_onPropertyChanged_Values, true);
if (m_onPropertyChanged_Values == null)
{
IMethodVisitor mv = VisitMethod(template_m_onPropertyChanged_Values);
mv.CallThisGetter(p_propertyChangeTemplate);
mv.LoadThis();
mv.GetThisField(f_propertyChangeSupport);
// getMethodHandle(sender, propertyName)
mv.CallThisGetter(p_propertyChangeTemplate);
mv.LoadThis();
mv.LoadArg(0);
mv.InvokeVirtual(m_getMethodHandle);
mv.LoadArg(1);
mv.LoadArg(2);
// firePropertyChange(sender, propertyChangeSupport, property, oldValue, newValue)
mv.InvokeVirtual(m_firePropertyChange);
mv.PopIfReturnValue(m_firePropertyChange);
mv.ReturnVoidOrThis();
mv.EndMethod();
m_onPropertyChanged_Values = mv.Method;
}
MethodInstance m_onPropertyChanged = MethodInstance.FindByTemplate(template_m_onPropertyChanged, true);
if (m_onPropertyChanged == null)
{
IMethodVisitor mv = VisitMethod(template_m_onPropertyChanged);
mv.LoadThis();
mv.LoadArg(0);
mv.PushNull();
mv.PushNull();
mv.InvokeVirtual(m_onPropertyChanged_Values);
mv.PopIfReturnValue(m_onPropertyChanged_Values);
mv.ReturnVoidOrThis();
mv.EndMethod();
m_onPropertyChanged = mv.Method;
}
PropertyInstance p_pceHandlers = PropertyInstance.FindByTemplate(p_propertyChangeSupport, true);
if (p_pceHandlers == null)
{
HideFromDebug(ImplementGetter(p_propertyChangeSupport.Getter, f_propertyChangeSupport));
p_pceHandlers = PropertyInstance.FindByTemplate(p_propertyChangeSupport, false);
}
if (EmbeddedEnhancementHint.HasMemberPath(State.Context))
{
PropertyInstance p_parentEntity = EmbeddedTypeVisitor.GetParentObjectProperty(this);
if (MethodInstance.FindByTemplate(p_parentChildEventHandler.Getter, true) == null)
{
IMethodVisitor mv = VisitMethod(p_parentChildEventHandler.Getter);
mv.CallThisGetter(p_parentEntity);
mv.InvokeInterface(p_parentChildEventHandler.Getter);
mv.ReturnValue();
mv.EndMethod();
HideFromDebug(mv.Method);
}
if (MethodInstance.FindByTemplate(p_collectionEventHandler.Getter, true) == null)
{
IMethodVisitor mv = VisitMethod(p_collectionEventHandler.Getter);
mv.CallThisGetter(p_parentEntity);
mv.InvokeInterface(p_collectionEventHandler.Getter);
mv.ReturnValue();
mv.EndMethod();
HideFromDebug(mv.Method);
}
}
else
{
if (MethodInstance.FindByTemplate(p_parentChildEventHandler.Getter, true) == null)
{
HideFromDebug(ImplementLazyInitProperty(p_parentChildEventHandler, delegate(IMethodVisitor mv)
{
MethodInstance method = new MethodInstance(null, typeof(NotifyPropertyChangedClassVisitor), typeof(PropertyChangedEventHandler), "CreateParentChildEventHandler", typeof(Object));
mv.LoadThis();
mv.InvokeStatic(method);
}));
}
if (MethodInstance.FindByTemplate(p_collectionEventHandler.Getter, true) == null)
{
HideFromDebug(ImplementLazyInitProperty(p_collectionEventHandler, delegate(IMethodVisitor mv)
{
MethodInstance method = new MethodInstance(null, typeof(NotifyPropertyChangedClassVisitor), typeof(NotifyCollectionChangedEventHandler), "CreateCollectionEventHandler", typeof(Object));
mv.LoadThis();
mv.InvokeStatic(method);
}));
}
}
//MethodAttributes ma = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
//{
// ConstructorInfo pceaCI = typeof(PropertyChangedEventArgs).GetConstructor(new Type[] { typeof(String) });
// MethodBuilder mb = VisitorUtil.DefineMethod(vs, onPropertyChangedMI_string, ma);
// ILGenerator gen = mb.GetILGenerator();
// gen.Emit(OpCodes.Ldarg_0);
// gen.Emit(OpCodes.Ldarg_1);
// gen.Emit(OpCodes.Newobj, pceaCI);
// gen.Emit(OpCodes.Call, onPropertyChangedMI_pceArg);
// gen.Emit(OpCodes.Ret);
//}
//{
// MethodBuilder mb = VisitorUtil.DefineMethod(vs, onPropertyChangedMI_pceArg, ma);
// ILGenerator gen = mb.GetILGenerator();
// gen.Emit(OpCodes.Ldarg_0);
// gen.Emit(OpCodes.Call, pctPI.GetGetMethod());
// gen.Emit(OpCodes.Ldarg_0);
// gen.Emit(OpCodes.Ldarg_1);
// gen.Emit(OpCodes.Call, FirePropertyChangedMI);
// gen.Emit(OpCodes.Ret);
//}
// List<PropertyChangedEventHandler> PropertyChangedEventHandlers { get; }
//void OnPropertyChanged(String propertyName);
//void OnPropertyChanged(PropertyChangedEventArgs args);
return p_pceHandlers;
}
protected void ImplementNotifyPropertyChanged(PropertyInstance p_propertyChangeTemplate, MethodInstance m_getPropertyChangeSupport)
{
// implement IPropertyChanged
foreach (MethodInfo rMethod in typeof(INotifyPropertyChanged).GetMethods())
{
MethodInstance existingMethod = MethodInstance.FindByTemplate(rMethod, true);
if (existingMethod != null)
{
continue;
}
MethodInstance method = new MethodInstance(rMethod);
IMethodVisitor mg = VisitMethod(method);
mg.CallThisGetter(p_propertyChangeTemplate);
// this.propertyChangeSupport
mg.CallThisGetter(m_getPropertyChangeSupport);
// listener
mg.LoadArg(0);
if ("add_PropertyChanged".Equals(method.Name))
{
// addPropertyChangeListener(propertyChangeSupport, listener)
mg.InvokeVirtual(m_addPropertyChangeListener);
}
else
{
// removePropertyChangeListener(propertyChangeSupport, listener)
mg.InvokeVirtual(m_removePropertyChangeListener);
}
mg.ReturnValue();
mg.EndMethod();
}
}
protected void ImplementPropertyChangeConfigurable()
{
String fieldName = "__propertyChangeActive";
if (State.GetAlreadyImplementedField(fieldName) != null)
{
if (properties == null)
{
throw new Exception("It seems that this visitor has been executing twice");
}
return;
}
else if (properties != null)
{
// do not apply in this case
return;
}
FieldInstance f_propertyChangeActive = ImplementField(new FieldInstance(FieldAttributes.Private, fieldName, typeof(bool)));
ConstructorInfo[] constructors = State.CurrentType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (int a = constructors.Length; a-- > 0;)
{
ConstructorInstance ci = new ConstructorInstance(constructors[a]);
IMethodVisitor mv = VisitMethod(ci);
mv.LoadThis();
mv.LoadArgs();
mv.InvokeSuperOfCurrentMethod();
mv.PutThisField(f_propertyChangeActive, delegate(IMethodVisitor mg)
{
mg.Push(true);
});
mv.ReturnValue();
mv.EndMethod();
}
ImplementGetter(template_m_isPropertyChangeActive, f_propertyChangeActive);
ImplementSetter(template_m_setPropertyChangeActive, f_propertyChangeActive);
}
public static NotifyCollectionChangedEventHandler CreateCollectionEventHandler(Object entity)
{
//typeof(INotifyCollectionChangedListener);
//MethodInfo method = ReflectUtil.GetDeclaredMethod(false, entity.GetType(), "CollectionChanged", typeof(Object), typeof(NotifyCollectionChangedEventArgs));
return (NotifyCollectionChangedEventHandler)Delegate.CreateDelegate(typeof(NotifyCollectionChangedEventHandler), entity, "CollectionChanged");
}
public static PropertyChangedEventHandler CreateParentChildEventHandler(Object entity)
{
//typeof(IPropertyChangeListener);
MethodInfo method = ReflectUtil.GetDeclaredMethod(true, entity.GetType(), template_m_PropertyChanged.ReturnType.Type, template_m_PropertyChanged.Name, typeof(Object), typeof(PropertyChangedEventArgs));
return (PropertyChangedEventHandler)Delegate.CreateDelegate(typeof(PropertyChangedEventHandler), entity, template_m_PropertyChanged.Name);
}
}
}
| |
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 Weald.Areas.HelpPage.SampleGeneration
{
/// <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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Reflection
{
using System;
using System.Reflection;
////using System.Reflection.Cache;
////using System.Reflection.Emit;
////using System.Globalization;
////using System.Threading;
////using System.Diagnostics;
////using System.Security.Permissions;
////using System.Collections;
////using System.Security;
////using System.Text;
using System.Runtime.ConstrainedExecution;
////using System.Runtime.CompilerServices;
////using System.Runtime.InteropServices;
////using System.Runtime.Serialization;
////using System.Runtime.Versioning;
////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
////using CorElementType = System.Reflection.CorElementType;
////using MdToken = System.Reflection.MetadataToken;
[Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo /*, ISerializable*/
{
#region Private Data Members
//// private int m_token;
//// private string m_name;
//// private void* m_utf8name;
//// private PropertyAttributes m_flags;
//// private RuntimeTypeCache m_reflectedTypeCache;
//// private RuntimeMethodInfo m_getterMethod;
//// private RuntimeMethodInfo m_setterMethod;
//// private MethodInfo[] m_otherMethod;
//// private RuntimeType m_declaringType;
//// private BindingFlags m_bindingFlags;
//// private Signature m_signature;
#endregion
#region Constructor
//// internal RuntimePropertyInfo( int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate )
//// {
//// ASSERT.PRECONDITION( declaredType != null );
//// ASSERT.PRECONDITION( reflectedTypeCache != null );
//// ASSERT.PRECONDITION( !reflectedTypeCache.IsGlobal );
////
//// MetadataImport scope = declaredType.Module.MetadataImport;
////
//// m_token = tkProperty;
//// m_reflectedTypeCache = reflectedTypeCache;
//// m_declaringType = declaredType;
////
//// RuntimeTypeHandle declaredTypeHandle = declaredType.GetTypeHandleInternal();
//// RuntimeTypeHandle reflectedTypeHandle = reflectedTypeCache.RuntimeTypeHandle;
//// RuntimeMethodInfo dummy;
////
//// scope.GetPropertyProps( tkProperty, out m_utf8name, out m_flags, out MetadataArgs.Skip.ConstArray );
////
//// int cAssociateRecord = scope.GetAssociatesCount( tkProperty );
////
//// AssociateRecord* associateRecord = stackalloc AssociateRecord[cAssociateRecord];
////
//// scope.GetAssociates( tkProperty, associateRecord, cAssociateRecord );
////
//// Associates.AssignAssociates( associateRecord, cAssociateRecord, declaredTypeHandle, reflectedTypeHandle,
//// out dummy, out dummy, out dummy,
//// out m_getterMethod, out m_setterMethod, out m_otherMethod,
//// out isPrivate, out m_bindingFlags );
//// }
#endregion
#region Internal Members
//// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
//// internal override bool CacheEquals( object o )
//// {
//// RuntimePropertyInfo m = o as RuntimePropertyInfo;
////
//// if(m == null)
//// {
//// return false;
//// }
////
//// return m.m_token == m_token && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle() );
//// }
////
//// internal Signature Signature
//// {
//// get
//// {
//// if(m_signature == null)
//// {
//// ConstArray sig;
////
//// void* name;
////
//// Module.MetadataImport.GetPropertyProps( m_token, out name, out MetadataArgs.Skip.PropertyAttributes, out sig );
////
//// m_signature = new Signature( sig.Signature.ToPointer(), (int)sig.Length, m_declaringType.GetTypeHandleInternal() );
//// }
////
//// return m_signature;
//// }
//// }
////
//// internal BindingFlags BindingFlags
//// {
//// get
//// {
//// return m_bindingFlags;
//// }
//// }
////
//// internal bool EqualsSig( RuntimePropertyInfo target )
//// {
//// //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
//// // The comparison is done by name and by sig. The EqualsSig comparison is expensive
//// // but forutnetly it is only called when an inherited property is hidden by name or
//// // when an interfaces declare properies with the same signature.
////
//// ASSERT.PRECONDITION( Name.Equals( target.Name ) );
//// ASSERT.PRECONDITION( this != target );
//// ASSERT.PRECONDITION( this.ReflectedType == target.ReflectedType );
////
//// return Signature.DiffSigs( target.Signature );
//// }
#endregion
#region Object Overrides
//// public override String ToString()
//// {
//// string toString = PropertyType.SigToString() + " " + Name;
////
//// RuntimeTypeHandle[] argumentHandles = Signature.Arguments;
//// if(argumentHandles.Length > 0)
//// {
//// Type[] paramters = new Type[argumentHandles.Length];
//// for(int i = 0; i < paramters.Length; i++)
//// {
//// paramters[i] = argumentHandles[i].GetRuntimeType();
//// }
////
//// toString += " [" + RuntimeMethodInfo.ConstructParameters( paramters, Signature.CallingConvention ) + "]";
//// }
////
//// return toString;
//// }
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes( bool inherit )
{
throw new NotImplementedException();
//// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType );
}
public override Object[] GetCustomAttributes( Type attributeType, bool inherit )
{
throw new NotImplementedException();
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType );
}
public override bool IsDefined( Type attributeType, bool inherit )
{
throw new NotImplementedException();
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.IsDefined( this, attributeRuntimeType );
}
#endregion
#region MemberInfo Overrides
//// public override MemberTypes MemberType
//// {
//// get
//// {
//// return MemberTypes.Property;
//// }
//// }
public override String Name
{
get
{
throw new NotImplementedException();
//// if(m_name == null)
//// {
//// m_name = new Utf8String( m_utf8name ).ToString();
//// }
////
//// return m_name;
}
}
public override Type DeclaringType
{
get
{
throw new NotImplementedException();
//// return m_declaringType;
}
}
//// public override Type ReflectedType
//// {
//// get
//// {
//// return m_reflectedTypeCache.RuntimeType;
//// }
//// }
////
//// public override int MetadataToken
//// {
//// get
//// {
//// return m_token;
//// }
//// }
////
//// public override Module Module
//// {
//// get
//// {
//// return m_declaringType.Module;
//// }
//// }
#endregion
#region PropertyInfo Overrides
#region Non Dynamic
//// public override Type[] GetRequiredCustomModifiers()
//// {
//// return Signature.GetCustomModifiers( 0, true );
//// }
////
//// public override Type[] GetOptionalCustomModifiers()
//// {
//// return Signature.GetCustomModifiers( 0, false );
//// }
////
//// internal object GetConstantValue( bool raw )
//// {
//// Object defaultValue = MdConstant.GetValue( Module.MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw );
////
//// if(defaultValue == DBNull.Value)
//// {
//// // Arg_EnumLitValueNotFound -> "Literal value was not found."
//// throw new InvalidOperationException( Environment.GetResourceString( "Arg_EnumLitValueNotFound" ) );
//// }
////
//// return defaultValue;
//// }
////
//// public override object GetConstantValue()
//// {
//// return GetConstantValue( false );
//// }
////
//// public override object GetRawConstantValue()
//// {
//// return GetConstantValue( true );
//// }
////
//// public override MethodInfo[] GetAccessors( bool nonPublic )
//// {
//// ArrayList accessorList = new ArrayList();
////
//// if(Associates.IncludeAccessor( m_getterMethod, nonPublic ))
//// {
//// accessorList.Add( m_getterMethod );
//// }
////
//// if(Associates.IncludeAccessor( m_setterMethod, nonPublic ))
//// {
//// accessorList.Add( m_setterMethod );
//// }
////
//// if(m_otherMethod != null)
//// {
//// for(int i = 0; i < m_otherMethod.Length; i++)
//// {
//// if(Associates.IncludeAccessor( m_otherMethod[i] as MethodInfo, nonPublic ))
//// {
//// accessorList.Add( m_otherMethod[i] );
//// }
//// }
//// }
////
//// return accessorList.ToArray( typeof( MethodInfo ) ) as MethodInfo[];
//// }
////
//// public override Type PropertyType
//// {
//// get
//// {
//// return Signature.ReturnTypeHandle.GetRuntimeType();
//// }
//// }
////
//// public override MethodInfo GetGetMethod( bool nonPublic )
//// {
//// if(!Associates.IncludeAccessor( m_getterMethod, nonPublic ))
//// {
//// return null;
//// }
////
//// return m_getterMethod;
//// }
////
//// public override MethodInfo GetSetMethod( bool nonPublic )
//// {
//// if(!Associates.IncludeAccessor( m_setterMethod, nonPublic ))
//// {
//// return null;
//// }
////
//// return m_setterMethod;
//// }
////
//// public override ParameterInfo[] GetIndexParameters()
//// {
//// // @History - Logic ported from RTM
////
//// int numParams = 0;
//// ParameterInfo[] methParams = null;
////
//// // First try to get the Get method.
//// MethodInfo m = GetGetMethod( true );
//// if(m != null)
//// {
//// // There is a Get method so use it.
//// methParams = m.GetParametersNoCopy();
//// numParams = methParams.Length;
//// }
//// else
//// {
//// // If there is no Get method then use the Set method.
//// m = GetSetMethod( true );
////
//// if(m != null)
//// {
//// methParams = m.GetParametersNoCopy();
//// numParams = methParams.Length - 1;
//// }
//// }
////
//// // Now copy over the parameter info's and change their
//// // owning member info to the current property info.
////
//// if(methParams != null && methParams.Length == 0)
//// {
//// return methParams;
//// }
////
//// ParameterInfo[] propParams = new ParameterInfo[numParams];
////
//// for(int i = 0; i < numParams; i++)
//// {
//// propParams[i] = new ParameterInfo( methParams[i], this );
//// }
////
//// return propParams;
//// }
////
//// public override PropertyAttributes Attributes
//// {
//// get
//// {
//// return m_flags;
//// }
//// }
////
//// public override bool CanRead
//// {
//// get
//// {
//// return m_getterMethod != null;
//// }
//// }
////
//// public override bool CanWrite
//// {
//// get
//// {
//// return m_setterMethod != null;
//// }
//// }
#endregion
#region Dynamic
//// [DebuggerStepThroughAttribute]
//// [Diagnostics.DebuggerHidden]
//// public override Object GetValue( Object obj, Object[] index )
//// {
//// return GetValue( obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, index, null );
//// }
////
//// [DebuggerStepThroughAttribute]
//// [Diagnostics.DebuggerHidden]
//// public override Object GetValue( Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture )
//// {
//// MethodInfo m = GetGetMethod( true );
//// if(m == null)
//// {
//// throw new ArgumentException( System.Environment.GetResourceString( "Arg_GetMethNotFnd" ) );
//// }
////
//// return m.Invoke( obj, invokeAttr, binder, index, null );
//// }
////
//// [DebuggerStepThroughAttribute]
//// [Diagnostics.DebuggerHidden]
//// public override void SetValue( Object obj, Object value, Object[] index )
//// {
//// SetValue( obj,
//// value,
//// BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
//// null,
//// index,
//// null );
//// }
////
//// [DebuggerStepThroughAttribute]
//// [Diagnostics.DebuggerHidden]
//// public override void SetValue( Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture )
//// {
//// MethodInfo m = GetSetMethod( true );
//// if(m == null)
//// {
//// throw new ArgumentException( System.Environment.GetResourceString( "Arg_SetMethNotFnd" ) );
//// }
////
//// Object[] args = null;
////
//// if(index != null)
//// {
//// args = new Object[index.Length + 1];
////
//// for(int i = 0; i < index.Length; i++)
//// {
//// args[i] = index[i];
//// }
////
//// args[index.Length] = value;
//// }
//// else
//// {
//// args = new Object[1];
//// args[0] = value;
//// }
////
//// m.Invoke( obj, invokeAttr, binder, args, culture );
//// }
#endregion
#endregion
#region ISerializable Implementation
//// public void GetObjectData( SerializationInfo info, StreamingContext context )
//// {
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
////
//// MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedType, ToString(), MemberTypes.Property );
//// }
#endregion
}
}
| |
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using Loon.Utils;
using Loon.Java;
namespace Loon.Core.Graphics.Opengl
{
public class LTextureBatch
{
public bool quad = true;
internal static bool isBatchCacheDitry;
private static System.Collections.Generic.Dictionary<Int32, LTextureBatch> batchPools = new System.Collections.Generic.Dictionary<Int32, LTextureBatch>(
10);
public static void ClearBatchCaches() {
if (LTextureBatch.isBatchCacheDitry) {
System.Collections.Generic.Dictionary<Int32, LTextureBatch> batchCaches;
lock (batchPools) {
batchCaches = new System.Collections.Generic.Dictionary<Int32, LTextureBatch>(batchPools);
batchPools.Clear();
}
foreach (LTextureBatch bt in batchCaches.Values) {
if (bt != null) {
lock (bt) {
bt.Dispose();
}
}
}
batchCaches = null;
LTextureBatch.isBatchCacheDitry = false;
}
}
public static LTextureBatch BindBatchCache( LTexture texture) {
return BindBatchCache(0, texture);
}
public static LTextureBatch BindBatchCache( int index,
LTexture texture) {
if (texture == null) {
return null;
}
int texId = texture.textureID;
return BindBatchCache(index, texId, texture);
}
public static LTextureBatch BindBatchCache( object o,
int texId, LTexture texture) {
return BindBatchCache(o.GetHashCode(), texId, texture);
}
public static LTextureBatch BindBatchCache( int index,
int texId, LTexture texture) {
if (batchPools.Count > 128) {
ClearBatchCaches();
}
int key = LSystem.Unite(index, texId);
LTextureBatch pBatch = (LTextureBatch)CollectionUtils.Get(batchPools, key);
if (pBatch == null) {
lock (batchPools) {
pBatch = new LTextureBatch(texture);
CollectionUtils.Put(batchPools,key, pBatch);
}
}
return pBatch;
}
public static LTextureBatch DisposeBatchCache(int texId) {
lock (batchPools) {
LTextureBatch pBatch = (LTextureBatch)CollectionUtils.Remove(batchPools, texId);
if (pBatch != null) {
lock (pBatch) {
pBatch.Dispose();
}
}
return pBatch;
}
}
public class GLCache : LRelease
{
internal VertexPositionColorTexture[] m_cache;
public float x, y;
internal int batchCount;
internal bool isColor;
internal short[] m_quadIndices;
internal int m_type;
public GLCache(LTextureBatch batch)
: this(batch, true)
{
}
public GLCache(LTextureBatch batch, bool Reset)
{
if (Reset)
{
batch.InsertVertices();
}
this.m_type = batch.batchType;
this.m_cache = new VertexPositionColorTexture[batch.glbase.GetVerticesSize()];
Array.Copy(batch.glbase.Vertices, m_cache, batch.glbase.GetVerticesSize());
this.m_quadIndices = new short[batch.glbase.GetQuadIndicesSize()];
Array.Copy(batch.glbase.QuadIndices, m_quadIndices, batch.glbase.GetQuadIndicesSize());
this.batchCount = batch.batchCount;
this.isColor = batch.isColor;
this.x = batch.moveX;
this.y = batch.moveY;
}
public void Dispose()
{
if (m_cache != null)
{
this.m_cache = null;
}
if (m_quadIndices != null)
{
this.m_quadIndices = null;
}
}
}
private LTexture textureBuffer;
private float moveX, moveY;
private int batchType;
private int ver, col, tex,maxCount;
private int texWidth, texHeight;
private float xOff, yOff, widthRatio, heightRatio;
private float drawWidth, drawHeight;
private float textureSrcX, textureSrcY;
private float srcWidth, srcHeight;
private float renderWidth, renderHeight;
internal bool useBegin, lockCoord, isColor, isLocked;
float invTexWidth;
float invTexHeight;
private const int DEFAULT_MAX_VERTICES = 2048;
internal Color default_color = Color.White;
private int batchCount;
public void Lock()
{
this.isLocked = true;
}
public void UnLock()
{
this.isLocked = false;
}
public void GLCacheCommit()
{
if (batchCount == 0)
{
return;
}
if (isLocked)
{
Submit();
}
}
private void InsertVertices()
{
if (isLocked)
{
return;
}
glbase.Transform(this.batchType, this.batchCount, this.vectors, this.coords, this.colors, this.isColor, true, this.default_color);
}
public void SetTexture(LTexture tex2d)
{
if (!tex2d.isLoaded)
{
tex2d.LoadTexture();
}
this.textureBuffer = tex2d;
this.texWidth = textureBuffer.width;
this.texHeight = textureBuffer.height;
this.invTexWidth = (1f / texWidth) * textureBuffer.widthRatio;
this.invTexHeight = (1f / texHeight) * textureBuffer.heightRatio;
}
public LTextureBatch(LTexture tex2d)
: this(tex2d, DEFAULT_MAX_VERTICES)
{
}
public LTextureBatch(LTexture tex2d, int batchCount)
{
if (tex2d != null)
{
this.SetTexture(tex2d);
}
this.isLocked = false;
this.Make(batchCount);
}
public LTextureBatch(GLBatch batch)
{
this.isLocked = false;
this.Make(batch);
}
private List<Vector3> vectors;
private List<Vector2> coords;
private List<Color> colors;
private GraphicsDevice device;
private GLBase glbase;
private void Make(GLBatch batch)
{
device = GL.device;
if (vectors == null)
{
ver = batch.GetMaxVertices();
vectors = new List<Vector3>(ver);
}
if (colors == null)
{
col = batch.GetMaxVertices() / 4;
colors = new List<Color>(col);
}
if (coords == null)
{
tex = batch.GetMaxVertices() / 2;
coords = new List<Vector2>(tex);
}
this.glbase = batch.Base;
this.maxCount = batch.GetMaxVertices();
}
private void Make(int size)
{
device = GL.device;
if (vectors == null)
{
ver = size;
vectors = new List<Vector3>(ver);
}
if (colors == null)
{
col = size / 4;
colors = new List<Color>(col);
}
if (coords == null)
{
tex = size / 2;
coords = new List<Vector2>(tex);
}
this.glbase = new GLBase(size);
this.maxCount = size;
}
public void GLBegin()
{
GLBegin(GL.GL_TRIANGLE_FAN);
}
protected internal bool ClearBatch = true;
public void GLBegin(int type)
{
this.batchType = type;
this.useBegin = true;
this.isColor = false;
if (!isLocked)
{
if (ClearBatch)
{
this.glbase.Clear(batchCount);
}
this.batchCount = 0;
}
}
public bool UseBegin
{
get
{
return useBegin;
}
}
private void Submit()
{
GL gl = GLEx.GL;
gl.GLBind(textureBuffer);
if (moveX != 0 || moveY != 0)
{
gl.GLPushMatrix();
gl.GLTranslate(moveX, moveY, 0);
}
glbase.Send(batchType, batchCount);
if (moveX != 0 || moveY != 0)
{
gl.GLPopMatrix();
}
}
public void GLEnd()
{
if (this.batchCount == 0 || !useBegin)
{
this.useBegin = false;
return;
}
this.InsertVertices();
this.Submit();
useBegin = false;
}
public void GLColor4f(LColor c)
{
colors.Add(c);
isColor = true;
}
public void GLColor4f(float r, float g, float b, float a)
{
colors.Add(new Color(r, g, b, a));
isColor = true;
}
public void GLTexCoord2f(float fcol, float frow)
{
coords.Add(new Vector2(fcol, frow));
}
public void GLVertex3f(float x, float y, float z)
{
vectors.Add(new Vector3(x, y, z));
batchCount++;
if (batchCount >= GetLimit(maxCount))
{
GLEnd();
}
}
private int GetLimit(int count)
{
switch (batchType)
{
case GL.GL_TRIANGLES:
return count / 3 ;
case GL.GL_LINES:
return count / 2;
case GL.GL_QUADS:
case GL.GL_TRIANGLE_FAN:
return count / 4;
}
return count;
}
private LColor[] image_colors;
public void SetImageColor(float r, float g, float b, float a)
{
SetColor(LTexture.TOP_LEFT, r, g, b, a);
SetColor(LTexture.TOP_RIGHT, r, g, b, a);
SetColor(LTexture.BOTTOM_LEFT, r, g, b, a);
SetColor(LTexture.BOTTOM_RIGHT, r, g, b, a);
}
public void SetImageColor(float r, float g, float b)
{
SetColor(LTexture.TOP_LEFT, r, g, b);
SetColor(LTexture.TOP_RIGHT, r, g, b);
SetColor(LTexture.BOTTOM_LEFT, r, g, b);
SetColor(LTexture.BOTTOM_RIGHT, r, g, b);
}
public void SetImageColor(LColor c)
{
if (c == null)
{
return;
}
if (image_colors == null)
{
image_colors = new LColor[] { new LColor(1f, 1f, 1f, 1f),
new LColor(1f, 1f, 1f, 1f), new LColor(1f, 1f, 1f, 1f),
new LColor(1f, 1f, 1f, 1f) };
}
image_colors[LTexture.TOP_LEFT] = c;
image_colors[LTexture.TOP_RIGHT] = c;
image_colors[LTexture.BOTTOM_LEFT] = c;
image_colors[LTexture.BOTTOM_RIGHT] = c;
}
public void SetColor(int corner, float r, float g, float b, float a)
{
if (image_colors == null)
{
image_colors = new LColor[] { new LColor(1f, 1f, 1f, 1f),
new LColor(1f, 1f, 1f, 1f), new LColor(1f, 1f, 1f, 1f),
new LColor(1f, 1f, 1f, 1f) };
}
image_colors[corner].SetFloatColor(r, g, b, a);
}
public void SetColor(int corner, float r, float g, float b)
{
if (image_colors == null)
{
image_colors = new LColor[] { new LColor(1f, 1f, 1f, 1f),
new LColor(1f, 1f, 1f, 1f), new LColor(1f, 1f, 1f, 1f),
new LColor(1f, 1f, 1f, 1f) };
}
image_colors[corner].SetFloatColor(r, g, b, 1f);
}
public void DrawQuad(float drawX, float drawY, float drawX2, float drawY2,
float srcX, float srcY, float srcX2, float srcY2)
{
drawWidth = drawX2 - drawX;
drawHeight = drawY2 - drawY;
textureSrcX = ((srcX / texWidth) * textureBuffer.widthRatio) + textureBuffer.xOff;
textureSrcY = ((srcY / texHeight) * textureBuffer.heightRatio) + textureBuffer.yOff;
srcWidth = srcX2 - srcX;
srcHeight = srcY2 - srcY;
renderWidth = ((srcWidth / texWidth) * textureBuffer.widthRatio);
renderHeight = ((srcHeight / texHeight) * textureBuffer.heightRatio);
GLTexCoord2f(textureSrcX, textureSrcY);
GLVertex3f(drawX, drawY, 0);
GLTexCoord2f(textureSrcX, textureSrcY + renderHeight);
GLVertex3f(drawX, drawY + drawHeight, 0);
GLTexCoord2f(textureSrcX + renderWidth, textureSrcY + renderHeight);
GLVertex3f(drawX + drawWidth, drawY + drawHeight, 0);
GLTexCoord2f(textureSrcX + renderWidth, textureSrcY);
GLVertex3f(drawX + drawWidth, drawY, 0);
}
public void Draw(float x, float y)
{
Draw(image_colors, x, y, textureBuffer.width, textureBuffer.height, 0, 0, textureBuffer.width,
textureBuffer.height);
}
public void Draw(float x, float y, float width, float height)
{
Draw(image_colors, x, y, width, height, 0, 0, textureBuffer.width, textureBuffer.height);
}
public void Draw(float x, float y, float width, float height, float srcX,
float srcY, float srcWidth, float srcHeight)
{
Draw(image_colors, x, y, width, height, srcX, srcY, srcWidth, srcHeight);
}
public void Draw(LColor[] colors, float x, float y, float width,
float height)
{
Draw(colors, x, y, width, height, 0, 0, textureBuffer.width, textureBuffer.height);
}
public void Draw(LColor[] colors, float x, float y, float width,
float height, float srcX, float srcY, float srcWidth,
float srcHeight)
{
if (!useBegin)
{
return;
}
if (isLocked)
{
return;
}
xOff = srcX * invTexWidth + textureBuffer.xOff;
yOff = srcY * invTexHeight + textureBuffer.yOff;
widthRatio = srcWidth * invTexWidth;
heightRatio = srcHeight * invTexHeight;
float fx2 = x + width;
float fy2 = y + height;
if (colors == null)
{
GLTexCoord2f(xOff, yOff);
GLVertex3f(x, y, 0);
GLTexCoord2f(xOff, heightRatio);
GLVertex3f(x, fy2, 0);
GLTexCoord2f(widthRatio, heightRatio);
GLVertex3f(fx2, fy2, 0);
GLTexCoord2f(widthRatio, yOff);
GLVertex3f(fx2, y, 0);
}
else
{
isColor = true;
GLColor4f(colors[LTexture.TOP_LEFT]);
GLTexCoord2f(xOff, yOff);
GLVertex3f(x, y, 0);
GLColor4f(colors[LTexture.BOTTOM_LEFT]);
GLTexCoord2f(xOff, heightRatio);
GLVertex3f(x, fy2, 0);
GLColor4f(colors[LTexture.BOTTOM_RIGHT]);
GLTexCoord2f(widthRatio, heightRatio);
GLVertex3f(fx2, fy2, 0);
GLColor4f(colors[LTexture.TOP_RIGHT]);
GLTexCoord2f(widthRatio, yOff);
GLVertex3f(fx2, y, 0);
}
}
public void Draw(LColor[] colors, float x, float y, float rotation)
{
Draw(colors, x, y, textureBuffer.width / 2, textureBuffer.height / 2,
textureBuffer.width, textureBuffer.height, 1f, 1f, rotation, 0,
0, textureBuffer.width, textureBuffer.height, false, false);
}
public void Draw(LColor[] colors, float x, float y, float width,
float height, float rotation)
{
Draw(colors, x, y, textureBuffer.width / 2, textureBuffer.height / 2,
width, height, 1f, 1f, rotation, 0, 0, textureBuffer.width,
textureBuffer.height, false, false);
}
public void Draw(LColor[] colors, float x, float y, float srcX, float srcY,
float srcWidth, float srcHeight, float rotation)
{
Draw(colors, x, y, textureBuffer.width / 2, textureBuffer.height / 2,
textureBuffer.width, textureBuffer.height, 1f, 1f, rotation,
srcX, srcY, srcWidth, srcHeight, false, false);
}
public void Draw(LColor[] colors, float x, float y, float width,
float height, float srcX, float srcY, float srcWidth,
float srcHeight, float rotation)
{
Draw(colors, x, y, width / 2, height / 2, width, height, 1f, 1f,
rotation, srcX, srcY, srcWidth, srcHeight, false, false);
}
public void Draw(float x, float y, float originX,
float originY, float width, float height, float scaleX,
float scaleY, float rotation, float srcX, float srcY,
float srcWidth, float srcHeight, bool flipX, bool flipY)
{
Draw(image_colors, x, y, originX, originY, width, height, scaleX, scaleY,
rotation, srcX, srcY, srcWidth, srcHeight, flipX, flipY);
}
public void Draw(LColor[] colors, float x, float y, float originX,
float originY, float width, float height, float scaleX,
float scaleY, float rotation, float srcX, float srcY,
float srcWidth, float srcHeight, bool flipX, bool flipY)
{
float worldOriginX = x + originX;
float worldOriginY = y + originY;
float fx = -originX;
float fy = -originY;
float fx2 = width - originX;
float fy2 = height - originY;
if (scaleX != 1 || scaleY != 1)
{
fx *= scaleX;
fy *= scaleY;
fx2 *= scaleX;
fy2 *= scaleY;
}
float p1x = fx;
float p1y = fy;
float p2x = fx;
float p2y = fy2;
float p3x = fx2;
float p3y = fy2;
float p4x = fx2;
float p4y = fy;
float x1;
float y1;
float x2;
float y2;
float x3;
float y3;
float x4;
float y4;
if (rotation != 0)
{
float cos = MathUtils.CosDeg(rotation);
float sin = MathUtils.SinDeg(rotation);
x1 = cos * p1x - sin * p1y;
y1 = sin * p1x + cos * p1y;
x2 = cos * p2x - sin * p2y;
y2 = sin * p2x + cos * p2y;
x3 = cos * p3x - sin * p3y;
y3 = sin * p3x + cos * p3y;
x4 = x1 + (x3 - x2);
y4 = y3 - (y2 - y1);
}
else
{
x1 = p1x;
y1 = p1y;
x2 = p2x;
y2 = p2y;
x3 = p3x;
y3 = p3y;
x4 = p4x;
y4 = p4y;
}
x1 += worldOriginX;
y1 += worldOriginY;
x2 += worldOriginX;
y2 += worldOriginY;
x3 += worldOriginX;
y3 += worldOriginY;
x4 += worldOriginX;
y4 += worldOriginY;
xOff = srcX * invTexWidth + textureBuffer.xOff;
yOff = srcY * invTexHeight + textureBuffer.yOff;
widthRatio = srcWidth * invTexWidth;
heightRatio = srcHeight * invTexHeight;
if (flipX)
{
float tmp = xOff;
xOff = widthRatio;
widthRatio = tmp;
}
if (flipY)
{
float tmp = yOff;
yOff = heightRatio;
heightRatio = tmp;
}
if (colors == null)
{
GLTexCoord2f(xOff, yOff);
GLVertex3f(x1, y1, 0);
GLTexCoord2f(xOff, heightRatio);
GLVertex3f(x2, y2, 0);
GLTexCoord2f(widthRatio, heightRatio);
GLVertex3f(x3, y3, 0);
GLTexCoord2f(widthRatio, yOff);
GLVertex3f(x4, y4, 0);
}
else
{
isColor = true;
GLColor4f(colors[LTexture.TOP_LEFT]);
GLTexCoord2f(xOff, yOff);
GLVertex3f(x1, y1, 0);
GLColor4f(colors[LTexture.BOTTOM_LEFT]);
GLTexCoord2f(xOff, heightRatio);
GLVertex3f(x2, y2, 0);
GLColor4f(colors[LTexture.BOTTOM_RIGHT]);
GLTexCoord2f(widthRatio, heightRatio);
GLVertex3f(x3, y3, 0);
GLColor4f(colors[LTexture.TOP_RIGHT]);
GLTexCoord2f(widthRatio, yOff);
GLVertex3f(x4, y4, 0);
}
}
public void Draw(float x, float y, float width,
float height, float srcX, float srcY, float srcWidth,
float srcHeight, bool flipX, bool flipY)
{
Draw(image_colors, x, y, width, height, srcX, srcY, srcWidth, srcHeight, flipX, flipY);
}
public void Draw(LColor[] colors, float x, float y, float width,
float height, float srcX, float srcY, float srcWidth,
float srcHeight, bool flipX, bool flipY)
{
xOff = srcX * invTexWidth + textureBuffer.xOff;
yOff = srcY * invTexHeight + textureBuffer.yOff;
widthRatio = srcWidth * invTexWidth;
heightRatio = srcHeight * invTexHeight;
float fx2 = x + width;
float fy2 = y + height;
if (flipX)
{
float tmp = xOff;
xOff = widthRatio;
widthRatio = tmp;
}
if (flipY)
{
float tmp = yOff;
yOff = heightRatio;
heightRatio = tmp;
}
if (colors == null)
{
GLTexCoord2f(xOff, yOff);
GLVertex3f(x, y, 0);
GLTexCoord2f(xOff, heightRatio);
GLVertex3f(x, fy2, 0);
GLTexCoord2f(widthRatio, heightRatio);
GLVertex3f(fx2, fx2, 0);
GLTexCoord2f(widthRatio, yOff);
GLVertex3f(fx2, y, 0);
}
else
{
isColor = true;
GLColor4f(colors[LTexture.TOP_LEFT]);
GLTexCoord2f(xOff, yOff);
GLVertex3f(x, y, 0);
GLColor4f(colors[LTexture.BOTTOM_LEFT]);
GLTexCoord2f(xOff, heightRatio);
GLVertex3f(x, fy2, 0);
GLColor4f(colors[LTexture.BOTTOM_RIGHT]);
GLTexCoord2f(widthRatio, heightRatio);
GLVertex3f(fx2, fx2, 0);
GLColor4f(colors[LTexture.TOP_RIGHT]);
GLTexCoord2f(widthRatio, yOff);
GLVertex3f(fx2, y, 0);
}
}
public void Draw(float x, float y, LColor[] c)
{
Draw(c, x, y, textureBuffer.width, textureBuffer.height);
}
public void Draw(float x, float y, LColor c)
{
bool update = CheckUpdateColor(c);
if (update)
{
SetImageColor(c);
}
Draw(image_colors, x, y, textureBuffer.width, textureBuffer.height);
if (update)
{
SetImageColor(LColor.white);
}
}
public void Draw(float x, float y, float width, float height, LColor c)
{
bool update = CheckUpdateColor(c);
if (update)
{
SetImageColor(c);
}
Draw(image_colors, x, y, width, height);
if (update)
{
SetImageColor(LColor.white);
}
}
public void Draw(float x, float y, float width, float height, float x1,
float y1, float x2, float y2, LColor[] c)
{
Draw(c, x, y, width, height, x1, y1, x2, y2);
}
public void Draw(float x, float y, float width, float height, float x1,
float y1, float x2, float y2, LColor c)
{
bool update = CheckUpdateColor(c);
if (update)
{
SetImageColor(c);
}
Draw(image_colors, x, y, width, height, x1, y1, x2, y2);
if (update)
{
SetImageColor(LColor.white);
}
}
public void Draw(float x, float y, float w, float h, float rotation,
LColor c)
{
bool update = CheckUpdateColor(c);
if (update)
{
SetImageColor(c);
}
Draw(image_colors, x, y, w, h, rotation);
if (update)
{
SetImageColor(LColor.white);
}
}
private bool CheckUpdateColor(LColor c)
{
return c != null && !LColor.white.Equals(c);
}
public LTexture GetTexture()
{
return textureBuffer;
}
public int GetHeight()
{
return texHeight;
}
public int GetWidth()
{
return texWidth;
}
public float GetX()
{
return moveX;
}
public void SetX(float x)
{
this.moveX = x;
}
public float GetY()
{
return moveY;
}
public void SetY(float y)
{
this.moveY = y;
}
public void SetLocation(float x, float y)
{
this.moveX = x;
this.moveY = y;
}
public bool IsLockCoord()
{
return lockCoord;
}
public void SetLockCoord(bool lockCoord)
{
this.lockCoord = lockCoord;
}
private GLCache m_lastCache;
public void PostLastCache()
{
if (m_lastCache != null)
{
LTextureBatch.Commit(textureBuffer, m_lastCache);
}
}
public static void Commit(LTexture tex2d, GLCache cache)
{
Commit(tex2d, cache, true);
}
public static void Commit(LTexture tex2d, GLCache cache, bool update)
{
if (cache.batchCount == 0)
{
return;
}
GL gl = GLEx.GL;
gl.GLBind(tex2d);
if (update)
{
if (cache.x != 0 || cache.y != 0)
{
gl.GLPushMatrix();
gl.GLTranslate(cache.x, cache.y, 0);
}
}
GLEx.GL.Submit(cache.m_type, cache.batchCount, cache.m_cache, cache.m_quadIndices, null);
if (update)
{
if (cache.x != 0 || cache.y != 0)
{
gl.GLPopMatrix();
}
}
}
public void CommitQuad(LColor c, float x, float y, float sx, float sy,
float ax, float ay, float rotation)
{
if (batchCount == 0 || !useBegin)
{
this.useBegin = false;
return;
}
this.isColor = false;
if (c != null)
{
default_color = c;
}
this.InsertVertices();
GL gl = GLEx.GL;
gl.GLBind(textureBuffer);
gl.GLPushMatrix();
if (x != 0 || y != 0)
{
gl.GLTranslate(x, y, 0);
}
if (sx != 0 || sx != 0)
{
gl.GLScale(sx, sy, 0);
}
if (rotation != 0)
{
if (ax != 0 || ay != 0)
{
gl.GLTranslate(ax, ay, 0f);
gl.GLRotate(rotation);
gl.GLTranslate(-ax, -ay, 0f);
}
else
{
gl.GLTranslate(textureBuffer.width / 2,
textureBuffer.height / 2, 0f);
gl.GLRotate(rotation);
gl.GLTranslate(-textureBuffer.width / 2,
-textureBuffer.height / 2, 0f);
}
}
glbase.Send(batchType,batchCount);
gl.GLPopMatrix();
}
public static void CommitQuad(LTexture tex2d, GLCache cache,
LColor c, float x, float y, float sx, float sy, float ax, float ay,
float rotation)
{
if (cache.batchCount == 0)
{
return;
}
GL gl = GLEx.GL;
gl.GLBind(tex2d);
gl.GLPushMatrix();
if (x != 0 || y != 0)
{
gl.GLTranslate(x, y, 0);
}
if (sx != 0 || sx != 0)
{
gl.GLScale(sx, sy, 0);
}
if (rotation != 0)
{
if (ax != 0 || ay != 0)
{
gl.GLTranslate(ax, ay, 0f);
gl.GLRotate(rotation);
gl.GLTranslate(-ax, -ay, 0f);
}
else
{
gl.GLTranslate(tex2d.width / 2,
tex2d.height / 2, 0f);
gl.GLRotate(rotation);
gl.GLTranslate(-tex2d.width / 2,
-tex2d.height / 2, 0f);
}
}
GLEx.GL.Submit(cache.m_type, cache.batchCount, cache.m_cache, cache.m_quadIndices, null);
gl.GLPopMatrix();
}
public GLCache GetLastCache()
{
return m_lastCache;
}
public GLCache NewGLCache(bool Reset)
{
return m_lastCache = new GLCache(this, Reset);
}
public GLCache NewGLCache()
{
return NewGLCache(false);
}
public void DisposeLastCache()
{
if (m_lastCache != null)
{
m_lastCache.Dispose();
m_lastCache = null;
}
}
public void DestoryAll()
{
Dispose();
Destroy();
}
public void Destroy()
{
if (textureBuffer != null)
{
textureBuffer.Destroy();
}
}
public void Dispose()
{
this.batchCount = 0;
this.useBegin = false;
this.isLocked = true;
this.vectors = null;
this.colors = null;
this.coords = null;
if (glbase != null)
{
this.glbase.Dispose();
this.glbase = null;
}
if (m_lastCache != null)
{
m_lastCache.Dispose();
m_lastCache = null;
}
if (image_colors != null)
{
image_colors = null;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace com.google.zxing.qrcode.encoder
{
using EncodeHintType = com.google.zxing.EncodeHintType;
using WriterException = com.google.zxing.WriterException;
using BitArray = com.google.zxing.common.BitArray;
using CharacterSetECI = com.google.zxing.common.CharacterSetECI;
using GenericGF = com.google.zxing.common.reedsolomon.GenericGF;
using ReedSolomonEncoder = com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
using Mode = com.google.zxing.qrcode.decoder.Mode;
using Version = com.google.zxing.qrcode.decoder.Version;
using com.google.zxing.common;
/// <summary>
/// @author satorux@google.com (Satoru Takabayashi) - creator
/// @author dswitkin@google.com (Daniel Switkin) - ported from C++
/// </summary>
public sealed class Encoder
{
// The original table is defined in the table 5 of JISX0510:2004 (p.19).
private static readonly int[] ALPHANUMERIC_TABLE = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1};
internal const string DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
private Encoder()
{
}
// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
private static int calculateMaskPenalty(ByteMatrix matrix)
{
return MaskUtil.applyMaskPenaltyRule1(matrix) + MaskUtil.applyMaskPenaltyRule2(matrix) + MaskUtil.applyMaskPenaltyRule3(matrix) + MaskUtil.applyMaskPenaltyRule4(matrix);
}
/// <summary>
/// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
/// internally by chooseMode(). On success, store the result in "qrCode".
///
/// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
/// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
/// strong error correction for this purpose.
///
/// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
/// with which clients can specify the encoding mode. For now, we don't need the functionality.
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static QRCode encode(String content, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel) throws com.google.zxing.WriterException
public static QRCode encode(string content, ErrorCorrectionLevel ecLevel)
{
return encode(content, ecLevel, null);
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static QRCode encode(String content, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel, java.util.Map<com.google.zxing.EncodeHintType,?> hints) throws com.google.zxing.WriterException
public static QRCode encode(string content, ErrorCorrectionLevel ecLevel, IDictionary<EncodeHintType, object> hints)
{
// Determine what character encoding has been specified by the caller, if any
//string encoding = hints == null ? null : (string) hints[EncodeHintType.CHARACTER_SET];
string encoding = null;
if (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET))
{
encoding = (string) hints[EncodeHintType.CHARACTER_SET];
}
if (encoding == null)
{
encoding = DEFAULT_BYTE_MODE_ENCODING;
}
// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
// multiple modes / segments even if that were more efficient. Twould be nice.
Mode mode = chooseMode(content, encoding);
// This will store the header information, like mode and
// length, as well as "header" segments like an ECI segment.
BitArray headerBits = new BitArray();
// Append ECI segment if applicable
if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding))
{
CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
if (eci != null)
{
appendECI(eci, headerBits);
}
}
// (With ECI in place,) Write the mode marker
appendModeInfo(mode, headerBits);
// Collect data within the main segment, separately, to count its size if needed. Don't add it to
// main payload yet.
BitArray dataBits = new BitArray();
appendBytes(content, mode, dataBits, encoding);
// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
int provisionalBitsNeeded = headerBits.Size + mode.getCharacterCountBits(Version.getVersionForNumber(1)) + dataBits.Size;
Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);
// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
int bitsNeeded = headerBits.Size + mode.getCharacterCountBits(provisionalVersion) + dataBits.Size;
Version version = chooseVersion(bitsNeeded, ecLevel);
BitArray headerAndDataBits = new BitArray();
headerAndDataBits.appendBitArray(headerBits);
// Find "length" of main segment and write it
int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
appendLengthInfo(numLetters, version, mode, headerAndDataBits);
// Put data together into the overall payload
headerAndDataBits.appendBitArray(dataBits);
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords;
// Terminate the bits properly.
terminateBits(numDataBytes, headerAndDataBits);
// Interleave data bits with error correction code.
BitArray finalBits = interleaveWithECBytes(headerAndDataBits, version.TotalCodewords, numDataBytes, ecBlocks.NumBlocks);
QRCode qrCode = new QRCode();
qrCode.ECLevel = ecLevel;
qrCode.Mode = mode;
qrCode.Version = version;
// Choose the mask pattern and set to "qrCode".
int dimension = version.DimensionForVersion;
ByteMatrix matrix = new ByteMatrix(dimension, dimension);
int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
qrCode.MaskPattern = maskPattern;
// Build the matrix and set it to "qrCode".
MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
qrCode.Matrix = matrix;
return qrCode;
}
/// <returns> the code point of the table used in alphanumeric mode or
/// -1 if there is no corresponding code in the table. </returns>
internal static int getAlphanumericCode(int code)
{
if (code < ALPHANUMERIC_TABLE.Length)
{
return ALPHANUMERIC_TABLE[code];
}
return -1;
}
public static Mode chooseMode(string content)
{
return chooseMode(content, null);
}
/// <summary>
/// Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
/// if it is Shift_JIS, and the input is only double-byte Kanji, then we return <seealso cref="Mode#KANJI"/>.
/// </summary>
private static Mode chooseMode(string content, string encoding)
{
if ("Shift_JIS".Equals(encoding))
{
// Choose Kanji mode if all input are double-byte characters
return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE;
}
bool hasNumeric = false;
bool hasAlphanumeric = false;
for (int i = 0; i < content.Length; ++i)
{
char c = content[i];
if (c >= '0' && c <= '9')
{
hasNumeric = true;
}
else if (getAlphanumericCode(c) != -1)
{
hasAlphanumeric = true;
}
else
{
return Mode.BYTE;
}
}
if (hasAlphanumeric)
{
return Mode.ALPHANUMERIC;
}
if (hasNumeric)
{
return Mode.NUMERIC;
}
return Mode.BYTE;
}
private static bool isOnlyDoubleByteKanji(string content)
{
sbyte[] bytes;
try
{
//bytes = content.getBytes("Shift_JIS");
Encoding en = Encoding.GetEncoding("Shift_JIS");
bytes = en.GetBytes(content).ToSBytes();
}
catch (System.IO.IOException)
{
return false;
}
int length = bytes.Length;
if (length % 2 != 0)
{
return false;
}
for (int i = 0; i < length; i += 2)
{
int byte1 = bytes[i] & 0xFF;
if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB))
{
return false;
}
}
return true;
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static int chooseMaskPattern(com.google.zxing.common.BitArray bits, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel, com.google.zxing.qrcode.decoder.Version version, ByteMatrix matrix) throws com.google.zxing.WriterException
private static int chooseMaskPattern(BitArray bits, ErrorCorrectionLevel ecLevel, Version version, ByteMatrix matrix)
{
int minPenalty = int.MaxValue; // Lower penalty is better.
int bestMaskPattern = -1;
// We try all mask patterns to choose the best one.
for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++)
{
MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
int penalty = calculateMaskPenalty(matrix);
if (penalty < minPenalty)
{
minPenalty = penalty;
bestMaskPattern = maskPattern;
}
}
return bestMaskPattern;
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static com.google.zxing.qrcode.decoder.Version chooseVersion(int numInputBits, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel) throws com.google.zxing.WriterException
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel)
{
// In the following comments, we use numbers of Version 7-H.
for (int versionNum = 1; versionNum <= 40; versionNum++)
{
Version version = Version.getVersionForNumber(versionNum);
// numBytes = 196
int numBytes = version.TotalCodewords;
// getNumECBytes = 130
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numEcBytes = ecBlocks.TotalECCodewords;
// getNumDataBytes = 196 - 130 = 66
int numDataBytes = numBytes - numEcBytes;
int totalInputBytes = (numInputBits + 7) / 8;
if (numDataBytes >= totalInputBytes)
{
return version;
}
}
throw new WriterException("Data too big");
}
/// <summary>
/// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void terminateBits(int numDataBytes, com.google.zxing.common.BitArray bits) throws com.google.zxing.WriterException
internal static void terminateBits(int numDataBytes, BitArray bits)
{
int capacity = numDataBytes << 3;
if (bits.Size > capacity)
{
throw new WriterException("data bits cannot fit in the QR Code" + bits.Size + " > " + capacity);
}
for (int i = 0; i < 4 && bits.Size < capacity; ++i)
{
bits.appendBit(false);
}
// Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
// If the last byte isn't 8-bit aligned, we'll add padding bits.
int numBitsInLastByte = bits.Size & 0x07;
if (numBitsInLastByte > 0)
{
for (int i = numBitsInLastByte; i < 8; i++)
{
bits.appendBit(false);
}
}
// If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
int numPaddingBytes = numDataBytes - bits.SizeInBytes;
for (int i = 0; i < numPaddingBytes; ++i)
{
bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8);
}
if (bits.Size != capacity)
{
throw new WriterException("Bits size does not equal capacity");
}
}
/// <summary>
/// Get number of data bytes and number of error correction bytes for block id "blockID". Store
/// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
/// JISX0510:2004 (p.30)
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) throws com.google.zxing.WriterException
internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock)
{
if (blockID >= numRSBlocks)
{
throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
// numRsBlocksInGroup1 = 5 - 1 = 4
int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
// numTotalBytesInGroup1 = 196 / 5 = 39
int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
// numTotalBytesInGroup2 = 39 + 1 = 40
int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
// numDataBytesInGroup1 = 66 / 5 = 13
int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
// numDataBytesInGroup2 = 13 + 1 = 14
int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
// numEcBytesInGroup1 = 39 - 13 = 26
int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
// numEcBytesInGroup2 = 40 - 14 = 26
int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
// Sanity checks.
// 26 = 26
if (numEcBytesInGroup1 != numEcBytesInGroup2)
{
throw new WriterException("EC bytes mismatch");
}
// 5 = 4 + 1.
if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2)
{
throw new WriterException("RS blocks mismatch");
}
// 196 = (13 + 26) * 4 + (14 + 26) * 1
if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2))
{
throw new WriterException("Total bytes mismatch");
}
if (blockID < numRsBlocksInGroup1)
{
numDataBytesInBlock[0] = numDataBytesInGroup1;
numECBytesInBlock[0] = numEcBytesInGroup1;
}
else
{
numDataBytesInBlock[0] = numDataBytesInGroup2;
numECBytesInBlock[0] = numEcBytesInGroup2;
}
}
/// <summary>
/// Interleave "bits" with corresponding error correction bytes. On success, store the result in
/// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static com.google.zxing.common.BitArray interleaveWithECBytes(com.google.zxing.common.BitArray bits, int numTotalBytes, int numDataBytes, int numRSBlocks) throws com.google.zxing.WriterException
internal static BitArray interleaveWithECBytes(BitArray bits, int numTotalBytes, int numDataBytes, int numRSBlocks)
{
// "bits" must have "getNumDataBytes" bytes of data.
if (bits.SizeInBytes != numDataBytes)
{
throw new WriterException("Number of bits and data bytes does not match");
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
// store the divided data bytes blocks and error correction bytes blocks into "blocks".
int dataBytesOffset = 0;
int maxNumDataBytes = 0;
int maxNumEcBytes = 0;
// Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
ICollection<BlockPair> blocks = new List<BlockPair>(numRSBlocks);
for (int i = 0; i < numRSBlocks; ++i)
{
int[] numDataBytesInBlock = new int[1];
int[] numEcBytesInBlock = new int[1];
getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock);
int size = numDataBytesInBlock[0];
sbyte[] dataBytes = new sbyte[size];
bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size);
sbyte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
blocks.Add(new BlockPair(dataBytes, ecBytes));
maxNumDataBytes = Math.Max(maxNumDataBytes, size);
maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.Length);
dataBytesOffset += numDataBytesInBlock[0];
}
if (numDataBytes != dataBytesOffset)
{
throw new WriterException("Data bytes does not match offset");
}
BitArray result = new BitArray();
// First, place data blocks.
for (int i = 0; i < maxNumDataBytes; ++i)
{
foreach (BlockPair block in blocks)
{
sbyte[] dataBytes = block.DataBytes;
if (i < dataBytes.Length)
{
result.appendBits(dataBytes[i], 8);
}
}
}
// Then, place error correction blocks.
for (int i = 0; i < maxNumEcBytes; ++i)
{
foreach (BlockPair block in blocks)
{
sbyte[] ecBytes = block.ErrorCorrectionBytes;
if (i < ecBytes.Length)
{
result.appendBits(ecBytes[i], 8);
}
}
}
if (numTotalBytes != result.SizeInBytes) // Should be same.
{
throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.SizeInBytes + " differ.");
}
return result;
}
internal static sbyte[] generateECBytes(sbyte[] dataBytes, int numEcBytesInBlock)
{
int numDataBytes = dataBytes.Length;
int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
for (int i = 0; i < numDataBytes; i++)
{
toEncode[i] = dataBytes[i] & 0xFF;
}
(new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256)).encode(toEncode, numEcBytesInBlock);
sbyte[] ecBytes = new sbyte[numEcBytesInBlock];
for (int i = 0; i < numEcBytesInBlock; i++)
{
ecBytes[i] = (sbyte) toEncode[numDataBytes + i];
}
return ecBytes;
}
/// <summary>
/// Append mode info. On success, store the result in "bits".
/// </summary>
internal static void appendModeInfo(Mode mode, BitArray bits)
{
bits.appendBits(mode.Bits, 4);
}
/// <summary>
/// Append length info. On success, store the result in "bits".
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void appendLengthInfo(int numLetters, com.google.zxing.qrcode.decoder.Version version, com.google.zxing.qrcode.decoder.Mode mode, com.google.zxing.common.BitArray bits) throws com.google.zxing.WriterException
internal static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits)
{
int numBits = mode.getCharacterCountBits(version);
if (numLetters >= (1 << numBits))
{
throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1));
}
bits.appendBits(numLetters, numBits);
}
/// <summary>
/// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void appendBytes(String content, com.google.zxing.qrcode.decoder.Mode mode, com.google.zxing.common.BitArray bits, String encoding) throws com.google.zxing.WriterException
internal static void appendBytes(string content, Mode mode, BitArray bits, string encoding)
{
if (mode == Mode.NUMERIC)
{
appendNumericBytes(content, bits);
}
else if (mode == Mode.ALPHANUMERIC)
{
appendAlphanumericBytes(content, bits);
}
else if (mode == Mode.BYTE)
{
append8BitBytes(content, bits, encoding);
}
else if (mode == Mode.KANJI)
{
appendKanjiBytes(content, bits);
} else
{
throw new WriterException("Invalid mode: " + mode);
}
//switch (mode)
//{
// case NUMERIC:
// appendNumericBytes(content, bits);
// break;
// case ALPHANUMERIC:
// appendAlphanumericBytes(content, bits);
// break;
// case BYTE:
// append8BitBytes(content, bits, encoding);
// break;
// case KANJI:
// appendKanjiBytes(content, bits);
// break;
// default:
// throw new WriterException("Invalid mode: " + mode);
//}
}
internal static void appendNumericBytes(string content, BitArray bits)
{
int length = content.Length;
int i = 0;
while (i < length)
{
int num1 = content[i] - '0';
if (i + 2 < length)
{
// Encode three numeric letters in ten bits.
int num2 = content[i + 1] - '0';
int num3 = content[i + 2] - '0';
bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
i += 3;
}
else if (i + 1 < length)
{
// Encode two numeric letters in seven bits.
int num2 = content[i + 1] - '0';
bits.appendBits(num1 * 10 + num2, 7);
i += 2;
}
else
{
// Encode one numeric letter in four bits.
bits.appendBits(num1, 4);
i++;
}
}
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void appendAlphanumericBytes(CharSequence content, com.google.zxing.common.BitArray bits) throws com.google.zxing.WriterException
internal static void appendAlphanumericBytes(string content, BitArray bits)
{
int length = content.Length;
int i = 0;
while (i < length)
{
int code1 = getAlphanumericCode(content[i]);
if (code1 == -1)
{
throw new WriterException();
}
if (i + 1 < length)
{
int code2 = getAlphanumericCode(content[i + 1]);
if (code2 == -1)
{
throw new WriterException();
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits(code1 * 45 + code2, 11);
i += 2;
}
else
{
// Encode one alphanumeric letter in six bits.
bits.appendBits(code1, 6);
i++;
}
}
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void append8BitBytes(String content, com.google.zxing.common.BitArray bits, String encoding) throws com.google.zxing.WriterException
internal static void append8BitBytes(string content, BitArray bits, string encoding)
{
sbyte[] bytes;
try
{
//bytes = content.getBytes(encoding);
Encoding en = Encoding.GetEncoding(encoding);
bytes = en.GetBytes(content).ToSBytes();
}
catch (System.IO.IOException uee)
{
throw new WriterException(uee);
}
foreach (sbyte b in bytes)
{
bits.appendBits(b, 8);
}
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static void appendKanjiBytes(String content, com.google.zxing.common.BitArray bits) throws com.google.zxing.WriterException
internal static void appendKanjiBytes(string content, BitArray bits)
{
sbyte[] bytes;
try
{
//bytes = content.getBytes("Shift_JIS");
Encoding en = Encoding.GetEncoding("Shift_JIS");
bytes = en.GetBytes(content).ToSBytes();
}
catch (System.IO.IOException uee)
{
throw new WriterException(uee);
}
int length = bytes.Length;
for (int i = 0; i < length; i += 2)
{
int byte1 = bytes[i] & 0xFF;
int byte2 = bytes[i + 1] & 0xFF;
int code = (byte1 << 8) | byte2;
int subtracted = -1;
if (code >= 0x8140 && code <= 0x9ffc)
{
subtracted = code - 0x8140;
}
else if (code >= 0xe040 && code <= 0xebbf)
{
subtracted = code - 0xc140;
}
if (subtracted == -1)
{
throw new WriterException("Invalid byte sequence");
}
int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded, 13);
}
}
private static void appendECI(CharacterSetECI eci, BitArray bits)
{
bits.appendBits(Mode.ECI.Bits, 4);
// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.Value, 8);
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Test
{
public class ElementAtPartitionerTests
{
//
// ElementAt and ElementAtOrDefault
//
[Fact]
public static void RunElementAtTest1()
{
RunElementAtTest1Core(1024, 512);
RunElementAtTest1Core(0, 512);
RunElementAtTest1Core(1, 512);
RunElementAtTest1Core(1024, 1024);
RunElementAtTest1Core(1024 * 1024, 1024);
}
[Fact]
public static void RunElementAtOrDefaultTest1()
{
RunElementAtOrDefaultTest1Core(1024, 512);
RunElementAtOrDefaultTest1Core(0, 512);
RunElementAtOrDefaultTest1Core(1, 512);
RunElementAtOrDefaultTest1Core(1024, 1024);
RunElementAtOrDefaultTest1Core(1024 * 1024, 1024);
}
private static void RunElementAtTest1Core(int size, int elementAt)
{
string methodInfo = string.Format("RunElementAtTest1(size={0}, elementAt={1})", size, elementAt);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
bool expectExcept = elementAt >= size;
try
{
int q = ints.AsParallel().ElementAt(elementAt);
if (expectExcept)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Expected an exception, but didn't get one"));
}
else
{
if (q != ints[elementAt])
{
Assert.True(false, string.Format(methodInfo + " > FAILED. Expected return value of {0}, saw {1} instead", ints[elementAt], q));
}
}
}
catch (ArgumentOutOfRangeException ioex)
{
if (!expectExcept)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Got exception, but didn't expect it {0}", ioex));
}
}
}
private static void RunElementAtOrDefaultTest1Core(int size, int elementAt)
{
string methodInfo = string.Format("RunElementAtOrDefaultTest1(size={0}, elementAt={1})", size, elementAt);
int[] ints = new int[size];
for (int i = 0; i < size; i++) ints[i] = i;
int q = ints.AsParallel().ElementAtOrDefault(elementAt);
int expectValue = (elementAt >= size) ? default(int) : ints[elementAt];
if (q != expectValue)
{
Assert.True(false, string.Format(methodInfo + " > Expected return value of {0}, saw {1} instead", expectValue, q));
}
}
//
// Custom Partitioner tests
//
[Fact]
public static void RunPartitionerTest1()
{
RunPartitionerTest1Core(0);
RunPartitionerTest1Core(1);
RunPartitionerTest1Core(999);
RunPartitionerTest1Core(1024);
}
[Fact]
public static void RunOrderablePartitionerTest1()
{
RunOrderablePartitionerTest1Core(0, true, true);
RunOrderablePartitionerTest1Core(1, true, true);
RunOrderablePartitionerTest1Core(999, true, true);
RunOrderablePartitionerTest1Core(1024, true, true);
RunOrderablePartitionerTest1Core(1024, false, true);
RunOrderablePartitionerTest1Core(1024, true, false);
RunOrderablePartitionerTest1Core(1024, false, false);
}
private static void RunPartitionerTest1Core(int size)
{
string methodInfo = string.Format("RunPartitionerTest1(size={0})", size);
int[] arr = Enumerable.Range(0, size).ToArray();
Partitioner<int> partitioner = new ListPartitioner<int>(arr);
// Without ordering:
int[] res = partitioner.AsParallel().Select(x => -x).ToArray().Select(x => -x).OrderBy(x => x).ToArray();
if (!res.OrderBy(i => i).SequenceEqual(arr))
{
Assert.True(false, string.Format(methodInfo + " > Failure: Incorrect output {0}", String.Join(" ", res.Select(x => x.ToString()).ToArray())));
}
// With ordering, expect an exception:
bool gotException = false;
try
{
partitioner.AsParallel().AsOrdered().Select(x => -x).ToArray();
}
catch (InvalidOperationException)
{
gotException = true;
}
if (!gotException)
{
Assert.True(false, string.Format(methodInfo + " > Failure: Expected an exception, but didn't get one"));
}
}
private static void RunOrderablePartitionerTest1Core(int size, bool keysIncreasingInEachPartition, bool keysNormalized)
{
string methodInfo = string.Format("RunOrderablePartitionerTest1(size={0}, keysIncreasingInEachPartition={1}, keysNormalized={2})",
size, keysIncreasingInEachPartition, keysNormalized);
int[] arr = Enumerable.Range(0, size).ToArray();
Partitioner<int> partitioner = new OrderableListPartitioner<int>(arr, keysIncreasingInEachPartition, keysNormalized);
// Without ordering:
int[] res = partitioner.AsParallel().Select(x => -x).ToArray().Select(x => -x).OrderBy(x => x).ToArray();
if (!res.OrderBy(i => i).SequenceEqual(arr))
{
Assert.True(false, string.Format(methodInfo + " > Failure: Incorrect output"));
}
// With ordering:
int[] resOrdered = partitioner.AsParallel().AsOrdered().Select(x => -x).ToArray().Select(x => -x).ToArray();
if (!resOrdered.SequenceEqual(arr))
{
Assert.True(false, string.Format(methodInfo + " > Failure: Incorrect output"));
}
}
//
// This query used to assert because PLINQ would call MoveNext twice on an enumerator from the partitioner.
// This issue should now be fixed from both ends - PLINQ should not call MoveNext twice, and PartitionerStatic should not assert
// on an extra MoveNext.
//
[Fact]
public static void RunPartitionerTest_Min()
{
try
{
Partitioner.Create(Enumerable.Range(0, 1))
.AsParallel()
.Min();
}
catch (Exception ex)
{
Assert.True(false, string.Format("RunPartitionerTest_Min: FAILED. Exception thrown: " + ex));
}
}
// An unordered partitioner for lists, used by the partitioner tests.
private class ListPartitioner<TSource> : Partitioner<TSource>
{
private OrderablePartitioner<TSource> _partitioner;
public ListPartitioner(IList<TSource> source)
{
_partitioner = new OrderableListPartitioner<TSource>(source, true, true);
}
public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
{
return _partitioner.GetPartitions(partitionCount);
}
public override IEnumerable<TSource> GetDynamicPartitions()
{
return _partitioner.GetDynamicPartitions();
}
}
//
// An orderable partitioner for lists, used by the partitioner tests
//
private class OrderableListPartitioner<TSource> : OrderablePartitioner<TSource>
{
private readonly IList<TSource> _input;
private readonly bool _keysOrderedInEachPartition;
private readonly bool _keysNormalized;
public OrderableListPartitioner(IList<TSource> input, bool keysOrderedInEachPartition, bool keysNormalized)
: base(keysOrderedInEachPartition, false, keysNormalized)
{
_input = input;
_keysOrderedInEachPartition = keysOrderedInEachPartition;
_keysNormalized = keysNormalized;
}
public override IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount)
{
IEnumerable<KeyValuePair<long, TSource>> dynamicPartitions = GetOrderableDynamicPartitions();
IEnumerator<KeyValuePair<long, TSource>>[] partitions = new IEnumerator<KeyValuePair<long, TSource>>[partitionCount];
for (int i = 0; i < partitionCount; i++)
{
partitions[i] = dynamicPartitions.GetEnumerator();
}
return partitions;
}
public override IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions()
{
return new ListDynamicPartitions(_input, _keysOrderedInEachPartition, _keysNormalized);
}
private class ListDynamicPartitions : IEnumerable<KeyValuePair<long, TSource>>
{
private IList<TSource> _input;
private int _pos = 0;
private bool _keysOrderedInEachPartition;
private bool _keysNormalized;
internal ListDynamicPartitions(IList<TSource> input, bool keysOrderedInEachPartition, bool keysNormalized)
{
_input = input;
_keysOrderedInEachPartition = keysOrderedInEachPartition;
_keysNormalized = keysNormalized;
}
public IEnumerator<KeyValuePair<long, TSource>> GetEnumerator()
{
while (true)
{
int elemIndex = Interlocked.Increment(ref _pos) - 1;
if (elemIndex >= _input.Count)
{
yield break;
}
if (!_keysOrderedInEachPartition)
{
elemIndex = _input.Count - 1 - elemIndex;
}
long key = _keysNormalized ? elemIndex : (elemIndex * 2);
yield return new KeyValuePair<long, TSource>(key, _input[elemIndex]);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<long, TSource>>)this).GetEnumerator();
}
}
}
}
}
| |
using UnityEngine;
namespace Pathfinding {
/** Extended Path.
* \ingroup paths
* This is the same as a standard path but it is possible to customize when the target should be considered reached.
* Can be used to for example signal a path as complete when it is within a specific distance from the target.
*
* \note More customizations does make it slower to calculate than an ABPath but not by very much.
* \astarpro
*
* \see Pathfinding.PathEndingCondition
*/
public class XPath : ABPath {
/**
* Ending Condition for the path.
* The ending condition determines when the path has been completed.
* Can be used to for example signal a path as complete when it is within a specific distance from the target.
*
* If ending conditions are used that are not centered around the endpoint of the path
* you should also switch the #heuristic to None to make sure that optimal paths are still found.
* This has quite a large performance impact so you might want to try to run it with the default
* heuristic and see if the path is optimal in enough cases.
*/
public PathEndingCondition endingCondition;
public XPath () {}
public new static XPath Construct (Vector3 start, Vector3 end, OnPathDelegate callback = null) {
var p = PathPool.GetPath<XPath>();
p.Setup(start, end, callback);
p.endingCondition = new ABPathEndingCondition(p);
return p;
}
protected override void Reset () {
base.Reset();
endingCondition = null;
}
#if !ASTAR_NO_GRID_GRAPH
protected override bool EndPointGridGraphSpecialCase (GraphNode endNode) {
// Don't use the grid graph special case for this path type
return false;
}
#endif
/** The start node need to be special cased and checked here if it is a valid target */
protected override void CompletePathIfStartIsValidTarget () {
var pNode = pathHandler.GetPathNode(startNode);
if (endingCondition.TargetFound(pNode)) {
ChangeEndNode(startNode);
Trace(pNode);
CompleteState = PathCompleteState.Complete;
}
}
/** Changes the #endNode to \a target and resets some temporary flags on the previous node.
* Also sets #endPoint to the position of \a target.
*/
void ChangeEndNode (GraphNode target) {
// Reset temporary flags on the previous end node, otherwise they might be
// left in the graph and cause other paths to calculate paths incorrectly
if (endNode != null && endNode != startNode) {
var pathNode = pathHandler.GetPathNode(endNode);
pathNode.flag1 = pathNode.flag2 = false;
}
endNode = target;
endPoint = (Vector3)target.position;
}
protected override void CalculateStep (long targetTick) {
int counter = 0;
// Continue to search as long as we haven't encountered an error and we haven't found the target
while (CompleteState == PathCompleteState.NotCalculated) {
searchedNodes++;
// Close the current node, if the current node is the target node then the path is finished
if (endingCondition.TargetFound(currentR)) {
CompleteState = PathCompleteState.Complete;
break;
}
// Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open(this, currentR, pathHandler);
// Any nodes left to search?
if (pathHandler.heap.isEmpty) {
FailWithError("Searched whole area but could not find target");
return;
}
// Select the node with the lowest F score and remove it from the open list
currentR = pathHandler.heap.Remove();
// Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
// Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (System.DateTime.UtcNow.Ticks >= targetTick) {
//Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
if (searchedNodes > 1000000) {
throw new System.Exception("Probable infinite loop. Over 1,000,000 nodes searched");
}
}
counter++;
}
if (CompleteState == PathCompleteState.Complete) {
ChangeEndNode(currentR.node);
Trace(currentR);
}
}
}
/** Customized ending condition for a path.
* This class can be used to implement a custom ending condition for e.g an Pathfinding.XPath.
* Inherit from this class and override the #TargetFound function to implement you own ending condition logic.
*
* For example, you might want to create an Ending Condition which stops when a node is close enough to a given point.
* Then what you do is that you create your own class, let's call it MyEndingCondition and override the function TargetFound to specify our own logic.
* We want to inherit from ABPathEndingCondition because only ABPaths have end points defined.
*
* \code
* public class MyEndingCondition : ABPathEndingCondition {
*
* // Maximum world distance to the target node before terminating the path
* public float maxDistance = 10;
*
* // Reuse the constructor in the superclass
* public MyEndingCondition (ABPath p) : base (p) {}
*
* public override bool TargetFound (PathNode node) {
* return ((Vector3)node.node.position - abPath.originalEndPoint).sqrMagnitude <= maxDistance*maxDistance;
* }
* }
* \endcode
*
* One part at a time. We need to cast the node's position to a Vector3 since internally, it is stored as an integer coordinate (Int3).
* Then we subtract the Pathfinding.Path.originalEndPoint from it to get their difference.
* The original end point is always the exact point specified when calling the path.
* As a last step we check the squared magnitude (squared distance, it is much faster than the non-squared distance) and check if it is lower or equal to our maxDistance squared.\n
* There you have it, it is as simple as that.
* Then you simply assign it to the \a endingCondition variable on, for example an XPath which uses the EndingCondition.
*
* \code
* XPath myXPath = XPath.Construct(startPoint, endPoint);
* MyEndingCondition ec = new MyEndingCondition();
* ec.maxDistance = 100; // Or some other value
* myXPath.endingCondition = ec;
*
* // Calculate the path!
* seeker.StartPath (ec);
* \endcode
*
* Where \a seeker is a #Seeker component, and \a myXPath is an Pathfinding.XPath.\n
*
* \note The above was written without testing. I hope I haven't made any mistakes, if you try it out, and it doesn't seem to work. Please post a comment in the forums.
*
* \version Method structure changed in 3.2
* \version Updated in version 3.6.8
*
* \see Pathfinding.XPath
* \see Pathfinding.ConstantPath
*
*/
public abstract class PathEndingCondition {
/** Path which this ending condition is used on */
protected Path path;
protected PathEndingCondition () {}
public PathEndingCondition (Path p) {
if (p == null) throw new System.ArgumentNullException("p");
this.path = p;
}
/** Has the ending condition been fulfilled.
* \param node The current node.
*/
public abstract bool TargetFound (PathNode node);
}
/** Ending condition which emulates the default one for the ABPath */
public class ABPathEndingCondition : PathEndingCondition {
/**
* Path which this ending condition is used on.
* Same as #path but downcasted to ABPath
*/
protected ABPath abPath;
public ABPathEndingCondition (ABPath p) {
if (p == null) throw new System.ArgumentNullException("p");
abPath = p;
path = p;
}
/** Has the ending condition been fulfilled.
* \param node The current node.
* This is per default the same as asking if \a node == \a p.endNode */
public override bool TargetFound (PathNode node) {
return node.node == abPath.endNode;
}
}
/** Ending condition which stops a fixed distance from the target point */
public class EndingConditionProximity : ABPathEndingCondition {
/** Maximum world distance to the target node before terminating the path */
public float maxDistance = 10;
public EndingConditionProximity (ABPath p, float maxDistance) : base(p) {
this.maxDistance = maxDistance;
}
public override bool TargetFound (PathNode node) {
return ((Vector3)node.node.position - abPath.originalEndPoint).sqrMagnitude <= maxDistance*maxDistance;
}
}
}
| |
// 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.Buffers.Text
{
public static partial class Utf8Parser
{
/// <summary>
/// Parses a Guid at the start of a Utf8 string.
/// </summary>
/// <param name="source">The Utf8 string to parse</param>
/// <param name="value">Receives the parsed value</param>
/// <param name="bytesConsumed">On a successful parse, receives the length in bytes of the substring that was parsed </param>
/// <param name="standardFormat">Expected format of the Utf8 string</param>
/// <returns>
/// true for success. "bytesConsumed" contains the length in bytes of the substring that was parsed.
/// false if the string was not syntactically valid or an overflow or underflow occurred. "bytesConsumed" is set to 0.
/// </returns>
/// <remarks>
/// Formats supported:
/// D (default) nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn
/// B {nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn}
/// P (nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn)
/// N nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryParse(ReadOnlySpan<byte> source, out Guid value, out int bytesConsumed, char standardFormat = default)
{
switch (standardFormat)
{
case default(char):
case 'D':
return TryParseGuidCore(source, false, ' ', ' ', out value, out bytesConsumed);
case 'B':
return TryParseGuidCore(source, true, '{', '}', out value, out bytesConsumed);
case 'P':
return TryParseGuidCore(source, true, '(', ')', out value, out bytesConsumed);
case 'N':
return TryParseGuidN(source, out value, out bytesConsumed);
default:
return ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed);
}
}
// nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn (not very Guid-like, but the format is what it is...)
private static bool TryParseGuidN(ReadOnlySpan<byte> text, out Guid value, out int bytesConsumed)
{
if (text.Length < 32)
{
value = default;
bytesConsumed = 0;
return false;
}
if (!TryParseUInt32X(text.Slice(0, 8), out uint i1, out int justConsumed) || justConsumed != 8)
{
value = default;
bytesConsumed = 0;
return false; // 8 digits
}
if (!TryParseUInt16X(text.Slice(8, 4), out ushort i2, out justConsumed) || justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
if (!TryParseUInt16X(text.Slice(12, 4), out ushort i3, out justConsumed) || justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
if (!TryParseUInt16X(text.Slice(16, 4), out ushort i4, out justConsumed) || justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
if (!TryParseUInt64X(text.Slice(20), out ulong i5, out justConsumed) || justConsumed != 12)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
bytesConsumed = 32;
value = new Guid((int)i1, (short)i2, (short)i3, (byte)(i4 >> 8), (byte)i4,
(byte)(i5 >> 40), (byte)(i5 >> 32), (byte)(i5 >> 24), (byte)(i5 >> 16), (byte)(i5 >> 8), (byte)i5);
return true;
}
// {8-4-4-4-12}, where number is the number of hex digits, and {/} are ends.
private static bool TryParseGuidCore(ReadOnlySpan<byte> source, bool ends, char begin, char end, out Guid value, out int bytesConsumed)
{
int expectedCodingUnits = 36 + (ends ? 2 : 0); // 32 hex digits + 4 delimiters + 2 optional ends
if (source.Length < expectedCodingUnits)
{
value = default;
bytesConsumed = 0;
return false;
}
if (ends)
{
if (source[0] != begin)
{
value = default;
bytesConsumed = 0;
return false;
}
source = source.Slice(1); // skip begining
}
if (!TryParseUInt32X(source, out uint i1, out int justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 8)
{
value = default;
bytesConsumed = 0;
return false; // 8 digits
}
if (source[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
source = source.Slice(9); // justConsumed + 1 for delimiter
if (!TryParseUInt16X(source, out ushort i2, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // 4 digits
}
if (source[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
source = source.Slice(5); // justConsumed + 1 for delimiter
if (!TryParseUInt16X(source, out ushort i3, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // 4 digits
}
if (source[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
source = source.Slice(5); // justConsumed + 1 for delimiter
if (!TryParseUInt16X(source, out ushort i4, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // 4 digits
}
if (source[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
source = source.Slice(5);// justConsumed + 1 for delimiter
if (!TryParseUInt64X(source, out ulong i5, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 12)
{
value = default;
bytesConsumed = 0;
return false; // 12 digits
}
if (ends && source[justConsumed] != end)
{
value = default;
bytesConsumed = 0;
return false;
}
bytesConsumed = expectedCodingUnits;
value = new Guid((int)i1, (short)i2, (short)i3, (byte)(i4 >> 8), (byte)i4,
(byte)(i5 >> 40), (byte)(i5 >> 32), (byte)(i5 >> 24), (byte)(i5 >> 16), (byte)(i5 >> 8), (byte)i5);
return true;
}
}
}
| |
using PlayFab.PfEditor.EditorModels;
using PlayFab.PfEditor.Json;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
[InitializeOnLoad]
public class PlayFabEditorDataService : UnityEditor.Editor
{
#region EditorPref data classes
public class PlayFab_SharedSettingsProxy
{
private readonly Dictionary<string, PropertyInfo> _settingProps = new Dictionary<string, PropertyInfo>();
private readonly string[] expectedProps = new[] { "titleid", "developersecretkey", "requesttype", "requestkeepalive", "requesttimeout" };
public string TitleId { get { return Get<string>("titleid"); } set { Set("titleid", value); } }
public string DeveloperSecretKey { get { return Get<string>("developersecretkey"); } set { Set("developersecretkey", value); } }
public PlayFabEditorSettings.WebRequestType WebRequestType { get { return Get<PlayFabEditorSettings.WebRequestType>("requesttype"); } set { Set("requesttype", (int)value); } }
public bool KeepAlive { get { return Get<bool>("requestkeepalive"); } set { Set("requestkeepalive", value); } }
public int TimeOut { get { return Get<int>("requesttimeout"); } set { Set("requesttimeout", value); } }
public PlayFab_SharedSettingsProxy()
{
LoadProps();
}
private PropertyInfo LoadProps(string name = null)
{
var playFabSettingsType = PlayFabEditorSDKTools.GetPlayFabSettings();
if (playFabSettingsType == null)
return null;
if (string.IsNullOrEmpty(name))
{
for (var i = 0; i < expectedProps.Length; i++)
LoadProps(expectedProps[i]);
return null;
}
else
{
var eachProperty = playFabSettingsType.GetProperty(name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);
if (eachProperty != null)
_settingProps[name.ToLowerInvariant()] = eachProperty;
return eachProperty;
}
}
private T Get<T>(string name)
{
PropertyInfo propInfo;
var success = _settingProps.TryGetValue(name.ToLowerInvariant(), out propInfo);
T output = !success ? default(T) : (T)propInfo.GetValue(null, null);
return output;
}
private void Set<T>(string name, T value)
{
PropertyInfo propInfo;
if (!_settingProps.TryGetValue(name.ToLowerInvariant(), out propInfo))
propInfo = LoadProps(name);
if (propInfo != null)
propInfo.SetValue(null, value, null);
else
Debug.LogWarning("Could not save " + name + " because PlayFabSettings could not be found.");
}
}
#endregion EditorPref data classes
public static PlayFab_SharedSettingsProxy SharedSettings = new PlayFab_SharedSettingsProxy();
private static string KeyPrefix
{
get
{
var dataPath = Application.dataPath;
var lastIndex = dataPath.LastIndexOf('/');
var secondToLastIndex = dataPath.LastIndexOf('/', lastIndex - 1);
return dataPath.Substring(secondToLastIndex, lastIndex - secondToLastIndex);
}
}
public static bool IsDataLoaded = false;
public static Title ActiveTitle
{
get
{
if (PlayFabEditorPrefsSO.Instance.StudioList != null && PlayFabEditorPrefsSO.Instance.StudioList.Count > 0)
{
if (string.IsNullOrEmpty(PlayFabEditorPrefsSO.Instance.SelectedStudio) || PlayFabEditorPrefsSO.Instance.SelectedStudio == PlayFabEditorHelper.STUDIO_OVERRIDE)
return new Title { Id = SharedSettings.TitleId, SecretKey = SharedSettings.DeveloperSecretKey, GameManagerUrl = PlayFabEditorHelper.GAMEMANAGER_URL };
if (string.IsNullOrEmpty(PlayFabEditorPrefsSO.Instance.SelectedStudio) || string.IsNullOrEmpty(SharedSettings.TitleId))
return null;
int studioIndex; int titleIndex;
if (DoesTitleExistInStudios(SharedSettings.TitleId, out studioIndex, out titleIndex))
return PlayFabEditorPrefsSO.Instance.StudioList[studioIndex].Titles[titleIndex];
}
return null;
}
}
public static void SaveEnvDetails(bool updateToScriptableObj = true)
{
UpdateScriptableObject();
}
private static TResult LoadFromEditorPrefs<TResult>(string key) where TResult : class, new()
{
if (!EditorPrefs.HasKey(KeyPrefix + key))
return new TResult();
var serialized = EditorPrefs.GetString(KeyPrefix + key);
var result = JsonWrapper.DeserializeObject<TResult>(serialized);
if (result != null)
return JsonWrapper.DeserializeObject<TResult>(serialized);
return new TResult();
}
private static void UpdateScriptableObject()
{
var playfabSettingsType = PlayFabEditorSDKTools.GetPlayFabSettings();
if (playfabSettingsType == null || !PlayFabEditorSDKTools.IsInstalled || !PlayFabEditorSDKTools.isSdkSupported)
return;
var props = playfabSettingsType.GetProperties();
foreach (var property in props)
{
switch (property.Name.ToLowerInvariant())
{
case "productionenvironmenturl":
property.SetValue(null, PlayFabEditorHelper.TITLE_ENDPOINT, null); break;
}
}
var getSoMethod = playfabSettingsType.GetMethod("GetSharedSettingsObjectPrivate", BindingFlags.NonPublic | BindingFlags.Static);
if (getSoMethod != null)
{
var so = getSoMethod.Invoke(null, new object[0]) as ScriptableObject;
if (so != null)
EditorUtility.SetDirty(so);
}
PlayFabEditorPrefsSO.Save();
AssetDatabase.SaveAssets();
}
public static bool DoesTitleExistInStudios(string searchFor) //out Studio studio
{
if (PlayFabEditorPrefsSO.Instance.StudioList == null)
return false;
searchFor = searchFor.ToLower();
foreach (var studio in PlayFabEditorPrefsSO.Instance.StudioList)
if (studio.Titles != null)
foreach (var title in studio.Titles)
if (title.Id.ToLower() == searchFor)
return true;
return false;
}
private static bool DoesTitleExistInStudios(string searchFor, out int studioIndex, out int titleIndex) //out Studio studio
{
studioIndex = 0; // corresponds to our _OVERRIDE_
titleIndex = -1;
if (PlayFabEditorPrefsSO.Instance.StudioList == null)
return false;
for (var studioIdx = 0; studioIdx < PlayFabEditorPrefsSO.Instance.StudioList.Count; studioIdx++)
{
for (var titleIdx = 0; titleIdx < PlayFabEditorPrefsSO.Instance.StudioList[studioIdx].Titles.Length; titleIdx++)
{
if (PlayFabEditorPrefsSO.Instance.StudioList[studioIdx].Titles[titleIdx].Id.ToLower() == searchFor.ToLower())
{
studioIndex = studioIdx;
titleIndex = titleIdx;
return true;
}
}
}
return false;
}
public static void RefreshStudiosList(bool onlyIfNull = false)
{
if (string.IsNullOrEmpty(PlayFabEditorPrefsSO.Instance.DevAccountToken))
return; // Can't load studios when not logged in
if (onlyIfNull && PlayFabEditorPrefsSO.Instance.StudioList != null)
return; // Don't spam load this, only load it the first time
if (PlayFabEditorPrefsSO.Instance.StudioList != null)
PlayFabEditorPrefsSO.Instance.StudioList.Clear();
PlayFabEditorApi.GetStudios(new GetStudiosRequest(), (getStudioResult) =>
{
if (PlayFabEditorPrefsSO.Instance.StudioList == null)
PlayFabEditorPrefsSO.Instance.StudioList = new List<Studio>();
foreach (var eachStudio in getStudioResult.Studios)
PlayFabEditorPrefsSO.Instance.StudioList.Add(eachStudio);
PlayFabEditorPrefsSO.Instance.StudioList.Add(Studio.OVERRIDE);
PlayFabEditorPrefsSO.Save();
}, PlayFabEditorHelper.SharedErrorCallback);
}
}
}
| |
//#define COSMOSDEBUG
using System;
using IL2CPU.API.Attribs;
namespace Cosmos.Core
{
public class MemoryBlock
{
public readonly uint Base;
public readonly uint Size;
public readonly MemoryBlock08 Bytes;
public readonly MemoryBlock16 Words;
public readonly MemoryBlock32 DWords;
public MemoryBlock(uint aBase, uint aSize)
{
Base = aBase;
Size = aSize;
Bytes = new MemoryBlock08(aBase, aSize);
Words = new MemoryBlock16(aBase, aSize);
DWords = new MemoryBlock32(aBase, aSize);
}
//TODO: Fill all these methods with fast ASM
//TODO: Make an attribute that can be applied to methods to tell the copmiler to inline them to save
// the overhead of a call on operations like this.
// Need to check bounds for 16 and 32 better so offset cannot be size - 1 and then the 4 bytes write past the end
public unsafe uint this[uint aByteOffset]
{
get
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
return *(uint*)(Base + aByteOffset);
}
set
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
(*(uint*)(Base + aByteOffset)) = value;
}
}
public void Fill(uint aData)
{
//Fill(0, Size / 4, aData);
Fill(0, Size, aData);
}
[DebugStub(Off = true)]
public unsafe void Fill(uint aStart, uint aCount, uint aData)
{
// TODO thow exception if aStart and aCount are not in bound. I've tried to do this but Bochs dies :-(
uint* xDest = (uint*)(Base + aStart);
MemoryOperations.Fill(xDest, aData, (int)aCount);
}
[DebugStub(Off = true)]
public unsafe void Fill(int aStart, int aCount, int aData)
{
// TODO thow exception if aStart and aCount are not in bound. I've tried to do this but Bochs dies :-(
int* xDest = (int*)(Base + aStart);
MemoryOperations.Fill(xDest, aData, (int)aCount);
}
public void Fill(byte aData)
{
Fill(0, Size, aData);
}
public void Fill(ushort aData)
{
Fill(0, Size, aData);
}
[DebugStub(Off = true)]
public unsafe void Fill(uint aStart, uint aCount, ushort aData)
{
// TODO thow exception if aStart and aCount are not in bound. I've tried to do this but Bochs dies :-(
ushort* xDest = (ushort*)(Base + aStart);
MemoryOperations.Fill(xDest, aData, (int)aCount);
}
[DebugStub(Off = true)]
public unsafe void Fill(uint aStart, uint aCount, byte aData)
{
// TODO thow exception if aStart and aCount are not in bound. I've tried to do this but Bochs dies :-(
byte* xDest = (byte*)(Base + aStart);
MemoryOperations.Fill(xDest, aData, (int)aCount);
}
[DebugStub(Off = true)]
public unsafe void Copy(uint[] aData)
{
Copy(0, aData, 0, aData.Length);
}
unsafe public void Copy(uint aStart, uint[] aData, int aIndex, int aCount)
{
// TODO thow exception if aStart and aCount are not in bound. I've tried to do this but Bochs dies :-(
uint* xDest = (uint*)(Base + aStart);
Global.mDebugger.SendInternal($"Base is {Base} xDest is {(uint)xDest}");
fixed (uint* aDataPtr = aData) {
MemoryOperations.Copy(xDest, aDataPtr + aIndex, aCount);
}
}
public void Copy(int[] aData)
{
Copy(0, aData, 0, aData.Length);
}
public void Copy(int []aData, int aIndex, int aCount)
{
Copy(0, aData, aIndex, aData.Length);
}
public unsafe void Copy(int aStart, int[] aData, int aIndex, int aCount)
{
// TODO thow exception if aStart and aCount are not in bound. I've tried to do this but Bochs dies :-(
int* xDest = (int*)(Base + aStart);
fixed (int* aDataPtr = aData)
{
MemoryOperations.Copy(xDest, aDataPtr + aIndex, aCount);
}
}
[DebugStub(Off = true)]
public unsafe void MoveDown(uint aDest, uint aSrc, uint aCount)
{
byte* xDest = (byte*)(Base + aDest);
byte* xSrc = (byte*)(Base + aSrc);
MemoryOperations.Copy(xDest, xSrc, (int)aCount);
}
public void MoveUp(uint aDest, uint aSrc, uint aCount)
{
throw new Exception("TODO");
}
#region ReadWrite
public unsafe void Read8(Byte[] aBuffer)
{
if(aBuffer.Length >= Size)
{
throw new Exception("Memory access violation");
}
for (int i = 0; i < aBuffer.Length; i++)
aBuffer[i] = (*(Byte*)(Base + i));
}
public unsafe void Write8(Byte[] aBuffer)
{
if(aBuffer.Length >= Size)
{
throw new Exception("Memory access violation");
}
for (int i = 0; i < aBuffer.Length; i++)
(*(Byte*)(Base + i)) = aBuffer[i];
}
public unsafe void Read16(ushort[] aBuffer)
{
if(aBuffer.Length >= Size)
{
throw new Exception("Memory access violation");
}
for (int i = 0; i < aBuffer.Length / 2; i++)
{
aBuffer[i] = (*(ushort*)(Base + i));
}
}
public unsafe void Write16(ushort[] aBuffer)
{
if(aBuffer.Length >= Size)
{
throw new Exception("Memory access violation");
}
for (int i = 0; i < aBuffer.Length / sizeof(ushort); i++)
{
(*(ushort*)(Base + i)) = aBuffer[i];
}
}
public unsafe void Read32(uint[] aBuffer)
{
if(aBuffer.Length >= Size)
{
throw new Exception("Memory access violation");
}
for (int i = 0; i < aBuffer.Length / sizeof(uint); i++)
aBuffer[i] = (*(uint*)(Base + i));
}
public unsafe void Write32(uint[] aBuffer)
{
if(aBuffer.Length >= Size)
{
throw new Exception("Memory access violation");
}
for (int i = 0; i < aBuffer.Length / sizeof(uint); i++)
(*(uint*)(Base + i)) = aBuffer[i];
}
#endregion ReadWrite
public unsafe uint[] ToArray(int aStart, int aIndex, int aCount)
{
uint* xDest = (uint*)(Base + aStart);
uint[] array = new uint[aCount];
fixed (uint* aArrayPtr = array)
{
MemoryOperations.Copy(aArrayPtr + aIndex, xDest, aCount);
}
return array;
}
public uint[] ToArray()
{
return ToArray(0, 0, (int)Size);
}
}
public class MemoryBlock08
{
public readonly uint Base;
public readonly uint Size;
internal MemoryBlock08(uint aBase, uint aSize)
{
Base = aBase;
Size = aSize;
}
public unsafe byte this[uint aByteOffset]
{
get
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
return *(byte*)(Base + aByteOffset);
}
set
{
if (aByteOffset >= Size)
{
// Also this exception gets eaten?
throw new Exception("Memory access violation");
}
(*(byte*)(Base + aByteOffset)) = value;
}
}
}
public class MemoryBlock16
{
public readonly uint Base;
public readonly uint Size;
internal MemoryBlock16(uint aBase, uint aSize)
{
Base = aBase;
Size = aSize;
}
public unsafe ushort this[uint aByteOffset]
{
get
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
return *(ushort*)(Base + aByteOffset);
}
set
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
(*(ushort*)(Base + aByteOffset)) = value;
}
}
}
public class MemoryBlock32
{
public readonly uint Base;
public readonly uint Size;
internal MemoryBlock32(uint aBase, uint aSize)
{
Base = aBase;
Size = aSize;
}
public unsafe uint this[uint aByteOffset]
{
get
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
return *(uint*)(Base + aByteOffset);
}
set
{
if (aByteOffset >= Size)
{
throw new Exception("Memory access violation");
}
(*(uint*)(Base + aByteOffset)) = value;
}
}
}
}
| |
using System;
using static OneOf.Functions;
namespace OneOf
{
public struct OneOf<T0, T1, T2, T3> : IOneOf
{
readonly T0 _value0;
readonly T1 _value1;
readonly T2 _value2;
readonly T3 _value3;
readonly int _index;
OneOf(int index, T0 value0 = default, T1 value1 = default, T2 value2 = default, T3 value3 = default)
{
_index = index;
_value0 = value0;
_value1 = value1;
_value2 = value2;
_value3 = value3;
}
public object Value =>
_index switch
{
0 => _value0,
1 => _value1,
2 => _value2,
3 => _value3,
_ => throw new InvalidOperationException()
};
public int Index => _index;
public bool IsT0 => _index == 0;
public bool IsT1 => _index == 1;
public bool IsT2 => _index == 2;
public bool IsT3 => _index == 3;
public T0 AsT0 =>
_index == 0 ?
_value0 :
throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}");
public T1 AsT1 =>
_index == 1 ?
_value1 :
throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}");
public T2 AsT2 =>
_index == 2 ?
_value2 :
throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}");
public T3 AsT3 =>
_index == 3 ?
_value3 :
throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}");
public static implicit operator OneOf<T0, T1, T2, T3>(T0 t) => new OneOf<T0, T1, T2, T3>(0, value0: t);
public static implicit operator OneOf<T0, T1, T2, T3>(T1 t) => new OneOf<T0, T1, T2, T3>(1, value1: t);
public static implicit operator OneOf<T0, T1, T2, T3>(T2 t) => new OneOf<T0, T1, T2, T3>(2, value2: t);
public static implicit operator OneOf<T0, T1, T2, T3>(T3 t) => new OneOf<T0, T1, T2, T3>(3, value3: t);
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3)
{
if (_index == 0 && f0 != null)
{
f0(_value0);
return;
}
if (_index == 1 && f1 != null)
{
f1(_value1);
return;
}
if (_index == 2 && f2 != null)
{
f2(_value2);
return;
}
if (_index == 3 && f3 != null)
{
f3(_value3);
return;
}
throw new InvalidOperationException();
}
public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3)
{
if (_index == 0 && f0 != null)
{
return f0(_value0);
}
if (_index == 1 && f1 != null)
{
return f1(_value1);
}
if (_index == 2 && f2 != null)
{
return f2(_value2);
}
if (_index == 3 && f3 != null)
{
return f3(_value3);
}
throw new InvalidOperationException();
}
public static OneOf<T0, T1, T2, T3> FromT0(T0 input) => input;
public static OneOf<T0, T1, T2, T3> FromT1(T1 input) => input;
public static OneOf<T0, T1, T2, T3> FromT2(T2 input) => input;
public static OneOf<T0, T1, T2, T3> FromT3(T3 input) => input;
public OneOf<TResult, T1, T2, T3> MapT0<TResult>(Func<T0, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => mapFunc(AsT0),
1 => AsT1,
2 => AsT2,
3 => AsT3,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, TResult, T2, T3> MapT1<TResult>(Func<T1, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => mapFunc(AsT1),
2 => AsT2,
3 => AsT3,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, TResult, T3> MapT2<TResult>(Func<T2, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => mapFunc(AsT2),
3 => AsT3,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, TResult> MapT3<TResult>(Func<T3, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => mapFunc(AsT3),
_ => throw new InvalidOperationException()
};
}
public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3> remainder)
{
value = IsT0 ? AsT0 : default;
remainder = _index switch
{
0 => default,
1 => AsT1,
2 => AsT2,
3 => AsT3,
_ => throw new InvalidOperationException()
};
return this.IsT0;
}
public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3> remainder)
{
value = IsT1 ? AsT1 : default;
remainder = _index switch
{
0 => AsT0,
1 => default,
2 => AsT2,
3 => AsT3,
_ => throw new InvalidOperationException()
};
return this.IsT1;
}
public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3> remainder)
{
value = IsT2 ? AsT2 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => default,
3 => AsT3,
_ => throw new InvalidOperationException()
};
return this.IsT2;
}
public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2> remainder)
{
value = IsT3 ? AsT3 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => default,
_ => throw new InvalidOperationException()
};
return this.IsT3;
}
bool Equals(OneOf<T0, T1, T2, T3> other) =>
_index == other._index &&
_index switch
{
0 => Equals(_value0, other._value0),
1 => Equals(_value1, other._value1),
2 => Equals(_value2, other._value2),
3 => Equals(_value3, other._value3),
_ => false
};
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is OneOf<T0, T1, T2, T3> o && Equals(o);
}
public override string ToString() =>
_index switch {
0 => FormatValue(_value0),
1 => FormatValue(_value1),
2 => FormatValue(_value2),
3 => FormatValue(_value3),
_ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.")
};
public override int GetHashCode()
{
unchecked
{
int hashCode = _index switch
{
0 => _value0?.GetHashCode(),
1 => _value1?.GetHashCode(),
2 => _value2?.GetHashCode(),
3 => _value3?.GetHashCode(),
_ => 0
} ?? 0;
return (hashCode*397) ^ _index;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Microsoft.AspNetCore.Razor.Language.Components
{
internal static class TagHelperDescriptorExtensions
{
public static bool IsAnyComponentDocumentTagHelper(this TagHelperDescriptor tagHelper)
{
return tagHelper.IsComponentTagHelper() || tagHelper.Metadata.ContainsKey(ComponentMetadata.SpecialKindKey);
}
public static bool IsBindTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.Metadata.TryGetValue(ComponentMetadata.SpecialKindKey, out var kind) &&
string.Equals(ComponentMetadata.Bind.TagHelperKind, kind);
}
public static bool IsFallbackBindTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.IsBindTagHelper() &&
tagHelper.Metadata.TryGetValue(ComponentMetadata.Bind.FallbackKey, out var fallback) &&
string.Equals(bool.TrueString, fallback);
}
public static bool IsGenericTypedComponent(this TagHelperDescriptor tagHelper)
{
return
IsComponentTagHelper(tagHelper) &&
tagHelper.Metadata.TryGetValue(ComponentMetadata.Component.GenericTypedKey, out var value) &&
string.Equals(bool.TrueString, value);
}
public static bool IsInputElementBindTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.IsBindTagHelper() &&
tagHelper.TagMatchingRules.Count == 1 &&
string.Equals("input", tagHelper.TagMatchingRules[0].TagName);
}
public static bool IsInputElementFallbackBindTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.IsInputElementBindTagHelper() &&
!tagHelper.Metadata.ContainsKey(ComponentMetadata.Bind.TypeAttribute);
}
public static string GetValueAttributeName(this TagHelperDescriptor tagHelper)
{
tagHelper.Metadata.TryGetValue(ComponentMetadata.Bind.ValueAttribute, out var result);
return result;
}
public static string GetChangeAttributeName(this TagHelperDescriptor tagHelper)
{
tagHelper.Metadata.TryGetValue(ComponentMetadata.Bind.ChangeAttribute, out var result);
return result;
}
public static string GetExpressionAttributeName(this TagHelperDescriptor tagHelper)
{
tagHelper.Metadata.TryGetValue(ComponentMetadata.Bind.ExpressionAttribute, out var result);
return result;
}
/// <summary>
/// Gets a value that indicates where the tag helper is a bind tag helper with a default
/// culture value of <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
/// <param name="tagHelper">The <see cref="TagHelperDescriptor"/>.</param>
/// <returns>
/// <c>true</c> if this tag helper is a bind tag helper and defaults in <see cref="CultureInfo.InvariantCulture"/>
/// </returns>
public static bool IsInvariantCultureBindTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.Metadata.TryGetValue(ComponentMetadata.Bind.IsInvariantCulture, out var text) &&
bool.TryParse(text, out var result) &&
result;
}
/// <summary>
/// Gets the default format value for a bind tag helper.
/// </summary>
/// <param name="tagHelper">The <see cref="TagHelperDescriptor"/>.</param>
/// <returns>The format, or <c>null</c>.</returns>
public static string GetFormat(this TagHelperDescriptor tagHelper)
{
tagHelper.Metadata.TryGetValue(ComponentMetadata.Bind.Format, out var result);
return result;
}
public static bool IsChildContentTagHelper(this TagHelperDescriptor tagHelper)
{
if (tagHelper.IsChildContentTagHelperCache is bool value)
{
return value;
}
value = tagHelper.Metadata.TryGetValue(ComponentMetadata.SpecialKindKey, out var specialKey) &&
string.Equals(specialKey, ComponentMetadata.ChildContent.TagHelperKind, StringComparison.Ordinal);
tagHelper.IsChildContentTagHelperCache = value;
return value;
}
public static bool IsComponentTagHelper(this TagHelperDescriptor tagHelper)
{
return
string.Equals(tagHelper.Kind, ComponentMetadata.Component.TagHelperKind) &&
!tagHelper.Metadata.ContainsKey(ComponentMetadata.SpecialKindKey);
}
public static bool IsEventHandlerTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.Metadata.TryGetValue(ComponentMetadata.SpecialKindKey, out var kind) &&
string.Equals(ComponentMetadata.EventHandler.TagHelperKind, kind);
}
public static bool IsKeyTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.Metadata.TryGetValue(ComponentMetadata.SpecialKindKey, out var kind) &&
string.Equals(ComponentMetadata.Key.TagHelperKind, kind);
}
public static bool IsSplatTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.Metadata.TryGetValue(ComponentMetadata.SpecialKindKey, out var kind) &&
string.Equals(ComponentMetadata.Splat.TagHelperKind, kind);
}
public static bool IsRefTagHelper(this TagHelperDescriptor tagHelper)
{
return
tagHelper.Metadata.TryGetValue(ComponentMetadata.SpecialKindKey, out var kind) &&
string.Equals(ComponentMetadata.Ref.TagHelperKind, kind);
}
/// <summary>
/// Gets whether the component matches a tag with a fully qualified name.
/// </summary>
/// <param name="tagHelper">The <see cref="TagHelperDescriptor"/>.</param>
public static bool IsComponentFullyQualifiedNameMatch(this TagHelperDescriptor tagHelper)
{
if (tagHelper.IsComponentFullyQualifiedNameMatchCache is bool value)
{
return value;
}
value = tagHelper.Metadata.TryGetValue(ComponentMetadata.Component.NameMatchKey, out var matchType) &&
string.Equals(ComponentMetadata.Component.FullyQualifiedNameMatch, matchType);
tagHelper.IsComponentFullyQualifiedNameMatchCache = value;
return value;
}
public static string GetEventArgsType(this TagHelperDescriptor tagHelper)
{
tagHelper.Metadata.TryGetValue(ComponentMetadata.EventHandler.EventArgsType, out var result);
return result;
}
/// <summary>
/// Gets the set of component attributes that can accept child content (<c>RenderFragment</c> or <c>RenderFragment{T}</c>).
/// </summary>
/// <param name="tagHelper">The <see cref="TagHelperDescriptor"/>.</param>
/// <returns>The child content attributes</returns>
public static IEnumerable<BoundAttributeDescriptor> GetChildContentProperties(this TagHelperDescriptor tagHelper)
{
for (var i = 0; i < tagHelper.BoundAttributes.Count; i++)
{
var attribute = tagHelper.BoundAttributes[i];
if (attribute.IsChildContentProperty())
{
yield return attribute;
}
}
}
/// <summary>
/// Gets the set of component attributes that represent generic type parameters of the component type.
/// </summary>
/// <param name="tagHelper">The <see cref="TagHelperDescriptor"/>.</param>
/// <returns>The type parameter attributes</returns>
public static IEnumerable<BoundAttributeDescriptor> GetTypeParameters(this TagHelperDescriptor tagHelper)
{
for (var i = 0; i < tagHelper.BoundAttributes.Count; i++)
{
var attribute = tagHelper.BoundAttributes[i];
if (attribute.IsTypeParameterProperty())
{
yield return attribute;
}
}
}
/// <summary>
/// Gets a flag that indicates whether the corresponding component supplies any cascading
/// generic type parameters to descendants.
/// </summary>
/// <param name="tagHelper">The <see cref="TagHelperDescriptor"/>.</param>
/// <returns>True if it does supply one or more generic type parameters to descendants; false otherwise.</returns>
public static bool SuppliesCascadingGenericParameters(this TagHelperDescriptor tagHelper)
{
for (var i = 0; i < tagHelper.BoundAttributes.Count; i++)
{
var attribute = tagHelper.BoundAttributes[i];
if (attribute.IsCascadingTypeParameterProperty())
{
return true;
}
}
return false;
}
}
}
| |
/*
Copyright Microsoft 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache 2 License for the specific language governing permissions and
limitations under the License. */
using System;
using MileageStats.Domain.Contracts;
using MileageStats.Domain.Contracts.Data;
using MileageStats.Domain.Handlers;
using MileageStats.Domain.Models;
using MileageStats.Web.Models;
using Moq;
using Xunit;
namespace MileageStats.Domain.Tests
{
public class WhenAddingFillup
{
private readonly Mock<IVehicleRepository> _vehicleRepo;
private readonly Mock<IFillupRepository> _fillupRepositoryMock;
private readonly Vehicle _vehicle;
private const int DefaultUserId = 99;
private const int DefaultVehicleId = 88;
public WhenAddingFillup()
{
_vehicleRepo = new Mock<IVehicleRepository>();
_fillupRepositoryMock = new Mock<IFillupRepository>();
_vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle" };
}
[Fact]
public void WhenAddingFillup_ThenDelegatesToFillupRepository()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Returns(_vehicle);
var fillupForm = new FillupEntryFormModel
{
PricePerUnit = 0,
TotalUnits = 0,
TransactionFee = 0
};
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
handler.Execute(DefaultUserId, DefaultVehicleId, fillupForm);
_fillupRepositoryMock
.Verify(r => r.Create(DefaultUserId, DefaultVehicleId, It.IsAny<FillupEntry>()),
Times.Once());
}
[Fact]
public void WhenAddingFillup_ThenCalculatesDistance()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Returns(_vehicle);
var fillups = new[]
{
new FillupEntry{FillupEntryId = 1, Date = new DateTime(2011, 3, 23), Odometer = 500},
new FillupEntry{FillupEntryId = 2, Date = new DateTime(2011, 3, 24), Odometer = 750}
};
var fillupForm = new FillupEntryFormModel
{
FillupEntryId = 3,
Date = new DateTime(2011, 3, 26),
Odometer = 1000,
PricePerUnit = 0,
TotalUnits = 0,
TransactionFee = 0
};
_fillupRepositoryMock
.Setup(x => x.GetFillups(DefaultVehicleId))
.Returns(fillups);
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
handler.Execute(DefaultUserId, DefaultVehicleId, fillupForm);
Assert.Equal(250, fillupForm.Distance);
}
[Fact]
public void WhenAddingFillupOnSameDate_ThenCalculatesDistance()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Returns(_vehicle);
var fillups = new[]
{
new FillupEntry{FillupEntryId = 1, Date = new DateTime(2011, 3, 25), Odometer = 500},
new FillupEntry{FillupEntryId = 2, Date = new DateTime(2011, 3, 25), Odometer = 750}
};
var fillupForm = new FillupEntryFormModel
{
FillupEntryId = 3,
Date = new DateTime(2011, 3, 25),
Odometer = 1000,
PricePerUnit = 0,
TotalUnits = 0,
TransactionFee = 0
};
_fillupRepositoryMock
.Setup(x => x.GetFillups(DefaultVehicleId))
.Returns(fillups);
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
handler.Execute(DefaultUserId, DefaultVehicleId, fillupForm);
Assert.Equal(250, fillupForm.Distance);
}
[Fact]
public void WhenAddingFirstFillup_ThenDoesNotCalculatesDistance()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Returns(_vehicle);
var fillups = new FillupEntry[] {};
var fillupForm = new FillupEntryFormModel
{
FillupEntryId = 3,
Date = new DateTime(2011, 3, 25),
Odometer = 1000,
PricePerUnit = 0,
TotalUnits = 0,
TransactionFee = 0
};
_fillupRepositoryMock
.Setup(x => x.GetFillups(DefaultVehicleId))
.Returns(fillups);
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
handler.Execute(DefaultUserId, DefaultVehicleId, fillupForm);
Assert.Null(fillupForm.Distance);
}
[Fact]
public void WhenAddingFillup_UsesLocationIfVendorNull()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Returns(_vehicle);
var fillupForm = new FillupEntryFormModel
{
Vendor = null,
Location = "testlocation",
PricePerUnit = 0,
TotalUnits = 0,
TransactionFee = 0
};
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
handler.Execute(DefaultUserId, DefaultVehicleId, fillupForm);
_fillupRepositoryMock
.Verify(r => r.Create(DefaultUserId, DefaultVehicleId, It.Is<FillupEntry>(f=>f.Vendor=="testlocation")));
}
[Fact]
public void WhenAddingFillupAndVehicleRepositoryThrows_ThenWrapsException()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Throws<InvalidOperationException>();
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
var ex = Assert
.Throws<UnauthorizedException>(() => handler.Execute(DefaultUserId, DefaultVehicleId, new FillupEntryFormModel()));
Assert.IsType<InvalidOperationException>(ex.InnerException);
}
[Fact]
public void WhenAddingFillupAndFillupRepositoryThrows_ThenWrapsException()
{
_vehicleRepo
.Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
.Returns(_vehicle);
_fillupRepositoryMock
.Setup(f => f.Create(DefaultUserId,DefaultVehicleId, It.IsAny<FillupEntry>()))
.Throws<InvalidOperationException>();
var handler = new AddFillupToVehicle(_vehicleRepo.Object, _fillupRepositoryMock.Object);
var ex = Assert
.Throws<UnauthorizedException>(() => handler.Execute(DefaultUserId, DefaultVehicleId, new FillupEntryFormModel()));
Assert.IsType<InvalidOperationException>(ex.InnerException);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneModDifficultyAdjustSettings : OsuManualInputManagerTestScene
{
private OsuModDifficultyAdjust modDifficultyAdjust;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create control", () =>
{
modDifficultyAdjust = new OsuModDifficultyAdjust();
Child = new Container
{
Size = new Vector2(300),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
ChildrenEnumerable = modDifficultyAdjust.CreateSettingsControls(),
},
}
};
});
}
[Test]
public void TestFollowsBeatmapDefaultsVisually()
{
setBeatmapWithDifficultyParameters(5);
checkSliderAtValue("Circle Size", 5);
checkBindableAtValue("Circle Size", null);
setBeatmapWithDifficultyParameters(8);
checkSliderAtValue("Circle Size", 8);
checkBindableAtValue("Circle Size", null);
}
[Test]
public void TestOutOfRangeValueStillApplied()
{
AddStep("set override cs to 11", () => modDifficultyAdjust.CircleSize.Value = 11);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
// this is a no-op, just showing that it won't reset the value during deserialisation.
setExtendedLimits(false);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
// setting extended limits will reset the serialisation exception.
// this should be fine as the goal is to allow, at most, the value of extended limits.
setExtendedLimits(true);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
}
[Test]
public void TestExtendedLimits()
{
setSliderValue("Circle Size", 99);
checkSliderAtValue("Circle Size", 10);
checkBindableAtValue("Circle Size", 10);
setExtendedLimits(true);
checkSliderAtValue("Circle Size", 10);
checkBindableAtValue("Circle Size", 10);
setSliderValue("Circle Size", 99);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
setExtendedLimits(false);
checkSliderAtValue("Circle Size", 10);
checkBindableAtValue("Circle Size", 10);
}
[Test]
public void TestUserOverrideMaintainedOnBeatmapChange()
{
setSliderValue("Circle Size", 9);
setBeatmapWithDifficultyParameters(2);
checkSliderAtValue("Circle Size", 9);
checkBindableAtValue("Circle Size", 9);
}
[Test]
public void TestResetToDefault()
{
setBeatmapWithDifficultyParameters(2);
setSliderValue("Circle Size", 9);
checkSliderAtValue("Circle Size", 9);
checkBindableAtValue("Circle Size", 9);
resetToDefault("Circle Size");
checkSliderAtValue("Circle Size", 2);
checkBindableAtValue("Circle Size", null);
}
[Test]
public void TestUserOverrideMaintainedOnMatchingBeatmapValue()
{
setBeatmapWithDifficultyParameters(3);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", null);
// need to initially change it away from the current beatmap value to trigger an override.
setSliderValue("Circle Size", 4);
setSliderValue("Circle Size", 3);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", 3);
setBeatmapWithDifficultyParameters(4);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", 3);
}
[Test]
public void TestResetToDefaults()
{
setBeatmapWithDifficultyParameters(5);
setSliderValue("Circle Size", 3);
setExtendedLimits(true);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", 3);
AddStep("reset mod settings", () => modDifficultyAdjust.ResetSettingsToDefaults());
checkSliderAtValue("Circle Size", 5);
checkBindableAtValue("Circle Size", null);
}
private void resetToDefault(string name)
{
AddStep($"Reset {name} to default", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.Current.SetDefault());
}
private void setExtendedLimits(bool status) =>
AddStep($"Set extended limits {status}", () => modDifficultyAdjust.ExtendedLimits.Value = status);
private void setSliderValue(string name, float value)
{
AddStep($"Set {name} slider to {value}", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.ChildrenOfType<SettingsSlider<float>>().First().Current.Value = value);
}
private void checkBindableAtValue(string name, float? expectedValue)
{
AddAssert($"Bindable {name} is {(expectedValue?.ToString() ?? "null")}", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.Current.Value == expectedValue);
}
private void checkSliderAtValue(string name, float expectedValue)
{
AddAssert($"Slider {name} at {expectedValue}", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.ChildrenOfType<SettingsSlider<float>>().First().Current.Value == expectedValue);
}
private void setBeatmapWithDifficultyParameters(float value)
{
AddStep($"set beatmap with all {value}", () => Beatmap.Value = CreateWorkingBeatmap(new Beatmap
{
BeatmapInfo = new BeatmapInfo
{
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = value,
CircleSize = value,
DrainRate = value,
ApproachRate = value,
}
}
}));
}
}
}
| |
// ============================================================
// Name: UMABonePoseMixerWindow
// Author: Eli Curtz
// Copyright: (c) 2013 Eli Curtz
// ============================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace UMA.PoseTools
{
public class UMABonePoseMixerWindow : EditorWindow
{
public Transform skeleton = null;
public UnityEngine.Object poseFolder = null;
public UMABonePose newComponent = null;
public string poseName = "";
private Dictionary<UMABonePose, float> poseComponents = new Dictionary<UMABonePose, float>();
private Dictionary<string, float> boneComponents = new Dictionary<string, float>();
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
void OnGUI()
{
Transform newSkeleton = EditorGUILayout.ObjectField("Rig Prefab", skeleton, typeof(Transform), true) as Transform;
if (skeleton != newSkeleton)
{
skeleton = newSkeleton;
boneComponents = new Dictionary<string, float>();
Transform[] transforms = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (Transform bone in transforms)
{
boneComponents.Add(bone.name, 1f);
}
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Poses");
EditorGUI.indentLevel++;
UMABonePose changedPose = null;
UMABonePose deletedPose = null;
float sliderVal = 0;
List<string> activeBones = new List<string>();
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
GUILayout.BeginHorizontal();
sliderVal = EditorGUILayout.Slider(entry.Key.name, entry.Value, 0f, 2f);
if (sliderVal != entry.Value)
{
changedPose = entry.Key;
}
if (GUILayout.Button("-", GUILayout.Width(20f)))
{
deletedPose = entry.Key;
}
else
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (!activeBones.Contains(pose.bone))
{
activeBones.Add(pose.bone);
}
}
}
GUILayout.EndHorizontal();
}
if (changedPose != null)
{
poseComponents[changedPose] = sliderVal;
}
if (deletedPose != null)
{
poseComponents.Remove(deletedPose);
}
GUILayout.BeginHorizontal();
newComponent = EditorGUILayout.ObjectField(newComponent, typeof(UMABonePose), false) as UMABonePose;
GUI.enabled = (newComponent != null);
if (GUILayout.Button("+", GUILayout.Width(30f)))
{
poseComponents.Add(newComponent, 1f);
newComponent = null;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Bones");
EditorGUI.indentLevel++;
foreach (string bone in activeBones)
{
GUILayout.BeginHorizontal();
if (boneComponents.ContainsKey(bone))
{
boneComponents[bone] = EditorGUILayout.Slider(bone, boneComponents[bone], 0f, 2f);
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Left"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 1f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 0f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Right"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 0f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 1f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Mirror"))
{
foreach (string bone in activeBones)
{
boneComponents[bone] = Mathf.Max(1f - boneComponents[bone], 0f);
}
if (poseName.EndsWith("_L"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "R";
}
else if (poseName.EndsWith("_R"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "L";
}
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
poseFolder = EditorGUILayout.ObjectField("Pose Folder", poseFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref poseFolder);
GUILayout.BeginHorizontal();
poseName = EditorGUILayout.TextField("New Pose", poseName);
if ((skeleton == null) || (poseFolder == null) || (poseComponents.Count < 1) || (poseName.Length < 1))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build", GUILayout.Width(60f)))
{
string folderPath = AssetDatabase.GetAssetPath(poseFolder);
UMABonePose newPose = CreatePoseAsset(folderPath, poseName);
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (string bone in activeBones)
{
Transform source = System.Array.Find<Transform>(sourceBones, entry => entry.name == bone);
if (source != null)
{
Vector3 position = source.localPosition;
Quaternion rotation = source.localRotation;
Vector3 scale = source.localScale;
bool include = false;
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
float strength = entry.Value * boneComponents[bone];
if (strength > 0f)
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (pose.bone == bone)
{
position += pose.position * strength;
Quaternion posedRotation = rotation * pose.rotation;
rotation = Quaternion.Slerp(rotation, posedRotation, strength);
scale = Vector3.Slerp(scale, pose.scale, strength);
}
}
include = true;
}
}
if (include)
{
newPose.AddBone(source, position, rotation, scale);
}
}
else
{
Debug.LogWarning("Bone not found in skeleton: " + bone);
}
}
EditorUtility.SetDirty(newPose);
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
public static UMABonePose CreatePoseAsset(string assetFolder, string assetName)
{
if (!System.IO.Directory.Exists(assetFolder))
{
System.IO.Directory.CreateDirectory(assetFolder);
}
UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>();
AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset");
return asset;
}
[MenuItem("UMA/Pose Tools/Bone Pose Mixer", priority = 1)]
public static void OpenUMABonePoseBuildWindow()
{
EditorWindow win = EditorWindow.GetWindow(typeof(UMABonePoseMixerWindow));
win.titleContent.text = "Pose Mixer";
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Security;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Internal.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.Runtime.InteropServices
{
/// <summary>
/// This class contains methods that are mainly used to marshal between unmanaged
/// and managed types.
/// </summary>
public static partial class Marshal
{
/// <summary>
/// The default character size for the system. This is always 2 because
/// the framework only runs on UTF-16 systems.
/// </summary>
public static readonly int SystemDefaultCharSize = 2;
/// <summary>
/// The max DBCS character size for the system.
/// </summary>
public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();
public static IntPtr AllocHGlobal(int cb) => AllocHGlobal((IntPtr)cb);
public static unsafe string? PtrToStringAnsi(IntPtr ptr)
{
if (IsNullOrWin32Atom(ptr))
{
return null;
}
return new string((sbyte*)ptr);
}
public static unsafe string PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len), len, SR.ArgumentOutOfRange_NeedNonNegNum);
}
return new string((sbyte*)ptr, 0, len);
}
public static unsafe string? PtrToStringUni(IntPtr ptr)
{
if (IsNullOrWin32Atom(ptr))
{
return null;
}
return new string((char*)ptr);
}
public static unsafe string PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len), len, SR.ArgumentOutOfRange_NeedNonNegNum);
}
return new string((char*)ptr, 0, len);
}
public static unsafe string? PtrToStringUTF8(IntPtr ptr)
{
if (IsNullOrWin32Atom(ptr))
{
return null;
}
int nbBytes = string.strlen((byte*)ptr);
return string.CreateStringFromEncoding((byte*)ptr, nbBytes, Encoding.UTF8);
}
public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (byteLen < 0)
{
throw new ArgumentOutOfRangeException(nameof(byteLen), byteLen, SR.ArgumentOutOfRange_NeedNonNegNum);
}
return string.CreateStringFromEncoding((byte*)ptr, byteLen, Encoding.UTF8);
}
public static int SizeOf(object structure)
{
if (structure is null)
{
throw new ArgumentNullException(nameof(structure));
}
return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true);
}
public static int SizeOf<T>(T structure)
{
if (structure is null)
{
throw new ArgumentNullException(nameof(structure));
}
return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true);
}
public static int SizeOf(Type t)
{
if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
if (!t.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
}
if (t.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
}
return SizeOfHelper(t, throwIfNotMarshalable: true);
}
public static int SizeOf<T>() => SizeOf(typeof(T));
/// <summary>
/// IMPORTANT NOTICE: This method does not do any verification on the array.
/// It must be used with EXTREME CAUTION since passing in invalid index or
/// an array that is not pinned can cause unexpected results.
/// </summary>
public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
if (arr is null)
throw new ArgumentNullException(nameof(arr));
void* pRawData = Unsafe.AsPointer(ref arr.GetRawArrayData());
return (IntPtr)((byte*)pRawData + (uint)index * (nuint)arr.GetElementSize());
}
public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
if (arr is null)
throw new ArgumentNullException(nameof(arr));
void* pRawData = Unsafe.AsPointer(ref arr.GetRawSzArrayData());
return (IntPtr)((byte*)pRawData + (uint)index * (nuint)Unsafe.SizeOf<T>());
}
public static IntPtr OffsetOf<T>(string fieldName) => OffsetOf(typeof(T), fieldName);
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
private static unsafe void CopyToNative<T>(T[] source, int startIndex, IntPtr destination, int length)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
if (destination == IntPtr.Zero)
throw new ArgumentNullException(nameof(destination));
// The rest of the argument validation is done by CopyTo
new Span<T>(source, startIndex, length).CopyTo(new Span<T>((void*)destination, length));
}
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
private static unsafe void CopyToManaged<T>(IntPtr source, T[] destination, int startIndex, int length)
{
if (source == IntPtr.Zero)
throw new ArgumentNullException(nameof(source));
if (destination is null)
throw new ArgumentNullException(nameof(destination));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
// The rest of the argument validation is done by CopyTo
new Span<T>((void*)source, length).CopyTo(new Span<T>(destination, startIndex, length));
}
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
return *addr;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static byte ReadByte(IntPtr ptr) => ReadByte(ptr, 0);
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
return *((short*)addr);
}
else
{
return Unsafe.ReadUnaligned<short>(addr);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static short ReadInt16(IntPtr ptr) => ReadInt16(ptr, 0);
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
return *((int*)addr);
}
else
{
return Unsafe.ReadUnaligned<int>(addr);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static int ReadInt32(IntPtr ptr) => ReadInt32(ptr, 0);
public static IntPtr ReadIntPtr(object ptr, int ofs)
{
#if BIT64
return (IntPtr)ReadInt64(ptr, ofs);
#else // 32
return (IntPtr)ReadInt32(ptr, ofs);
#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#if BIT64
return (IntPtr)ReadInt64(ptr, ofs);
#else // 32
return (IntPtr)ReadInt32(ptr, ofs);
#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr) => ReadIntPtr(ptr, 0);
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
return *((long*)addr);
}
else
{
return Unsafe.ReadUnaligned<long>(addr);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static long ReadInt64(IntPtr ptr) => ReadInt64(ptr, 0);
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
try
{
byte* addr = (byte*)ptr + ofs;
*addr = val;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteByte(IntPtr ptr, byte val) => WriteByte(ptr, 0, val);
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
*((short*)addr) = val;
}
else
{
Unsafe.WriteUnaligned(addr, val);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteInt16(IntPtr ptr, short val) => WriteInt16(ptr, 0, val);
public static void WriteInt16(IntPtr ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val);
public static void WriteInt16([In, Out]object ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val);
public static void WriteInt16(IntPtr ptr, char val) => WriteInt16(ptr, 0, (short)val);
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
*((int*)addr) = val;
}
else
{
Unsafe.WriteUnaligned(addr, val);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteInt32(IntPtr ptr, int val) => WriteInt32(ptr, 0, val);
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
#if BIT64
WriteInt64(ptr, ofs, (long)val);
#else // 32
WriteInt32(ptr, ofs, (int)val);
#endif
}
public static void WriteIntPtr(object ptr, int ofs, IntPtr val)
{
#if BIT64
WriteInt64(ptr, ofs, (long)val);
#else // 32
WriteInt32(ptr, ofs, (int)val);
#endif
}
public static void WriteIntPtr(IntPtr ptr, IntPtr val) => WriteIntPtr(ptr, 0, val);
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
*((long*)addr) = val;
}
else
{
Unsafe.WriteUnaligned(addr, val);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteInt64(IntPtr ptr, long val) => WriteInt64(ptr, 0, val);
public static void Prelink(MethodInfo m)
{
if (m is null)
{
throw new ArgumentNullException(nameof(m));
}
PrelinkCore(m);
}
public static void PrelinkAll(Type c)
{
if (c is null)
{
throw new ArgumentNullException(nameof(c));
}
MethodInfo[] mi = c.GetMethods();
for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
public static void StructureToPtr<T>([DisallowNull] T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure!, ptr, fDeleteOld);
}
/// <summary>
/// Creates a new instance of "structuretype" and marshals data from a
/// native memory block to it.
/// </summary>
public static object? PtrToStructure(IntPtr ptr, Type structureType)
{
if (ptr == IntPtr.Zero)
{
return null;
}
if (structureType is null)
{
throw new ArgumentNullException(nameof(structureType));
}
if (structureType.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType));
}
if (!structureType.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(structureType));
}
return PtrToStructureHelper(ptr, structureType);
}
/// <summary>
/// Marshals data from a native memory block to a preallocated structure class.
/// </summary>
public static void PtrToStructure(IntPtr ptr, object structure)
{
PtrToStructureHelper(ptr, structure, allowValueClasses: false);
}
public static void PtrToStructure<T>(IntPtr ptr, [DisallowNull] T structure)
{
PtrToStructure(ptr, (object)structure!);
}
[return: MaybeNull]
public static T PtrToStructure<T>(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T))!;
public static void DestroyStructure<T>(IntPtr ptr) => DestroyStructure(ptr, typeof(T));
/// <summary>
/// Converts the HRESULT to a CLR exception.
/// </summary>
public static Exception? GetExceptionForHR(int errorCode) => GetExceptionForHR(errorCode, IntPtr.Zero);
public static Exception? GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode >= 0)
{
return null;
}
return GetExceptionForHRInternal(errorCode, errorInfo);
}
/// <summary>
/// Throws a CLR exception based on the HRESULT.
/// </summary>
public static void ThrowExceptionForHR(int errorCode)
{
if (errorCode < 0)
{
throw GetExceptionForHR(errorCode, IntPtr.Zero)!;
}
}
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
{
throw GetExceptionForHR(errorCode, errorInfo)!;
}
}
public static IntPtr SecureStringToBSTR(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToBSTR();
}
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: false);
}
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: true);
}
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: false);
}
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: true);
}
public static unsafe IntPtr StringToHGlobalAnsi(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
int nb = (int)lnb;
// Overflow checking
if (nb != lnb)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocHGlobal((IntPtr)nb);
StringToAnsiString(s, (byte*)hglobal, nb);
return hglobal;
}
public static unsafe IntPtr StringToHGlobalUni(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocHGlobal((IntPtr)nb);
fixed (char* firstChar = s)
{
string.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
private static unsafe IntPtr StringToHGlobalUTF8(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = Encoding.UTF8.GetMaxByteCount(s.Length);
IntPtr pMem = AllocHGlobal(nb + 1);
int nbWritten;
byte* pbMem = (byte*)pMem;
fixed (char* firstChar = s)
{
nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);
}
pbMem[nbWritten] = 0;
return pMem;
}
public static unsafe IntPtr StringToCoTaskMemUni(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocCoTaskMem(nb);
fixed (char* firstChar = s)
{
string.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
public static unsafe IntPtr StringToCoTaskMemUTF8(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = Encoding.UTF8.GetMaxByteCount(s.Length);
IntPtr pMem = AllocCoTaskMem(nb + 1);
int nbWritten;
byte* pbMem = (byte*)pMem;
fixed (char* firstChar = s)
{
nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);
}
pbMem[nbWritten] = 0;
return pMem;
}
public static unsafe IntPtr StringToCoTaskMemAnsi(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
int nb = (int)lnb;
// Overflow checking
if (nb != lnb)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocCoTaskMem(nb);
StringToAnsiString(s, (byte*)hglobal, nb);
return hglobal;
}
/// <summary>
/// Generates a GUID for the specified type. If the type has a GUID in the
/// metadata then it is returned otherwise a stable guid is generated based
/// on the fully qualified name of the type.
/// </summary>
public static Guid GenerateGuidForType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!type.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
}
return type.GUID;
}
/// <summary>
/// This method generates a PROGID for the specified type. If the type has
/// a PROGID in the metadata then it is returned otherwise a stable PROGID
/// is generated based on the fully qualified name of the type.
/// </summary>
public static string? GenerateProgIdForType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsImport)
{
throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type));
}
if (type.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
}
ProgIdAttribute? progIdAttribute = type.GetCustomAttribute<ProgIdAttribute>();
if (progIdAttribute != null)
{
return progIdAttribute.Value ?? string.Empty;
}
// If there is no prog ID attribute then use the full name of the type as the prog id.
return type.FullName;
}
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
if (!t.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
}
if (t.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
}
Type? c = t.BaseType;
if (c != typeof(Delegate) && c != typeof(MulticastDelegate))
{
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t));
}
return GetDelegateForFunctionPointerInternal(ptr, t);
}
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
}
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
if (d is null)
{
throw new ArgumentNullException(nameof(d));
}
return GetFunctionPointerForDelegateInternal(d);
}
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) where TDelegate : notnull
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
}
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
{
return dwLastError;
}
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
public static IntPtr /* IDispatch */ GetIDispatchForObject(object o) => throw new PlatformNotSupportedException();
public static unsafe void ZeroFreeBSTR(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, SysStringByteLen(s));
FreeBSTR(s);
}
public static unsafe void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
ZeroFreeCoTaskMemUTF8(s);
}
public static unsafe void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.wcslen((char*)s) * sizeof(char));
FreeCoTaskMem(s);
}
public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.strlen((byte*)s));
FreeCoTaskMem(s);
}
public static unsafe void ZeroFreeGlobalAllocAnsi(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.strlen((byte*)s));
FreeHGlobal(s);
}
public static unsafe void ZeroFreeGlobalAllocUnicode(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.wcslen((char*)s) * sizeof(char));
FreeHGlobal(s);
}
internal static unsafe uint SysStringByteLen(IntPtr s)
{
return *(((uint*)s) - 1);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
using static MicrosoftCodeQualityAnalyzersResources;
/// <summary>
/// CA1710: Identifiers should have correct suffix
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class IdentifiersShouldHaveCorrectSuffixAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1710";
private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(IdentifiersShouldHaveCorrectSuffixTitle));
private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(IdentifiersShouldHaveCorrectSuffixDescription));
internal static readonly DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(IdentifiersShouldHaveCorrectSuffixMessageDefault)),
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor SpecialCollectionRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(IdentifiersShouldHaveCorrectSuffixMessageSpecialCollection)),
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(DefaultRule, SpecialCollectionRule);
// Tuple says <TypeInheritedOrImplemented, AppropriateSuffix, Bool value saying if the suffix can `Collection` or the `AppropriateSuffix`>s
// The bool values are as mentioned in the Uri
private static readonly List<(string typeName, string suffix, bool canSuffixBeCollection)> s_baseTypesAndTheirSuffix = new()
{
("System.Attribute", "Attribute", false),
("System.EventArgs", "EventArgs", false),
("System.Exception", "Exception", false),
("System.Collections.ICollection", "Collection", false),
("System.Collections.IDictionary", "Dictionary", false),
("System.Collections.IEnumerable", "Collection", false),
("System.Collections.Queue", "Queue", true),
("System.Collections.Stack", "Stack", true),
("System.Collections.Generic.Queue`1", "Queue", true),
("System.Collections.Generic.Stack`1", "Stack", true),
("System.Collections.Generic.ICollection`1", "Collection", false),
("System.Collections.Generic.IDictionary`2", "Dictionary", false),
("System.Collections.Generic.IReadOnlyDictionary`2", "Dictionary", false),
("System.Data.DataSet", "DataSet", false),
("System.Data.DataTable", "DataTable", true),
("System.IO.Stream", "Stream", false),
("System.Security.IPermission", "Permission", false),
("System.Security.Policy.IMembershipCondition", "Condition", false)
};
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(AnalyzeCompilationStart);
}
private static void AnalyzeCompilationStart(CompilationStartAnalysisContext context)
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(context.Compilation);
var baseTypeSuffixMapBuilder = ImmutableDictionary.CreateBuilder<INamedTypeSymbol, SuffixInfo>();
var interfaceTypeSuffixMapBuilder = ImmutableDictionary.CreateBuilder<INamedTypeSymbol, SuffixInfo>();
foreach (var (typeName, suffix, canSuffixBeCollection) in s_baseTypesAndTheirSuffix)
{
var wellKnownNamedType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(typeName);
if (wellKnownNamedType != null && wellKnownNamedType.OriginalDefinition != null)
{
// If the type is interface
if (wellKnownNamedType.OriginalDefinition.TypeKind == TypeKind.Interface)
{
interfaceTypeSuffixMapBuilder.Add(wellKnownNamedType.OriginalDefinition, SuffixInfo.Create(suffix, canSuffixBeCollection));
}
else
{
baseTypeSuffixMapBuilder.Add(wellKnownNamedType.OriginalDefinition, SuffixInfo.Create(suffix, canSuffixBeCollection));
}
}
}
var baseTypeSuffixMap = baseTypeSuffixMapBuilder.ToImmutable();
var interfaceTypeSuffixMap = interfaceTypeSuffixMapBuilder.ToImmutable();
context.RegisterSymbolAction((saContext) =>
{
var namedTypeSymbol = (INamedTypeSymbol)saContext.Symbol;
if (!saContext.Options.MatchesConfiguredVisibility(DefaultRule, namedTypeSymbol, saContext.Compilation))
{
Debug.Assert(!saContext.Options.MatchesConfiguredVisibility(SpecialCollectionRule, namedTypeSymbol, saContext.Compilation));
return;
}
Debug.Assert(saContext.Options.MatchesConfiguredVisibility(SpecialCollectionRule, namedTypeSymbol, saContext.Compilation));
var excludeIndirectBaseTypes = context.Options.GetBoolOptionValue(EditorConfigOptionNames.ExcludeIndirectBaseTypes, DefaultRule,
namedTypeSymbol, context.Compilation, defaultValue: true);
var baseTypes = excludeIndirectBaseTypes
? namedTypeSymbol.BaseType != null ? ImmutableArray.Create(namedTypeSymbol.BaseType) : ImmutableArray<INamedTypeSymbol>.Empty
: namedTypeSymbol.GetBaseTypes();
var userTypeSuffixMap = context.Options.GetAdditionalRequiredSuffixesOption(DefaultRule, saContext.Symbol,
context.Compilation);
if (TryGetTypeSuffix(baseTypes, baseTypeSuffixMap, userTypeSuffixMap, out var typeSuffixInfo))
{
// SpecialCollectionRule - Rename 'LastInFirstOut<T>' to end in either 'Collection' or 'Stack'.
// DefaultRule - Rename 'MyStringObjectHashtable' to end in 'Dictionary'.
var rule = typeSuffixInfo.CanSuffixBeCollection ? SpecialCollectionRule : DefaultRule;
if ((typeSuffixInfo.CanSuffixBeCollection && !namedTypeSymbol.Name.EndsWith("Collection", StringComparison.Ordinal) && !namedTypeSymbol.Name.EndsWith(typeSuffixInfo.Suffix, StringComparison.Ordinal)) ||
(!typeSuffixInfo.CanSuffixBeCollection && !namedTypeSymbol.Name.EndsWith(typeSuffixInfo.Suffix, StringComparison.Ordinal)))
{
saContext.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(rule, namedTypeSymbol.ToDisplayString(), typeSuffixInfo.Suffix));
}
return;
}
var interfaces = excludeIndirectBaseTypes
? namedTypeSymbol.Interfaces
: namedTypeSymbol.AllInterfaces;
if (TryGetTypeSuffix(interfaces, interfaceTypeSuffixMap, userTypeSuffixMap, out var interfaceSuffixInfo) &&
!namedTypeSymbol.Name.EndsWith(interfaceSuffixInfo.Suffix, StringComparison.Ordinal))
{
saContext.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(DefaultRule, namedTypeSymbol.ToDisplayString(), interfaceSuffixInfo.Suffix));
}
}
, SymbolKind.NamedType);
var eventArgsType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs);
if (eventArgsType != null)
{
context.RegisterSymbolAction((saContext) =>
{
const string eventHandlerString = "EventHandler";
var eventSymbol = (IEventSymbol)saContext.Symbol;
if (!eventSymbol.Type.Name.EndsWith(eventHandlerString, StringComparison.Ordinal) &&
eventSymbol.Type.IsInSource() &&
eventSymbol.Type.TypeKind == TypeKind.Delegate &&
((INamedTypeSymbol)eventSymbol.Type).DelegateInvokeMethod?.HasEventHandlerSignature(eventArgsType) == true)
{
saContext.ReportDiagnostic(eventSymbol.CreateDiagnostic(DefaultRule, eventSymbol.Type.Name, eventHandlerString));
}
},
SymbolKind.Event);
}
}
private static bool TryGetTypeSuffix(IEnumerable<INamedTypeSymbol> typeSymbols, ImmutableDictionary<INamedTypeSymbol, SuffixInfo> hardcodedMap,
SymbolNamesWithValueOption<string?> userMap, [NotNullWhen(true)] out SuffixInfo? suffixInfo)
{
foreach (var type in typeSymbols)
{
// User specific mapping has higher priority than hardcoded one
if (userMap.TryGetValue(type.OriginalDefinition, out var suffix))
{
if (!RoslynString.IsNullOrWhiteSpace(suffix))
{
suffixInfo = SuffixInfo.Create(suffix, canSuffixBeCollection: false);
return true;
}
}
else if (hardcodedMap.TryGetValue(type.OriginalDefinition, out suffixInfo))
{
return true;
}
}
suffixInfo = null;
return false;
}
}
internal class SuffixInfo
{
public string Suffix { get; private set; }
public bool CanSuffixBeCollection { get; private set; }
private SuffixInfo(
string suffix,
bool canSuffixBeCollection)
{
Suffix = suffix;
CanSuffixBeCollection = canSuffixBeCollection;
}
internal static SuffixInfo Create(string suffix, bool canSuffixBeCollection)
{
return new SuffixInfo(suffix, canSuffixBeCollection);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Test
{
public class TaskContinueWhenAnyTests
{
#region TaskFactory.ContinueWhenAny tests
[Fact]
public static void RunContinueWhenAnyTests()
{
TaskCompletionSource<int> tcs = null;
ManualResetEvent mre1 = null;
ManualResetEvent mre2 = null;
Task[] antecedents;
Task continuation = null;
for (int i = 0; i < 2; i++)
{
bool antecedentsAreFutures = (i == 0);
for (int j = 0; j < 2; j++)
{
bool continuationIsFuture = (j == 0);
for (int k = 0; k < 2; k++)
{
bool preCanceledToken = (k == 0);
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
if (preCanceledToken)
cts.Cancel();
for (int x = 0; x < 2; x++)
{
bool longRunning = (x == 0);
TaskContinuationOptions tco = longRunning ? TaskContinuationOptions.LongRunning : TaskContinuationOptions.None;
for (int y = 0; y < 2; y++)
{
bool preCompletedTask = (y == 0);
for (int z = 0; z < 2; z++)
{
bool useFutureFactory = (z == 0);
// This would be a nonsensical combination
if (useFutureFactory && !continuationIsFuture)
continue;
//Assert.True(false, string.Format(" - Test Task{5}.Factory.ContinueWhenAny(Task{0}[]({1} completed), {2}, ct({3}), {4}, ts.Default)",
// antecedentsAreFutures ? "<int>" : "",
// preCompletedTask ? 1 : 0,
// continuationIsFuture ? "func" : "action",
// preCanceledToken ? "signaled" : "unsignaled",
// tco,
// useFutureFactory ? "<int>" : ""));
TaskScheduler ts = TaskScheduler.Default;
if (antecedentsAreFutures)
antecedents = new Task<int>[3];
else
antecedents = new Task[3];
tcs = new TaskCompletionSource<int>();
mre1 = new ManualResetEvent(false);
mre2 = new ManualResetEvent(false);
continuation = null;
if (antecedentsAreFutures)
{
antecedents[0] = new Task<int>(() => { mre2.WaitOne(); return 0; });
antecedents[1] = new Task<int>(() => { mre1.WaitOne(); return 1; });
antecedents[2] = new Task<int>(() => { mre2.WaitOne(); return 2; });
}
else
{
antecedents[0] = new Task(() => { mre2.WaitOne(); tcs.TrySetResult(0); });
antecedents[1] = new Task(() => { mre1.WaitOne(); tcs.TrySetResult(1); });
antecedents[2] = new Task(() => { mre2.WaitOne(); tcs.TrySetResult(2); });
}
if (preCompletedTask)
{
mre1.Set();
antecedents[1].Start();
antecedents[1].Wait();
}
if (continuationIsFuture)
{
if (antecedentsAreFutures)
{
if (useFutureFactory)
{
continuation = Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { tcs.TrySetResult(t.Result); return 10; }, ct, tco, ts);
}
else
{
continuation = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => { tcs.TrySetResult(t.Result); return 10; }, ct, tco, ts);
}
}
else // antecedents are tasks
{
if (useFutureFactory)
{
continuation = Task<int>.Factory.ContinueWhenAny(antecedents, _ => 10, ct, tco, ts);
}
else
{
continuation = Task.Factory.ContinueWhenAny<int>(antecedents, _ => 10, ct, tco, ts);
}
}
}
else // continuation is task
{
if (antecedentsAreFutures)
{
continuation = Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => tcs.TrySetResult(t.Result), ct, tco, ts);
}
else
{
continuation = Task.Factory.ContinueWhenAny(antecedents, _ => { }, ct, tco, ts);
}
}
// If we have a pre-canceled token, the continuation should have completed by now
Assert.False(preCanceledToken && !continuation.IsCompleted, " > FAILED. Continuation should complete early on pre-canceled ct");
// Slightly different than the previous assert:
// We should only have completed by now if we have a preCanceledToken or a preCompletedTask
Assert.True(!continuation.IsCompleted || preCompletedTask || preCanceledToken, " > FAILED! Continuation should fire early only if (preCanceledToken or preCompletedTask)(1).");
// Kick off our antecedents array
startTaskArray(antecedents);
//Thread.Sleep(50);
// re-assert that the only way that the continuation should have completed by now is preCompletedTask or preCanceledToken
Assert.True(!continuation.IsCompleted || preCompletedTask || preCanceledToken, " > FAILED! Continuation should fire early only if (preCanceledToken or preCompletedTask)(2).");
// signal mre1 if we have not done so already
if (!preCompletedTask)
mre1.Set();
Exception ex = null;
int result = 0;
try
{
if (continuationIsFuture)
result = ((Task<int>)continuation).Result;
else
continuation.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True((ex == null) == !preCanceledToken,
"RunContinueWhenAnyTests: > FAILED! continuation.Wait() should throw exception iff preCanceledToken");
if (preCanceledToken)
{
if (ex == null)
{
Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (no exception thrown)"));
;
}
else if (ex.GetType() != typeof(AggregateException))
{
Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (didn't throw aggregate exception)"));
}
else if (((AggregateException)ex).InnerException.GetType() != typeof(TaskCanceledException))
{
ex = ((AggregateException)ex).InnerException;
Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (threw " + ex.GetType().Name + " instead of TaskCanceledException)"));
}
}
Assert.True(preCanceledToken || (tcs.Task.Result == 1),
"RunContinueWhenAnyTests: > FAILED! Wrong task was recorded as completed.");
Assert.True((result == 10) || !continuationIsFuture || preCanceledToken,
"RunContinueWhenAnyTests:> FAILED! continuation yielded wrong result");
Assert.Equal((continuation.CreationOptions & TaskCreationOptions.LongRunning) != 0, longRunning);
Assert.True((continuation.CreationOptions == TaskCreationOptions.None) || longRunning, "continuation CreationOptions should be None unless longRunning is true");
// Allow remaining antecedents to finish
mre2.Set();
// Make sure that you wait for the antecedents to complete.
// When this line wasn't here, antecedent completion could sneak into
// the next loop iteration, causing tcs to be set to 0 or 2 instead of 1,
// resulting in intermittent test failures.
Task.WaitAll(antecedents);
// We don't need to call this for every combination of i/j/k/x/y/z. So only
// call under these conditions.
if (preCanceledToken && longRunning && preCompletedTask)
{
TestContinueWhenAnyException(antecedents, useFutureFactory, continuationIsFuture);
}
} //end z-loop (useFutureFactory)
} // end y-loop (preCompletedTask)
} // end x-loop (longRunning)
} // end k-loop (preCanceledToken)
} // end j-loop (continuationIsFuture)
} // end i-loop (antecedentsAreFutures)
}
public static void TestContinueWhenAnyException(Task[] antecedents, bool FutureFactory, bool continuationIsFuture)
{
bool antecedentsAreFutures = (antecedents as Task<int>[]) != null;
Debug.WriteLine(" * Test Exceptions in TaskFactory{0}.ContinueWhenAny(Task{1}[],Task{2})",
FutureFactory ? "<TResult>" : "",
antecedentsAreFutures ? "<TResult>" : "",
continuationIsFuture ? "<TResult>" : "");
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
cts.Cancel();
Task t1 = Task.Factory.StartNew(() => { });
Task<int> f1 = Task<int>.Factory.StartNew(() => 10);
Task[] dummyTasks = new Task[] { t1 };
Task<int>[] dummyFutures = new Task<int>[] { f1 };
if (FutureFactory) //TaskFactory<TResult> methods
{
if (antecedentsAreFutures)
{
Assert.ThrowsAsync<ArgumentNullException>(
() => Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => Task<int>.Factory.ContinueWhenAny<int>(null, t => 0));
var cFuture = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, ct);
CheckForCorrectCT(cFuture, ct);
antecedents[0] = null;
Assert.ThrowsAsync<ArgumentException>(
() => Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0));
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(new Task<int>[] { }, t => 0); });
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
else //antecedents are tasks
{
var dummy = Task.Factory.StartNew(delegate { });
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task<int>.Factory.ContinueWhenAny(new Task[] { dummy }, t => 0, TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously));
dummy.Wait();
Assert.ThrowsAsync<ArgumentNullException>(
() => Task<int>.Factory.ContinueWhenAny(antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task<int>.Factory.ContinueWhenAny(antecedents, t => 0, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => Task<int>.Factory.ContinueWhenAny(null, t => 0));
var cTask = Task.Factory.ContinueWhenAny(antecedents, t => 0, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.ThrowsAsync<ArgumentException>(
() => Task<int>.Factory.ContinueWhenAny(antecedents, (t) => 0));
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAny(new Task[] { }, t => 0); });
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
}
else //TaskFactory methods
{
//test exceptions
if (continuationIsFuture)
{
if (antecedentsAreFutures)
{
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny<int, int>(null, t => 0));
var cTask = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.ThrowsAsync<ArgumentException>(
() => Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0));
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny<int, int>(new Task<int>[] { }, t => 0); });
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
else // antecedents are tasks
{
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny<int>(antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task.Factory.ContinueWhenAny<int>(antecedents, t => 0, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny<int>(null, t => 0));
var cTask = Task.Factory.ContinueWhenAny(antecedents, delegate (Task t) { }, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.ThrowsAsync<ArgumentException>(
() => Task.Factory.ContinueWhenAny<int>(antecedents, t => 0));
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny<int>(new Task[] { }, t => 0); });
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
}
else //Continuation is task
{
if (antecedentsAreFutures)
{
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny<int>(null, t => { }));
var cTask = Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.ThrowsAsync<ArgumentException>(
() => Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }));
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny<int>(new Task<int>[] { }, t => { }); });
//
// Test for exception on null continuation action
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
else // antecedents are tasks
{
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny(antecedents, t => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => Task.Factory.ContinueWhenAny(antecedents, t => { }, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => Task.Factory.ContinueWhenAny(null, t => { }));
var task = Task.Factory.ContinueWhenAny(antecedents, t => { }, ct);
CheckForCorrectCT(task, ct);
antecedents[0] = null;
Assert.ThrowsAsync<ArgumentException>(
() => Task.Factory.ContinueWhenAny(antecedents, t => { }));
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny(new Task[] { }, t => { }); });
//
// Test for exception on null continuation action
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
}
}
}
#endregion
#region Helper Methods
// used in ContinueWhenAll/ContinueWhenAny tests
public static void startTaskArray(Task[] tasks)
{
for (int i = 0; i < tasks.Length; i++)
{
if (tasks[i].Status == TaskStatus.Created)
tasks[i].Start();
}
}
public static void CheckForCorrectCT(Task canceledTask, CancellationToken correctToken)
{
try
{
canceledTask.Wait();
Assert.True(false, string.Format(" > FAILED! Pre-canceled result did not throw from Wait()"));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e =>
{
var tce = e as TaskCanceledException;
if (tce == null)
{
Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw non-TCE from Wait()"));
}
else if (tce.CancellationToken != correctToken)
{
Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw TCE w/ wrong token"));
}
return true;
});
}
}
#endregion
}
}
| |
// 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 Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static DiagnosticResult GetCA3075DataTableReadXmlCSharpResultAt(int line, int column)
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml");
private static DiagnosticResult GetCA3075DataTableReadXmlBasicResultAt(int line, int column)
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml");
[Fact]
public async Task UseDataTableReadXmlShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataTableReadXml
{
public void TestMethod(Stream stream)
{
DataTable table = new DataTable();
table.ReadXml(stream);
}
}
}
",
GetCA3075DataTableReadXmlCSharpResultAt(13, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataTableReadXml
Public Sub TestMethod(stream As Stream)
Dim table As New DataTable()
table.ReadXml(stream)
End Sub
End Class
End Namespace",
GetCA3075DataTableReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInGetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
public DataTable Test
{
get {
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
return dt;
}
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(11, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Public ReadOnly Property Test() As DataTable
Get
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
Return dt
End Get
End Property
End Class",
GetCA3075DataTableReadXmlBasicResultAt(9, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInSetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
DataTable privateDoc;
public DataTable GetDoc
{
set
{
if (value == null)
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
privateDoc = dt;
}
else
privateDoc = value;
}
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(15, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private privateDoc As DataTable
Public WriteOnly Property GetDoc() As DataTable
Set
If value Is Nothing Then
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
privateDoc = dt
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075DataTableReadXmlBasicResultAt(11, 17)
);
}
[Fact]
public async Task UseDataTableReadXmlInTryBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(13, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInCatchBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
}
finally { }
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(14, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
Finally
End Try
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInFinallyBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
}
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(15, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
End Try
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(13, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInAsyncAwaitShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Data;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Data
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInDelegateShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
delegate void Del();
Del d = delegate () {
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
};
}",
GetCA3075DataTableReadXmlCSharpResultAt(11, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(10, 5)
);
}
[Fact]
public async Task UseDataTableReadXmlWithXmlReaderShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataTableReadXml
{
public void TestMethod(XmlReader reader)
{
DataTable table = new DataTable();
table.ReadXml(reader);
}
}
}
"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataTableReadXml
Public Sub TestMethod(reader As XmlReader)
Dim table As New DataTable()
table.ReadXml(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
namespace GraphLibrary
{
using System;
using System.Collections.Generic;
using System.Text;
public class Graph<T>
{
private readonly HashSet<Node<T>> visited;
public Graph()
{
this.Nodes = new Dictionary<T, Node<T>>();
this.visited = new HashSet<Node<T>>();
}
public IDictionary<T, Node<T>> Nodes { get; private set; }
public void AddNode(T name)
{
var node = new Node<T>(name);
if (Nodes.ContainsKey(name))
{
throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", name));
}
Nodes.Add(name, node);
}
public void AddNode(Node<T> node)
{
if (this.Nodes.ContainsKey(node.Name))
{
throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", node.Name));
}
this.Nodes.Add(node.Name, node);
}
public void AddConnection(T fromNode, T toNode, int distance, bool twoWay)
{
if (!Nodes.ContainsKey(fromNode))
{
this.AddNode(fromNode);
}
if (!Nodes.ContainsKey(toNode))
{
this.AddNode(toNode);
}
Nodes[fromNode].AddConnection(Nodes[toNode], distance, twoWay);
}
public List<Node<T>> FindShortestDistanceToAllNodes(T startNodeName)
{
if (!Nodes.ContainsKey(startNodeName))
{
throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName));
}
SetShortestDistances(Nodes[startNodeName]);
var nodes = new List<Node<T>>();
foreach (var item in Nodes)
{
if (!item.Key.Equals(startNodeName))
{
nodes.Add(item.Value);
}
}
return nodes;
}
private void SetShortestDistances(Node<T> startNode)
{
var queue = new PriorityQueue<Node<T>>();
// set to all nodes DijkstraDistance to PositiveInfinity
foreach (var node in Nodes)
{
if (!startNode.Name.Equals(node.Key))
{
node.Value.DijkstraDistance = double.PositiveInfinity;
//queue.Enqueue(node.Value);
}
}
startNode.DijkstraDistance = 0.0d;
queue.Enqueue(startNode);
while (queue.Count != 0)
{
Node<T> currentNode = queue.Dequeue();
if (double.IsPositiveInfinity(currentNode.DijkstraDistance))
{
break;
}
foreach (var neighbour in Nodes[currentNode.Name].Connections)
{
double subDistance = currentNode.DijkstraDistance + neighbour.Distance;
if (subDistance < neighbour.Target.DijkstraDistance)
{
neighbour.Target.DijkstraDistance = subDistance;
queue.Enqueue(neighbour.Target);
}
}
}
}
public void SetAllDijkstraDistanceValue(double value)
{
foreach (var node in Nodes)
{
node.Value.DijkstraDistance = value;
}
}
public double GetSumOfAllDijkstraDistance()
{
foreach (var item in Nodes)
{
if (!visited.Contains(item.Value))
{
EmployDfs(item.Value);
}
}
double sum = 0;
foreach (var node in Nodes)
{
sum += node.Value.DijkstraDistance;
}
return sum;
}
public void EmployDfs(Node<T> node)
{
visited.Add(node);
foreach (var item in node.Connections)
{
if (!visited.Contains(item.Target))
{
EmployDfs(item.Target);
}
node.DijkstraDistance += item.Target.DijkstraDistance;
}
if (node.DijkstraDistance == 0)
{
node.DijkstraDistance++;
}
}
public void EmployBfs(T nodeName)
{
var nodes = new Queue<Node<T>>();
Node<T> node = Nodes[nodeName];
nodes.Enqueue(node);
while (nodes.Count != 0)
{
Node<T> currentNode = nodes.Dequeue();
currentNode.DijkstraDistance++;
foreach (var connection in Nodes[currentNode.Name].Connections)
{
nodes.Enqueue(connection.Target);
}
}
}
public List<Edge<T>> PrimeMinimumSpanningTree(T startNodeName)
{
if (!Nodes.ContainsKey(startNodeName))
{
throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName));
}
var mpdTree = new List<Edge<T>>();
var queue = new PriorityQueue<Edge<T>>();
Node<T> node = Nodes[startNodeName];
foreach (var edge in node.Connections)
{
queue.Enqueue(edge);
}
visited.Add(node);
while (queue.Count > 0)
{
Edge<T> edge = queue.Dequeue();
if (!visited.Contains(edge.Target))
{
node = edge.Target;
visited.Add(node); //we "visit" this node
mpdTree.Add(edge);
foreach (var item in node.Connections)
{
if (!mpdTree.Contains(item))
{
if (!visited.Contains(item.Target))
{
queue.Enqueue(item);
}
}
}
}
}
visited.Clear();
return mpdTree;
}
public override string ToString()
{
var result = new StringBuilder();
foreach (var node in this.Nodes)
{
result.Append("(" + node.Key + ") -> ");
foreach (var conection in node.Value.Connections)
{
result.Append("(" + conection.Target + ") with:" + conection.Distance + " ");
}
result.AppendLine();
}
return result.ToString();
}
}
}
| |
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// 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.Drawing;
using System.Windows.Forms;
using Sharpex2D.Math;
namespace Sharpex2D.Surface
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
public class GameWindow : IDisposable
{
private readonly Form _surface;
private bool _cursorVisibility = true;
private bool _isDisposed;
private SurfaceLayout _surfaceLayout;
private SurfaceStyle _surfaceStyle;
/// <summary>
/// Initializes a new GameWindow class.
/// </summary>
/// <param name="handle">The Handle.</param>
internal GameWindow(IntPtr handle)
{
_surface = (Form) Control.FromHandle(handle);
_surfaceStyle = SurfaceStyle.Normal;
_surfaceLayout = new SurfaceLayout(true, false, true);
CursorVisibility = false;
_surface.FormClosing += _surface_FormClosing;
_surface.Activated += _surface_Activated;
_surface.Deactivate += _surface_Deactivate;
MethodInvoker br = delegate { _surface.KeyPreview = true; };
_surface.Invoke(br);
}
/// <summary>
/// Gets or sets the Title.
/// </summary>
public string Title
{
set
{
MethodInvoker br = delegate { _surface.Text = value; };
_surface.Invoke(br);
}
get
{
string title = "";
MethodInvoker br = delegate { title = _surface.Text; };
_surface.Invoke(br);
return title;
}
}
/// <summary>
/// Gets or sets the Icon.
/// </summary>
public Icon Icon
{
set
{
MethodInvoker br = delegate { _surface.Icon = value; };
_surface.Invoke(br);
}
get
{
Icon icon = null;
MethodInvoker br = delegate { icon = _surface.Icon; };
_surface.Invoke(br);
return icon;
}
}
/// <summary>
/// Gets or sets the Size.
/// </summary>
public Vector2 Size
{
set
{
FreeWindow();
MethodInvoker br = delegate { _surface.ClientSize = new Size((int) value.X, (int) value.Y); };
_surface.Invoke(br);
FixWindow();
if (ScreenSizeChanged != null)
{
ScreenSizeChanged(this, EventArgs.Empty);
}
}
get
{
var vector = new Vector2(0);
MethodInvoker br =
delegate { vector = new Vector2(_surface.ClientSize.Width, _surface.ClientSize.Height); };
_surface.Invoke(br);
return vector;
}
}
/// <summary>
/// Gets or sets the Position.
/// </summary>
public Vector2 Position
{
set
{
MethodInvoker br = delegate { _surface.Location = new Point((int) value.X, (int) value.Y); };
_surface.Invoke(br);
}
get
{
var vector = new Vector2(0);
MethodInvoker br = delegate { vector = new Vector2(_surface.Location.X, _surface.Location.Y); };
_surface.Invoke(br);
return vector;
}
}
/// <summary>
/// Gets or sets the CursorVisibility.
/// </summary>
public bool CursorVisibility
{
get { return _cursorVisibility; }
set
{
_cursorVisibility = value;
if (value)
{
Cursor.Show();
}
else
{
Cursor.Hide();
}
}
}
/// <summary>
/// Gets or sets the SurfaceStyle.
/// </summary>
public SurfaceStyle SurfaceStyle
{
get { return _surfaceStyle; }
set
{
if (value == _surfaceStyle)
{
return;
}
FreeWindow();
MethodInvoker br = delegate
{
if (value == SurfaceStyle.Fullscreen)
{
_surface.FormBorderStyle = FormBorderStyle.None;
_surface.Location = new Point(0, 0);
_surface.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
IsFullscreen = true;
}
else
{
_surface.FormBorderStyle = FormBorderStyle.Sizable;
_surface.ClientSize = new Size(SGL.GraphicsDevice.BackBuffer.Width,
SGL.GraphicsDevice.BackBuffer.Height);
_surface.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - _surface.Width)/2,
(Screen.PrimaryScreen.WorkingArea.Height - _surface.Height)/2);
IsFullscreen = false;
}
};
_surface.Invoke(br);
_surfaceStyle = value;
FixWindow();
if (FullscreenChanged != null)
{
FullscreenChanged(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the SurfaceLayout.
/// </summary>
public SurfaceLayout SurfaceLayout
{
get { return _surfaceLayout; }
set
{
MethodInvoker br = delegate
{
_surface.MaximizeBox = value.CanMaximize;
_surface.MinimizeBox = value.CanMinimize;
_surface.ControlBox = value.CanClose;
};
_surface.Invoke(br);
_surfaceLayout = value;
}
}
/// <summary>
/// A value indicating whether the window is fullscreened.
/// </summary>
public bool IsFullscreen { private set; get; }
/// <summary>
/// A value indicating whether the window is active.
/// </summary>
public bool IsActive
{
get
{
bool flag = true;
MethodInvoker br = delegate { flag = _surface.Focused; };
_surface.Invoke(br);
return flag;
}
}
/// <summary>
/// Centers the Window.
/// </summary>
public void CenterWindow()
{
MethodInvoker br = delegate
{
_surface.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width/2 - _surface.Width/2,
Screen.PrimaryScreen.WorkingArea.Height/2 - _surface.Height/2);
};
_surface.Invoke(br);
}
/// <summary>
/// ScreenSizeChanged event.
/// </summary>
public event ScreenSizeEventHandler ScreenSizeChanged;
/// <summary>
/// FullscreenChanged event.
/// </summary>
public event ScreenSizeEventHandler FullscreenChanged;
/// <summary>
/// Sets the CursorIcon.
/// </summary>
/// <param name="path">The Path.</param>
public void SetCursorIcon(string path)
{
MethodInvoker br = delegate { Cursor.Current = new Cursor(path); };
_surface.Invoke(br);
}
/// <summary>
/// Fixes the size of the window.
/// </summary>
private void FixWindow()
{
MethodInvoker br = delegate
{
_surface.MaximumSize = _surface.Size;
_surface.MinimumSize = _surface.Size;
};
_surface.Invoke(br);
}
/// <summary>
/// Frees the window size.
/// </summary>
private void FreeWindow()
{
MethodInvoker br = delegate
{
_surface.MaximumSize = new Size(0, 0);
_surface.MinimumSize = new Size(0, 0);
};
_surface.Invoke(br);
}
/// <summary>
/// Deactivate Event.
/// </summary>
/// <param name="sender">The Sender.</param>
/// <param name="e">The EventArgs.</param>
private void _surface_Deactivate(object sender, EventArgs e)
{
SGL.GameInstance.OnDeactivation();
}
/// <summary>
/// Activate Event.
/// </summary>
/// <param name="sender">The Sender.</param>
/// <param name="e">The EventArgs.</param>
private void _surface_Activated(object sender, EventArgs e)
{
SGL.GameInstance.OnActivation();
}
/// <summary>
/// FormClosing Event.
/// </summary>
/// <param name="sender">The Sender.</param>
/// <param name="e">The EventArgs.</param>
private void _surface_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
SGL.Shutdown();
}
#region IDisposable Implementation
/// <summary>
/// Disposes the object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the object.
/// </summary>
/// <param name="disposing">Indicates whether managed resources should be disposed.</param>
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
if (disposing)
{
MethodInvoker br = () => _surface.Dispose();
_surface.Invoke(br);
}
}
}
#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 System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Security.Tests
{
public class ServerAsyncAuthenticateTest : IDisposable
{
private readonly ITestOutputHelper _log;
private readonly ITestOutputHelper _logVerbose;
private readonly X509Certificate2 _serverCertificate;
public ServerAsyncAuthenticateTest()
{
_log = TestLogging.GetInstance();
_logVerbose = VerboseTestLogging.GetInstance();
_serverCertificate = Configuration.Certificates.GetServerCertificate();
}
public void Dispose()
{
_serverCertificate.Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol)
{
await ServerAsyncSslHelper(protocol, protocol);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachServerUnsupportedProtocol_Fail(SslProtocols protocol)
{
await Assert.ThrowsAsync<NotSupportedException>(() =>
{
return ServerAsyncSslHelper(
SslProtocolSupport.SupportedSslProtocols,
protocol,
expectedToFail: true);
});
}
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(11170)]
[Theory]
[MemberData(nameof(ProtocolMismatchData))]
public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails(
SslProtocols serverProtocol,
SslProtocols clientProtocol,
Type expectedException)
{
await Assert.ThrowsAsync(
expectedException,
() =>
{
return ServerAsyncSslHelper(
serverProtocol,
clientProtocol,
expectedToFail: true);
});
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task ServerAsyncAuthenticate_UnsuportedAllServer_Fail()
{
await Assert.ThrowsAsync<NotSupportedException>(() =>
{
return ServerAsyncSslHelper(
SslProtocolSupport.SupportedSslProtocols,
SslProtocolSupport.UnsupportedSslProtocols,
expectedToFail: true);
});
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success(
SslProtocols serverProtocol)
{
await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol);
}
private static IEnumerable<object[]> ProtocolMismatchData()
{
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(TimeoutException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(TimeoutException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(TimeoutException) };
}
#region Helpers
private async Task ServerAsyncSslHelper(
SslProtocols clientSslProtocols,
SslProtocols serverSslProtocols,
bool expectedToFail = false)
{
_log.WriteLine(
"Server: " + serverSslProtocols + "; Client: " + clientSslProtocols +
" expectedToFail: " + expectedToFail);
int timeOut = expectedToFail ? TestConfiguration.FailingTestTimeoutMiliseconds
: TestConfiguration.PassingTestTimeoutMilliseconds;
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
var server = new TcpListener(endPoint);
server.Start();
using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
{
IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;
Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
Task<TcpClient> serverAccept = server.AcceptTcpClientAsync();
// We expect that the network-level connect will always complete.
await Task.WhenAll(new Task[] { clientConnect, serverAccept }).TimeoutAfter(
TestConfiguration.PassingTestTimeoutMilliseconds);
using (TcpClient serverConnection = await serverAccept)
using (SslStream sslClientStream = new SslStream(clientConnection.GetStream()))
using (SslStream sslServerStream = new SslStream(
serverConnection.GetStream(),
false,
AllowAnyServerCertificate))
{
string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsClientAsync start.");
Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
serverName,
null,
clientSslProtocols,
false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsServerAsync start.");
Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
_serverCertificate,
true,
serverSslProtocols,
false);
try
{
await clientAuthentication.TimeoutAfter(timeOut);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.clientAuthentication complete.");
}
catch (Exception ex)
{
// Ignore client-side errors: we're only interested in server-side behavior.
_log.WriteLine("Client exception: " + ex);
}
await serverAuthentication.TimeoutAfter(timeOut);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.serverAuthentication complete.");
_log.WriteLine(
"Server({0}) authenticated with encryption cipher: {1} {2}-bit strength",
serverEndPoint,
sslServerStream.CipherAlgorithm,
sslServerStream.CipherStrength);
Assert.True(
sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null,
"Cipher algorithm should not be NULL");
Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0");
}
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
private bool AllowAnyServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Assert.True(
(sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable,
"Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors);
return true; // allow everything
}
#endregion Helpers
}
}
| |
namespace AngleSharp.Dom
{
using AngleSharp.Attributes;
using System;
/// <summary>
/// The Element interface represents an object within a DOM document.
/// </summary>
[DomName("Element")]
public interface IElement : INode, IParentNode, IChildNode, INonDocumentTypeChildNode
{
/// <summary>
/// Gets the namespace prefix of this element.
/// </summary>
[DomName("prefix")]
String? Prefix { get; }
/// <summary>
/// Gets the local part of the qualified name of this element.
/// </summary>
[DomName("localName")]
String LocalName { get; }
/// <summary>
/// Gets the namespace URI of this element.
/// </summary>
[DomName("namespaceURI")]
String? NamespaceUri { get; }
/// <summary>
/// Gets the sequence of associated attributes.
/// </summary>
[DomName("attributes")]
INamedNodeMap Attributes { get; }
/// <summary>
/// Gets the list of class names.
/// </summary>
[DomName("classList")]
ITokenList ClassList { get; }
/// <summary>
/// Gets or sets the value of the class attribute.
/// </summary>
[DomName("className")]
String? ClassName { get; set; }
/// <summary>
/// Gets or sets the id value of the element.
/// </summary>
[DomName("id")]
String? Id { get; set; }
/// <summary>
/// Inserts new HTML elements specified by the given HTML string at
/// a position relative to the current element specified by the
/// position.
/// </summary>
/// <param name="position">The relation to the current element.</param>
/// <param name="html">The HTML code to generate elements for.</param>
[DomName("insertAdjacentHTML")]
void Insert(AdjacentPosition position, String html);
/// <summary>
/// Returns a boolean value indicating whether the specified element
/// has the specified attribute or not.
/// </summary>
/// <param name="name">The attributes name.</param>
/// <returns>The return value of true or false.</returns>
[DomName("hasAttribute")]
Boolean HasAttribute(String name);
/// <summary>
/// Returns a boolean value indicating whether the specified element
/// has the specified attribute or not.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="localName">The attributes name.</param>
/// <returns>The return value of true or false.</returns>
[DomName("hasAttributeNS")]
Boolean HasAttribute(String? namespaceUri, String localName);
/// <summary>
/// Returns the value of the named attribute on the specified element.
/// </summary>
/// <param name="name">
/// The name of the attribute whose value you want to get.
/// </param>
/// <returns>
/// If the named attribute does not exist, the value returned will be
/// null, otherwise the attribute's value.
/// </returns>
[DomName("getAttribute")]
String? GetAttribute(String name);
/// <summary>
/// Returns the value of the named attribute on the specified element.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="localName">
/// The name of the attribute whose value you want to get.
/// </param>
/// <returns>
/// If the named attribute does not exist, the value returned will be
/// null, otherwise the attribute's value.
/// </returns>
[DomName("getAttributeNS")]
String? GetAttribute(String? namespaceUri, String localName);
/// <summary>
/// Adds a new attribute or changes the value of an existing attribute
/// on the specified element.
/// </summary>
/// <param name="name">The name of the attribute as a string.</param>
/// <param name="value">The desired new value of the attribute.</param>
/// <returns>The current element.</returns>
[DomName("setAttribute")]
void SetAttribute(String name, String value);
/// <summary>
/// Adds a new attribute or changes the value of an existing attribute
/// on the specified element.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="name">The name of the attribute as a string.</param>
/// <param name="value">The desired new value of the attribute.</param>
[DomName("setAttributeNS")]
void SetAttribute(String? namespaceUri, String name, String value);
/// <summary>
/// Removes an attribute from the specified element.
/// </summary>
/// <param name="name">
/// Is a string that names the attribute to be removed.
/// </param>
/// <returns>True if an attribute was removed, otherwise false.</returns>
[DomName("removeAttribute")]
Boolean RemoveAttribute(String name);
/// <summary>
/// Removes an attribute from the specified element.
/// </summary>
/// <param name="namespaceUri">
/// A string specifying the namespace of the attribute.
/// </param>
/// <param name="localName">
/// Is a string that names the attribute to be removed.
/// </param>
/// <returns>True if an attribute was removed, otherwise false.</returns>
[DomName("removeAttributeNS")]
Boolean RemoveAttribute(String? namespaceUri, String localName);
/// <summary>
/// Returns a set of elements which have all the given class names.
/// </summary>
/// <param name="classNames">
/// A string representing the list of class names to match; class names
/// are separated by whitespace.
/// </param>
/// <returns>A collection of elements.</returns>
[DomName("getElementsByClassName")]
IHtmlCollection<IElement> GetElementsByClassName(String classNames);
/// <summary>
/// Returns a NodeList of elements with the given tag name. The
/// complete document is searched, including the root node.
/// </summary>
/// <param name="tagName">
/// A string representing the name of the elements. The special string
/// "*" represents all elements.
/// </param>
/// <returns>
/// A collection of elements in the order they appear in the tree.
/// </returns>
[DomName("getElementsByTagName")]
IHtmlCollection<IElement> GetElementsByTagName(String tagName);
/// <summary>
/// Returns a list of elements with the given tag name belonging to the
/// given namespace. The complete document is searched, including the
/// root node.
/// </summary>
/// <param name="namespaceUri">
/// The namespace URI of elements to look for.
/// </param>
/// <param name="tagName">
/// Either the local name of elements to look for or the special value
/// "*", which matches all elements.
/// </param>
/// <returns>
/// A collection of elements in the order they appear in the tree.
/// </returns>
[DomName("getElementsByTagNameNS")]
IHtmlCollection<IElement> GetElementsByTagNameNS(String? namespaceUri, String tagName);
/// <summary>
/// Checks if the element is matched by the given selector.
/// </summary>
/// <param name="selectors">Represents the selector to test.</param>
/// <returns>
/// True if the element would be selected by the specified selector,
/// otherwise false.
/// </returns>
[DomName("matches")]
Boolean Matches(String selectors);
/// <summary>
/// Returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in the parameter.
/// </summary>
/// <param name="selectors">Represents the selector to test.</param>
/// <returns>
/// The closest ancestor of the current element (or the current element itself) which matches the selectors given. If there isn't such an ancestor, it returns null.
/// </returns>
[DomName("closest")]
IElement? Closest(String selectors);
/// <summary>
/// Gets or sets the inner HTML (excluding the current element) of the
/// element.
/// </summary>
[DomName("innerHTML")]
String InnerHtml { get; set; }
/// <summary>
/// Gets or sets the outer HTML (including the current element) of the
/// element.
/// </summary>
[DomName("outerHTML")]
String OuterHtml { get; set; }
/// <summary>
/// Gets the name of the tag that represents the current element.
/// </summary>
[DomName("tagName")]
String TagName { get; }
/// <summary>
/// Creates a new shadow root for the current element, if there is none
/// already.
/// </summary>
/// <param name="mode">The mode of the shadow root.</param>
/// <returns>The new shadow root.</returns>
[DomName("attachShadow")]
[DomInitDict]
IShadowRoot AttachShadow(ShadowRootMode mode = ShadowRootMode.Open);
/// <summary>
/// Gets the assigned slot of the current element, if any.
/// </summary>
[DomName("assignedSlot")]
IElement? AssignedSlot { get; }
/// <summary>
/// Gets the value of the slot attribute.
/// </summary>
[DomName("slot")]
String? Slot { get; set; }
/// <summary>
/// Gets the shadow root of the current element, if any.
/// </summary>
[DomName("shadowRoot")]
IShadowRoot? ShadowRoot { get; }
/// <summary>
/// Gets if the element is currently focused.
/// </summary>
Boolean IsFocused { get; }
/// <summary>
/// Gets the source reference if available.
/// </summary>
ISourceReference? SourceReference { get; }
}
}
| |
/*
* Copyright (c) 2010-2012, Achim 'ahzf' Friedland <achim@graph-database.org>
* This file is part of Styx <http://www.github.com/Vanaheimr/Styx>
*
* 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 Usings
using System;
using System.Collections;
using System.Collections.Generic;
#endregion
namespace de.ahzf.Styx
{
#region IStartPipe
/// <summary>
/// An interface for the element consuming part of a pipe.
/// Pipes implementing just this interface do not neccessarily
/// emit elements, but e.g. might send them via network.
/// </summary>
public interface IStartPipe
{
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource(Object SourceElement);
/// <summary>
/// Set the elements emitted by the given IEnumerator as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator as element source.</param>
void SetSource(IEnumerator IEnumerator);
/// <summary>
/// Set the elements emitted from the given IEnumerable as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable as element source.</param>
void SetSourceCollection(IEnumerable IEnumerable);
}
#endregion
#region IStartPipe<in S>
/// <summary>
/// An interface for the element consuming part of a pipe.
/// Pipes implementing just this interface do not neccessarily
/// emit elements, but e.g. might send them via network.
/// </summary>
/// <typeparam name="S">The type of the consuming objects.</typeparam>
public interface IStartPipe<in S> : IStartPipe
{
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource(S SourceElement);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S> as element source.</param>
void SetSource(IEnumerator<S> IEnumerator);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S> as element source.</param>
void SetSourceCollection(IEnumerable<S> IEnumerable);
}
#endregion
#region IStartPipe<in S1, in S2>
/// <summary>
/// An interface for the element consuming part of a pipe.
/// Pipes implementing just this interface do not neccessarily
/// emit elements, but e.g. might send them via network.
/// </summary>
/// <typeparam name="S1">The type of the first consuming objects.</typeparam>
/// <typeparam name="S2">The type of the second consuming objects.</typeparam>
public interface IStartPipe<in S1, in S2> : IStartPipe
{
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource1(S1 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource2(S2 SourceElement);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S1> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S1> as element source.</param>
void SetSource1(IEnumerator<S1> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S2> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S2> as element source.</param>
void SetSource2(IEnumerator<S2> IEnumerator);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S1> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S1> as element source.</param>
void SetSourceCollection1(IEnumerable<S1> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S2> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S2> as element source.</param>
void SetSourceCollection2(IEnumerable<S2> IEnumerable);
}
#endregion
#region IStartPipe<in S1, in S2, in S3>
/// <summary>
/// An interface for the element consuming part of a pipe.
/// Pipes implementing just this interface do not neccessarily
/// emit elements, but e.g. might send them via network.
/// </summary>
/// <typeparam name="S1">The type of the first consuming objects.</typeparam>
/// <typeparam name="S2">The type of the second consuming objects.</typeparam>
/// <typeparam name="S3">The type of the third consuming objects.</typeparam>
public interface IStartPipe<in S1, in S2, in S3> : IStartPipe
{
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource1(S1 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource2(S2 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource3(S3 SourceElement);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S1> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S1> as element source.</param>
void SetSource1(IEnumerator<S1> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S2> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S2> as element source.</param>
void SetSource2(IEnumerator<S2> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S3> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S3> as element source.</param>
void SetSource3(IEnumerator<S3> IEnumerator);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S1> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S1> as element source.</param>
void SetSourceCollection1(IEnumerable<S1> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S2> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S2> as element source.</param>
void SetSourceCollection2(IEnumerable<S2> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S3> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S3> as element source.</param>
void SetSourceCollection3(IEnumerable<S3> IEnumerable);
}
#endregion
#region IStartPipe<in S1, in S2, in S3, in S4>
/// <summary>
/// An interface for the element consuming part of a pipe.
/// Pipes implementing just this interface do not neccessarily
/// emit elements, but e.g. might send them via network.
/// </summary>
/// <typeparam name="S1">The type of the first consuming objects.</typeparam>
/// <typeparam name="S2">The type of the second consuming objects.</typeparam>
/// <typeparam name="S3">The type of the third consuming objects.</typeparam>
/// <typeparam name="S4">The type of the fourth consuming objects.</typeparam>
public interface IStartPipe<in S1, in S2, in S3, in S4> : IStartPipe
{
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource1(S1 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource2(S2 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource3(S3 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource4(S4 SourceElement);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S1> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S1> as element source.</param>
void SetSource1(IEnumerator<S1> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S2> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S2> as element source.</param>
void SetSource2(IEnumerator<S2> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S3> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S3> as element source.</param>
void SetSource3(IEnumerator<S3> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S4> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S4> as element source.</param>
void SetSource4(IEnumerator<S4> IEnumerator);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S1> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S1> as element source.</param>
void SetSourceCollection1(IEnumerable<S1> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S2> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S2> as element source.</param>
void SetSourceCollection2(IEnumerable<S2> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S3> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S3> as element source.</param>
void SetSourceCollection3(IEnumerable<S3> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S4> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S4> as element source.</param>
void SetSourceCollection4(IEnumerable<S4> IEnumerable);
}
#endregion
#region IStartPipe<in S1, in S2, in S3, in S4, in S5>
/// <summary>
/// An interface for the element consuming part of a pipe.
/// Pipes implementing just this interface do not neccessarily
/// emit elements, but e.g. might send them via network.
/// </summary>
/// <typeparam name="S1">The type of the first consuming objects.</typeparam>
/// <typeparam name="S2">The type of the second consuming objects.</typeparam>
/// <typeparam name="S3">The type of the third consuming objects.</typeparam>
/// <typeparam name="S4">The type of the fourth consuming objects.</typeparam>
/// <typeparam name="S5">The type of the fifth consuming objects.</typeparam>
public interface IStartPipe<in S1, in S2, in S3, in S4, in S5> : IStartPipe
{
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource1(S1 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource2(S2 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource3(S3 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource4(S4 SourceElement);
/// <summary>
/// Set the given element as source.
/// </summary>
/// <param name="SourceElement">A single source element.</param>
void SetSource5(S5 SourceElement);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S1> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S1> as element source.</param>
void SetSource1(IEnumerator<S1> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S2> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S2> as element source.</param>
void SetSource2(IEnumerator<S2> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S3> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S3> as element source.</param>
void SetSource3(IEnumerator<S3> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S4> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S4> as element source.</param>
void SetSource4(IEnumerator<S4> IEnumerator);
/// <summary>
/// Set the elements emitted by the given IEnumerator<S5> as input.
/// </summary>
/// <param name="IEnumerator">An IEnumerator<S5> as element source.</param>
void SetSource5(IEnumerator<S5> IEnumerator);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S1> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S1> as element source.</param>
void SetSourceCollection1(IEnumerable<S1> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S2> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S2> as element source.</param>
void SetSourceCollection2(IEnumerable<S2> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S3> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S3> as element source.</param>
void SetSourceCollection3(IEnumerable<S3> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S4> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S4> as element source.</param>
void SetSourceCollection4(IEnumerable<S4> IEnumerable);
/// <summary>
/// Set the elements emitted from the given IEnumerable<S5> as input.
/// </summary>
/// <param name="IEnumerable">An IEnumerable<S5> as element source.</param>
void SetSourceCollection5(IEnumerable<S5> IEnumerable);
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Linq;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// SupplierList (read only list).<br/>
/// This is a generated <see cref="SupplierList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="SupplierInfo"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class SupplierList : ReadOnlyBindingListBase<SupplierList, SupplierInfo>
#else
public partial class SupplierList : ReadOnlyListBase<SupplierList, SupplierInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="SupplierInfo"/> item is in the collection.
/// </summary>
/// <param name="supplierId">The SupplierId of the item to search for.</param>
/// <returns><c>true</c> if the SupplierInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int supplierId)
{
foreach (var supplierInfo in this)
{
if (supplierInfo.SupplierId == supplierId)
{
return true;
}
}
return false;
}
#endregion
#region Private Fields
private static SupplierList _list;
#endregion
#region Cache Management Methods
/// <summary>
/// Clears the in-memory SupplierList cache so it is reloaded on the next request.
/// </summary>
public static void InvalidateCache()
{
_list = null;
}
/// <summary>
/// Used by async loaders to load the cache.
/// </summary>
/// <param name="list">The list to cache.</param>
internal static void SetCache(SupplierList list)
{
_list = list;
}
internal static bool IsCached
{
get { return _list != null; }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="SupplierList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="SupplierList"/> collection.</returns>
public static SupplierList GetSupplierList()
{
if (_list == null)
_list = DataPortal.Fetch<SupplierList>();
return _list;
}
/// <summary>
/// Factory method. Loads a <see cref="SupplierList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the SupplierList to fetch.</param>
/// <returns>A reference to the fetched <see cref="SupplierList"/> collection.</returns>
public static SupplierList GetSupplierList(string name)
{
return DataPortal.Fetch<SupplierList>(name);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="SupplierList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetSupplierList(EventHandler<DataPortalResult<SupplierList>> callback)
{
if (_list == null)
DataPortal.BeginFetch<SupplierList>((o, e) =>
{
_list = e.Object;
callback(o, e);
});
else
callback(null, new DataPortalResult<SupplierList>(_list, null, null));
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="SupplierList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the SupplierList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetSupplierList(string name, EventHandler<DataPortalResult<SupplierList>> callback)
{
DataPortal.BeginFetch<SupplierList>(name, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="SupplierList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public SupplierList()
{
// Use factory methods and do not use direct creation.
SupplierEditSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="SupplierEdit"/> to update the list of <see cref="SupplierInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void SupplierEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (SupplierEdit)e.NewObject;
if (((SupplierEdit)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(SupplierInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((SupplierEdit)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.SupplierId == obj.SupplierId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.SupplierId == obj.SupplierId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="SupplierList"/> collection from the database or from the cache.
/// </summary>
protected void DataPortal_Fetch()
{
if (IsCached)
{
LoadCachedList();
return;
}
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ISupplierListDal>();
var data = dal.Fetch();
LoadCollection(data);
}
OnFetchPost(args);
_list = this;
}
private void LoadCachedList()
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AddRange(_list);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
/// <summary>
/// Loads a <see cref="SupplierList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="name">The Name.</param>
protected void DataPortal_Fetch(string name)
{
var args = new DataPortalHookArgs(name);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ISupplierListDal>();
var data = dal.Fetch(name);
LoadCollection(data);
}
OnFetchPost(args);
}
private void LoadCollection(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="SupplierList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<SupplierInfo>(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
#region SupplierEditSaved nested class
// TODO: edit "SupplierList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: SupplierEditSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="SupplierEdit"/>
/// to update the list of <see cref="SupplierInfo"/> objects.
/// </summary>
private static class SupplierEditSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a SupplierList instance to handle Saved events.
/// to update the list of <see cref="SupplierInfo"/> objects.
/// </summary>
/// <param name="obj">The SupplierList instance.</param>
public static void Register(SupplierList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (SupplierList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
SupplierEdit.SupplierEditSaved += SupplierEditSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="SupplierEdit"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void SupplierEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((SupplierList) reference.Target).SupplierEditSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered SupplierList instances.
/// </summary>
public static void Unregister()
{
SupplierEdit.SupplierEditSaved -= SupplierEditSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.Composition;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public partial class TestWorkspace
{
private const string CSharpExtension = ".cs";
private const string CSharpScriptExtension = ".csx";
private const string VisualBasicExtension = ".vb";
private const string VisualBasicScriptExtension = ".vbx";
private const string WorkspaceElementName = "Workspace";
private const string ProjectElementName = "Project";
private const string SubmissionElementName = "Submission";
private const string MetadataReferenceElementName = "MetadataReference";
private const string MetadataReferenceFromSourceElementName = "MetadataReferenceFromSource";
private const string ProjectReferenceElementName = "ProjectReference";
private const string CompilationOptionsElementName = "CompilationOptions";
private const string RootNamespaceAttributeName = "RootNamespace";
private const string OutputTypeAttributeName = "OutputType";
private const string ReportDiagnosticAttributeName = "ReportDiagnostic";
private const string ParseOptionsElementName = "ParseOptions";
private const string LanguageVersionAttributeName = "LanguageVersion";
private const string FeaturesAttributeName = "Features";
private const string DocumentationModeAttributeName = "DocumentationMode";
private const string DocumentElementName = "Document";
private const string AnalyzerElementName = "Analyzer";
private const string AssemblyNameAttributeName = "AssemblyName";
private const string CommonReferencesAttributeName = "CommonReferences";
private const string CommonReferencesWinRTAttributeName = "CommonReferencesWinRT";
private const string CommonReferencesNet45AttributeName = "CommonReferencesNet45";
private const string CommonReferencesPortableAttributeName = "CommonReferencesPortable";
private const string CommonReferenceFacadeSystemRuntimeAttributeName = "CommonReferenceFacadeSystemRuntime";
private const string FilePathAttributeName = "FilePath";
private const string FoldersAttributeName = "Folders";
private const string KindAttributeName = "Kind";
private const string LanguageAttributeName = "Language";
private const string GlobalImportElementName = "GlobalImport";
private const string IncludeXmlDocCommentsAttributeName = "IncludeXmlDocComments";
private const string IsLinkFileAttributeName = "IsLinkFile";
private const string LinkAssemblyNameAttributeName = "LinkAssemblyName";
private const string LinkProjectNameAttributeName = "LinkProjectName";
private const string LinkFilePathAttributeName = "LinkFilePath";
private const string PreprocessorSymbolsAttributeName = "PreprocessorSymbols";
private const string AnalyzerDisplayAttributeName = "Name";
private const string AnalyzerFullPathAttributeName = "FullPath";
private const string AliasAttributeName = "Alias";
private const string ProjectNameAttribute = "Name";
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content)
{
return CreateAsync(language, compilationOptions, parseOptions, new[] { content });
}
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static Task<TestWorkspace> CreateAsync(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content)
{
return CreateAsync(workspaceKind, language, compilationOptions, parseOptions, new[] { content });
}
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static Task<TestWorkspace> CreateAsync(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content,
ExportProvider exportProvider)
{
return CreateAsync(language, compilationOptions, parseOptions, new[] { content }, exportProvider: exportProvider, workspaceKind: workspaceKind);
}
/// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
internal static Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
params string[] files)
{
return CreateAsync(language, compilationOptions, parseOptions, files, exportProvider: null);
}
/// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
internal static Task<TestWorkspace> CreateAsync(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
params string[] files)
{
return CreateAsync(language, compilationOptions, parseOptions, files, exportProvider: null, workspaceKind: workspaceKind);
}
internal static async Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string[] files,
ExportProvider exportProvider,
string[] metadataReferences = null,
string workspaceKind = null,
string extension = null,
bool commonReferences = true)
{
var documentElements = new List<XElement>();
var index = 1;
if (extension == null)
{
extension = language == LanguageNames.CSharp
? CSharpExtension
: VisualBasicExtension;
}
foreach (var file in files)
{
documentElements.Add(CreateDocumentElement(file, "test" + index++ + extension, parseOptions));
}
metadataReferences = metadataReferences ?? Array.Empty<string>();
foreach (var reference in metadataReferences)
{
documentElements.Add(CreateMetadataReference(reference));
}
var workspaceElement = CreateWorkspaceElement(
CreateProjectElement(compilationOptions?.ModuleName ?? "Test", language, commonReferences, parseOptions, compilationOptions, documentElements));
return await CreateAsync(workspaceElement, exportProvider: exportProvider, workspaceKind: workspaceKind);
}
internal static Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions[] parseOptions,
string[] files,
ExportProvider exportProvider)
{
Contract.Requires(parseOptions == null || (files.Length == parseOptions.Length), "Please specify a parse option for each file.");
var documentElements = new List<XElement>();
var index = 1;
var extension = "";
for (int i = 0; i < files.Length; i++)
{
if (language == LanguageNames.CSharp)
{
extension = parseOptions[i].Kind == SourceCodeKind.Regular
? CSharpExtension
: CSharpScriptExtension;
}
else if (language == LanguageNames.VisualBasic)
{
extension = parseOptions[i].Kind == SourceCodeKind.Regular
? VisualBasicExtension
: VisualBasicScriptExtension;
}
else
{
extension = language;
}
documentElements.Add(CreateDocumentElement(files[i], "test" + index++ + extension, parseOptions == null ? null : parseOptions[i]));
}
var workspaceElement = CreateWorkspaceElement(
CreateProjectElement("Test", language, true, parseOptions.FirstOrDefault(), compilationOptions, documentElements));
return CreateAsync(workspaceElement, exportProvider: exportProvider);
}
#region C#
public static Task<TestWorkspace> CreateCSharpAsync(
string file,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateCSharpAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences);
}
public static Task<TestWorkspace> CreateCSharpAsync(
string[] files,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider, metadataReferences);
}
public static Task<TestWorkspace> CreateCSharpAsync(
string[] files,
ParseOptions[] parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null)
{
return CreateAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider);
}
#endregion
#region VB
public static Task<TestWorkspace> CreateVisualBasicAsync(
string file,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateVisualBasicAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences);
}
public static Task<TestWorkspace> CreateVisualBasicAsync(
string[] files,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider, metadataReferences);
}
/// <param name="files">Can pass in multiple file contents with individual source kind: files will be named test1.vb, test2.vbx, etc.</param>
public static Task<TestWorkspace> CreateVisualBasicAsync(
string[] files,
ParseOptions[] parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null)
{
return CreateAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SubscriberManagement.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Pattern;
using Akka.Streams.Actors;
using Reactive.Streams;
namespace Akka.Streams.Implementation
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
internal interface ISubscriptionWithCursor<in T> : ISubscription, ICursor
{
/// <summary>
/// TBD
/// </summary>
ISubscriber<T> Subscriber { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
void Dispatch(T element);
/// <summary>
/// TBD
/// </summary>
bool IsActive { get; set; }
/// <summary>
/// Do not increment directly, use <see cref="SubscriberManagement{T}.MoreRequested"/> instead (it provides overflow protection)!
/// </summary>
long TotalDemand { get; set; } // number of requested but not yet dispatched elements
}
#region End of stream
/// <summary>
/// TBD
/// </summary>
internal static class SubscriberManagement
{
/// <summary>
/// TBD
/// </summary>
public interface IEndOfStream
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="subscriber">TBD</param>
void Apply<T>(ISubscriber<T> subscriber);
}
/// <summary>
/// TBD
/// </summary>
public sealed class NotReached : IEndOfStream
{
/// <summary>
/// TBD
/// </summary>
public static readonly NotReached Instance = new NotReached();
private NotReached() { }
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="subscriber">TBD</param>
/// <exception cref="IllegalStateException">TBD</exception>
public void Apply<T>(ISubscriber<T> subscriber)
{
throw new IllegalStateException("Called Apply on NotReached");
}
}
/// <summary>
/// TBD
/// </summary>
public sealed class Completed : IEndOfStream
{
/// <summary>
/// TBD
/// </summary>
public static readonly Completed Instance = new Completed();
private Completed() { }
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="subscriber">TBD</param>
public void Apply<T>(ISubscriber<T> subscriber) => ReactiveStreamsCompliance.TryOnComplete(subscriber);
}
/// <summary>
/// TBD
/// </summary>
public sealed class ErrorCompleted : IEndOfStream
{
/// <summary>
/// TBD
/// </summary>
public readonly Exception Cause;
/// <summary>
/// TBD
/// </summary>
/// <param name="cause">TBD</param>
public ErrorCompleted(Exception cause)
{
Cause = cause;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="subscriber">TBD</param>
public void Apply<T>(ISubscriber<T> subscriber) => ReactiveStreamsCompliance.TryOnError(subscriber, Cause);
}
/// <summary>
/// TBD
/// </summary>
public static readonly IEndOfStream ShutDown = new ErrorCompleted(ActorPublisher.NormalShutdownReason);
}
#endregion
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
internal abstract class SubscriberManagement<T> : ICursors
{
private readonly Lazy<ResizableMultiReaderRingBuffer<T>> _buffer;
// optimize for small numbers of subscribers by keeping subscribers in a plain list
private ICollection<ISubscriptionWithCursor<T>> _subscriptions = new List<ISubscriptionWithCursor<T>>();
// number of elements already requested but not yet received from upstream
private long _pendingFromUpstream;
// if non-null, holds the end-of-stream state
private SubscriberManagement.IEndOfStream _endOfStream = SubscriberManagement.NotReached.Instance;
/// <summary>
/// TBD
/// </summary>
protected SubscriberManagement()
{
_buffer = new Lazy<ResizableMultiReaderRingBuffer<T>>(() =>
new ResizableMultiReaderRingBuffer<T>(InitialBufferSize, MaxBufferSize, this));
}
/// <summary>
/// TBD
/// </summary>
public abstract int InitialBufferSize { get; }
/// <summary>
/// TBD
/// </summary>
public abstract int MaxBufferSize { get; }
/// <summary>
/// TBD
/// </summary>
public IEnumerable<ICursor> Cursors => _subscriptions;
/// <summary>
/// Called when we are ready to consume more elements from our upstream.
/// MUST NOT call <see cref="PushToDownstream"/>.
/// </summary>
/// <param name="elements">TBD</param>
protected abstract void RequestFromUpstream(long elements);
/// <summary>
/// Called before <see cref="Shutdown"/> if the stream is *not* being regularly completed
/// but shut-down due to the last subscriber having cancelled its subscription
/// </summary>
protected abstract void CancelUpstream();
/// <summary>
/// Called when the spi.Publisher/Processor is ready to be shut down.
/// </summary>
/// <param name="isCompleted">TBD</param>
protected abstract void Shutdown(bool isCompleted);
/// <summary>
/// Use to register a subscriber
/// </summary>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
protected abstract ISubscriptionWithCursor<T> CreateSubscription(ISubscriber<T> subscriber);
/// <summary>
/// More demand was signaled from a given subscriber.
/// </summary>
/// <param name="subscription">TBD</param>
/// <param name="elements">TBD</param>
protected void MoreRequested(ISubscriptionWithCursor<T> subscription, long elements)
{
if (subscription.IsActive)
{
// check for illegal demand See 3.9
if (elements < 1)
{
try
{
ReactiveStreamsCompliance.TryOnError(subscription.Subscriber, ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException);
}
finally
{
UnregisterSubscriptionInternal(subscription);
}
}
else
{
if (_endOfStream is SubscriberManagement.NotReached || _endOfStream is SubscriberManagement.Completed)
{
var d = subscription.TotalDemand + elements;
// Long overflow, Reactive Streams Spec 3:17: effectively unbounded
var demand = d < 1 ? long.MaxValue : d;
subscription.TotalDemand = demand;
// returns Long.MinValue if the subscription is to be terminated
var remainingRequested = DispatchFromBufferAndReturnRemainingRequested(demand, subscription, _endOfStream);
if (remainingRequested == long.MinValue)
{
_endOfStream.Apply(subscription.Subscriber);
UnregisterSubscriptionInternal(subscription);
}
else
{
subscription.TotalDemand = remainingRequested;
RequestFromUpstreamIfRequired();
}
}
}
}
}
private long DispatchFromBufferAndReturnRemainingRequested(long requested, ISubscriptionWithCursor<T> subscription, SubscriberManagement.IEndOfStream endOfStream)
{
while (requested != 0)
{
if (_buffer.Value.Count(subscription) > 0)
{
bool goOn;
try
{
subscription.Dispatch(_buffer.Value.Read(subscription));
goOn = true;
}
catch (Exception e)
{
if (e is ISpecViolation)
{
UnregisterSubscriptionInternal(subscription);
goOn = false;
}
else
throw;
}
if (!goOn)
return long.MinValue;
requested--;
}
else if (!(endOfStream is SubscriberManagement.NotReached))
return long.MinValue;
else
return requested;
}
// if request == 0
// if we are at end-of-stream and have nothing more to read we complete now rather than after the next requestMore
return !(endOfStream is SubscriberManagement.NotReached) && _buffer.Value.Count(subscription) == 0 ? long.MinValue : 0;
}
private void RequestFromUpstreamIfRequired()
{
var maxRequested = _subscriptions.Select(x => x.TotalDemand).Max();
var desired =
(int) Math.Min(int.MaxValue, Math.Min(maxRequested, _buffer.Value.CapacityLeft) - _pendingFromUpstream);
if (desired > 0)
{
_pendingFromUpstream += desired;
RequestFromUpstream(desired);
}
}
/// <summary>
/// This method must be called by the implementing class whenever a new value is available to be pushed downstream.
/// </summary>
/// <param name="value">TBD</param>
/// <exception cref="IllegalStateException">TBD</exception>
protected void PushToDownstream(T value)
{
if (_endOfStream is SubscriberManagement.NotReached)
{
_pendingFromUpstream--;
if (!_buffer.Value.Write(value))
throw new IllegalStateException("Output buffer overflow");
if (Dispatch(_subscriptions))
RequestFromUpstreamIfRequired();
}
else throw new IllegalStateException("PushToDownStream(...) after CompleteDownstream() or AbortDownstream(...)");
}
private bool Dispatch(ICollection<ISubscriptionWithCursor<T>> subscriptions)
{
var wasSend = false;
foreach (var subscription in subscriptions)
{
if (subscription.TotalDemand > 0)
{
var element = _buffer.Value.Read(subscription);
subscription.Dispatch(element);
subscription.TotalDemand--;
wasSend = true;
}
}
return wasSend;
}
/// <summary>
/// This method must be called by the implementing class whenever
/// it has been determined that no more elements will be produced
/// </summary>
protected void CompleteDownstream()
{
if (_endOfStream is SubscriberManagement.NotReached)
{
_endOfStream = SubscriberManagement.Completed.Instance;
_subscriptions = CompleteDoneSubscriptions(_subscriptions);
if (_subscriptions.Count == 0)
Shutdown(true);
}
// else ignore, we need to be idempotent
}
private ICollection<ISubscriptionWithCursor<T>> CompleteDoneSubscriptions(ICollection<ISubscriptionWithCursor<T>> subscriptions)
{
var result = new List<ISubscriptionWithCursor<T>>();
foreach (var subscription in subscriptions)
{
if (_buffer.Value.Count(subscription) == 0)
{
subscription.IsActive = false;
SubscriberManagement.Completed.Instance.Apply(subscription.Subscriber);
}
else
result.Add(subscription);
}
return result;
}
/// <summary>
/// This method must be called by the implementing class to push an error downstream.
/// </summary>
/// <param name="cause">TBD</param>
protected void AbortDownstream(Exception cause)
{
_endOfStream = new SubscriberManagement.ErrorCompleted(cause);
foreach (var subscription in _subscriptions)
_endOfStream.Apply(subscription.Subscriber);
_subscriptions.Clear();
}
/// <summary>
/// Register a new subscriber.
/// </summary>
/// <param name="subscriber">TBD</param>
protected void RegisterSubscriber(ISubscriber<T> subscriber)
{
if (_endOfStream is SubscriberManagement.NotReached)
if (_subscriptions.Any(s => s.Subscriber.Equals(subscriber)))
ReactiveStreamsCompliance.RejectAdditionalSubscriber(subscriber, "SubscriberManagement");
else
AddSubscription(subscriber);
else if (_endOfStream is SubscriberManagement.Completed && !_buffer.Value.IsEmpty)
AddSubscription(subscriber);
else _endOfStream.Apply(subscriber);
}
private void AddSubscription(ISubscriber<T> subscriber)
{
var newSubscription = CreateSubscription(subscriber);
_subscriptions.Add(newSubscription);
_buffer.Value.InitCursor(newSubscription);
try
{
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, newSubscription);
}
catch (Exception e)
{
if (e is ISpecViolation)
UnregisterSubscriptionInternal(newSubscription);
else throw;
}
}
/// <summary>
/// Called from <see cref="ISubscription.Cancel"/>, i.e. from another thread,
/// override to add synchronization with itself, <see cref="Subscribe{T}"/> and <see cref="MoreRequested"/>
/// </summary>
/// <param name="subscription">TBD</param>
protected void UnregisterSubscription(ISubscriptionWithCursor<T> subscription)
=> UnregisterSubscriptionInternal(subscription);
// must be idempotent
private void UnregisterSubscriptionInternal(ISubscriptionWithCursor<T> subscription)
{
if (subscription.IsActive)
{
_subscriptions.Remove(subscription);
_buffer.Value.OnCursorRemoved(subscription);
subscription.IsActive = false;
if (_subscriptions.Count == 0)
{
if (_endOfStream is SubscriberManagement.NotReached)
{
_endOfStream = SubscriberManagement.ShutDown;
CancelUpstream();
}
Shutdown(false);
}
else RequestFromUpstreamIfRequired(); // we might have removed a "blocking" subscriber and can continue now
}
// else ignore, we need to be idempotent
}
}
}
| |
using System;
using OTFontFile;
namespace OTFontFileVal
{
/// <summary>
/// Summary description for val_PCLT.
/// </summary>
public class val_PCLT : Table_PCLT, ITableValidate
{
/************************
* constructors
*/
public val_PCLT(OTTag tag, MBOBuffer buf) : base(tag, buf)
{
}
/************************
* public methods
*/
public bool Validate(Validator v, OTFontVal fontOwner)
{
bool bRet = true;
if (v.PerformTest(T.PCLT_TableLength))
{
if (GetLength() == 54)
{
v.Pass(T.PCLT_TableLength, P.PCLT_P_TableLength, m_tag);
}
else
{
v.Error(T.PCLT_TableLength, E.PCLT_E_TableLength, m_tag, GetLength().ToString());
bRet = false;
}
}
if (v.PerformTest(T.PCLT_Version))
{
if (Version.GetUint() == 0x00010000)
{
v.Pass(T.PCLT_Version, P.PCLT_P_Version, m_tag);
}
else
{
v.Error(T.PCLT_Version, E.PCLT_E_Version, m_tag, "0x"+Version.GetUint().ToString("x8"));
bRet = false;
}
}
if (v.PerformTest(T.PCLT_Pitch))
{
Table_hmtx hmtxTable = (Table_hmtx)fontOwner.GetTable("hmtx");
Table_maxp maxpTable = (Table_maxp)fontOwner.GetTable("maxp");
if (hmtxTable == null)
{
v.Error(T.PCLT_Pitch, E._TEST_E_TableMissing, m_tag, "hmtx");
bRet = false;
}
else if (maxpTable == null)
{
v.Error(T.PCLT_Pitch, E._TEST_E_TableMissing, m_tag, "maxp");
bRet = false;
}
else
{
uint iSpaceGlyph = fontOwner.FastMapUnicodeToGlyphID(' ');
if (iSpaceGlyph < fontOwner.GetMaxpNumGlyphs())
{
Table_hmtx.longHorMetric hmSpace = hmtxTable.GetOrMakeHMetric(iSpaceGlyph, fontOwner);
if (hmSpace != null)
{
if (Pitch == hmSpace.advanceWidth)
{
v.Pass(T.PCLT_Pitch, P.PCLT_P_Pitch, m_tag);
}
else
{
string s = "actual = " + Pitch + ", expected = " + hmSpace.advanceWidth;
v.Error(T.PCLT_Pitch, E.PCLT_E_Pitch, m_tag, s);
bRet = false;
}
}
}
else
{
// JJF Figure out what to do
v.Warning(T.PCLT_Pitch, W._TEST_W_ErrorInAnotherTable, m_tag, "can't validate Pitch field, error getting the space glyph");
bRet = false;
}
}
}
if (v.PerformTest(T.PCLT_Style))
{
ushort Posture = (ushort)(Style & 0x0003);
ushort Width = (ushort)((Style>>2) & 0x0007);
ushort Structure = (ushort)((Style>>5) & 0x001f);
ushort Reserved = (ushort)(Style>>10);
bool bBitsOk = true;
if (Posture == 3)
{
v.Error(T.PCLT_Style, E.PCLT_E_Style_Posture, m_tag, "0x"+Style.ToString("x4"));
bBitsOk = false;
bRet = false;
}
if (Width == 5)
{
v.Error(T.PCLT_Style, E.PCLT_E_Style_Width, m_tag, "0x"+Style.ToString("x4"));
bBitsOk = false;
bRet = false;
}
if (Structure > 17)
{
v.Error(T.PCLT_Style, E.PCLT_E_Style_Structure, m_tag, "0x"+Style.ToString("x4"));
bBitsOk = false;
bRet = false;
}
if (Reserved != 0)
{
v.Error(T.PCLT_Style, E.PCLT_E_Style_Reserved, m_tag, "0x"+Style.ToString("x4"));
bBitsOk = false;
bRet = false;
}
if (bBitsOk)
{
v.Pass(T.PCLT_Style, P.PCLT_P_Style, m_tag);
}
}
if (v.PerformTest(T.PCLT_StrokeWeight))
{
if (StrokeWeight >= -7 && StrokeWeight <= 7)
{
v.Pass(T.PCLT_StrokeWeight, P.PCLT_P_StrokeWeight, m_tag, StrokeWeight.ToString());
}
else
{
v.Error(T.PCLT_StrokeWeight, E.PCLT_E_StrokeWeight, m_tag, StrokeWeight.ToString());
bRet = false;
}
}
if (v.PerformTest(T.PCLT_WidthType))
{
if (WidthType >= -5 && WidthType <= 5)
{
v.Pass(T.PCLT_WidthType, P.PCLT_P_WidthType, m_tag, WidthType.ToString());
}
else
{
v.Error(T.PCLT_WidthType, E.PCLT_E_WidthType, m_tag, WidthType.ToString());
bRet = false;
}
}
if (v.PerformTest(T.PCLT_SerifStyle))
{
uint bot6 = (uint)SerifStyle & 0x3f;
uint top2 = (uint)SerifStyle>>6;
bool bBitsOk = true;
if (bot6 > 12)
{
v.Error(T.PCLT_SerifStyle, E.PCLT_E_Bottom6, m_tag, "0x"+SerifStyle.ToString("x2"));
bBitsOk = false;
bRet = false;
}
if (top2 == 0 || top2 == 3)
{
v.Error(T.PCLT_SerifStyle, E.PCLT_E_Top2, m_tag);
bBitsOk = false;
bRet = false;
}
if (bBitsOk)
{
v.Pass(T.PCLT_SerifStyle, P.PCLT_P_SerifStyle, m_tag);
}
}
if (v.PerformTest(T.PCLT_Reserved))
{
if (Reserved == 0)
{
v.Pass(T.PCLT_Reserved, P.PCLT_P_Reserved, m_tag);
}
else
{
v.Error(T.PCLT_Reserved, E.PCLT_E_Reserved, m_tag, Reserved.ToString());
bRet = false;
}
}
return bRet;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionaryTests
{
[Fact]
public static void TestBasicScenarios()
{
ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
var ret = cd.TryAdd(1, 11);
if (!ret)
{
ret = cd.TryUpdate(1, 11, 111);
Assert.True(ret);
}
ret = cd.TryAdd(2, 22);
if (!ret)
{
ret = cd.TryUpdate(2, 22, 222);
Assert.True(ret);
}
});
tks[1] = Task.Run(() =>
{
var ret = cd.TryAdd(2, 222);
if (!ret)
{
ret = cd.TryUpdate(2, 222, 22);
Assert.True(ret);
}
ret = cd.TryAdd(1, 111);
if (!ret)
{
ret = cd.TryUpdate(1, 111, 11);
Assert.True(ret);
}
});
Task.WaitAll(tks);
}
[Fact]
public static void TestAdd1()
{
TestAdd1(1, 1, 1, 10000);
TestAdd1(5, 1, 1, 10000);
TestAdd1(1, 1, 2, 5000);
TestAdd1(1, 1, 5, 2000);
TestAdd1(4, 0, 4, 2000);
TestAdd1(16, 31, 4, 2000);
TestAdd1(64, 5, 5, 5000);
TestAdd1(5, 5, 5, 2500);
}
private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread)
{
ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1);
IDictionary<int, int> dict = dictConcurrent;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread));
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
int itemCount = threads * addsPerThread;
for (int i = 0; i < itemCount; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine +
"TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread)
);
}
// Finally, let's verify that the count is reported correctly.
int expectedCount = threads * addsPerThread;
Assert.Equal(expectedCount, dict.Count);
Assert.Equal(expectedCount, dictConcurrent.ToArray().Length);
}
[Fact]
public static void TestUpdate1()
{
TestUpdate1(1, 1, 10000);
TestUpdate1(5, 1, 10000);
TestUpdate1(1, 2, 5000);
TestUpdate1(1, 5, 2001);
TestUpdate1(4, 4, 2001);
TestUpdate1(15, 5, 2001);
TestUpdate1(64, 5, 5000);
TestUpdate1(5, 5, 25000);
}
private static void TestUpdate1(int cLevel, int threads, int updatesPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 1; i <= updatesPerThread; i++) dict[i] = i;
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 1; j <= updatesPerThread; j++)
{
dict[j] = (ii + 2) * j;
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
var div = pair.Value / pair.Key;
var rem = pair.Value % pair.Key;
Assert.Equal(0, rem);
Assert.True(div > 1 && div <= threads + 1,
String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div));
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 1; i <= updatesPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine +
"TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread)
);
}
}
[Fact]
public static void TestRead1()
{
TestRead1(1, 1, 10000);
TestRead1(5, 1, 10000);
TestRead1(1, 2, 5000);
TestRead1(1, 5, 2001);
TestRead1(4, 4, 2001);
TestRead1(15, 5, 2001);
TestRead1(64, 5, 5000);
TestRead1(5, 5, 25000);
}
private static void TestRead1(int cLevel, int threads, int readsPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 0; i < readsPerThread; i += 2) dict[i] = i;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < readsPerThread; j++)
{
int val = 0;
if (dict.TryGetValue(j, out val))
{
Assert.Equal(0, j % 2);
Assert.Equal(j, val);
}
else
{
Assert.Equal(1, j % 2);
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
}
[Fact]
public static void TestRemove1()
{
TestRemove1(1, 1, 10000);
TestRemove1(5, 1, 1000);
TestRemove1(1, 5, 2001);
TestRemove1(4, 4, 2001);
TestRemove1(15, 5, 2001);
TestRemove1(64, 5, 5000);
}
private static void TestRemove1(int cLevel, int threads, int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread);
int N = 2 * threads * removesPerThread;
for (int i = 0; i < N; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < removesPerThread; j++)
{
int value;
int key = 2 * (ii + j * threads);
Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters);
Assert.Equal(-key, value);
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < (threads * removesPerThread); i++)
expectKeys.Add(2 * i + 1);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters);
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(expectKeys.Count, dict.Count);
Assert.Equal(expectKeys.Count, dict.ToArray().Length);
}
[Fact]
public static void TestRemove2()
{
TestRemove2(1);
TestRemove2(10);
TestRemove2(5000);
}
private static void TestRemove2(int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
for (int i = 0; i < removesPerThread; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys.
const int SIZE = 2;
int running = SIZE;
bool[][] seen = new bool[SIZE][];
for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread];
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int t = 0; t < SIZE; t++)
{
int thread = t;
Task.Run(
() =>
{
for (int key = 0; key < removesPerThread; key++)
{
int value;
if (dict.TryRemove(key, out value))
{
seen[thread][key] = true;
Assert.Equal(-key, value);
}
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
Assert.Equal(0, dict.Count);
for (int i = 0; i < removesPerThread; i++)
{
Assert.False(seen[0][i] == seen[1][i],
String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread)
);
}
}
[Fact]
public static void TestRemove3()
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
dict[99] = -99;
ICollection<KeyValuePair<int, int>> col = dict;
// Make sure we cannot "remove" a key/value pair which is not in the dictionary
for (int i = 0; i < 200; i++)
{
if (i != 99)
{
Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)");
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)");
}
}
// Can we remove a key/value pair successfully?
Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair");
// Make sure the key/value pair is gone
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed");
// And that the dictionary is empty. We will check the count in a few different ways:
Assert.Equal(0, dict.Count);
Assert.Equal(0, dict.ToArray().Length);
}
[Fact]
public static void TestGetOrAdd()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, true);
TestGetOrAddOrUpdate(5, 1, 1, 10000, true);
TestGetOrAddOrUpdate(1, 1, 2, 5000, true);
TestGetOrAddOrUpdate(1, 1, 5, 2000, true);
TestGetOrAddOrUpdate(4, 0, 4, 2000, true);
TestGetOrAddOrUpdate(16, 31, 4, 2000, true);
TestGetOrAddOrUpdate(64, 5, 5, 5000, true);
TestGetOrAddOrUpdate(5, 5, 5, 25000, true);
}
[Fact]
public static void TestAddOrUpdate()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, false);
TestGetOrAddOrUpdate(5, 1, 1, 10000, false);
TestGetOrAddOrUpdate(1, 1, 2, 5000, false);
TestGetOrAddOrUpdate(1, 1, 5, 2000, false);
TestGetOrAddOrUpdate(4, 0, 4, 2000, false);
TestGetOrAddOrUpdate(16, 31, 4, 2000, false);
TestGetOrAddOrUpdate(64, 5, 5, 5000, false);
TestGetOrAddOrUpdate(5, 5, 5, 25000, false);
}
private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
if (isAdd)
{
//call one of the overloads of GetOrAdd
switch (j % 3)
{
case 0:
dict.GetOrAdd(j, -j);
break;
case 1:
dict.GetOrAdd(j, x => -x);
break;
case 2:
dict.GetOrAdd(j, (x,m) => x * m, -1);
break;
}
}
else
{
switch (j % 3)
{
case 0:
dict.AddOrUpdate(j, -j, (k, v) => -j);
break;
case 1:
dict.AddOrUpdate(j, (k) => -k, (k, v) => -k);
break;
case 2:
dict.AddOrUpdate(j, (k,m) => k*m, (k, v, m) => k * m, -1);
break;
}
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < addsPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine +
"> FAILED. The set of keys in the dictionary is are not the same as the expected.",
cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate"));
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(addsPerThread, dict.Count);
Assert.Equal(addsPerThread, dict.ToArray().Length);
}
[Fact]
public static void TestBugFix669376()
{
var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer());
cd["test"] = 10;
Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work");
}
private class OrdinalStringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
var xlower = x.ToLowerInvariant();
var ylower = y.ToLowerInvariant();
return string.CompareOrdinal(xlower, ylower) == 0;
}
public int GetHashCode(string obj)
{
return 0;
}
}
[Fact]
public static void TestConstructor()
{
var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) });
Assert.False(dictionary.IsEmpty);
Assert.Equal(1, dictionary.Keys.Count);
Assert.Equal(1, dictionary.Values.Count);
}
[Fact]
public static void TestDebuggerAttributes()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>());
}
[Fact]
public static void TestConstructor_Negative()
{
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) }));
// "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed");
Assert.Throws<ArgumentException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) }));
// "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, 1, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(0, 10));
// "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(-1, 0));
// "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed");
}
[Fact]
public static void TestExceptions()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryAdd(null, 0));
// "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.ContainsKey(null));
// "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed");
int item;
Assert.Throws<ArgumentNullException>(
() => dictionary.TryRemove(null, out item));
// "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.TryGetValue(null, out item));
// "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => { var x = dictionary[null]; });
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<KeyNotFoundException>(
() => { var x = dictionary["1"]; });
// "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 1);
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, (k,m) => 0, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd("1", null, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, (k) => 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd("1", null));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k, m) => 0, (k, v, m) => 0, 42));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", (k, m) => 0, null, 42));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", null, (k, v, m) => 0, 42));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", null, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, null));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed");
dictionary.TryAdd("1", 1);
Assert.Throws<ArgumentException>(
() => ((IDictionary<string, int>)dictionary).Add("1", 2));
// "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed");
}
[Fact]
public static void TestIDictionary()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.False(dictionary.IsReadOnly);
// Empty dictionary should not enumerate
Assert.Empty(dictionary);
const int SIZE = 10;
for (int i = 0; i < SIZE; i++)
dictionary.Add(i.ToString(), i);
Assert.Equal(SIZE, dictionary.Count);
//test contains
Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain returned true for incorrect key type");
Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain returned true for incorrect key");
Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain returned false for correct key");
//test GetEnumerator
int count = 0;
foreach (var obj in dictionary)
{
DictionaryEntry entry = (DictionaryEntry)obj;
string key = (string)entry.Key;
int value = (int)entry.Value;
int expectedValue = int.Parse(key);
Assert.True(value == expectedValue,
String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue));
count++;
}
Assert.Equal(SIZE, count);
Assert.Equal(SIZE, dictionary.Keys.Count);
Assert.Equal(SIZE, dictionary.Values.Count);
//Test Remove
dictionary.Remove("9");
Assert.Equal(SIZE - 1, dictionary.Count);
//Test this[]
for (int i = 0; i < dictionary.Count; i++)
Assert.Equal(i, (int)dictionary[i.ToString()]);
dictionary["1"] = 100; // try a valid setter
Assert.Equal(100, (int)dictionary["1"]);
//non-existing key
Assert.Null(dictionary["NotAKey"]);
}
[Fact]
public static void TestIDictionary_Negative()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.Add(null, 1));
// "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add(1, 1));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add("1", "1"));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.Contains(null));
// "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed");
//Test Remove
Assert.Throws<ArgumentNullException>(
() => dictionary.Remove(null));
// "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed");
//Test this[]
Assert.Throws<ArgumentNullException>(
() => { object val = dictionary[null]; });
// "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary[1] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary["1"] = "0");
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed");
}
[Fact]
public static void IDictionary_Remove_NullKeyInKeyValuePair_ThrowsArgumentNullException()
{
IDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(() => dictionary.Remove(new KeyValuePair<string, int>(null, 0)));
}
[Fact]
public static void TestICollection()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
int key = -1;
int value = +1;
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value);
var objectArray = new Object[1];
dictionary.CopyTo(objectArray, 0);
Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key);
Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value);
var keyValueArray = new KeyValuePair<int, int>[1];
dictionary.CopyTo(keyValueArray, 0);
Assert.Equal(key, keyValueArray[0].Key);
Assert.Equal(value, keyValueArray[0].Value);
var entryArray = new DictionaryEntry[1];
dictionary.CopyTo(entryArray, 0);
Assert.Equal(key, (int)entryArray[0].Key);
Assert.Equal(value, (int)entryArray[0].Value);
}
[Fact]
public static void TestICollection_Negative()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; });
// "TestICollection: FAILED. SyncRoot property didn't throw");
Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0));
// "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed");
Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1));
// "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed");
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1);
Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0));
// "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count");
}
[Fact]
public static void TestClear()
{
var dictionary = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i, i);
Assert.Equal(10, dictionary.Count);
dictionary.Clear();
Assert.Equal(0, dictionary.Count);
int item;
Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear");
Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear");
}
[Fact]
public static void TestTryUpdate()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryUpdate(null, 0, 0));
// "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed");
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i.ToString(), i);
for (int i = 0; i < 10; i++)
{
Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!");
Assert.Equal(i + 1, dictionary[i.ToString()]);
}
//test TryUpdate concurrently
dictionary.Clear();
for (int i = 0; i < 1000; i++)
dictionary.TryAdd(i.ToString(), i);
var mres = new ManualResetEventSlim();
Task[] tasks = new Task[10];
ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true);
for (int i = 0; i < tasks.Length; i++)
{
// We are creating the Task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
tasks[i] = Task.Factory.StartNew((obj) =>
{
mres.Wait();
int index = (((int)obj) + 1) + 1000;
updatedKeys.Value = new ThreadData();
updatedKeys.Value.ThreadIndex = index;
for (int j = 0; j < dictionary.Count; j++)
{
if (dictionary.TryUpdate(j.ToString(), index, j))
{
if (dictionary[j.ToString()] != index)
{
updatedKeys.Value.Succeeded = false;
return;
}
updatedKeys.Value.Keys.Add(j.ToString());
}
}
}, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
mres.Set();
Task.WaitAll(tasks);
int numberSucceeded = 0;
int totalKeysUpdated = 0;
foreach (var threadData in updatedKeys.Values)
{
totalKeysUpdated += threadData.Keys.Count;
if (threadData.Succeeded)
numberSucceeded++;
}
Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!");
Assert.True(totalKeysUpdated == dictionary.Count,
String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated));
foreach (var value in updatedKeys.Values)
{
for (int i = 0; i < value.Keys.Count; i++)
Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex,
String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]]));
}
//test TryUpdate with non atomic values (intPtr > 8)
var dict = new ConcurrentDictionary<int, Struct16>();
dict.TryAdd(1, new Struct16(1, -1));
Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)");
}
#region Helper Classes and Methods
private class ThreadData
{
public int ThreadIndex;
public bool Succeeded = true;
public List<string> Keys = new List<string>();
}
private struct Struct16 : IEqualityComparer<Struct16>
{
public long L1, L2;
public Struct16(long l1, long l2)
{
L1 = l1;
L2 = l2;
}
public bool Equals(Struct16 x, Struct16 y)
{
return x.L1 == y.L1 && x.L2 == y.L2;
}
public int GetHashCode(Struct16 obj)
{
return (int)L1;
}
}
#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.
////////////////////////////////////////////////////////////////////////////
//
// Class: RegionInfo
//
// Purpose: This class represents settings specified by de jure or
// de facto standards for a particular country/region. In
// contrast to CultureInfo, the RegionInfo does not represent
// preferences of the user and does not depend on the user's
// language or culture.
//
// Date: March 31, 1999
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class RegionInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
//
// Name of this region (ie: es-US): serialized, the field used for deserialization
//
internal String m_name;
//
// The CultureData instance that we are going to read data from.
//
internal CultureData m_cultureData;
//
// The RegionInfo for our current region
//
internal static volatile RegionInfo s_currentRegionInfo;
////////////////////////////////////////////////////////////////////////
//
// RegionInfo Constructors
//
// Note: We prefer that a region be created with a full culture name (ie: en-US)
// because otherwise the native strings won't be right.
//
// In Silverlight we enforce that RegionInfos must be created with a full culture name
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
public RegionInfo(String name)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0) //The InvariantCulture has no matching region
{
throw new ArgumentException(SR.Argument_NoRegionInvariantCulture);
}
Contract.EndContractBlock();
//
// For CoreCLR we only want the region names that are full culture names
//
this.m_cultureData = CultureData.GetCultureDataForRegion(name, true);
if (this.m_cultureData == null)
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.Argument_InvalidCultureName, name), "name");
// Not supposed to be neutral
if (this.m_cultureData.IsNeutralCulture)
throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), "name");
SetName(name);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal RegionInfo(CultureData cultureData)
{
this.m_cultureData = cultureData;
this.m_name = this.m_cultureData.SREGIONNAME;
}
[System.Security.SecurityCritical] // auto-generated
private void SetName(string name)
{
// Use the name of the region we found
this.m_name = this.m_cultureData.SREGIONNAME;
}
////////////////////////////////////////////////////////////////////////
//
// GetCurrentRegion
//
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
//
////////////////////////////////////////////////////////////////////////
public static RegionInfo CurrentRegion
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
RegionInfo temp = s_currentRegionInfo;
if (temp == null)
{
temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData);
// Need full name for custom cultures
temp.m_name = temp.m_cultureData.SREGIONNAME;
s_currentRegionInfo = temp;
}
return temp;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetName
//
// Returns the name of the region (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
return (m_name);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetEnglishName
//
// Returns the name of the region in English. (ie: United States)
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SENGCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetDisplayName
//
// Returns the display name (localized) of the region. (ie: United States
// if the current UI language is en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SLOCALIZEDCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetNativeName
//
// Returns the native name of the region. (ie: Deutschland)
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual String NativeName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SNATIVECOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// TwoLetterISORegionName
//
// Returns the two letter ISO region name (ie: US)
//
////////////////////////////////////////////////////////////////////////
public virtual String TwoLetterISORegionName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SISO3166CTRYNAME);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsMetric
//
// Returns true if this region uses the metric measurement system
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsMetric
{
get
{
int value = this.m_cultureData.IMEASURE;
return (value == 0);
}
}
////////////////////////////////////////////////////////////////////////
//
// CurrencySymbol
//
// Currency Symbol for this locale, ie: Fr. or $
//
////////////////////////////////////////////////////////////////////////
public virtual String CurrencySymbol
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SCURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
// ISOCurrencySymbol
//
// ISO Currency Symbol for this locale, ie: CHF
//
////////////////////////////////////////////////////////////////////////
public virtual String ISOCurrencySymbol
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SINTLSYMBOL);
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same RegionInfo as the current instance.
//
// RegionInfos are considered equal if and only if they have the same name
// (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
RegionInfo that = value as RegionInfo;
if (that != null)
{
return this.Name.Equals(that.Name);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for RegionInfo
// A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns the name of the Region, ie: es-US
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return (Name);
}
}
}
| |
using System;
using System.Collections.Generic;
using CoreGraphics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Localizations;
using UIKit;
using MusicPlayer.Models;
using MusicPlayer.Playback;
using MusicPlayer.Managers;
using MusicPlayer.iOS.ViewControllers;
using MusicPlayer.Data;
namespace MusicPlayer.iOS
{
internal class EqualizerViewController : UIViewController
{
public EqualizerViewController()
{
Title = Strings.Equalizer;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
view.combobox.Items = Equalizer.Shared.Presets.ToArray();
view.onSwitch.On = Equalizer.Shared.Active;
view.SetPreset(Equalizer.Shared.CurrentPreset);
NotificationManager.Shared.EqualizerChanged += HandleEqualizerChanged;
NotificationManager.Shared.VideoPlaybackChanged += Shared_VideoPlaybackChanged;
EqualizerManager.Shared.EqualizerReloaded += EqualizerManager_Shared_EqualizerReloaded;
ApplyStyle();
}
void ApplyStyle()
{
this.StyleViewController();
view.ApplyStyle();
}
void EqualizerManager_Shared_EqualizerReloaded ()
{
view.combobox.Items = Equalizer.Shared.Presets.ToArray();
}
private void Shared_VideoPlaybackChanged(object sender, SimpleTables.EventArgs<bool> e)
{
View.SetNeedsLayout();
}
void HandleEqualizerChanged(object sender, EventArgs e)
{
view.combobox.SelectedItem = Equalizer.Shared.CurrentPreset;
view.onSwitch.On = Equalizer.Shared.Active;
}
public override UIStatusBarStyle PreferredStatusBarStyle()
{
return UIStatusBarStyle.LightContent;
}
EqualizerView view;
UIBarButtonItem menuButton;
public override void LoadView()
{
View = view = new EqualizerView(this);
var style = View.GetStyle();
if (NavigationController == null)
return;
NavigationController.NavigationBar.TitleTextAttributes = new UIStringAttributes
{
ForegroundColor = style.AccentColor
};
menuButton = new UIBarButtonItem(Images.MenuImage, UIBarButtonItemStyle.Plain,
(s, e) => { NotificationManager.Shared.ProcToggleMenu(); })
{
AccessibilityIdentifier = "menu",
};
NavigationItem.LeftBarButtonItem = BaseViewController.ShouldShowMenuButton(this) ? menuButton : null;
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
NavigationItem.LeftBarButtonItem = BaseViewController.ShouldShowMenuButton(this) ? menuButton : null;
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
NotificationManager.Shared.EqualizerChanged -= HandleEqualizerChanged;
NotificationManager.Shared.VideoPlaybackChanged -= Shared_VideoPlaybackChanged;
EqualizerManager.Shared.EqualizerReloaded -= EqualizerManager_Shared_EqualizerReloaded;
try
{
EqualizerManager.Shared.SaveCurrent();
}
catch (Exception ex)
{
//Logger.Log (ex);
}
}
public class EqualizerView : UIView
{
UILabel active = new UILabel();
UILabel preset = new UILabel();
List<UISlider> Sliders = new List<UISlider>();
List<UILabel> labels = new List<UILabel>();
public UISwitch onSwitch;
nfloat sliderH = 0f;
EqualizerViewController Parent;
const float topItemsPadding = 10;
const float sidePadding = 20f;
UIView line1;
UIView line2;
public UIComboBox combobox;
UIToolbar toolbar;
public EqualizerView(EqualizerViewController eqvc)
{
BackgroundColor = UIColor.White;
Parent = eqvc;
line1 = new UIView()
{
// BackgroundColor =Style.Current.Equalizer.LineColor.Value,
};
this.AddSubview(line1);
line2 = new UIView()
{
// BackgroundColor =Style.Current.Equalizer.LineColor.Value,
};
this.AddSubview(line2);
active.Text = Strings.Active;
// active.Font =Style.Current.Equalizer.TitleFont.Value;
// active.TextColor =Style.Current.Equalizer.TitleFontColor.Value;
active.SizeToFit();
this.AddSubview(active);
preset.Text = Strings.DefaultPreset;
// preset.Font =Style.Current.Equalizer.TitleFont.Value;
// preset.TextColor =Style.Current.Equalizer.TitleFontColor.Value;
preset.SizeToFit();
this.AddSubview(preset);
onSwitch = new UISwitch(new CGRect(0, 0, 47, 10)).StyleSwitch();
onSwitch.On = Settings.EqualizerEnabled;
// onSwitch.TintColor = UIColor.FromPatternImage(Images.SwitchOffBackground.Value);
// onSwitch.OnTintColor = UIColor.FromPatternImage(Images.SwitchOnBackground.Value);
// onSwitch.ThumbTintColor =Style.Current.Equalizer.SwitchOnThumbColor.Value;
onSwitch.ValueChanged += delegate
{
Equalizer.Shared.Active = onSwitch.On;
updateImages();
};
//onLabel = new UILabel(new CGRect(0,0,100,22)){Text = "On".Translate(), BackgroundColor = UIColor.Clear};
this.AddSubview(onSwitch);
//this.AddSubview(onLabel);
init();
combobox = new UIComboBox
{
Items = Equalizer.Shared.Presets.ToArray(),
DisplayMember = "Name",
ViewForPicker = Parent,
TextColor = textColor,
// Font =Style.Current.Equalizer.PresetFont.Value,
TextAlignment = UITextAlignment.Right
};
combobox.ValueChanged += delegate { SetPreset((EqualizerPreset) combobox.SelectedItem); };
this.AddSubview(combobox);
SetCombobox();
toolbar = new UIToolbar();
// toolbar.SetBackgroundImage(Images.ToolbarBackground.Value, UIToolbarPosition.Any, UIBarMetrics.Default);
toolbar.SetItems(new UIBarButtonItem[]
{
new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace) {Width = 10},
new UIBarButtonItem(Images.GetEditIcon(25), UIBarButtonItemStyle.Plain, (sender, args) => Rename()),
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
new UIBarButtonItem(Images.GetCopyIcon(25), UIBarButtonItemStyle.Plain, (sender, args) => Duplicate()),
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
new UIBarButtonItem(Images.GetDeleteIcon(25), UIBarButtonItemStyle.Plain, (sender, args) => Delete()),
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
new UIBarButtonItem(Images.GetUndoImage(25), UIBarButtonItemStyle.Plain, (sender, args) => Undo()),
new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace) {Width = 10},
}, false);
this.AddSubview(toolbar);
}
public void ApplyStyle()
{
var style = this.GetStyle();
BackgroundColor = style.BackgroundColor;
toolbar.BarStyle = style.BarStyle;
combobox.TextColor = style.MainTextColor;
labels.ForEach(x => x.TextColor = style.SubTextColor);
active.StyleAsMainText();
preset.StyleAsMainText();
combobox.TitleLabel.StyleAsMainText();
}
public async void Rename()
{
try
{
var currentPreset = EqualizerManager.Shared.GetCurrent();
var newName = await PopupManager.Shared.GetTextInput(Strings.RenamePreset, currentPreset.Name);
if (string.IsNullOrWhiteSpace(newName))
{
App.ShowAlert(Strings.RenameError, Strings.InvalidName);
return;
}
currentPreset.Name = newName;
currentPreset.Save();
EqualizerManager.Shared.ReloadPresets();
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex);
}
}
public async void Duplicate()
{
try
{
var currentPreset = EqualizerManager.Shared.GetCurrent();
var newName = await PopupManager.Shared.GetTextInput(Strings.CopyPreset, currentPreset.Name + Strings.Copy);
currentPreset.Clone();
currentPreset.Name = newName;
currentPreset.Save();
EqualizerManager.Shared.ReloadPresets();
SetPreset(currentPreset);
}
catch (TaskCanceledException ex)
{
}
}
public void Undo()
{
var currentPreset = EqualizerManager.Shared.GetCurrent();
var alert = new UIAlertView(Strings.AreYouSure, $"{Strings.Reset} {currentPreset.Name}", null, Strings.No, Strings.Yes);
alert.Clicked += (sender, args) =>
{
if (args.ButtonIndex != 1)
return;
EqualizerManager.Shared.Reset(currentPreset);
SetPreset(currentPreset);
return;
};
alert.Show();
}
public void Delete()
{
var currentPreset = EqualizerManager.Shared.GetCurrent();
var alert = new UIAlertView(Strings.AreYouSure, $"{Strings.Delete} {currentPreset.Name}", null, Strings.No, Strings.Yes);
alert.Clicked += (sender, args) =>
{
if (args.ButtonIndex != 1)
return;
EqualizerManager.Shared.Delete(currentPreset);
return;
};
alert.Show();
}
public async void AddPreset()
{
try
{
var newName = await PopupManager.Shared.GetTextInput(Strings.NewPreset, "");
EqualizerManager.Shared.AddPreset(newName);
}
catch (TaskCanceledException ex)
{
}
}
public void SetCombobox()
{
combobox.SelectedItem = Equalizer.Shared.CurrentPreset;
SetPreset((EqualizerPreset) combobox.SelectedItem);
}
const float EqSliderMaxHeight = 250f;
public override void LayoutSubviews()
{
var width = this.Bounds.Width/(Sliders.Count + 1);
var padding = width/2;
var right = Bounds.Width - sidePadding;
var leftPadding = this.GetSafeArea().Left;
var frame = onSwitch.Frame;
frame.X = right - frame.Width;
frame.Y = this.Parent.NavigationController.NavigationBar.Frame.Bottom + topItemsPadding;
onSwitch.Frame = frame;
active.Center = new CGPoint(active.Frame.Width/2 + sidePadding/2 + leftPadding, onSwitch.Center.Y);
var fullwidth = Bounds.Width;
line1.Frame = new CGRect(0, frame.Bottom + topItemsPadding/2, fullwidth, 1);
frame = combobox.Frame;
frame.X = right - frame.Width;
frame.Y = onSwitch.Frame.Bottom + topItemsPadding;
combobox.Frame = frame;
preset.Center = new CGPoint(preset.Frame.Width/2 + sidePadding/2 + leftPadding, combobox.Center.Y);
line2.Frame = new CGRect(0, frame.Bottom + topItemsPadding/2, fullwidth, 1);
const float BottomBarHeight = 34;
toolbar.Frame = new CGRect(0, Bounds.Height - NowPlayingViewController.Current.GetCurrentTopHeight() - BottomBarHeight, Bounds.Width,
BottomBarHeight);
var sliderTop = line2.Frame.Bottom;
var available = toolbar.Frame.Top - sliderTop - (topItemsPadding*2) - 25;
nfloat height = 0;
//if (Util.IsIphone)
height = NMath.Min(available, EqSliderMaxHeight);
//else
// height = this.Bounds.Height - 65;
sliderH = sliderTop + ((available - height)/2) + topItemsPadding;
for (int i = 0; i < Sliders.Count; i++)
{
var x = width*i + padding;
var slider = Sliders[i];
var label = labels[i];
slider.Frame = new CGRect(x, sliderH, width, height);
label.Frame = new CGRect(x, slider.Frame.Bottom, width, 25);
}
//combobox.Frame = combobox.Frame.SetLocation (xOffset + padding, height + 75);
//SetNeedsDisplay();
}
EqualizerPreset currentPreset;
public void SetPreset(EqualizerPreset preset)
{
if (preset == null || currentPreset == preset)
return;
currentPreset = preset;
try
{
EqualizerManager.Shared.SaveCurrent();
shouldSave = false;
Equalizer.Shared.CurrentPreset = preset;
Settings.EqualizerPreset = preset.Id;
for (int i = 0; i < preset.Values.Length; i++)
{
Sliders[i].SetValue((float) preset.Values[i].Value, true);
EqualizerManager.Shared.SetGain((int) Sliders[i].Tag, Sliders[i].Value);
}
shouldSave = true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
void updateImages()
{
//onSwitch.ThumbTintColor = Settings.EqualizerEnabled ?Style.Current.Equalizer.SwitchOnThumbColor.Value :Style.Current.Equalizer.SwitchOffThumbColor.Value;
var image = Settings.EqualizerEnabled ? thumbImageOn : thumbImageOff;
foreach (var slider in Sliders)
{
slider.SetThumbImage(image, UIControlState.Normal);
slider.SetThumbImage(image, UIControlState.Highlighted);
var track = Settings.EqualizerEnabled ? Images.AccentImage.Value : Images.GetSliderTrack();
slider.SetMinTrackImage(track, UIControlState.Normal);
}
}
void init()
{
clearSliders();
for (int i = 0; i < Equalizer.Shared.Bands.Length; i++)
{
createSlider(i);
//UpdateGain(i);
}
updateImages();
}
void clearSliders()
{
foreach (var slider in Sliders)
{
slider.RemoveFromSuperview();
slider.ValueChanged -= HandleValueChanged;
}
foreach (var label in labels)
{
label.RemoveFromSuperview();
}
labels = new List<UILabel>();
Sliders = new List<UISlider>();
}
UIImage thumbImageOn, thumbImageOff;
UIColor textColor = UIColor.Black;
void createSlider(int index)
{
if (thumbImageOn == null)
{
thumbImageOn = UIImage.FromBundle("slider-handle-rotated");
thumbImageOff = UIImage.FromBundle("slider-handle-off-rotated");
}
var band = Equalizer.Shared.Bands[index];
var slider = new UISlider() {MinValue = -1*range, MaxValue = range, Value = band.Gain};
slider.Transform = CGAffineTransform.MakeRotation((float) Math.PI*-.5f);
slider.ValueChanged += HandleValueChanged;
slider.Tag = index;
slider.MaximumTrackTintColor = UIColor.DarkGray;
slider.MinimumTrackTintColor = UIColor.DarkGray;
Sliders.Add(slider);
// slider.SetMaxTrackImage(Images.EqSliderOffImage.Value, UIControlState.Normal);
this.AddSubview(slider);
var label = new UILabel()
{
Text = band.ToString(),
TextColor = textColor,
BackgroundColor = UIColor.Clear,
Font = UIFont.SystemFontOfSize(10),
TextAlignment = UITextAlignment.Center
};
labels.Add(label);
this.AddSubview(label);
}
static float range = 12f;
bool shouldSave = true;
void HandleValueChanged(object sender, EventArgs e)
{
var slider = sender as UISlider;
var gain = slider.Value;
EqualizerManager.Shared.SetGain((int) slider.Tag, gain);
if (shouldSave)
EqualizerManager.Shared.SaveCurrent();
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
//// General Declarations
var colorSpace = CGColorSpace.CreateDeviceRGB();
var context = UIGraphics.GetCurrentContext();
// //// Color Declarations
// UIColor gradient2Color = UIColor.FromRGBA(0.906f, 0.910f, 0.910f, 1.000f);
// UIColor gradient2Color2 = UIColor.FromRGBA(0.588f, 0.600f, 0.616f, 1.000f);
//
// //// Gradient Declarations
// var gradient2Colors = new CGColor [] {gradient2Color.CGColor, gradient2Color2.CGColor};
// var gradient2Locations = new float [] {0, 1};
// var gradient2 = new CGGradient(colorSpace, gradient2Colors, gradient2Locations);
//// Abstracted Attributes
var textContent = "+ " + range;
var text2Content = "0";
var text3Content = "- " + range;
//// Rectangle Drawing
// var rectanglePath = UIBezierPath.FromRect(rect);
// context.SaveState();
// rectanglePath.AddClip();
// context.DrawLinearGradient(gradient2, new CGPoint(rect.Height, 0), new CGPoint(rect.Height, rect.Height), 0);
// context.RestoreState();
if (Sliders.Count == 0)
return;
var sliderFrame = Sliders[0].Frame;
var thumbH = 0; //Sliders[0].CurrentThumbImage.Size.Height / 2;
var h = (sliderFrame.Height - (thumbH*2))/8;
var offset = sliderFrame.Y;
var x = sliderFrame.X;
var width = Sliders.Last().Frame.Right;
for (int i = 0; i < 9; i++)
{
UIColor.Black.ColorWithAlpha(0f).SetStroke();
var currH = (i*h) + thumbH;
//if (i == 0)
//{
// //// Text Drawing
// var textRect = new CGRect(0, currH + offset - 7.5f, 37, 13);
// textColor.SetFill();
// new Foundation.NSString(textContent).DrawString(textRect, UIFont.FromName(Style.Fonts.AvenirLight, 10), UILineBreakMode.WordWrap, UITextAlignment.Right);
// //UIColor.Black.ColorWithAlpha(.5f).SetStroke ();
//}
//else
if (i == 4)
{
//// Text Drawing
//var textRect = new CGRect(0, currH + offset - 7.5f, 37, 13);
//textColor.SetFill();
//new Foundation.NSString(text2Content).DrawString(textRect, UIFont.FromName(Style.Fonts.AvenirLight, 10), UILineBreakMode.WordWrap, UITextAlignment.Right);
//textColor.ColorWithAlpha(.5f).SetStroke();
// Style.Colors.LightGray.Value.ColorWithAlpha (.1f).SetStroke ();
}
//else if (i == 8)
//{
// //// Text Drawing
// var textRect = new CGRect(0, currH + offset - 7.5f, 37, 13);
// textColor.SetFill();
// new Foundation.NSString(text3Content).DrawString(textRect, UIFont.FromName(Style.Fonts.AvenirLight, 10), UILineBreakMode.WordWrap, UITextAlignment.Right);
// //UIColor.Black.ColorWithAlpha(.5f).SetStroke ();
//}
context.MoveTo(x, currH + offset);
context.AddLineToPoint(width, currH + offset);
context.StrokePath();
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the GuardiaTiposIngreso class.
/// </summary>
[Serializable]
public partial class GuardiaTiposIngresoCollection : ActiveList<GuardiaTiposIngreso, GuardiaTiposIngresoCollection>
{
public GuardiaTiposIngresoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>GuardiaTiposIngresoCollection</returns>
public GuardiaTiposIngresoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
GuardiaTiposIngreso o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Guardia_TiposIngreso table.
/// </summary>
[Serializable]
public partial class GuardiaTiposIngreso : ActiveRecord<GuardiaTiposIngreso>, IActiveRecord
{
#region .ctors and Default Settings
public GuardiaTiposIngreso()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public GuardiaTiposIngreso(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public GuardiaTiposIngreso(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public GuardiaTiposIngreso(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Guardia_TiposIngreso", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = -1;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Guardia_TiposIngreso",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.GuardiaRegistroCollection colGuardiaRegistros;
public DalSic.GuardiaRegistroCollection GuardiaRegistros
{
get
{
if(colGuardiaRegistros == null)
{
colGuardiaRegistros = new DalSic.GuardiaRegistroCollection().Where(GuardiaRegistro.Columns.IngresoTipo, Id).Load();
colGuardiaRegistros.ListChanged += new ListChangedEventHandler(colGuardiaRegistros_ListChanged);
}
return colGuardiaRegistros;
}
set
{
colGuardiaRegistros = value;
colGuardiaRegistros.ListChanged += new ListChangedEventHandler(colGuardiaRegistros_ListChanged);
}
}
void colGuardiaRegistros_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colGuardiaRegistros[e.NewIndex].IngresoTipo = Id;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
GuardiaTiposIngreso item = new GuardiaTiposIngreso();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,string varNombre)
{
GuardiaTiposIngreso item = new GuardiaTiposIngreso();
item.Id = varId;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colGuardiaRegistros != null)
{
foreach (DalSic.GuardiaRegistro item in colGuardiaRegistros)
{
if (item.IngresoTipo != Id)
{
item.IngresoTipo = Id;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colGuardiaRegistros != null)
{
colGuardiaRegistros.SaveAll();
}
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the ConTurnosDelDiaConAsistencium class.
/// </summary>
[Serializable]
public partial class ConTurnosDelDiaConAsistenciumCollection : ReadOnlyList<ConTurnosDelDiaConAsistencium, ConTurnosDelDiaConAsistenciumCollection>
{
public ConTurnosDelDiaConAsistenciumCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the CON_TurnosDelDiaConAsistencia view.
/// </summary>
[Serializable]
public partial class ConTurnosDelDiaConAsistencium : ReadOnlyRecord<ConTurnosDelDiaConAsistencium>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_TurnosDelDiaConAsistencia", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarCantidadTurnos = new TableSchema.TableColumn(schema);
colvarCantidadTurnos.ColumnName = "cantidadTurnos";
colvarCantidadTurnos.DataType = DbType.Int32;
colvarCantidadTurnos.MaxLength = 0;
colvarCantidadTurnos.AutoIncrement = false;
colvarCantidadTurnos.IsNullable = true;
colvarCantidadTurnos.IsPrimaryKey = false;
colvarCantidadTurnos.IsForeignKey = false;
colvarCantidadTurnos.IsReadOnly = false;
schema.Columns.Add(colvarCantidadTurnos);
TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema);
colvarIdAgenda.ColumnName = "idAgenda";
colvarIdAgenda.DataType = DbType.Int32;
colvarIdAgenda.MaxLength = 0;
colvarIdAgenda.AutoIncrement = false;
colvarIdAgenda.IsNullable = false;
colvarIdAgenda.IsPrimaryKey = false;
colvarIdAgenda.IsForeignKey = false;
colvarIdAgenda.IsReadOnly = false;
schema.Columns.Add(colvarIdAgenda);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_TurnosDelDiaConAsistencia",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public ConTurnosDelDiaConAsistencium()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public ConTurnosDelDiaConAsistencium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public ConTurnosDelDiaConAsistencium(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public ConTurnosDelDiaConAsistencium(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get
{
return GetColumnValue<string>("nombre");
}
set
{
SetColumnValue("nombre", value);
}
}
[XmlAttribute("CantidadTurnos")]
[Bindable(true)]
public int? CantidadTurnos
{
get
{
return GetColumnValue<int?>("cantidadTurnos");
}
set
{
SetColumnValue("cantidadTurnos", value);
}
}
[XmlAttribute("IdAgenda")]
[Bindable(true)]
public int IdAgenda
{
get
{
return GetColumnValue<int>("idAgenda");
}
set
{
SetColumnValue("idAgenda", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Nombre = @"nombre";
public static string CantidadTurnos = @"cantidadTurnos";
public static string IdAgenda = @"idAgenda";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// 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.AcceptanceTestsRequiredOptional
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// ImplicitModel operations.
/// </summary>
public partial class ImplicitModel : IServiceOperations<AutoRestRequiredOptionalTestService>, IImplicitModel
{
/// <summary>
/// Initializes a new instance of the ImplicitModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ImplicitModel(AutoRestRequiredOptionalTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestRequiredOptionalTestService
/// </summary>
public AutoRestRequiredOptionalTestService Client { get; private set; }
/// <summary>
/// Test implicitly required path parameter
/// </summary>
/// <param name='pathParameter'>
/// </param>
/// <param name='customHeaders'>
/// 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> GetRequiredPathWithHttpMessagesAsync(string pathParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (pathParameter == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pathParameter");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("pathParameter", pathParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRequiredPath", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/required/path/{pathParameter}").ToString();
_url = _url.Replace("{pathParameter}", Uri.EscapeDataString(pathParameter));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional query parameter
/// </summary>
/// <param name='queryParameter'>
/// </param>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutOptionalQueryWithHttpMessagesAsync(string queryParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("queryParameter", queryParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutOptionalQuery", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/query").ToString();
List<string> _queryParameters = new List<string>();
if (queryParameter != null)
{
_queryParameters.Add(string.Format("queryParameter={0}", Uri.EscapeDataString(queryParameter)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional header parameter
/// </summary>
/// <param name='queryParameter'>
/// </param>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutOptionalHeaderWithHttpMessagesAsync(string queryParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("queryParameter", queryParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutOptionalHeader", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/header").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (queryParameter != null)
{
if (_httpRequest.Headers.Contains("queryParameter"))
{
_httpRequest.Headers.Remove("queryParameter");
}
_httpRequest.Headers.TryAddWithoutValidation("queryParameter", queryParameter);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional body parameter
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutOptionalBodyWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("bodyParameter", bodyParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutOptionalBody", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/body").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(bodyParameter != null)
{
_requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly required path parameter
/// </summary>
/// <param name='customHeaders'>
/// 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> GetRequiredGlobalPathWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.RequiredGlobalPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RequiredGlobalPath");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRequiredGlobalPath", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/required/path/{required-global-path}").ToString();
_url = _url.Replace("{required-global-path}", Uri.EscapeDataString(this.Client.RequiredGlobalPath));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly required query parameter
/// </summary>
/// <param name='customHeaders'>
/// 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> GetRequiredGlobalQueryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.RequiredGlobalQuery == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RequiredGlobalQuery");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRequiredGlobalQuery", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/required/query").ToString();
List<string> _queryParameters = new List<string>();
if (this.Client.RequiredGlobalQuery != null)
{
_queryParameters.Add(string.Format("required-global-query={0}", Uri.EscapeDataString(this.Client.RequiredGlobalQuery)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional query parameter
/// </summary>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> GetOptionalGlobalQueryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOptionalGlobalQuery", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/optional/query").ToString();
List<string> _queryParameters = new List<string>();
if (this.Client.OptionalGlobalQuery != null)
{
_queryParameters.Add(string.Format("optional-global-query={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(this.Client.OptionalGlobalQuery, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdv = Google.Cloud.DocumentAI.V1;
using sys = System;
namespace Google.Cloud.DocumentAI.V1
{
/// <summary>Resource name for the <c>Processor</c> resource.</summary>
public sealed partial class ProcessorName : gax::IResourceName, sys::IEquatable<ProcessorName>
{
/// <summary>The possible contents of <see cref="ProcessorName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/processors/{processor}</c>.
/// </summary>
ProjectLocationProcessor = 1,
}
private static gax::PathTemplate s_projectLocationProcessor = new gax::PathTemplate("projects/{project}/locations/{location}/processors/{processor}");
/// <summary>Creates a <see cref="ProcessorName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ProcessorName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ProcessorName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ProcessorName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ProcessorName"/> with the pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ProcessorName"/> constructed from the provided ids.</returns>
public static ProcessorName FromProjectLocationProcessor(string projectId, string locationId, string processorId) =>
new ProcessorName(ResourceNameType.ProjectLocationProcessor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), processorId: gax::GaxPreconditions.CheckNotNullOrEmpty(processorId, nameof(processorId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProcessorName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProcessorName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string processorId) =>
FormatProjectLocationProcessor(projectId, locationId, processorId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProcessorName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProcessorName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}</c>.
/// </returns>
public static string FormatProjectLocationProcessor(string projectId, string locationId, string processorId) =>
s_projectLocationProcessor.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(processorId, nameof(processorId)));
/// <summary>Parses the given resource name string into a new <see cref="ProcessorName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/processors/{processor}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="processorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProcessorName"/> if successful.</returns>
public static ProcessorName Parse(string processorName) => Parse(processorName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ProcessorName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/processors/{processor}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="processorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ProcessorName"/> if successful.</returns>
public static ProcessorName Parse(string processorName, bool allowUnparsed) =>
TryParse(processorName, allowUnparsed, out ProcessorName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProcessorName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/processors/{processor}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="processorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProcessorName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string processorName, out ProcessorName result) => TryParse(processorName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProcessorName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/processors/{processor}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="processorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProcessorName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string processorName, bool allowUnparsed, out ProcessorName result)
{
gax::GaxPreconditions.CheckNotNull(processorName, nameof(processorName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationProcessor.TryParseName(processorName, out resourceName))
{
result = FromProjectLocationProcessor(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(processorName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ProcessorName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string processorId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProcessorId = processorId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ProcessorName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
public ProcessorName(string projectId, string locationId, string processorId) : this(ResourceNameType.ProjectLocationProcessor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), processorId: gax::GaxPreconditions.CheckNotNullOrEmpty(processorId, nameof(processorId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Processor</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProcessorId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationProcessor: return s_projectLocationProcessor.Expand(ProjectId, LocationId, ProcessorId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ProcessorName);
/// <inheritdoc/>
public bool Equals(ProcessorName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ProcessorName a, ProcessorName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ProcessorName a, ProcessorName b) => !(a == b);
}
/// <summary>Resource name for the <c>HumanReviewConfig</c> resource.</summary>
public sealed partial class HumanReviewConfigName : gax::IResourceName, sys::IEquatable<HumanReviewConfigName>
{
/// <summary>The possible contents of <see cref="HumanReviewConfigName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>.
/// </summary>
ProjectLocationProcessor = 1,
}
private static gax::PathTemplate s_projectLocationProcessor = new gax::PathTemplate("projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig");
/// <summary>Creates a <see cref="HumanReviewConfigName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="HumanReviewConfigName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static HumanReviewConfigName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new HumanReviewConfigName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="HumanReviewConfigName"/> with the pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="HumanReviewConfigName"/> constructed from the provided ids.</returns>
public static HumanReviewConfigName FromProjectLocationProcessor(string projectId, string locationId, string processorId) =>
new HumanReviewConfigName(ResourceNameType.ProjectLocationProcessor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), processorId: gax::GaxPreconditions.CheckNotNullOrEmpty(processorId, nameof(processorId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="HumanReviewConfigName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="HumanReviewConfigName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>.
/// </returns>
public static string Format(string projectId, string locationId, string processorId) =>
FormatProjectLocationProcessor(projectId, locationId, processorId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="HumanReviewConfigName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="HumanReviewConfigName"/> with pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>.
/// </returns>
public static string FormatProjectLocationProcessor(string projectId, string locationId, string processorId) =>
s_projectLocationProcessor.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(processorId, nameof(processorId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="HumanReviewConfigName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="humanReviewConfigName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="HumanReviewConfigName"/> if successful.</returns>
public static HumanReviewConfigName Parse(string humanReviewConfigName) => Parse(humanReviewConfigName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="HumanReviewConfigName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="humanReviewConfigName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="HumanReviewConfigName"/> if successful.</returns>
public static HumanReviewConfigName Parse(string humanReviewConfigName, bool allowUnparsed) =>
TryParse(humanReviewConfigName, allowUnparsed, out HumanReviewConfigName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="HumanReviewConfigName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="humanReviewConfigName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="HumanReviewConfigName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string humanReviewConfigName, out HumanReviewConfigName result) =>
TryParse(humanReviewConfigName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="HumanReviewConfigName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="humanReviewConfigName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="HumanReviewConfigName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string humanReviewConfigName, bool allowUnparsed, out HumanReviewConfigName result)
{
gax::GaxPreconditions.CheckNotNull(humanReviewConfigName, nameof(humanReviewConfigName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationProcessor.TryParseName(humanReviewConfigName, out resourceName))
{
result = FromProjectLocationProcessor(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(humanReviewConfigName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private HumanReviewConfigName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string processorId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProcessorId = processorId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="HumanReviewConfigName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorId">The <c>Processor</c> ID. Must not be <c>null</c> or empty.</param>
public HumanReviewConfigName(string projectId, string locationId, string processorId) : this(ResourceNameType.ProjectLocationProcessor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), processorId: gax::GaxPreconditions.CheckNotNullOrEmpty(processorId, nameof(processorId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Processor</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProcessorId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationProcessor: return s_projectLocationProcessor.Expand(ProjectId, LocationId, ProcessorId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as HumanReviewConfigName);
/// <inheritdoc/>
public bool Equals(HumanReviewConfigName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(HumanReviewConfigName a, HumanReviewConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(HumanReviewConfigName a, HumanReviewConfigName b) => !(a == b);
}
public partial class ProcessRequest
{
/// <summary>
/// <see cref="gcdv::ProcessorName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::ProcessorName ProcessorName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::ProcessorName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class BatchProcessRequest
{
/// <summary>
/// <see cref="gcdv::ProcessorName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::ProcessorName ProcessorName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::ProcessorName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ReviewDocumentRequest
{
/// <summary>
/// <see cref="HumanReviewConfigName"/>-typed view over the <see cref="HumanReviewConfig"/> resource name
/// property.
/// </summary>
public HumanReviewConfigName HumanReviewConfigAsHumanReviewConfigName
{
get => string.IsNullOrEmpty(HumanReviewConfig) ? null : HumanReviewConfigName.Parse(HumanReviewConfig, allowUnparsed: true);
set => HumanReviewConfig = value?.ToString() ?? "";
}
}
}
| |
/***********************************************************************************************************************
*
* Unity-SCORM Integration Toolkit Version 1.4 Beta
* ==========================================
*
* Copyright (C) 2011, by ADL (Advance Distributed Learning). (http://www.adlnet.gov)
* http://www.adlnet.gov/UnityScormIntegration/
*
***********************************************************************************************************************
*
* 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 UnityEngine;
using System.Collections;
using UnityEditor;
using System.Web;
using Ionic.Zip;
using System.IO;
//This class handles the editor window
public class ScormExport : EditorWindow {
public GUISkin skin;
static bool foldout1,foldout2,foldout3,foldout4;
static ScormExport window;
static Vector2 scrollview;
//Add this to the main editor gui
[MenuItem("SCORM/Export SCORM Package",false,0)]
static void ShowWindow()
{
EditorUtility.DisplayDialog("Export this scene as a WebPlayer first","Because this software is developed for Unity Basic, we cannot automatically build the web player. Please export your simulation to the web player first. Remember to select the SCORM Integration web player template.","OK");
window = (ScormExport)EditorWindow.GetWindow (typeof (ScormExport));
window.ShowAuxWindow();
foldout1=foldout2=foldout3=foldout4 = true;
}
static void Init () {
// Get existing open window or if none, make a new one:
window = (ScormExport)EditorWindow.GetWindow (typeof (ScormExport));
window.ShowAuxWindow();
}
[MenuItem("SCORM/Create SCORM Manager",false,0)]
static void CreateManager()
{
GameObject manager = GameObject.Find("ScormManager");
if(manager == null)
{
manager = (GameObject)UnityEditor.SceneView.Instantiate(Resources.Load("ScormManager"));
manager.name = "ScormManager";
EditorUtility.DisplayDialog("The SCORM Manager has been added to the scene","Remember to place objects that need messages from the ScormManager under it in the scene heirarchy. It will send the message 'Scorm_Initialize_Complete' when it finishes communicating with the LMS.","OK");
}else
{
EditorUtility.DisplayDialog("SCORM Manager is already present","You only need one SCORM Manager game object in your simulation. Remember to place objects that need messages from the ScormManager under it in the scene heirarchy.","OK");
}
}
//Add this to the main editor gui
[MenuItem("SCORM/About SCORM Integration",false,0)]
static void About()
{
EditorUtility.DisplayDialog("Unity-SCORM Integration Toolkit Version 1.4 Beta","This software is a demonstation of integration between web deployed immersive 3D training and a Learning Managment System (LMS) using the Sharable Content Object Reference Model (SCORM) developed at the US Department of Defence Advance Distributed Learning (ADL) Inititive. This software is provided 'as-is' and is available free of charge at http://www.adlnet.gov. This software may be used under the provisions of the Apache 2.0 license. Source code is available from www.adlnet.gov. ","OK");
}
//Add this to the main editor gui
[MenuItem("SCORM/Help",false,0)]
static void Help()
{
Application.OpenURL("http://www.adlnet.gov/scorm-unity-integration");
}
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
string GetParameterString()
{
string parameters = "?";
int num = PlayerPrefs.GetInt("Param_Count");
for( int i = 0; i < num; i++)
{
if(PlayerPrefs.GetString("Param_"+i.ToString()+"_Name") != "")
{
parameters+= PlayerPrefs.GetString("Param_"+i.ToString()+"_Name") + "="+ PlayerPrefs.GetString("Param_"+i.ToString()+"_Value") + "&";
}
}
return parameters;
}
void Publish()
{
string webplayer = PlayerPrefs.GetString("Course_Export");
string tempdir = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName();
System.IO.Directory.CreateDirectory(tempdir);
CopyFilesRecursively(new System.IO.DirectoryInfo(webplayer),new System.IO.DirectoryInfo(tempdir));
string zipfile = EditorUtility.SaveFilePanel("Choose Output File",webplayer,PlayerPrefs.GetString("Course_Title"),"zip");
if(zipfile!= "")
{
if(File.Exists(zipfile))
File.Delete(zipfile);
Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipfile);
zip.AddDirectory(tempdir);
if(PlayerPrefs.GetInt("SCORM_Version") < 3)
{
zip.AddItem(Application.dataPath + "/ADL SCORM/Plugins/2004");
string manifest =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- exported by Unity-SCORM Integration Toolkit Version 1.4 Beta-->"+
"<manifest xmlns=\"http://www.imsglobal.org/xsd/imscp_v1p1\" xmlns:imsmd=\"http://www.imsglobal.org/xsd/imsmd_v1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_v1p3\" xmlns:imsss=\"http://www.imsglobal.org/xsd/imsss\" xmlns:adlseq=\"http://www.adlnet.org/xsd/adlseq_v1p3\" xmlns:adlnav=\"http://www.adlnet.org/xsd/adlnav_v1p3\" identifier=\"MANIFEST-AECEF15E-06B8-1FAB-5289-73A0B058E2DD\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd http://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd http://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd http://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd\" version=\"1.3\">"+
" <metadata>"+
" <schema>ADL SCORM</schema>"
+((PlayerPrefs.GetInt("SCORM_Version") == 0)?" <schemaversion>2004 4th Edition</schemaversion>":"")
+((PlayerPrefs.GetInt("SCORM_Version") == 1)?" <schemaversion>2004 3rd Edition</schemaversion>":"")
+((PlayerPrefs.GetInt("SCORM_Version") == 2)?" <schemaversion>2004 CAM 1.3</schemaversion>":"")
+
" </metadata>"+
" <organizations default=\"ORG-8770D9D9-AD66-06BB-9A3D-E87784C697FF\">"+
" <organization identifier=\"ORG-8770D9D9-AD66-06BB-9A3D-E87784C697FF\">"+
" <title>"+PlayerPrefs.GetString("Course_Title")+"</title>"+
" <item identifier=\"ITEM-79701DB3-F0AD-9426-8C43-819F3CB0EE6E\" identifierref=\"RES-4F17946A-9286-D5F0-7B6A-04E980C04F46\" parameters=\"" + GetParameterString() +"\">"+
" <title>"+PlayerPrefs.GetString("SCO_Title")+"</title>"+
" <adlcp:dataFromLMS>"+ PlayerPrefs.GetString("Data_From_Lms") +"</adlcp:dataFromLMS>"+
" <adlcp:completionThreshold completedByMeasure = \""+ (System.Convert.ToBoolean(PlayerPrefs.GetInt("completedByMeasure"))).ToString().ToLower() +"\" minProgressMeasure= \""+PlayerPrefs.GetFloat("minProgressMeasure") +"\" />";
if(PlayerPrefs.GetInt("satisfiedByMeasure") == 1)
{
manifest += " <imsss:sequencing>"+
" <imsss:objectives>"+
" <imsss:primaryObjective objectiveID = \"PRIMARYOBJ\""+
" satisfiedByMeasure = \"" + (System.Convert.ToBoolean(PlayerPrefs.GetInt("satisfiedByMeasure"))).ToString().ToLower() + "\">"+
" <imsss:minNormalizedMeasure>"+ PlayerPrefs.GetFloat("minNormalizedMeasure") +"</imsss:minNormalizedMeasure>"+
" </imsss:primaryObjective>"+
" </imsss:objectives>"+
" </imsss:sequencing>";
}
manifest +=
" </item>"+
" </organization>"+
" </organizations>"+
" <resources>"+
" <resource identifier=\"RES-4F17946A-9286-D5F0-7B6A-04E980C04F46\" type=\"webcontent\" href=\"WebPlayer/WebPlayer.html\" adlcp:scormType=\"sco\">"+
" <file href=\"WebPlayer/WebPlayer.html\" />"+
" <file href=\"WebPlayer/scripts/scorm.js\" />"+
" <file href=\"WebPlayer/scripts/ScormSimulator.js\" />"+
" <file href=\"WebPlayer/UnityObject.js\" />"+
" <file href=\"WebPlayer/Webplayer.unity3d\" />"+
" <file href=\"WebPlayer/images/scorm_progres_bar.png\" />"+
" <file href=\"WebPlayer/images/thumbnail.png\" />"+
" </resource>"+
" </resources>"+
"</manifest>";
zip.AddEntry("imsmanifest.xml",".",System.Text.ASCIIEncoding.ASCII.GetBytes(manifest));
}else
{
zip.AddItem(Application.dataPath + "/ADL SCORM/Plugins/1.2");
string manifest =
"<?xml version=\"1.0\"?>"+
"<!-- exported by Unity-SCORM Integration Toolkit Version 1.4 Beta-->"+
"<manifest identifier=\"SingleCourseManifest\" version=\"1.1\""+
" xmlns=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2\""+
" xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_rootv1p2\""+
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:schemaLocation=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd"+
" http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd"+
" http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd\">"+
" <organizations default=\"B0\">"+
" <organization identifier=\"B0\">"+
" <title>"+PlayerPrefs.GetString("Course_Title")+"</title>"+
" <item identifier=\"IS12\" identifierref=\"RS12\" parameters=\""+ GetParameterString() +"\">"+
" <title>"+PlayerPrefs.GetString("SCO_Title")+"</title>"+
" <adlcp:dataFromLMS>"+ PlayerPrefs.GetString("Data_From_Lms") +"</adlcp:dataFromLMS>"+
" <adlcp:masteryscore>"+PlayerPrefs.GetFloat("masteryscore")+"</adlcp:masteryscore>"+
" </item>"+
" </organization>"+
" </organizations>"+
" <resources>"+
" <resource identifier=\"RS12\" type=\"webcontent\""+
" adlcp:scormtype=\"sco\" href=\"WebPlayer/WebPlayer.html\">"+
" </resource>"+
" </resources>"+
" </manifest>";
zip.AddEntry("imsmanifest.xml",".",System.Text.ASCIIEncoding.ASCII.GetBytes(manifest));
}
zip.Save();
}
}
//If there is no selection,show the search page and results, otherwise show the selection
void OnGUI()
{
//window.position = new Rect(window.position.x,window.position.y,330,450);
EditorStyles.miniLabel.wordWrap = true;
EditorStyles.foldout.fontStyle = FontStyle.Bold;
GUILayout.BeginHorizontal();
foldout1 = EditorGUILayout.Foldout(foldout1,"Player Location", EditorStyles.foldout);
bool help1 = GUILayout.Button(new GUIContent ("Help", "Help for the Player Location section"),EditorStyles.miniBoldLabel);
if(help1)
EditorUtility.DisplayDialog("Help","You must export this simulation as a webplayer, then tell this packaging tool the location of that exported webplayer folder. Be sure to select the SCORM webplayer template, or the necessary JavaScript components will not be included, and the system will fail to connect to the LMS.","OK");
GUILayout.EndHorizontal();
if(foldout1)
{
GUILayout.BeginVertical("TextArea");
GUILayout.Label("Choose the location where the Webplayer was exported", EditorStyles.miniLabel);
//GUILayout.BeginHorizontal();
PlayerPrefs.SetString("Course_Export", EditorGUILayout.TextField("Player Folder", PlayerPrefs.GetString("Course_Export")));
GUI.skin.button.fontSize = 8;
GUILayout.BeginHorizontal();
GUILayout.Space(window.position.width - 85);
bool ChooseDir = GUILayout.Button(new GUIContent("Choose Folder","Select the folder containing the webplayer"),GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
if(ChooseDir)
{
string export_dir = EditorUtility.OpenFolderPanel("Choose WebPlayer",PlayerPrefs.GetString("Course_Export"),"WebPlayer");
if(export_dir != "")
{
if(export_dir.Substring(export_dir.LastIndexOf('/')+1).Equals("WebPlayer"))
{
export_dir = export_dir.Substring(0,export_dir.LastIndexOf('/'));
}
if(Directory.Exists(export_dir + "/WebPlayer"))
PlayerPrefs.SetString("Course_Export",export_dir);
else
EditorUtility.DisplayDialog("Invalid Directory","Please Choose a directory with a WebPlayer folder in it.","OK");
}
}
//GUILayout.EndHorizontal();
//Create the label
GUILayout.EndVertical();
}
GUILayout.BeginHorizontal();
foldout2 = EditorGUILayout.Foldout(foldout2,"Course Properties", EditorStyles.foldout);
bool help2 = GUILayout.Button(new GUIContent ("Help", "Help for the Course Properties section"),EditorStyles.miniBoldLabel);
if(help2)
EditorUtility.DisplayDialog("Help","The properties will control how the LMS controls and displays your course content. These values will be written into the imsmanifest.xml file within the exported zip package. There are many other settings that can be specified in the manifest - for more information read the Content Aggregation Model documents at http://www.adlnet.gov/capabilities/scorm","OK");
GUILayout.EndHorizontal();
if(foldout2)
{
GUILayout.BeginVertical("TextArea");
GUILayout.Label("Information about your SCORM package including the title and various configuration values.", EditorStyles.miniLabel);
PlayerPrefs.SetString("Course_Title", EditorGUILayout.TextField(new GUIContent("Course Title:","The title of the course, as listed in the learning management system (LMS)"), PlayerPrefs.GetString("Course_Title")));
PlayerPrefs.SetString("SCO_Title", EditorGUILayout.TextField(new GUIContent("Scene Title:","The title of the Unity content. Note, the X title may show as the first item in an LMS-provided table of contents."), PlayerPrefs.GetString("SCO_Title")));
PlayerPrefs.SetString("Launch_Data", EditorGUILayout.TextField(new GUIContent("Launch Data:","User-defined string value that can be used as initial learning experience state data."), PlayerPrefs.GetString("Launch_Data")));
PlayerPrefs.SetString("Data_From_Lms", EditorGUILayout.TextField(new GUIContent("Data from LMS:","User-defined string value that can be used as initial learning experience state data."), PlayerPrefs.GetString("Data_From_Lms")));
//2004
if(PlayerPrefs.GetInt("SCORM_Version") < 3)
{
bool satisified = GUILayout.Toggle(System.Convert.ToBoolean(PlayerPrefs.GetInt("satisfiedByMeasure")),new GUIContent("Satisfied By Measure","If true, then this objective's satisfaction status will be determined by the score's relation to the passing score."));
PlayerPrefs.SetInt("satisfiedByMeasure",System.Convert.ToInt16(satisified));
if(satisified)
{
GUILayout.Label(new GUIContent("Passing Score: " + PlayerPrefs.GetFloat("minNormalizedMeasure").ToString(),"Defines a 'passing score' for this objective for use in conjunction with objective satisfied by measure."), EditorStyles.miniLabel);
PlayerPrefs.SetFloat("minNormalizedMeasure",(float)System.Math.Round(GUILayout.HorizontalSlider(PlayerPrefs.GetFloat("minNormalizedMeasure"),-1.0f,1.0f)*100.0f)/100.0f);
}
bool progress = GUILayout.Toggle(System.Convert.ToBoolean(PlayerPrefs.GetInt("completedByMeasure")),new GUIContent("Completed By Measure","If true, then this activity's completion status will be determined by the progress measure's relation to the minimum progress measure. This derived completion status will override what it explicitly set."));
PlayerPrefs.SetInt("completedByMeasure",System.Convert.ToInt16(progress));
if(progress)
{
GUILayout.Label(new GUIContent("Minimum Progress Measure: " + PlayerPrefs.GetFloat("minProgressMeasure").ToString(),"Defines a minimum completion percentage for this activity for use in conjunction with completed by measure.") , EditorStyles.miniLabel);
PlayerPrefs.SetFloat("minProgressMeasure",(float)System.Math.Round(GUILayout.HorizontalSlider(PlayerPrefs.GetFloat("minProgressMeasure"),0.0f,1.0f)*100.0f)/100.0f);
}
}
//1.2
else
{
GUILayout.Label(new GUIContent("Mastery Score: " + PlayerPrefs.GetFloat("masteryscore").ToString(),"The score required of a learner to achieve \"mastery\" or pass a given SCO"), EditorStyles.miniLabel);
PlayerPrefs.SetFloat("masteryscore",(float)System.Math.Round(GUILayout.HorizontalSlider(PlayerPrefs.GetFloat("masteryscore"),0.0f,100.0f)));
}
foldout4 = EditorGUILayout.Foldout(foldout4,new GUIContent("Launch Parameters","Querystring parameters appended to the player URL during launch"), EditorStyles.foldout);
GUI.skin.textArea.alignment = TextAnchor.MiddleLeft;
if(foldout4)
{
int num = PlayerPrefs.GetInt("Param_Count");
GUILayout.BeginVertical("TextArea");
int notblank = 0;
for( int i = 0; i < num; i++)
{
if(PlayerPrefs.GetString("Param_"+i.ToString()+"_Name") != "")
notblank++;
}
if(notblank > 2)
scrollview = GUILayout.BeginScrollView(scrollview,GUILayout.MinHeight(Mathf.Clamp(notblank*20,0,80)));
int total = 0;
for( int i = 0; i < num; i++)
{
if(PlayerPrefs.GetString("Param_"+i.ToString()+"_Name") != "")
{
GUILayout.BeginHorizontal();
bool delete = GUILayout.Button(new GUIContent("x","Remove this entry"),GUILayout.ExpandWidth(false));
string name = GUILayout.TextArea(PlayerPrefs.GetString("Param_"+i.ToString()+"_Name"),GUILayout.MaxWidth((window.position.width - 10)/2));
string val = GUILayout.TextArea(PlayerPrefs.GetString("Param_"+i.ToString()+"_Value"));
GUILayout.EndHorizontal();
if(delete)
{
name = "";
val = "";
}
PlayerPrefs.SetString("Param_"+i.ToString()+"_Name",name);
PlayerPrefs.SetString("Param_"+i.ToString()+"_Value",val);
}
}
if(notblank > 2)
GUILayout.EndScrollView();
GUILayout.BeginHorizontal();
bool add = GUILayout.Button(new GUIContent("Add Entry","Add a new entry"),GUILayout.ExpandWidth(false));
if(add)
{
PlayerPrefs.SetString("Param_"+num.ToString()+"_Name","name");
PlayerPrefs.SetString("Param_"+num.ToString()+"_Value","val");
num++;
PlayerPrefs.SetInt("Param_Count",num);
}
bool clear = GUILayout.Button(new GUIContent("Clear Entrys","Remove All Entries"),GUILayout.ExpandWidth(false));
if(clear)
{
PlayerPrefs.SetInt("Param_Count",0);
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
GUILayout.EndVertical();
}
GUILayout.BeginHorizontal();
foldout3 = EditorGUILayout.Foldout(foldout3,"SCORM Version", EditorStyles.foldout);
bool help3 = GUILayout.Button(new GUIContent ("Help", "Help for the SCORM Version section"),EditorStyles.miniBoldLabel);
if(help3)
EditorUtility.DisplayDialog("Help","Select the version that your LMS supports. Some LMSs support multiple SCORM versions. Choose the highest level supported. The calls to the SCORM Manager within your game code will be translated into the correct SCORM version. Please note that some data cannot be mapped between the SCORM 2004 and SCORM 1.2 datamodels, and will be lost when running the course in a 1.2 LMS. Contact ADL for information on this topic.","OK");
GUILayout.EndHorizontal();
if(foldout3)
{
GUILayout.BeginVertical("TextArea");
//GUILayout.EndHorizontal();
GUILayout.Label("Select the SCORM version used by the target LMS", EditorStyles.miniLabel);
//PlayerPrefs.SetInt("SCORM_Version",GUILayout.SelectionGrid(PlayerPrefs.GetInt("SCORM_Version"),new string[]{"SCORM 2004 v. 4","SCORM 1.2"},2));
PlayerPrefs.SetInt("SCORM_Version",EditorGUILayout.Popup(PlayerPrefs.GetInt("SCORM_Version"),new string[]{"SCORM 2004 v. 4","SCORM 2004 v. 3","SCORM 2004 v. 2","SCORM 1.2"},GUILayout.ExpandWidth(false)));
GUILayout.EndVertical();
}
GUIStyle s = new GUIStyle();
GUI.skin.button.fontSize = 12;
bool publish = GUILayout.Button(new GUIContent ("Publish", "Export this course to a SCORM package."));
if(publish)
Publish();
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Scriban.Functions;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban.Parsing
{
public partial class Parser
{
private int _allowNewLineLevel = 0;
private int _expressionLevel = 0;
public int ExpressionLevel => _expressionLevel;
private static readonly int PrecedenceOfMultiply = GetDefaultBinaryOperatorPrecedence(ScriptBinaryOperator.Multiply);
private bool TryBinaryOperator(out ScriptBinaryOperator binaryOperator, out int precedence)
{
var tokenType = Current.Type;
precedence = 0;
binaryOperator = ScriptBinaryOperator.None;
switch (tokenType)
{
case TokenType.Asterisk: binaryOperator = ScriptBinaryOperator.Multiply; break;
case TokenType.Divide: binaryOperator = ScriptBinaryOperator.Divide; break;
case TokenType.DoubleDivide: binaryOperator = ScriptBinaryOperator.DivideRound; break;
case TokenType.Plus: binaryOperator = ScriptBinaryOperator.Add; break;
case TokenType.Minus: binaryOperator = ScriptBinaryOperator.Substract; break;
case TokenType.Percent: binaryOperator = ScriptBinaryOperator.Modulus; break;
case TokenType.DoubleLessThan: binaryOperator = ScriptBinaryOperator.ShiftLeft; break;
case TokenType.DoubleGreaterThan: binaryOperator = ScriptBinaryOperator.ShiftRight; break;
case TokenType.DoubleQuestion: binaryOperator = ScriptBinaryOperator.EmptyCoalescing; break;
case TokenType.DoubleAmp: binaryOperator = ScriptBinaryOperator.And; break;
case TokenType.DoubleVerticalBar: binaryOperator = ScriptBinaryOperator.Or; break;
case TokenType.DoubleEqual: binaryOperator = ScriptBinaryOperator.CompareEqual; break;
case TokenType.ExclamationEqual: binaryOperator = ScriptBinaryOperator.CompareNotEqual; break;
case TokenType.Greater: binaryOperator = ScriptBinaryOperator.CompareGreater; break;
case TokenType.GreaterEqual: binaryOperator = ScriptBinaryOperator.CompareGreaterOrEqual; break;
case TokenType.Less: binaryOperator = ScriptBinaryOperator.CompareLess; break;
case TokenType.LessEqual: binaryOperator = ScriptBinaryOperator.CompareLessOrEqual; break;
case TokenType.DoubleDot: binaryOperator = ScriptBinaryOperator.RangeInclude; break;
case TokenType.DoubleDotLess: binaryOperator = ScriptBinaryOperator.RangeExclude; break;
default:
if (_isScientific)
{
switch (tokenType)
{
case TokenType.Caret: binaryOperator = ScriptBinaryOperator.Power; break;
case TokenType.Amp: binaryOperator = ScriptBinaryOperator.BinaryAnd; break;
case TokenType.VerticalBar: binaryOperator = ScriptBinaryOperator.BinaryOr; break;
}
}
break;
}
if (binaryOperator != ScriptBinaryOperator.None)
{
precedence = GetDefaultBinaryOperatorPrecedence(binaryOperator);
}
return binaryOperator != ScriptBinaryOperator.None;
}
private ScriptExpression ParseExpressionAsVariableOrStringOrExpression(ScriptNode parentNode)
{
switch (Current.Type)
{
case TokenType.Identifier:
case TokenType.IdentifierSpecial:
return ParseVariable();
case TokenType.String:
return ParseString();
case TokenType.VerbatimString:
return ParseVerbatimString();
default:
return ParseExpression(parentNode);
}
}
private ScriptExpression ParseExpression(ScriptNode parentNode, ScriptExpression parentExpression = null, int precedence = 0, ParseExpressionMode mode = ParseExpressionMode.Default, bool allowAssignment = true)
{
bool hasAnonymousFunction = false;
int expressionCount = 0;
_expressionLevel++;
var expressionDepthBeforeEntering = _expressionDepth;
var enteringPrecedence = precedence;
EnterExpression();
try
{
ScriptFunctionCall functionCall = null;
parseExpression:
expressionCount++;
// Allow custom parsing for a first pre-expression
ScriptExpression leftOperand = null;
bool isLeftOperandClosed = false;
switch (Current.Type)
{
case TokenType.Identifier:
case TokenType.IdentifierSpecial:
leftOperand = ParseVariable();
// In case of liquid template, we accept the syntax colon after a tag
if (_isLiquid && parentNode is ScriptPipeCall && Current.Type == TokenType.Colon)
{
NextToken();
}
// Special handle of the $$ block delegate variable
if (ScriptVariable.BlockDelegate.Equals(leftOperand))
{
if (expressionCount != 1 || _expressionLevel > 1)
{
LogError("Cannot use block delegate $$ in a nested expression");
}
if (!(parentNode is ScriptExpressionStatement))
{
LogError(parentNode, "Cannot use block delegate $$ outside an expression statement");
}
return leftOperand;
}
break;
case TokenType.Integer:
leftOperand = ParseInteger();
break;
case TokenType.HexaInteger:
leftOperand = ParseHexaInteger();
break;
case TokenType.BinaryInteger:
leftOperand = ParseBinaryInteger();
break;
case TokenType.Float:
leftOperand = ParseFloat();
break;
case TokenType.String:
leftOperand = ParseString();
break;
case TokenType.ImplicitString:
leftOperand = ParseImplicitString();
break;
case TokenType.VerbatimString:
leftOperand = ParseVerbatimString();
break;
case TokenType.OpenParen:
leftOperand = ParseParenthesis();
break;
case TokenType.OpenBrace:
leftOperand = ParseObjectInitializer();
break;
case TokenType.OpenBracket:
leftOperand = ParseArrayInitializer();
break;
default:
if (IsStartingAsUnaryExpression())
{
leftOperand = ParseUnaryExpression();
}
break;
}
// Should not happen but in case
if (leftOperand == null)
{
if (functionCall != null)
{
LogError($"Unexpected token `{GetAsText(Current)}` while parsing function call `{functionCall}`");
}
else
{
LogError($"Unexpected token `{GetAsText(Current)}` while parsing expression");
}
return null;
}
if (leftOperand is ScriptAnonymousFunction)
{
hasAnonymousFunction = true;
}
while (!hasAnonymousFunction)
{
if (_isLiquid && Current.Type == TokenType.Comma && functionCall != null)
{
NextToken(); // Skip the comma for arguments in a function call
}
// Parse Member expression are expected to be followed only by an identifier
if (Current.Type == TokenType.Dot || (!_isLiquid && Current.Type == TokenType.QuestionDot))
{
var nextToken = PeekToken();
if (nextToken.Type == TokenType.Identifier)
{
var dotToken = ParseToken(Current.Type);
if (GetAsText(Current) == "empty" && PeekToken().Type == TokenType.Question)
{
var memberExpression = Open<ScriptIsEmptyExpression>();
memberExpression.Span = leftOperand.Span;
memberExpression.DotToken = dotToken;
memberExpression.Member = (ScriptVariable)ParseVariable();
ExpectAndParseTokenTo(memberExpression.QuestionToken, TokenType.Question);
memberExpression.Target = leftOperand;
leftOperand = Close(memberExpression);
}
else
{
var memberExpression = Open<ScriptMemberExpression>();
memberExpression.Span = leftOperand.Span;
memberExpression.DotToken = dotToken;
memberExpression.Target = leftOperand;
var member = ParseVariable();
if (!(member is ScriptVariable))
{
LogError("Unexpected literal member `{member}`");
return null;
}
memberExpression.Member = (ScriptVariable)member;
leftOperand = Close(memberExpression);
}
}
else
{
LogError(nextToken, $"Invalid token `{nextToken.Type}`. The dot operator is expected to be followed by a plain identifier");
return null;
}
continue;
}
// If we have a bracket but left operand is a (variable || member || indexer), then we consider next as an indexer
// unit test: 130-indexer-accessor-accept1.txt
if (Current.Type == TokenType.OpenBracket && (leftOperand is IScriptVariablePath || leftOperand is ScriptLiteral || leftOperand is ScriptFunctionCall) && !IsPreviousCharWhitespace())
{
var indexerExpression = Open<ScriptIndexerExpression>();
indexerExpression.Span = leftOperand.Span;
indexerExpression.Target = leftOperand;
ExpectAndParseTokenTo(indexerExpression.OpenBracket, TokenType.OpenBracket); // parse [
// unit test: 130-indexer-accessor-error5.txt
indexerExpression.Index = ExpectAndParseExpression(indexerExpression, functionCall, 0, $"Expecting <index_expression> instead of `{GetAsText(Current)}`");
if (Current.Type != TokenType.CloseBracket)
{
LogError($"Unexpected `{GetAsText(Current)}`. Expecting ']'");
}
else
{
ExpectAndParseTokenTo(indexerExpression.CloseBracket, TokenType.CloseBracket); // parse ]
}
leftOperand = Close(indexerExpression);
continue;
}
if (mode == ParseExpressionMode.BasicExpression)
{
break;
}
// Named argument
if (mode != ParseExpressionMode.DefaultNoNamedArgument && Current.Type == TokenType.Colon)
{
if (!(leftOperand is ScriptVariable))
{
LogError(leftOperand.Span, $"Expecting a simple global or local variable before `:` in order to create a named argument");
break;
}
var namedArgument = Open<ScriptNamedArgument>();
namedArgument.Name = (ScriptVariable) leftOperand;
namedArgument.ColonToken = ParseToken(TokenType.Colon);
namedArgument.Value = ExpectAndParseExpression(parentNode);
Close(namedArgument);
leftOperand = namedArgument;
break;
}
if (Current.Type == TokenType.Equal)
{
if (leftOperand is ScriptFunctionCall call && call.TryGetFunctionDeclaration(out ScriptFunction declaration))
{
if (_expressionLevel > 1 || !allowAssignment)
{
LogError(leftOperand, $"Creating a function is only allowed for a top level assignment");
}
declaration.EqualToken = ParseToken(TokenType.Equal); // eat equal token
declaration.Body = ParseExpressionStatement();
declaration.Span.End = declaration.Body.Span.End;
leftOperand = new ScriptExpressionAsStatement(declaration) {Span = declaration.Span};
}
else
{
var assignExpression = Open<ScriptAssignExpression>();
if (leftOperand != null)
{
assignExpression.Span.Start = leftOperand.Span.Start;
}
if (leftOperand != null && !(leftOperand is IScriptVariablePath) || functionCall != null || _expressionLevel > 1 || !allowAssignment)
{
// unit test: 101-assign-complex-error1.txt
LogError(assignExpression, $"Expression is only allowed for a top level assignment");
}
ExpectAndParseTokenTo(assignExpression.EqualToken, TokenType.Equal);
assignExpression.Target = TransformKeyword(leftOperand);
// unit test: 105-assign-error3.txt
assignExpression.Value = ExpectAndParseExpression(assignExpression, parentExpression);
leftOperand = Close(assignExpression);
}
break;
}
// Handle binary operators here
ScriptBinaryOperator binaryOperatorType;
int newPrecedence;
if (TryBinaryOperator(out binaryOperatorType, out newPrecedence) || (_isLiquid && TryLiquidBinaryOperator(out binaryOperatorType, out newPrecedence)))
{
// Check precedence to see if we should "take" this operator here (Thanks TimJones for the tip code! ;)
if (newPrecedence <= precedence)
{
if (_isScientific)
{
if (functionCall != null)
{
// if we were in the middle of a function call and the new operator
// doesn't have the same associativity (/*%^) we will transform
// the pending call into a left operand and let the current operator (eg +)
// to work on it. Example: cos 2x + 1
// functionCall: cos 2
// leftOperand: x
// binaryOperatorType: Add
if (newPrecedence < precedence)
{
functionCall.AddArgument(leftOperand);
leftOperand = functionCall;
functionCall = null;
}
precedence = newPrecedence;
}
else
{
if (enteringPrecedence == 0)
{
precedence = enteringPrecedence;
continue;
}
break;
}
}
else
{
if (enteringPrecedence == 0)
{
precedence = enteringPrecedence;
continue;
}
break;
}
}
// In scientific mode, with a pending function call, we can't detect how
// operations of similar precedence (*/%^) are going to behave until
// we resolve the functions (to detect if they take a parameter or not)
// In fact case, we need create a ScriptArgumentBinary for the operator
// and push it as an argument of the function call:
// expression to parse: cos 2x * cos 2x
// function call will be => cos(2, x, *, cos, 2, x)
// which is incorrect so we will rewrite it to cos(2 * x) * cos(2 * x)
if (_isScientific && (functionCall != null || newPrecedence >= PrecedenceOfMultiply))
{
// Store %*/^ in a pseudo function call
if (functionCall == null)
{
functionCall = Open<ScriptFunctionCall>();
functionCall.Target = leftOperand;
functionCall.Span = leftOperand.Span;
}
else
{
functionCall.AddArgument(leftOperand);
}
var binaryArgument = Open<ScriptArgumentBinary>();
binaryArgument.Operator = binaryOperatorType;
binaryArgument.OperatorToken = ParseToken(Current.Type);
Close(binaryArgument);
functionCall.AddArgument(binaryArgument);
precedence = newPrecedence;
goto parseExpression;
}
// We fake entering an expression here to limit the number of expression
EnterExpression();
var binaryExpression = Open<ScriptBinaryExpression>();
binaryExpression.Span = leftOperand.Span;
binaryExpression.Left = leftOperand;
binaryExpression.Operator = binaryOperatorType;
// Parse the operator
binaryExpression.OperatorToken = ParseToken(Current.Type);
// Special case for liquid, we revert the verbatim to the original scriban operator
if (_isLiquid && binaryOperatorType != ScriptBinaryOperator.Custom)
{
binaryExpression.OperatorToken.Value = binaryOperatorType.ToText();
}
// unit test: 110-binary-simple-error1.txt
binaryExpression.Right = ExpectAndParseExpression(binaryExpression,
functionCall ?? parentExpression, newPrecedence,
$"Expecting an <expression> to the right of the operator instead of `{GetAsText(Current)}`");
leftOperand = Close(binaryExpression);
continue;
}
// Parse conditional expression
if (!_isLiquid && Current.Type == TokenType.Question)
{
if (precedence > 0)
{
break;
}
// If we have any pending function call, we close it
if (functionCall != null)
{
functionCall.Arguments.Add(leftOperand);
Close(functionCall);
leftOperand = functionCall;
functionCall = null;
}
var conditionalExpression = Open<ScriptConditionalExpression>();
conditionalExpression.Span = leftOperand.Span;
conditionalExpression.Condition = leftOperand;
// Parse ?
ExpectAndParseTokenTo(conditionalExpression.QuestionToken, TokenType.Question);
conditionalExpression.ThenValue = ExpectAndParseExpression(parentNode, mode: ParseExpressionMode.DefaultNoNamedArgument);
// Parse :
ExpectAndParseTokenTo(conditionalExpression.ColonToken, TokenType.Colon);
conditionalExpression.ElseValue = ExpectAndParseExpression(parentNode, mode: ParseExpressionMode.DefaultNoNamedArgument);
Close(conditionalExpression);
leftOperand = conditionalExpression;
break;
}
if (IsStartOfExpression())
{
// If we can parse a statement, we have a method call
if (parentExpression != null)
{
break;
}
// Parse named parameters
var paramContainer = parentNode as IScriptNamedArgumentContainer;
if (!_isScientific && Current.Type == TokenType.Identifier && (parentNode is IScriptNamedArgumentContainer || !_isLiquid && PeekToken().Type == TokenType.Colon))
{
if (paramContainer == null)
{
if (functionCall == null)
{
functionCall = Open<ScriptFunctionCall>();
functionCall.Target = leftOperand;
functionCall.Span.Start = leftOperand.Span.Start;
}
else
{
functionCall.Arguments.Add(leftOperand);
}
}
Close(leftOperand);
isLeftOperandClosed = true;
while (true)
{
// Don't parse boolean parameters as named parameters for function calls
if (Current.Type != TokenType.Identifier || (paramContainer == null && PeekToken().Type != TokenType.Colon))
{
break;
}
var parameter = Open<ScriptNamedArgument>();
// Parse the name
var variable = ParseVariable();
if (!(variable is ScriptVariable))
{
LogError(variable.Span, $"Invalid identifier passed as a named argument. Expecting a simple variable name");
break;
}
parameter.Name = (ScriptVariable)variable;
if (paramContainer != null)
{
paramContainer.AddParameter(Close(parameter));
}
else
{
functionCall.Arguments.Add(parameter);
}
// If we have a colon, we have a value
// otherwise it is a boolean argument name
if (Current.Type == TokenType.Colon)
{
// Parse : token
parameter.ColonToken = ScriptToken.Colon();
ExpectAndParseTokenTo(parameter.ColonToken, TokenType.Colon);
parameter.Value = ExpectAndParseExpression(parentNode, mode: ParseExpressionMode.BasicExpression);
parameter.Span.End = parameter.Value.Span.End;
}
if (functionCall != null)
{
functionCall.Span.End = parameter.Span.End;
if (parameter.Value is ScriptAnonymousFunction)
{
break;
}
}
}
if (paramContainer != null || !IsStartOfExpression())
{
if (functionCall != null)
{
leftOperand = functionCall;
functionCall = null;
}
// We don't allow anything after named parameters for IScriptNamedArgumentContainer
break;
}
// Otherwise we allow to mix normal parameters within named parameters
goto parseExpression;
}
bool isLikelyExplicitFunctionCall = Current.Type == TokenType.OpenParen && !IsPreviousCharWhitespace();
if (functionCall == null || isLikelyExplicitFunctionCall)
{
if (_isScientific && !isLikelyExplicitFunctionCall)
{
newPrecedence = PrecedenceOfMultiply;
if (newPrecedence <= precedence)
{
break;
}
precedence = newPrecedence;
}
var pendingFunctionCall = functionCall;
functionCall = Open<ScriptFunctionCall>();
functionCall.Target = leftOperand;
// If we need to convert liquid to scriban functions:
if (_isLiquid && Options.LiquidFunctionsToScriban)
{
TransformLiquidFunctionCallToScriban(functionCall);
}
functionCall.Span.Start = leftOperand.Span.Start;
// Regular function call target(arg0, arg1, arg3, arg4...)
if (Current.Type == TokenType.OpenParen && !IsPreviousCharWhitespace())
{
// This is an explicit call
functionCall.ExplicitCall = true;
functionCall.OpenParent = ParseToken(TokenType.OpenParen);
bool isFirst = true;
while (true)
{
// Parse any required comma (before each new non-first argument)
// Or closing parent (and we exit the loop)
if (Current.Type == TokenType.CloseParen)
{
functionCall.CloseParen = ParseToken(TokenType.CloseParen);
break;
}
if (!isFirst)
{
if (Current.Type == TokenType.Comma)
{
PushTokenToTrivia();
NextToken();
FlushTriviasToLastTerminal();
}
else
{
LogError(Current, "Expecting a comma to separate arguments in a function call.");
}
}
isFirst = false;
// Else we expect an expression
if (IsStartOfExpression())
{
var arg = ParseExpression(functionCall);
functionCall.Arguments.Add(arg);
functionCall.Span.End = arg.Span.End;
}
else
{
LogError(Current, "Expecting an expression for argument function calls instead of this token.");
break;
}
}
if (functionCall.CloseParen == null)
{
LogError(Current, "Expecting a closing parenthesis for a function call.");
}
leftOperand = functionCall;
functionCall = pendingFunctionCall;
continue;
}
}
else
{
functionCall.AddArgument(leftOperand);
functionCall.Span.End = leftOperand.Span.End;
if (leftOperand is ScriptAnonymousFunction)
{
break;
}
}
goto parseExpression;
}
if (enteringPrecedence > 0)
{
break;
}
if (_isScientific && Current.Type == TokenType.PipeGreater || !_isScientific && (Current.Type == TokenType.VerticalBar || Current.Type == TokenType.PipeGreater))
{
if (functionCall != null)
{
functionCall.Arguments.Add(leftOperand);
leftOperand = functionCall;
functionCall = null;
}
var pipeCall = Open<ScriptPipeCall>();
if (leftOperand != null)
{
pipeCall.Span.Start = leftOperand.Span.Start;
}
pipeCall.From = leftOperand;
pipeCall.PipeToken = ParseToken(Current.Type); // skip | or |>
// unit test: 310-func-pipe-error1.txt
pipeCall.To = ExpectAndParseExpression(pipeCall);
return Close(pipeCall);
}
break;
}
if (functionCall != null)
{
functionCall.Arguments.Add(leftOperand);
functionCall.Span.End = leftOperand.Span.End;
return functionCall;
}
return isLeftOperandClosed ? leftOperand : Close(leftOperand);
}
finally
{
LeaveExpression();
// Force to restore back to a level
_expressionDepth = expressionDepthBeforeEntering;
_expressionLevel--;
}
}
private ScriptExpression ParseArrayInitializer()
{
var scriptArray = Open<ScriptArrayInitializerExpression>();
// Should happen before the NextToken to consume any EOL after
_allowNewLineLevel++;
// Parse [
ExpectAndParseTokenTo(scriptArray.OpenBracketToken, TokenType.OpenBracket);
bool expectingEndOfInitializer = false;
// unit test: 120-array-initializer-accessor.txt
while (true)
{
if (Current.Type == TokenType.CloseBracket)
{
break;
}
if (!expectingEndOfInitializer)
{
// unit test: 120-array-initializer-error2.txt
var expression = ExpectAndParseExpression(scriptArray);
if (expression == null)
{
break;
}
scriptArray.Values.Add(expression);
if (Current.Type == TokenType.Comma)
{
// Record trailing Commas
if (_isKeepTrivia)
{
PushTokenToTrivia();
}
NextToken();
if (_isKeepTrivia)
{
FlushTriviasToLastTerminal();
}
}
else
{
expectingEndOfInitializer = true;
}
}
else
{
break;
}
}
// Should happen before NextToken() to stop on the next EOF
_allowNewLineLevel--;
// Parse ]
// unit test: 120-array-initializer-error1.txt
ExpectAndParseTokenTo(scriptArray.CloseBracketToken, TokenType.CloseBracket);
return Close(scriptArray);
}
private ScriptExpression ParseObjectInitializer()
{
var scriptObject = Open<ScriptObjectInitializerExpression>();
// Should happen before the NextToken to consume any EOL after
_allowNewLineLevel++;
ExpectAndParseTokenTo(scriptObject.OpenBrace, TokenType.OpenBrace); // Parse {
// unit test: 140-object-initializer-accessor.txt
bool expectingEndOfInitializer = false;
bool hasErrors = false;
while (true)
{
if (Current.Type == TokenType.CloseBrace)
{
break;
}
if (!expectingEndOfInitializer && (Current.Type == TokenType.Identifier || Current.Type == TokenType.String))
{
var positionBefore = Current;
var objectMember = Open<ScriptObjectMember>();
var variableOrLiteral = ParseExpressionAsVariableOrStringOrExpression(scriptObject);
var variable = variableOrLiteral as ScriptVariable;
var literal = variableOrLiteral as ScriptLiteral;
if (variable == null && literal == null)
{
hasErrors = true;
LogError(positionBefore, $"Unexpected member type `{variableOrLiteral}/{ScriptSyntaxAttribute.Get(variableOrLiteral).TypeName}` found for object initializer member name");
break;
}
if (literal != null && !(literal.Value is string))
{
hasErrors = true;
LogError(positionBefore,
$"Invalid literal member `{literal.Value}/{literal.Value?.GetType()}` found for object initializer member name. Only literal string or identifier name are allowed");
break;
}
if (variable != null)
{
if (variable.Scope != ScriptVariableScope.Global)
{
// unit test: 140-object-initializer-error3.txt
hasErrors = true;
LogError("Expecting a simple identifier for member names");
break;
}
}
if (Current.Type != TokenType.Colon)
{
// unit test: 140-object-initializer-error4.txt
hasErrors = true;
LogError($"Unexpected token `{GetAsText(Current)}` Expecting a colon : after identifier `{variable?.Name}` for object initializer member name");
break;
}
ExpectAndParseTokenTo(objectMember.ColonToken, TokenType.Colon); // Parse :
objectMember.Name = variableOrLiteral;
if (!IsStartOfExpression())
{
// unit test: 140-object-initializer-error5.txt
hasErrors = true;
LogError($"Unexpected token `{GetAsText(Current)}`. Expecting an expression for the value of the member.");
break;
}
var expression = ParseExpression(scriptObject);
objectMember.Value = expression;
objectMember.Span.End = expression.Span.End;
Close(objectMember);
// Erase any previous declaration of this member
scriptObject.Members.Add(objectMember);
if (Current.Type == TokenType.Comma)
{
// Record trailing Commas
if (_isKeepTrivia)
{
PushTokenToTrivia();
FlushTriviasToLastTerminal();
}
NextToken();
}
else
{
expectingEndOfInitializer = true;
}
}
else
{
// unit test: 140-object-initializer-error1.txt
hasErrors = true;
LogError($"Unexpected token `{GetAsText(Current)}` while parsing object initializer. Expecting a simple identifier for the member name.");
break;
}
}
// Should happen before NextToken() to stop on the next EOF
_allowNewLineLevel--;
if (!hasErrors)
{
ExpectAndParseTokenTo(scriptObject.CloseBrace, TokenType.CloseBrace); // Parse }
}
return Close(scriptObject);
}
private ScriptExpression ParseParenthesis()
{
// unit test: 106-parenthesis.txt
var expression = Open<ScriptNestedExpression>();
ExpectAndParseTokenTo(expression.OpenParen, TokenType.OpenParen); // Parse (
expression.Expression = ExpectAndParseExpression(expression);
if (Current.Type == TokenType.CloseParen)
{
ExpectAndParseTokenTo(expression.CloseParen, TokenType.CloseParen); // Parse )
}
else
{
// unit test: 106-parenthesis-error1.txt
LogError(Current, $"Invalid token `{GetAsText(Current)}`. Expecting a closing `)`.");
}
return Close(expression);
}
private ScriptToken ParseToken(TokenType tokenType)
{
var verbatim = Open<ScriptToken>();
if (Current.Type != tokenType)
{
LogError(CurrentSpan, $"Unexpected token found `{GetAsText(Current)}` while expecting `{tokenType.ToText()}`.");
}
verbatim.TokenType = Current.Type;
verbatim.Value = tokenType.ToText();
NextToken();
return Close(verbatim);
}
private void ExpectAndParseTokenTo(ScriptToken existingToken, TokenType expectedTokenType)
{
var verbatim = Open(existingToken);
if (Current.Type != expectedTokenType)
{
LogError(CurrentSpan, $"Unexpected token found `{GetAsText(Current)}` while expecting `{expectedTokenType.ToText()}`.");
}
NextToken();
Close(verbatim);
}
private ScriptKeyword ExpectAndParseKeywordTo(ScriptKeyword existingKeyword)
{
if (existingKeyword == null) throw new ArgumentNullException(nameof(existingKeyword));
if (existingKeyword.Value == null) throw new InvalidOperationException($"{nameof(ScriptKeyword)}.{nameof(ScriptKeyword.Value)} cannot be null");
var verbatim = Open(existingKeyword);
if (!MatchText(Current, existingKeyword.Value))
{
LogError(CurrentSpan, $"Unexpected keyword found `{GetAsText(Current)}` while expecting `{existingKeyword.Value}`.");
}
NextToken();
Close(verbatim);
return existingKeyword;
}
private ScriptExpression ParseUnaryExpression()
{
// unit test: 113-unary.txt
var unaryExpression = Open<ScriptUnaryExpression>();
int newPrecedence;
// Parse the operator as verbatim text
var unaryTokenType = Current.Type;
unaryExpression.OperatorToken = ParseToken(Current.Type);
// Else we parse standard unary operators
switch (unaryTokenType)
{
case TokenType.Exclamation:
unaryExpression.Operator = ScriptUnaryOperator.Not;
break;
case TokenType.Minus:
unaryExpression.Operator = ScriptUnaryOperator.Negate;
break;
case TokenType.Plus:
unaryExpression.Operator = ScriptUnaryOperator.Plus;
break;
case TokenType.Arroba:
unaryExpression.Operator = ScriptUnaryOperator.FunctionAlias;
break;
default:
if (_isScientific && unaryTokenType == TokenType.DoubleCaret || !_isScientific && unaryTokenType == TokenType.Caret)
{
unaryExpression.Operator = ScriptUnaryOperator.FunctionParametersExpand;
}
if (unaryExpression.Operator == ScriptUnaryOperator.None)
{
LogError($"Unexpected token `{unaryTokenType}` for unary expression");
}
break;
}
newPrecedence = GetDefaultUnaryOperatorPrecedence(unaryExpression.Operator);
// unit test: 115-unary-error1.txt
unaryExpression.Right = ExpectAndParseExpression(unaryExpression, null, newPrecedence);
return Close(unaryExpression);
}
private ScriptExpression TransformKeyword(ScriptExpression leftOperand)
{
// In case we are in liquid and we are assigning to a scriban keyword, we escape the variable with a nested expression
if (_isLiquid && leftOperand is IScriptVariablePath && IsScribanKeyword(((IScriptVariablePath) leftOperand).GetFirstPath()) && !(leftOperand is ScriptNestedExpression))
{
var nestedExpression = ScriptNestedExpression.Wrap(leftOperand, _isKeepTrivia);
return nestedExpression;
}
return leftOperand;
}
private void TransformLiquidFunctionCallToScriban(ScriptFunctionCall functionCall)
{
var liquidTarget = functionCall.Target as ScriptVariable;
string targetName;
string memberName;
// In case of cycle we transform it to array.cycle at runtime
if (liquidTarget != null && LiquidBuiltinsFunctions.TryLiquidToScriban(liquidTarget.Name, out targetName, out memberName))
{
var targetVariable = new ScriptVariableGlobal(targetName) {Span = liquidTarget.Span};
var memberVariable = new ScriptVariableGlobal(memberName) {Span = liquidTarget.Span};
var arrayCycle = new ScriptMemberExpression
{
Span = liquidTarget.Span,
Target = targetVariable,
Member = memberVariable,
};
// Transfer trivias accordingly to target (trivias before) and member (trivias after)
if (_isKeepTrivia && liquidTarget.Trivias != null)
{
targetVariable.AddTrivias(liquidTarget.Trivias.Before, true);
memberVariable.AddTrivias(liquidTarget.Trivias.After, false);
}
functionCall.Target = arrayCycle;
}
}
private void EnterExpression()
{
_expressionDepth++;
if (Options.ExpressionDepthLimit.HasValue && !_isExpressionDepthLimitReached && _expressionDepth > Options.ExpressionDepthLimit.Value)
{
LogError(GetSpanForToken(Previous), $"The statement depth limit `{Options.ExpressionDepthLimit.Value}` was reached when parsing this statement");
_isExpressionDepthLimitReached = true;
}
}
private ScriptExpression ExpectAndParseExpression(ScriptNode parentNode, ScriptExpression parentExpression = null, int newPrecedence = 0, string message = null, ParseExpressionMode mode = ParseExpressionMode.Default, bool allowAssignment = true)
{
if (IsStartOfExpression())
{
return ParseExpression(parentNode, parentExpression, newPrecedence, mode, allowAssignment);
}
LogError(parentNode, CurrentSpan, message ?? $"Expecting <expression> instead of `{GetAsText(Current)}`");
return null;
}
private ScriptExpression ExpectAndParseExpressionAndAnonymous(ScriptNode parentNode, ParseExpressionMode mode = ParseExpressionMode.Default)
{
if (IsStartOfExpression())
{
return ParseExpression(parentNode, null, 0, mode);
}
LogError(parentNode, CurrentSpan, $"Expecting <expression> instead of `{GetAsText(Current)}`");
return null;
}
public bool IsStartOfExpression()
{
if (IsStartingAsUnaryExpression()) return true;
switch (Current.Type)
{
case TokenType.Identifier:
case TokenType.IdentifierSpecial:
case TokenType.Integer:
case TokenType.HexaInteger:
case TokenType.BinaryInteger:
case TokenType.Float:
case TokenType.String:
case TokenType.ImplicitString:
case TokenType.VerbatimString:
case TokenType.OpenParen:
case TokenType.OpenBrace:
case TokenType.OpenBracket:
return true;
}
return false;
}
private bool IsStartingAsUnaryExpression()
{
switch (Current.Type)
{
case TokenType.Exclamation:
case TokenType.Minus:
case TokenType.Plus:
case TokenType.Arroba:
return true;
case TokenType.Caret:
case TokenType.DoubleCaret:
// In scientific Caret is used for exponent (so it is a binary operator)
if (_isScientific && Current.Type == TokenType.DoubleCaret || !_isScientific && Current.Type == TokenType.Caret)
{
return true;
}
break;
}
return false;
}
private bool TryLiquidBinaryOperator(out ScriptBinaryOperator binaryOperator, out int precedence)
{
binaryOperator = ScriptBinaryOperator.None;
precedence = 0;
var text = GetAsText(Current);
if (Current.Type != TokenType.Identifier)
{
return false;
}
switch (text)
{
case "or":
binaryOperator = ScriptBinaryOperator.Or;
break;
case "and":
binaryOperator = ScriptBinaryOperator.And;
break;
case "contains":
binaryOperator = ScriptBinaryOperator.LiquidContains;
break;
case "startsWith":
binaryOperator = ScriptBinaryOperator.LiquidStartsWith;
break;
case "endsWith":
binaryOperator = ScriptBinaryOperator.LiquidEndsWith;
break;
case "hasKey":
binaryOperator = ScriptBinaryOperator.LiquidHasKey;
break;
case "hasValue":
binaryOperator = ScriptBinaryOperator.LiquidHasValue;
break;
}
if (binaryOperator != ScriptBinaryOperator.None)
{
precedence = GetDefaultBinaryOperatorPrecedence(binaryOperator);
}
return binaryOperator != ScriptBinaryOperator.None;
}
internal static int GetDefaultBinaryOperatorPrecedence(ScriptBinaryOperator op)
{
switch (op)
{
case ScriptBinaryOperator.EmptyCoalescing:
return 20;
case ScriptBinaryOperator.Or:
return 30;
case ScriptBinaryOperator.And:
return 40;
case ScriptBinaryOperator.BinaryOr:
return 50;
case ScriptBinaryOperator.BinaryAnd:
return 60;
case ScriptBinaryOperator.CompareEqual:
case ScriptBinaryOperator.CompareNotEqual:
return 70;
case ScriptBinaryOperator.CompareLess:
case ScriptBinaryOperator.CompareLessOrEqual:
case ScriptBinaryOperator.CompareGreater:
case ScriptBinaryOperator.CompareGreaterOrEqual:
return 80;
case ScriptBinaryOperator.LiquidContains:
case ScriptBinaryOperator.LiquidStartsWith:
case ScriptBinaryOperator.LiquidEndsWith:
case ScriptBinaryOperator.LiquidHasKey:
case ScriptBinaryOperator.LiquidHasValue:
return 90;
case ScriptBinaryOperator.Add:
case ScriptBinaryOperator.Substract:
return 100;
case ScriptBinaryOperator.Multiply:
case ScriptBinaryOperator.Divide:
case ScriptBinaryOperator.DivideRound:
case ScriptBinaryOperator.Modulus:
case ScriptBinaryOperator.ShiftLeft:
case ScriptBinaryOperator.ShiftRight:
return 110;
case ScriptBinaryOperator.Power:
return 120;
case ScriptBinaryOperator.RangeInclude:
case ScriptBinaryOperator.RangeExclude:
return 130;
default:
return 0;
}
}
private static int GetDefaultUnaryOperatorPrecedence(ScriptUnaryOperator op)
{
switch (op)
{
case ScriptUnaryOperator.Not:
case ScriptUnaryOperator.Negate:
case ScriptUnaryOperator.Plus:
case ScriptUnaryOperator.FunctionAlias:
case ScriptUnaryOperator.FunctionParametersExpand:
return 200;
default:
return 0;
}
}
bool IsPreviousCharWhitespace()
{
int position = Current.Start.Offset - 1;
if (position >= 0)
{
return char.IsWhiteSpace(_lexer.Text[position]);
}
return false;
}
bool IsNextCharWhitespace()
{
int position = Current.End.Offset + 1;
if (position >= 0 && position < _lexer.Text.Length)
{
return char.IsWhiteSpace(_lexer.Text[position]);
}
return false;
}
private void LeaveExpression()
{
_expressionDepth--;
}
private enum ParseExpressionMode
{
/// <summary>
/// All expressions (e.g literals, function calls, function pipes...etc.)
/// </summary>
Default,
/// <summary>
/// All expressions (e.g literals, function calls, function pipes...etc.)
/// </summary>
DefaultNoNamedArgument,
/// <summary>
/// Only literal, unary, nested, array/object initializer, dot access, array access
/// </summary>
BasicExpression,
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Globalization
{
public partial class CompareInfo
{
[SecurityCritical]
private readonly Interop.GlobalizationInterop.SafeSortHandle m_sortHandle;
private readonly bool m_isAsciiEqualityOrdinal;
[SecuritySafeCritical]
internal CompareInfo(CultureInfo culture)
{
m_name = culture.m_name;
m_sortName = culture.SortName;
m_sortHandle = Interop.GlobalizationInterop.GetSortHandle(System.Text.Encoding.UTF8.GetBytes(m_sortName));
m_isAsciiEqualityOrdinal = (m_sortName == "en-US" || m_sortName == "");
}
[SecurityCritical]
internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
[SecurityCritical]
internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
[SecurityCritical]
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
}
[SecurityCritical]
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Contract.Assert(string1 != null);
Contract.Assert(string2 != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
fixed (char* pString2 = string2)
{
return Interop.GlobalizationInterop.CompareString(m_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
}
}
}
[SecurityCritical]
private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && target.IsAscii())
{
return IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOf(m_sortHandle, target, target.Length, pSource + startIndex, count, options);
return index != -1 ? index + startIndex : -1;
}
}
[SecurityCritical]
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && target.IsAscii())
{
return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.LastIndexOf(m_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
}
[SecuritySafeCritical]
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(prefix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && prefix.IsAscii())
{
return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.StartsWith(m_sortHandle, prefix, prefix.Length, source, source.Length, options);
}
[SecuritySafeCritical]
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(suffix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && suffix.IsAscii())
{
return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.EndsWith(m_sortHandle, suffix, suffix.Length, source, source.Length, options);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
[SecuritySafeCritical]
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(m_sortHandle, source, source.Length, null, 0, options);
// As an optimization, for small sort keys we allocate the buffer on the stack.
if (sortKeyLength <= 256)
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(m_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
byte[] sortKey = new byte[sortKeyLength];
fixed(byte* pSortKey = sortKey)
{
Interop.GlobalizationInterop.GetSortKey(m_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
}
[SecurityCritical]
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Authentication;
using System.Text;
using System.Threading ;
using WebFront;
namespace WebBack
{
public interface IServer {void Start(); void HandleGET(HTTPProcessor sp); void HandlePOST(HTTPProcessor sp, StreamReader sr);}
public static class StringRandom {
public const string Num = "1234567890";
public const string NumLet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
public const string Let = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string LetL = "abcdefghijklmnopqrstuvwxyz";
public const string LetU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static string GenerateNumLet (int length) {
Random r = new Random((int)DateTime.Now.Ticks);
char[] c = new char[length];
for (int i=0;i<length;i++) {
c[i] = NumLet[r.Next(0,NumLet.Length)];
}
return new string(c);
}
public static string GenerateUnicode (int length) {
Random r = new Random((int)DateTime.Now.Ticks);
byte[] b = new byte[length];
for (int i=0;i<length;i++) {
b[i] = (byte)r.Next(0,256);
}
return Encoding.Unicode.GetString(b);
}
}
public static class URLOperations {
public static string Decode(string URL) {
URL = URL.Replace("%20", " ");
return URL;
}
public static string Encode(string URL) {
URL = URL.Replace(" ", "%20");
return URL;
}
}
public class HTTPProcessor {
public TcpClient socket;
public IServer srv;
private Stream inputStream;
public StreamWriter outputStream;
public BinaryWriter outputBinary;
public BufferedStream outputCore;
public SslStream outputSecure;
public String http_method;
public String http_url;
public String http_protocol_versionstring;
public string http_host;
public IPAddress clientip;
public List<SCookie> clientcookies = new List<SCookie>();
public Hashtable httpHeaders = new Hashtable();
public bool secure;
private DateTime startTime;
public TimeSpan elapsedTime {get {return DateTime.Now - this.startTime;}}
private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB
public HTTPProcessor(TcpClient s, IServer srv, bool secure = false) {
this.clientip = ((IPEndPoint)s.Client.RemoteEndPoint).Address;
this.socket = s;
this.srv = srv;
this.secure = secure;
}
private string streamReadLine(Stream inputStream) {
int next_char;
string data = "";
while (true) {
next_char = inputStream.ReadByte();
if (next_char == '\n') { break; }
if (next_char == '\r') { continue; }
if (next_char == -1) { Thread.Sleep(1); continue; };
data += Convert.ToChar(next_char);
}
return data;
}
public void process() {
this.startTime = DateTime.Now;
try {
inputStream = new BufferedStream(socket.GetStream());
outputCore = new BufferedStream(socket.GetStream());
outputStream = new StreamWriter(outputCore);
outputBinary = new BinaryWriter(outputCore);
if (this.secure) {
Console.WriteLine("Secure requested.");
outputSecure = new SslStream(socket.GetStream(), false);
Console.WriteLine("Attempting to authenticate.");
outputSecure.AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("snsys.us.cert"), false, SslProtocols.Tls, false);
Console.WriteLine("Authenticated.");
}
try {
parseRequest();
readHeaders();
if (http_method.Equals("GET")) {
handleGETRequest();
} else if (http_method.Equals("POST")) {
handlePOSTRequest();
}
} catch (Exception e) {
Console.WriteLine("Exception: " + e.ToString());
writeFailure();
}
outputBinary.Flush();
outputStream.Flush();
outputCore.Flush();
inputStream = null; outputBinary = null; outputStream = null; outputCore = null;
socket.Close();
} catch (Exception e){
Console.WriteLine("-----CORE CONNECTION ERROR BEGINS-----");
Console.WriteLine(e);
Console.WriteLine("-----CORE CONNECTION ERROR ENDS-----");
}
}
public void parseRequest() {
try {
string request = this.secure?streamReadLine(outputSecure):streamReadLine(inputStream);
string[] tokens = request.Split(' ');
if (tokens.Length != 3) {
throw new Exception("invalid http request line");
}
http_method = tokens[0].ToUpper();
http_url = URLOperations.Decode(tokens[1]);
http_protocol_versionstring = tokens[2];
} catch (Exception e){
Console.WriteLine ("A parsing error occured:");
Console.WriteLine (e);
}
}
public void readHeaders() {
try {
string line;
while ((line = this.secure?streamReadLine(outputSecure):streamReadLine(inputStream)) != null) {
Console.WriteLine(line);
if (line.Equals("")) {
return;
}
if (line.StartsWith("Host:")) {
http_host = line.Substring(6);
}
if (line.StartsWith("Cookie:")) {
string[] t = line.Substring(8).Split('=');
clientcookies.Add(new SCookie(t[0], t[1]));
}
int separator = line.IndexOf(':');
if (separator == -1) {
throw new Exception("invalid http header line: " + line);
}
string name = line.Substring(0, separator);
int pos = separator + 1;
while ((pos < line.Length) && (line[pos] == ' ')) {
pos++; // strip any spaces
}
string value = line.Substring(pos, line.Length - pos);
httpHeaders[name] = value;
}
} catch (Exception e){
Console.WriteLine("A header reading error occured:");
Console.WriteLine (e);
}
}
public void handleGETRequest() {
srv.HandleGET(this);
}
private const int BUF_SIZE = 4096;
public void handlePOSTRequest() {
// this post data processing just reads everything into a memory stream.
// this is fine for smallish things, but for large stuff we should really
// hand an input stream to the request processor. However, the input stream
// we hand him needs to let him see the "end of the stream" at this content
// length, because otherwise he won't know when he's seen it all!
int content_len = 0;
MemoryStream ms = new MemoryStream();
if (this.httpHeaders.ContainsKey("Content-Length")) {
content_len = Convert.ToInt32(this.httpHeaders["Content-Length"]);
if (content_len > MAX_POST_SIZE) {
throw new Exception(
String.Format("POST Content-Length({0}) too big for this simple server",
content_len));
}
byte[] buf = new byte[BUF_SIZE];
int to_read = content_len;
while (to_read > 0) {
int numread = this.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
if (numread == 0) {
if (to_read == 0) {
break;
} else {
throw new Exception("client disconnected during post");
}
}
to_read -= numread;
ms.Write(buf, 0, numread);
}
ms.Seek(0, SeekOrigin.Begin);
}
srv.HandlePOST(this, new StreamReader(ms));
}
public void write200() {
WriteToClient("HTTP/1.0 200 OK");
}
public void writeType(string content_type="text/html") {
WriteToClient("Content-Type: " + content_type);
}
public void writeCookie(SCookie c) {
WriteToClient(String.Format("Set-Cookie: {0}", c.ToString()));
}
public void writeClose() {
WriteToClient("Connection: close");
WriteToClient("");
}
public void writeSuccess(string content_type="text/html") {
write200();
writeType(content_type);
writeClose();
}
public void writeFailure() {
WriteToClient("HTTP/1.0 404 File not found");
writeClose();
}
public void writeSuccessOmitMIME () {
write200();
writeClose();
}
public void WriteToClient (string data, string Enc) {WriteToClient(data, Encoding.GetEncoding(Enc));}
public void WriteToClient (string data) {WriteToClient(data, Encoding.UTF8);}
public void WriteToClient (string data, Encoding Enc) {
WriteToClient(Enc.GetBytes(data+"\n"));
}
public void WriteToClient (byte[] data) {
outputBinary.Write(data);
}
public static Dictionary<string,Dictionary<string,string>> ProcessPOST (string POSTstring) {
Dictionary<string,Dictionary<string,string>> typeDictionary = new Dictionary<string,Dictionary<string,string>>();
string curtype = "UNSET";
foreach (string i in POSTstring.Split('&')) {
string[] P = i.Split('=');
if (P[0] == "POSTType") {
curtype = P[1];
continue;
}
if (!typeDictionary.ContainsKey(curtype)){typeDictionary.Add(curtype, new Dictionary<string, string>());}
typeDictionary[curtype].Add(P[0],P[1]);
}
return typeDictionary;
}
}
public class FileProcessor {
//extension //MIME
public static Dictionary<string, string> defaultfiletypes = new Dictionary<string, string> {
//{"", ""},
{".css", "text/css"},
{".gif", "image/gif"},
{".htm", "text/html"},
{".html", "text/html"},
{".ico", "image/x-icon"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".png", "image/png"},
{".txt", "text/plain"},
{".zip", "application/zip"},
};
public Dictionary<string, string> filetypes;
private readonly HTTPProcessor HTTP;
public readonly string filename;
public readonly string filepath;
public readonly string totalpath;
public List<string> processMethodStrings;
public FileProcessor(HTTPProcessor sp) : this(sp, Environment.CurrentDirectory, FileProcessor.defaultfiletypes) {}
public FileProcessor(HTTPProcessor sp, Dictionary<string,string> types) : this(sp, Environment.CurrentDirectory, types) {}
public FileProcessor(HTTPProcessor sp, string startingdirectory) : this(sp, startingdirectory, FileProcessor.defaultfiletypes) {}
public FileProcessor(HTTPProcessor sp, string startingdirectory, Dictionary<string,string> types) {
this.filetypes = types;
this.HTTP = sp;
string urlinfo = sp.http_url;
string[] divurl = urlinfo.Split('/');
this.filename = divurl[divurl.Length-1];
this.filepath = startingdirectory;
if (divurl.Length > 2) {
string[] splitfilepath = new string[divurl.Length - 1];
splitfilepath[0] = startingdirectory;
for (int i=1;i<divurl.Length-1;i++) {splitfilepath[i] = divurl[i];}
this.filepath = Path.Combine(splitfilepath);
}
this.totalpath = Path.Combine(filepath, filename);
}
public bool Process (METHOD M, bool caseSensitive = true, bool sendunknowntypes = false) {
if (M != METHOD.GREY && processMethodStrings == null) {throw new NullReferenceException();}
if (filename != "" && File.Exists(totalpath) && ListCheck(M, caseSensitive)) {
foreach (KeyValuePair<string, string> KVP in this.filetypes) {
if (filename.ToLower().EndsWith(KVP.Key)) {
HTTP.writeSuccess(KVP.Value);
byte[] filedata = File.ReadAllBytes(totalpath);
HTTP.WriteToClient(filedata);
return true;
}
}
if (sendunknowntypes) {
HTTP.writeSuccessOmitMIME();
HTTP.WriteToClient(File.ReadAllBytes(totalpath));
return true;
}
}
return false;
}
public enum METHOD {WHITELIST_CONTAINS, WHITELIST_IS, WHITELIST_BEGINS, WHITELIST_ENDS, BLACKLIST_CONTAINS, BLACKLIST_IS, BLACKLIST_BEGINS, BLACKLIST_ENDS, GREY}
private bool ListCheck (METHOD M, bool caseSensitive = true) {
if (M == METHOD.BLACKLIST_BEGINS || M == METHOD.BLACKLIST_ENDS ||M == METHOD.BLACKLIST_CONTAINS ||M == METHOD.BLACKLIST_IS) {
switch (M) {
case METHOD.BLACKLIST_BEGINS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename.StartsWith(s) : filename.ToLower().StartsWith(s.ToLower())) { return false; } continue; }
break;
case METHOD.BLACKLIST_ENDS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename.EndsWith(s) : filename.ToLower().EndsWith(s.ToLower())) { return false; } continue; }
break;
case METHOD.BLACKLIST_CONTAINS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename.Contains(s) : filename.ToLower().Contains(s.ToLower())) { return false; } continue; }
break;
case METHOD.BLACKLIST_IS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename == s : filename.ToLower() == s.ToLower()) { return false; } continue; }
break;
}
return true;
} else if (M == METHOD.WHITELIST_BEGINS || M == METHOD.WHITELIST_ENDS ||M == METHOD.WHITELIST_CONTAINS ||M == METHOD.WHITELIST_IS) {
switch (M) {
case METHOD.WHITELIST_BEGINS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename.StartsWith(s) : filename.ToLower().StartsWith(s.ToLower())) { return true; } continue; }
break;
case METHOD.WHITELIST_ENDS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename.EndsWith(s) : filename.ToLower().EndsWith(s.ToLower())) { return true; } continue; }
break;
case METHOD.WHITELIST_CONTAINS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename.Contains(s) : filename.ToLower().Contains(s.ToLower())) { return true; } continue; }
break;
case METHOD.WHITELIST_IS:
foreach (string s in processMethodStrings) { if (caseSensitive ? filename == s : filename.ToLower() == s.ToLower()) { return true; } continue; }
break;
}
return false;
} else {
return true;
}
}
}
}
| |
/*``The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved via the world wide web at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Initial Developer of the Original Code is Ericsson Utvecklings AB.
* Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
* AB. All Rights Reserved.''
*
* Converted from Java to C# by Vlad Dumitrescu (vlad_Dumitrescu@hotmail.com)
*/
namespace Otp.Erlang
{
using System;
/*
* Provides a C# representation of Erlang refs. There are two
* styles of Erlang refs, old style (one id value) and new style
* (array of id values). This class manages both types.
**/
[Serializable]
public class Ref:Erlang.Object
{
private System.String _node;
private int _creation;
// old style refs have one 18-bit id
// r6 "new" refs have array of ids, first one is only 18 bits however
private int[] _ids = null;
/*
* Create a unique Erlang ref belonging to the local node.
*
* @param self the local node.
*
@deprecated use OtpLocalNode:createRef() instead
**/
public Ref(OtpLocalNode self)
{
Ref r = self.createRef();
this._ids = r._ids;
this._creation = r._creation;
this._node = r._node;
}
/*
* Create an Erlang ref from a stream containing a ref encoded in
* Erlang external format.
*
* @param buf the stream containing the encoded ref.
*
* @exception DecodeException if the buffer does not
* contain a valid external representation of an Erlang ref.
**/
public Ref(OtpInputStream buf)
{
Ref r = buf.read_ref();
this._node = r.node();
this._creation = r.creation();
this._ids = r.ids();
}
/*
* Create an old style Erlang ref from its components.
*
* @param node the nodename.
*
* @param id an arbitrary number. Only the low order 18 bits will
* be used.
*
* @param creation another arbitrary number. Only the low order
* 2 bits will be used.
**/
public Ref(System.String node, int id, int creation)
{
this._node = node;
this._ids = new int[1];
this._ids[0] = id & 0x3ffff; // 18 bits
this._creation = creation & 0x03; // 2 bits
}
/*
* Create a new style Erlang ref from its components.
*
* @param node the nodename.
*
* @param ids an array of arbitrary numbers. Only the low order 18
* bits of the first number will be used. If the array contains only
* one number, an old style ref will be written instead. At most
* three numbers will be read from the array.
*
* @param creation another arbitrary number. Only the low order
* 2 bits will be used.
**/
public Ref(System.String node, int[] ids, int creation)
{
this._node = node;
this._creation = creation & 0x03; // 2 bits
// use at most 82 bits (18 + 32 + 32)
int len = (int) (ids.Length);
this._ids = new int[3];
this._ids[0] = 0;
this._ids[1] = 0;
this._ids[2] = 0;
if (len > 3)
len = 3;
Array.Copy(ids, 0, this._ids, 0, len);
this._ids[0] &= 0x3ffff; // only 18 significant bits in first number
}
/*
* Get the id number from the ref. Old style refs have only one id
* number. If this is a new style ref, the first id number is returned.
*
* @return the id number from the ref.
**/
public virtual int id()
{
return _ids[0];
}
/*
* Get the array of id numbers from the ref. If this is an old style
* ref, the array is of length 1. If this is a new style ref, the
* array has length 3.
*
* @return the array of id numbers from the ref.
**/
public virtual int[] ids()
{
return _ids;
}
/*
* Determine whether this is a new style ref.
*
* @return true if this ref is a new style ref, false otherwise.
**/
public virtual bool isNewRef()
{
return (_ids.Length > 1);
}
/*
* Get the creation number from the ref.
*
* @return the creation number from the ref.
**/
public virtual int creation()
{
return _creation;
}
/*
* Get the node name from the ref.
*
* @return the node name from the ref.
**/
public virtual System.String node()
{
return _node;
}
/*
* Get the string representation of the ref. Erlang refs are printed
* as #Ref<node.id>
*
* @return the string representation of the ref.
**/
public override System.String ToString()
{
System.String s = "#Ref<" + _node;
for (int i = 0; i < _ids.Length; i++)
{
s += "." + _ids[i];
}
s += ">";
return s;
}
/*
* Convert this ref to the equivalent Erlang external representation.
*
* @param buf an output stream to which the encoded ref should be
* written.
**/
public override void encode(OtpOutputStream buf)
{
buf.write_ref(_node, _ids, _creation);
}
/*
* Determine if two refs are equal. Refs are equal if their
* components are equal. New refs and old refs are considered equal
* if the node, creation and first id numnber are equal.
*
* @param o the other ref to compare to.
*
* @return true if the refs are equal, false otherwise.
**/
public override bool Equals(System.Object o)
{
if (!(o is Ref))
return false;
Ref ref_Renamed = (Ref) o;
if (!(this._node.Equals(ref_Renamed.node()) && this._creation == ref_Renamed.creation()))
return false;
if (this.isNewRef() && ref_Renamed.isNewRef())
{
return (this._ids[0] == ref_Renamed._ids[0] && this._ids[1] == ref_Renamed._ids[1] && this._ids[2] == ref_Renamed._ids[2]);
}
return (this._ids[0] == ref_Renamed._ids[0]);
}
public override int GetHashCode()
{
return 1;
}
public override System.Object clone()
{
Ref newRef = (Ref) (base.clone());
newRef._ids = new int[_ids.Length];
_ids.CopyTo(newRef._ids, 0);
return newRef;
}
}
}
| |
// <copyright file=UtilitiesImage.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:57 PM</date>
using Emgu.CV;
using Emgu.CV.Features2D;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
namespace HciLab.Utilities
{
public static class UtilitiesImage
{
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
/// <summary>
///
/// </summary>
/// <param name="pValue"></param>
/// <param name="pMin"></param>
/// <param name="pMax"></param>
/// <returns></returns>
public static System.Drawing.Color ToRGBSpec(int pValue, int pMin, int pMax)
{
int range = pMax - pMin;
double value = (360.0 / range) * (double)(pValue - pMin);
int red = (int)(Math.Sin(value + 2) * 127.0 + 128.0);
int green = (int)(Math.Sin(value * 2 + 2) * 127.0 + 128.0);
int blue = (int)(Math.Sin(value * 4 + 2) * 127.0 + 128.0);
return HsvToRgb(value, 1, 1);
}
/// <summary>
///
/// </summary>
/// <param name="h"></param>
/// <param name="s"></param>
/// <param name="v"></param>
/// <returns></returns>
public static System.Drawing.Color HsvToRgb(double h, double s, double v)
{
int hi = (int)Math.Floor(h / 60.0) % 6;
double f = (h / 60.0) - Math.Floor(h / 60.0);
double p = v * (1.0 - s);
double q = v * (1.0 - (f * s));
double t = v * (1.0 - ((1.0 - f) * s));
System.Drawing.Color ret;
switch (hi)
{
case 0:
ret = GetRgb(v, t, p);
break;
case 1:
ret = GetRgb(q, v, p);
break;
case 2:
ret = GetRgb(p, v, t);
break;
case 3:
ret = GetRgb(p, q, v);
break;
case 4:
ret = GetRgb(t, p, v);
break;
case 5:
ret = GetRgb(v, p, q);
break;
default:
ret = System.Drawing.Color.FromArgb(0);
break;
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
public static System.Drawing.Color GetRgb(double r, double g, double b)
{
return System.Drawing.Color.FromArgb(255, (byte)(r * 255.0), (byte)(g * 255.0), (byte)(b * 255.0));
}
/// <summary>
///
/// </summary>
/// <param name="objectDepth"></param>
/// <returns></returns>
[System.Obsolete("use WriteableBitmap", false)]
public static BitmapSource DepthToImage(int[,] objectDepth)
{
const int BlueIndex = 0;
const int GreenIndex = 1;
const int RedIndex = 2;
int colorIndex = 0;
var pixels = new byte[objectDepth.GetLength(1) * objectDepth.GetLength(0) * 4];
for (int y = 0; y < objectDepth.GetLength(1); y++)
{
for (int x = 0; x < objectDepth.GetLength(0); x++)
{
int depth = objectDepth[x, y];
byte intensity = (byte)(depth >= 800 && depth < 1040 ? depth : 0);
// Apply the intensity to the color channels
pixels[colorIndex + BlueIndex] = intensity; //blue
pixels[colorIndex + GreenIndex] = intensity; //green
pixels[colorIndex + RedIndex] = intensity; //red
colorIndex += 4;
}
}
return BitmapSource.Create(objectDepth.GetLength(0), objectDepth.GetLength(1), 96, 96, PixelFormats.Bgr32, null, pixels, objectDepth.GetLength(0) * 4);
}
/// <summary>
/// Crop the depthImageFrame depending on rectangle.
/// </summary>
/// <param name="colorBS"></param>
/// <param name="rect"></param>
/// <returns>cropped image</returns>
public static Image<Gray, Int32> CropImage(Image<Gray, Int32> colorBS, RectangleF rect)
{
Image<Gray, Int32> tempCropImg = colorBS.Copy();
int x = (int)(rect.X * tempCropImg.Width);
int y = (int)(rect.Y * tempCropImg.Height) - 10;
int width = (int)(rect.Width * tempCropImg.Width) + 5;
int height = (int)(rect.Height * tempCropImg.Height) + 5;
System.Drawing.Rectangle newRec = new System.Drawing.Rectangle(x, y, width, height);
tempCropImg.ROI = newRec;
tempCropImg = tempCropImg.Copy();
CvInvoke.cvResetImageROI(tempCropImg.Ptr);
return tempCropImg;
}
/// <summary>
/// Crop the depthImageFrame depending on rectangle.
/// </summary>
/// <param name="colorBS"></param>
/// <param name="rect"></param>
/// <returns>cropped image</returns>
public static Image<Bgra, byte> CropImage(Image<Bgra, byte> pImage, Rectangle pCropArea)
{
Image<Bgra, byte> pImageToCrop = pImage.Clone();
Image<Bgra, byte> imageCropped = new Image<Bgra, byte>(pCropArea.Width, pCropArea.Height);
pImageToCrop.ROI = pCropArea;
CvInvoke.cvCopy(pImageToCrop.Ptr, imageCropped.Ptr, IntPtr.Zero);
return imageCropped;
}
public static Image<Bgra, byte> CropImage(Image<Bgra, byte> colorBS, RectangleF rect)
{
Image<Bgra, byte> tempCropImg = colorBS.Copy();
int x = (int)(rect.X * tempCropImg.Width);
int y = (int)(rect.Y * tempCropImg.Height) - 10;
int width = (int)(rect.Width * tempCropImg.Width) + 5;
int height = (int)(rect.Height * tempCropImg.Height) + 5;
System.Drawing.Rectangle newRec = new System.Drawing.Rectangle(x, y, width, height);
tempCropImg.ROI = newRec;
tempCropImg = tempCropImg.Copy();
CvInvoke.cvResetImageROI(tempCropImg.Ptr);
return tempCropImg;
}
public static Image<Gray, byte> CropImage(Image<Gray, byte> colorBS, RectangleF rect)
{
Image<Gray, byte> tempCropImg = colorBS.Copy();
int x = (int)(rect.X * tempCropImg.Width);
int y = (int)(rect.Y * tempCropImg.Height) - 10;
int width = (int)(rect.Width * tempCropImg.Width) + 5;
int height = (int)(rect.Height * tempCropImg.Height) + 5;
System.Drawing.Rectangle newRec = new System.Drawing.Rectangle(x, y, width, height);
tempCropImg.ROI = newRec;
tempCropImg = tempCropImg.Copy();
CvInvoke.cvResetImageROI(tempCropImg.Ptr);
return tempCropImg;
}
/// <summary>
///
/// </summary>
/// <param name="pImageToCrop"></param>
/// <param name="pCropArea"></param>
/// <returns></returns>
public static Image<Gray, Int32> CropImage(Image<Gray, Int32> pImage, Rectangle pCropArea)
{
Image<Gray, Int32> pImageToCrop = pImage.Clone();
Image<Gray, Int32> imageCropped = new Image<Gray, Int32>(pCropArea.Width, pCropArea.Height);
pImageToCrop.ROI = pCropArea;
CvInvoke.cvCopy(pImageToCrop.Ptr, imageCropped.Ptr, IntPtr.Zero);
return imageCropped;
}
/// <summary>
///
/// </summary>
/// <param name="colorPixelsRGB"></param>
/// <param name="pBytesPerPixel"></param>
/// <param name="pImageWidth"></param>
/// <param name="pRect"></param>
/// <returns></returns>
public static byte[] CropImage(byte[] colorPixelsRGB, int pBytesPerPixel, int pImageWidth, Rectangle pRect)
{
//Image<Gray, byte> ret = new Image<Gray, byte>(pRect.Width, pRect.Height);
byte[] ret = new byte[pRect.Width * pRect.Height * pBytesPerPixel];
int colorIndex = 0;
for (int y = pRect.Y; y < pRect.Y + pRect.Height; y++)
for (int x = pRect.X; x < pRect.X + pRect.Width; x++)
{
int pixelPos = ((y * pImageWidth) + x) * pBytesPerPixel;
for (int i = 0; i < pBytesPerPixel; i++)
ret[colorIndex + i] = colorPixelsRGB[pixelPos + i];
//1.byte = blue 2.byte = green 3.byte = red; 4.byte = alpha
colorIndex += pBytesPerPixel;
}
return ret;
}
/// <summary>
/// from System.Media.BitmapImage to System.Drawing.Bitmap
/// </summary>
/// <param name="pBitmapSource"></param>
/// <returns></returns>
[System.Obsolete("use WriteableBitmap", true)]
public static Bitmap ToBitmap(BitmapSource pBitmapSource)
{
using (var outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(pBitmapSource));
enc.Save(outStream);
return new System.Drawing.Bitmap(outStream);
}
}
/// <summary>
///
/// </summary>
/// <param name="writeBmp"></param>
/// <returns></returns>
public static Bitmap ToBitmap(WriteableBitmap writeBmp)
{
System.Drawing.Bitmap bmp;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));
enc.Save(outStream);
bmp = new System.Drawing.Bitmap(outStream);
}
return bmp;
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
[System.Obsolete("use WriteableBitmap", true)]
public static BitmapSource ToBitmapSource(Bitmap source)
{
IntPtr ptr = source.GetHbitmap();
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ptr,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ptr);
return bs;
}
/// <summary>
///
/// </summary>
/// <param name="pValue"></param>
/// <param name="pMin"></param>
/// <param name="pMax"></param>
/// <returns></returns>
public static Gray ToGraySpec(double pValue, double pMin, double pMax)
{
return new Gray(((double)byte.MaxValue / (pMax - pMin)) * (pValue - pMin));
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pBytesPerPixel"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static Image<Bgra, byte> ToImage(byte[] bytes, uint pBytesPerPixel, int width, int height)
{
Image<Bgra, byte> img = new Image<Bgra, byte>(width, height);
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
IntPtr imageHeaderForBytes = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MIplImage)));
CvInvoke.cvInitImageHeader(
imageHeaderForBytes,
new System.Drawing.Size(width, height),
Image<Bgra, Byte>.CvDepth,
(int)pBytesPerPixel,
1,
(int)pBytesPerPixel);
Marshal.WriteIntPtr(imageHeaderForBytes,
(int)Marshal.OffsetOf(typeof(MIplImage), "imageData"),
handle.AddrOfPinnedObject());
CvInvoke.cvCopy(imageHeaderForBytes, img, IntPtr.Zero);
Marshal.FreeHGlobal(imageHeaderForBytes);
handle.Free();
return img.Convert<Bgra, byte>();
}
/// <summary>
/// Creat lines between the vertices, for drawing in viewbox
/// </summary>
/// <param name="poi"></param>
/// <param name="imageWidth"></param>
/// <param name="imageHeight"></param>
/// <returns>list of lines</returns>
public static List<LineSegment2DF> PointsToImageLine(PointF[] percentPoint, int imageWidth, int imageHeight)
{
List<LineSegment2DF> boxLine = new List<LineSegment2DF>();
PointF upLeft = new PointF(percentPoint[0].X * imageWidth, percentPoint[0].Y * imageHeight);
PointF buttomLeft = new PointF(percentPoint[1].X * imageWidth, percentPoint[1].Y * imageHeight);
PointF upRight = new PointF(percentPoint[2].X * imageWidth, percentPoint[2].Y * imageHeight);
PointF buttomRight = new PointF(percentPoint[3].X * imageWidth, percentPoint[3].Y * imageHeight);
boxLine.Add(new LineSegment2DF(upLeft, upRight));
boxLine.Add(new LineSegment2DF(buttomLeft, buttomRight));
boxLine.Add(new LineSegment2DF(upLeft, buttomLeft));
boxLine.Add(new LineSegment2DF(upRight, buttomRight));
return boxLine;
}
/// <summary>
/// Converts Rectangle depending on the image size.
/// </summary>
/// <param name="poi"></param>
/// <param name="imageWidth"></param>
/// <param name="imageHeight"></param>
/// <returns>rectangle coordinates between 0 and 1 back</returns>
public static RectangleF ToPercent(System.Drawing.Rectangle rect, int imageWidth, int imageHeight)
{
return new RectangleF((float)rect.Location.X / imageWidth, (float)rect.Location.Y / imageHeight, (float)rect.Width / imageWidth, (float)rect.Height / imageHeight);
}
/// <summary>
/// Converts point coordinates in order depending on the image size.
/// </summary>
/// <param name="poi"></param>
/// <param name="imageWidth"></param>
/// <param name="imageHeight"></param>
/// <returns>point coordinates between 0 and 1</returns>
public static PointF ToPercent(System.Drawing.Point poi, int imageWidth, int imageHeight)
{
return new PointF(poi.X / imageWidth, poi.Y / imageHeight);
}
/// <summary>
/// Converts point coordinates in order depending on the image size.
/// </summary>
/// <param name="poi"></param>
/// <param name="imageWidth"></param>
/// <param name="imageHeight"></param>
/// <returns>point coordinates between 0 and 1 back.</returns>
public static PointF ToPercent(PointF poi, int imageWidth, int imageHeight)
{
return new PointF(poi.X / imageWidth, poi.Y / imageHeight);
}
/// <summary>
/// Converts vertices depending on the image size.
/// </summary>
/// <param name="poi"></param>
/// <param name="imageWidth"></param>
/// <param name="imageHeight"></param>
/// <returns>vertices coordinates between 0 and 1 back.</returns>
public static PointF[] ToPercent(PointF[] po, int imageWidth, int imageHeight)
{
PointF[] convertPointF = new PointF[4];
po = po.OrderBy(s => s.X).ThenBy(s => s.Y).ToArray();
for (int i = 0; i < po.Count(); i++)
convertPointF[i] = new PointF(po[i].X / imageWidth, po[i].Y / imageHeight);
return convertPointF;
}
/// <summary>
///
/// </summary>
/// <param name="Image"></param>
/// <returns></returns>
/*public static Bitmap ToBitmap(ColorImageFrame Image)
{
byte[] pixeldata = new byte[Image.PixelDataLength];
Image.CopyPixelDataTo(pixeldata);
Bitmap bmap = new Bitmap(Image.Width, Image.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
BitmapData bmapdata = bmap.LockBits(
new Rectangle(0, 0, Image.Width, Image.Height),
ImageLockMode.WriteOnly,
bmap.PixelFormat);
IntPtr ptr = bmapdata.Scan0;
Marshal.Copy(pixeldata, 0, ptr, Image.PixelDataLength);
bmap.UnlockBits(bmapdata);
return bmap;
}*/
/// <summary>
///
/// </summary>
/// <param name="depthPixels"></param>
/// <param name="r"></param>
/// <returns></returns>
public static int[] SaveBackground(Image<Gray,Int32> depthPixels, System.Drawing.Rectangle r)
{
int[] depth = new int[r.Width * r.Height];
int index = 0;
Parallel.For(r.Y, r.Y + r.Height, y =>
{
for (int x = r.X; x < r.X + r.Width; ++x)
{
depth[(y - r.Y) * r.Height + x - r.X] = depthPixels.Data[y,x,0];
index++;
}
});
return depth;
}
/// <summary>
///
/// </summary>
/// <param name="pPoint1"></param>
/// <param name="pPoint2"></param>
/// <returns></returns>
public static System.Drawing.Rectangle ToRectangle(System.Drawing.Point pPoint1, System.Drawing.Point pPoint2)
{
return new Rectangle(pPoint1, new System.Drawing.Size(pPoint2.X - pPoint1.X, pPoint2.Y - pPoint1.Y));
}
public static System.Drawing.Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)
{
System.Drawing.Bitmap bmp;
using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));
enc.Save(outStream);
bmp = new System.Drawing.Bitmap(outStream);
}
return bmp;
}
/// <summary>
///
/// </summary>
/// <param name="m_DepthPixels"></param>
/// <param name="maxDepth"></param>
/// <param name="minDepth"></param>
/// <param name="pFramePixelDataLength"></param>
/// <returns></returns>
public static byte[] ToGray(Int32[] m_DepthPixels, int maxDepth, int minDepth,
int pFramePixelDataLength)
{
byte[] colorPixelsDepth = new byte[pFramePixelDataLength * sizeof(int)];
byte intensity = (byte)0;
// Convert the depth to RGB
int colorPixelIndex = 0;
for (int i = 0; i < m_DepthPixels.Length; ++i)
{
// Get the depth for this pixel
Int32 depth = m_DepthPixels[i];
// To convert to a byte, we're discarding the most-significant
// rather than least-significant bits.
// We're preserving detail, although the intensity will "wrap."
// Values outside the reliable depth range are mapped to 0 (black).
// Note: Using conditionals in this loop could degrade performance.
// Consider using a lookup table instead when writing production code.
// See the KinectDepthViewer class used by the KinectExplorer sample
// for a lookup table example.
intensity = (byte)(depth >= minDepth && depth <= maxDepth ? depth : 0);
// Write out blue byte
colorPixelsDepth[colorPixelIndex++] = intensity;
// Write out green byte
colorPixelsDepth[colorPixelIndex++] = intensity;
// Write out red byte
colorPixelsDepth[colorPixelIndex++] = intensity;
// We're outputting Bgra, the last byte in the 32 bits is unused so skip it
// If we were outputting BGRA, we would write alpha here.
++colorPixelIndex;
}
return colorPixelsDepth;
}
/// <summary>
///
/// </summary>
/// <param name="pDepthPixels"></param>
/// <param name="pMaxDepth"></param>
/// <param name="pMinDepth"></param>
/// <param name="pFramePixelDataLength"></param>
/// <param name="pWidth"></param>
/// <param name="pHeight"></param>
/// <returns></returns>
public static Image<Gray, Int32> ToImageGray(Int32[] pDepthPixels, int pWidth, int pHeight)
{
try
{
Image<Gray, Int32> ret = new Image<Gray, Int32> (pWidth, pHeight);
byte[] bytes = new byte[pWidth * pHeight * 4];
for (int i = 0; i < pDepthPixels.Length; i = i +4)
{
byte[] b = BitConverter.GetBytes(pDepthPixels[i]);
bytes[i] = b[0];
bytes[i+1] = b[1];
bytes[i+2] = b[2];
bytes[i+3] = b[3];
}
ret.Bytes = bytes;
return ret;
}
catch (ArgumentOutOfRangeException e)
{
throw e;
}
}
/// <summary>
/// Convert the depth to RGB
/// </summary>
/// <param name="pDepthPixels"></param>
/// <param name="pMinDepth"></param>
/// <param name="pMaxDepth"></param>
/// <returns></returns>
public static byte[] ToGrayByte(Int32[] pDepthPixels,
int pMinDepth,
int pMaxDepth,
int pFramePixelDataLength)
{
byte[] ret = new byte[pFramePixelDataLength];
byte intensity = (byte)0;
for (int i = 0; i < pDepthPixels.Length; i = i + 4)
{
// Get the depth for this pixel
Int32 depth = pDepthPixels[i];
// To convert to a byte, we're discarding the most-significant
// rather than least-significant bits.
// We're preserving detail, although the intensity will "wrap."
// Values outside the reliable depth range are mapped to 0 (black).
// Note: Using conditionals in this loop could degrade performance.
// Consider using a lookup table instead when writing production code.
// See the KinectDepthViewer class used by the KinectExplorer sample
// for a lookup table example.
intensity = (byte)(depth >= pMinDepth && depth <= pMaxDepth ? depth : 0);
// Write out blue byte
ret[i] = intensity;
// Write out green byte
ret[i + 1] = intensity;
// Write out red byte
ret[i + 2] = intensity;
// We're outputting Bgra, the last byte in the 32 bits is unused so skip it
// If we were outputting BGRA, we would write alpha here.
//ret[i+3] = Alpa;
}
return ret;
}
/// <summary>
///
/// the depthImageFrame depending on two points.
/// </summary>
/// <param name="pDepthPixels"></param>
/// <param name="pDepthImageWidth"></param>
/// <param name="pPoint0"></param>
/// <param name="pPoint1"></param>
/// <returns>cropped image</returns>
public static Image<Gray, Int32> CropImage(Int32[] pDepthPixels,
int pDepthImageWidth,
int pMaxDepth,
int pMinDepth,
Rectangle pRect,
out int[][] pDepthMask)
{
int [][] depthMask = new int[pRect.Height][];
var pixels = new byte[pRect.Height * pRect.Width * 4];
Image<Gray, Int32> ret = new Image<Gray, Int32>(pRect.Width, pRect.Height);
int index = 0;
Parallel.For(pRect.Y, pRect.Y + pRect.Height, y =>
{
depthMask[y - pRect.Y] = new int[pRect.Width];
for (int x = pRect.X; x < pRect.X + pRect.Width; x++)
{
int depthIndex = (y * pDepthImageWidth) + x;
depthMask[(y - pRect.Y)][(x - pRect.X)] = pDepthPixels[depthIndex];
ret[y - pRect.Y, x - pRect.X] = ToGraySpec(pDepthPixels[depthIndex], pMinDepth, pMaxDepth);
index++;
}
});
pDepthMask = depthMask;
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
[System.Obsolete("use WriteableBitmap", true)]
public static BitmapSource ToBitmapSource(UIElement element)
{
RenderTargetBitmap target = new RenderTargetBitmap((int)(element.RenderSize.Width), (int)(element.RenderSize.Height), 96, 96, PixelFormats.Pbgra32);
VisualBrush brush = new VisualBrush(element);
DrawingVisual visual = new DrawingVisual();
var drawingContext = visual.RenderOpen();
drawingContext.DrawRectangle(brush, null, new Rect(new System.Windows.Point(0, 0),
new System.Windows.Point(element.RenderSize.Width, element.RenderSize.Height)));
drawingContext.PushOpacityMask(brush);
drawingContext.Close();
target.Render(visual);
return target;
}
[System.Obsolete("use WriteableBitmap", true)]
public static BitmapSource ToBitmapSource(System.Windows.Controls.Canvas element)
{
RenderTargetBitmap target = new RenderTargetBitmap((int)(element.RenderSize.Width), (int)(element.RenderSize.Height), 96, 96, PixelFormats.Pbgra32);
VisualBrush brush = new VisualBrush(element);
DrawingVisual visual = new DrawingVisual();
var drawingContext = visual.RenderOpen();
drawingContext.DrawRectangle(brush, null, new Rect(new System.Windows.Point(0, 0),
new System.Windows.Point(element.RenderSize.Width, element.RenderSize.Height)));
drawingContext.PushOpacityMask(brush);
drawingContext.Close();
target.Render(visual);
return target;
}
/// <summary>
///
/// </summary>
/// <param name="Point"></param>
/// <param name="rect"></param>
/// <param name="depthMask"></param>
/// <returns></returns>
public static int[,,] ObjectDepthPoint(PointF Point, RectangleF rect, Image<Gray,Int32> depthMask)
{
depthMask.ROI = new Rectangle((int)Point.X, (int)Point.Y, (int)rect.Width, (int)rect.Height);
Image<Gray, Int32> mask = depthMask.Copy();
return mask.Data;
}
/// <summary>
///
/// </summary>
/// <param name="modelImage"></param>
/// <param name="observedImage"></param>
/// <param name="homography"></param>
public static void FindMatch(Image<Gray, Int32> modelImage, Image<Gray, Int32> observedImage, out HomographyMatrix homography)
{
VectorOfKeyPoint modelKeyPoints, observedKeyPoints;
Matrix<int> indices;
Matrix<byte> mask;
int k = 2;
double uniquenessThreshold = 0.8;
SURFDetector surfCPU = new SURFDetector(500, false);
homography = null;
//extract features from the object image
modelKeyPoints = new VectorOfKeyPoint();
Matrix<float> modelDescriptors = surfCPU.DetectAndCompute(modelImage.Convert<Gray, byte>(), null, modelKeyPoints);
// extract features from the observed image
observedKeyPoints = new VectorOfKeyPoint();
Matrix<float> observedDescriptors = surfCPU.DetectAndCompute(observedImage.Convert<Gray, byte>(), null, observedKeyPoints);
BruteForceMatcher<float> matcher = new BruteForceMatcher<float>(DistanceType.L2);
matcher.Add(modelDescriptors);
indices = new Matrix<int>(observedDescriptors.Rows, k);
Matrix<float> dist = new Matrix<float>(observedDescriptors.Rows, k);
matcher.KnnMatch(observedDescriptors, indices, dist, k, null);
mask = new Matrix<byte>(dist.Rows, 1);
mask.SetValue(255);
Features2DToolbox.VoteForUniqueness(dist, uniquenessThreshold, mask);
int nonZeroCount = CvInvoke.cvCountNonZero(mask.Ptr);
if (nonZeroCount >= 4)
{
nonZeroCount = Features2DToolbox.VoteForSizeAndOrientation(modelKeyPoints, observedKeyPoints, indices, mask, 1.5, 20);
if (nonZeroCount >= 4)
homography = Features2DToolbox.GetHomographyMatrixFromMatchedFeatures(modelKeyPoints, observedKeyPoints, indices, mask, 2);
}
}
/// <summary>
/// Convert a number to a color between green and red
/// </summary>
/// <param name="count"></param>
/// <returns>color value</returns>
public static Bgra MappingColor(int count)
{
int colorG, colorR;
int color = count * 8;
if (color <= 255)
{
colorG = 255;
colorR = color;
}
else
{
colorG = 255 - (int)(color / 2);
colorR = 255;
}
return new Bgra(0, colorG, colorR, 0);
}
/// <summary>
/// Detect the number of FeaturePoints
/// </summary>
/// <param name="colorBS"></param>
/// <param name="rect"></param>
/// <returns>FeaturePoint count</returns>
public static int FeaturePerObject(Image<Bgra, byte> colorBS, RectangleF rect)
{
Image<Bgra, byte> smallColor = CropImage(colorBS, rect);
SURFDetector surfCPU = new SURFDetector(500, false);
MKeyPoint[] modelKeyPoints = surfCPU.DetectKeyPoints(smallColor.Convert<Gray, byte>(), null);
return modelKeyPoints.Count();
}
public static bool MatchIsSame(Image<Gray, Int32> image1, Image<Gray, Int32> image2, out VectorOfKeyPoint keypoints1, out VectorOfKeyPoint keypoints2, out Matrix<float> symMatches)
{
return MatchIsSame(image1.Convert<Gray, byte>(), image2.Convert<Gray, byte>(), out keypoints1, out keypoints2, out symMatches);
}
/// <summary>
/// Match faeture points using symmetry test
/// </summary>
/// <param name="image1">input image1</param>
/// <param name="image2">input image2</param>
/// <param name="keypoints1">output keypoint1</param>
/// <param name="keypoints2">output keypoint2</param>
/// <returns></returns>
public static bool MatchIsSame(Image<Gray, byte> image1, Image<Gray, byte> image2, out VectorOfKeyPoint keypoints1, out VectorOfKeyPoint keypoints2, out Matrix<float> symMatches)
{
Feature2DBase<float> detector = new SURFDetector(100, false);
bool isSame = false;
//1a. Detection of the SURF features
keypoints1 = detector.DetectKeyPointsRaw(image1, null);
keypoints2 = detector.DetectKeyPointsRaw(image2, null);
//1b. Extraction of the SURF descriptors
Matrix<float> descriptors1 = detector.ComputeDescriptorsRaw(image1, null, keypoints1);
Matrix<float> descriptors2 = detector.ComputeDescriptorsRaw(image2, null, keypoints2);
//2. Match the two image descriptors
//Construction of the match
BruteForceMatcher<float> matcher = new BruteForceMatcher<float>(DistanceType.L2);
//from image 1 to image 2
//based on k nearest neighbours (with k=2)
matcher.Add(descriptors1);
//Number of nearest neighbors to search for
int k = 2;
int n = descriptors2.Rows;
//The resulting n*k matrix of descriptor index from the training descriptors
Matrix<int> trainIdx1 = new Matrix<int>(n, k);
//The resulting n*k matrix of distance value from the training descriptors
Matrix<float> distance1 = new Matrix<float>(n, k);
matcher.KnnMatch(descriptors2, trainIdx1, distance1, k, null);
//from image 1 to image 2
matcher = new BruteForceMatcher<float>(DistanceType.L2);
matcher.Add(descriptors2);
n = descriptors1.Rows;
//The resulting n*k matrix of descriptor index from the training descriptors
Matrix<int> trainIdx2 = new Matrix<int>(n, k);
//The resulting n*k matrix of distance value from the training descriptors
Matrix<float> distance2 = new Matrix<float>(n, k);
matcher.KnnMatch(descriptors1, trainIdx2, distance2, k, null);
//3. Remove matches for which NN ratio is > than threshold
int removed = RatioTest(ref trainIdx1, ref distance1);
removed = RatioTest(ref trainIdx2, ref distance2);
//4. Create symmetrical matches
int symNumber = SymmetryTest(trainIdx1, distance1, trainIdx2, distance2, out symMatches);
if (symNumber > 2)
{
isSame = true;
}
return isSame;
}
public static bool MatchIsSame(Image<Gray, Int32> image1, Image<Gray, Int32> image2)
{
return MatchIsSame(image1.Convert<Gray, byte>(), image2.Convert<Gray, byte>());
}
public static bool MatchIsSame(Image<Gray, byte> image1, Image<Gray, byte> image2)
{
Matrix<float> symMatches;
Feature2DBase<float> detector = new SURFDetector(100, false);
bool isSame = false;
//1a. Detection of the SURF features
VectorOfKeyPoint keypoints1 = detector.DetectKeyPointsRaw(image1, null);
VectorOfKeyPoint keypoints2 = detector.DetectKeyPointsRaw(image2, null);
if (keypoints1.Size == 0 || keypoints2.Size == 0)
{
return isSame;
}
//1b. Extraction of the SURF descriptors
Matrix<float> descriptors1 = detector.ComputeDescriptorsRaw(image1, null, keypoints1);
Matrix<float> descriptors2 = detector.ComputeDescriptorsRaw(image2, null, keypoints2);
//2. Match the two image descriptors
//Construction of the match
BruteForceMatcher<float> matcher = new BruteForceMatcher<float>(DistanceType.L2);
//from image 1 to image 2
//based on k nearest neighbours (with k=2)
matcher.Add(descriptors1);
//Number of nearest neighbors to search for
int k = 2;
int n = descriptors2.Rows;
//The resulting n*k matrix of descriptor index from the training descriptors
Matrix<int> trainIdx1 = new Matrix<int>(n, k);
//The resulting n*k matrix of distance value from the training descriptors
Matrix<float> distance1 = new Matrix<float>(n, k);
matcher.KnnMatch(descriptors2, trainIdx1, distance1, k, null);
//matcher.Dispose();
//from image 1 to image 2
matcher = new BruteForceMatcher<float>(DistanceType.L2);
matcher.Add(descriptors2);
n = descriptors1.Rows;
//The resulting n*k matrix of descriptor index from the training descriptors
Matrix<int> trainIdx2 = new Matrix<int>(n, k);
//The resulting n*k matrix of distance value from the training descriptors
Matrix<float> distance2 = new Matrix<float>(n, k);
matcher.KnnMatch(descriptors1, trainIdx2, distance2, k, null);
//3. Remove matches for which NN ratio is > than threshold
int removed = RatioTest(ref trainIdx1, ref distance1);
removed = RatioTest(ref trainIdx2, ref distance2);
//4. Create symmetrical matches
int symNumber = SymmetryTest(trainIdx1, distance1, trainIdx2, distance2, out symMatches);
if (symNumber > 2)
{
isSame = true;
}
return isSame;
}
/// <summary>
/// Clear matches for which NN ratio is > than threshold
/// </summary>
/// <param name="trainIdx">match descriptor index</param>
/// <param name="distance">match distance value</param>
/// <returns>return the number of removed points</returns>
public static int RatioTest(ref Matrix<int> trainIdx, ref Matrix<float> distance)
{
float ratio = 0.55f;
int removed = 0;
for (int i = 0; i < distance.Rows; i++)
{
if (distance[i, 0] / distance[i, 1] > ratio)
{
trainIdx[i, 0] = -1;
trainIdx[i, 1] = -1;
removed++;
}
}
return removed;
}
/// <summary>
/// Create symMatches vector
/// </summary>
/// <param name="trainIdx1">match descriptor index 1</param>
/// <param name="distance1">match distance value 1</param>
/// <param name="trainIdx2">match descriptor index 2</param>
/// <param name="distance2">match distance value 2</param>
/// <param name="symMatches">return symMatches vector</param>
/// <returns>return the number of symmetrical matches</returns>
public static int SymmetryTest(Matrix<int> trainIdx1, Matrix<float> distance1, Matrix<int> trainIdx2, Matrix<float> distance2, out Matrix<float> symMatches)
{
symMatches = new Matrix<float>(trainIdx1.Rows, 4);
int count = 0;
//for all matches image1 -> image2
for (int i = 0; i < trainIdx1.Rows; i++)
{
//ignore deleted matches
if (trainIdx1[i, 0] == -1 && trainIdx1[i, 1] == -1)
{
continue;
}
//for all matches image2 -> image1
for (int j = 0; j < trainIdx2.Rows; j++)
{
//ignore deleted matches
if (trainIdx2[j, 0] == -1 && trainIdx2[j, 1] == -1)
{
continue;
}
//Match symmetry test
//if (trainIdx1[i, 0] == trainIdx2[j, 1] &&
// trainIdx1[i, 1] == trainIdx2[j, 0])
if (trainIdx1[i, 0] == j && trainIdx2[j, 0] == i)
{
symMatches[i, 0] = j;
symMatches[i, 1] = i;
symMatches[i, 2] = distance1[i, 0];
symMatches[i, 3] = distance1[i, 1];
count++;
break;
}
}
}
return count;
}
/// <summary>
/// Calculate the rotation
/// </summary>
/// <param name="matches"></param>
/// <param name="keyPoints1"></param>
/// <param name="keyPoints2"></param>
/// <returns>angle degree</returns>
public static int GetRotationDiff(Matrix<float> matches, VectorOfKeyPoint keyPoints1, VectorOfKeyPoint keyPoints2)
{
List<PointF> selPoint1 = new List<PointF>();
List<PointF> selPoint2 = new List<PointF>();
for (int i = 0; i < matches.Rows; i++)
{
if (matches[i, 0] == 0 && matches[i, 1] == 0)
{
continue;
}
selPoint1.Add(keyPoints1[(int)matches[i, 0]].Point);
selPoint2.Add(keyPoints2[(int)matches[i, 1]].Point);
}
double d = 0;
// warum tuple id reicht doch (distanze zischen 0 und x)
// oder tuple und distance zischen x und y berechnen.
Tuple<int, int> bestPoints = new Tuple<int, int>(0, 0);
for (int i = 1; i < selPoint1.Count; i++)
{
double tempd = Distance(selPoint1[0], selPoint1[i]);
if (tempd > d)
{
d = tempd;
bestPoints = new Tuple<int, int>(0, i);
}
}
double firstGard = GetGradient(selPoint1[0], selPoint1[bestPoints.Item2]);
double secGard = GetGradient(selPoint2[0], selPoint2[bestPoints.Item2]);
return (int)(firstGard - secGard);
}
/// <summary>
/// Calculate the gradient.
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns>gradient</returns>
public static double GetGradient(PointF p1, PointF p2)
{
float yDiff = p2.Y - p1.Y;
float xDiff = p2.X - p1.X;
double grad = Math.Atan2(yDiff, xDiff) * 180 / Math.PI;
return grad;
}
/// <summary>
/// Calculate the distance between two points
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns>distance</returns>
public static double Distance(PointF p1, PointF p2)
{
double d;
d = Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
return d;
}
public static double DiffSize(SizeF box, SizeF box2)
{
double d;
double boxArea = box.Height * box.Width;
double boxArea2 = box2.Height * box2.Width;
if (boxArea > boxArea2)
{
d = boxArea - boxArea2;
}
else
{
d = boxArea - boxArea2;
}
return d;
}
/// <summary>
///
/// </summary>
/// <param name="rgbImage"></param>
public static void AnalyseObjectColor(Image<Gray, Int32> rgbImage)
{
//FeaturePoint
SURFDetector surfCPU = new SURFDetector(500, false);
MKeyPoint[] modelKeyPoints = surfCPU.DetectKeyPoints(rgbImage.Convert<Gray, byte>(), null);
int keyPoints = modelKeyPoints.Count();
//Colorintensity
int intensity = (int)rgbImage.GetAverage().Intensity;
}
/// <summary>
///
/// </summary>
/// <param name="corners"></param>
public static void SortCorners(PointF[] corners)
{
corners = corners.OrderBy(p => p.X).ThenBy(p => p.Y).ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="depth"></param>
/// <returns></returns>
public static MeshGeometry3D BuildMesh(int[,] depth)
{
MeshGeometry3D tmesh = new MeshGeometry3D();
List<Vector3D> Normalvec = new List<Vector3D>();
// collection of corners for the triangles
Point3DCollection corners = new Point3DCollection();
// collection of points
Point3D[] points_array = new Point3D[4];
// collection of all the triangles
Int32Collection Triangles = new Int32Collection();
// collection of all the cross product normals
Vector3DCollection Normals = new Vector3DCollection();
// collection of vectors
Vector3D[] vectors_array = new Vector3D[5];
int i = 0;
for (int y = 0; y < depth.GetLength(2); y++)
{
for (int x = 0; x < depth.GetLength(1); x++)
{
// triangle point locations
points_array[0] = new Point3D(x, y++, depth[x, y++]);
points_array[1] = new Point3D(x, y, depth[x, y]);
points_array[2] = new Point3D(x++, y, depth[x++, y]);
points_array[3] = new Point3D(x++, y++, depth[x++, y++]);
// create vectors of size difference between points
vectors_array[0] = new Vector3D(points_array[1].X - points_array[0].X, points_array[1].Y - points_array[0].Y, points_array[1].Z - points_array[0].Z);
vectors_array[1] = new Vector3D(points_array[1].X - points_array[2].X, points_array[1].Y - points_array[2].Y, points_array[1].Z - points_array[2].Z);
vectors_array[2] = new Vector3D(points_array[2].X - points_array[0].X, points_array[2].Y - points_array[0].Y, points_array[2].Z - points_array[0].Z);
vectors_array[3] = new Vector3D(points_array[0].X - points_array[3].X, points_array[0].Y - points_array[3].Y, points_array[0].Z - points_array[3].Z);
vectors_array[4] = new Vector3D(points_array[2].X - points_array[3].X, points_array[2].Y - points_array[3].Y, points_array[2].Z - points_array[3].Z);
// add the corners to the 2 triangles to form a square
corners.Add(points_array[0]);
corners.Add(points_array[1]);
corners.Add(points_array[2]);
corners.Add(points_array[2]);
corners.Add(points_array[3]);
corners.Add(points_array[0]);
// add triangles to the collection
Triangles.Add(i);
Triangles.Add(i + 1);
Triangles.Add(i + 2);
Triangles.Add(i + 3);
Triangles.Add(i + 4);
Triangles.Add(i + 5);
// find the normals of the triangles by taking the cross product
Normals.Add(Vector3D.CrossProduct(vectors_array[0], vectors_array[2]));
Normals.Add(Vector3D.CrossProduct(vectors_array[1], vectors_array[0]));
Normals.Add(Vector3D.CrossProduct(vectors_array[1], vectors_array[2]));
Normals.Add(Vector3D.CrossProduct(vectors_array[1], vectors_array[2]));
Normals.Add(Vector3D.CrossProduct(vectors_array[3], vectors_array[4]));
Normals.Add(Vector3D.CrossProduct(vectors_array[0], vectors_array[2]));
i = i + 6;
}
}
// add texture to all the points
tmesh.Positions = corners;
tmesh.TriangleIndices = Triangles;
tmesh.Normals = Normals;
return tmesh;
}
public static void ToImage(System.Windows.Controls.Image pImage, Image<Bgra, byte> pImageToDraw)
{
//Zeichenn
if (!(pImage.Source is WriteableBitmap) || pImage.Source.Width != pImageToDraw.Width || pImage.Source.Height != pImageToDraw.Height)
pImage.Source = new WriteableBitmap(pImageToDraw.Width, pImageToDraw.Height, 96.0, 96.0, PixelFormats.Bgr32, null);
WriteableBitmap source = pImage.Source as WriteableBitmap;
// Write the pixel data into our bitmap
source.WritePixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
pImageToDraw.Bytes,
source.PixelWidth * 4,
0);
}
public static void ToImage(System.Windows.Controls.Image pImage, Image<Gray, Int32> pImageToDraw)
{
Image<Gray, Int16> imageCon = pImageToDraw.Convert<Gray, Int16>();
if (!(pImage.Source is WriteableBitmap) || pImage.Source.Width != pImageToDraw.Width || pImage.Source.Height != pImageToDraw.Height)
pImage.Source = new WriteableBitmap(imageCon.Width, imageCon.Height, 96.0, 96.0, PixelFormats.Gray16, null);
WriteableBitmap source = pImage.Source as WriteableBitmap;
// Write the pixel data into our bitmap
source.WritePixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
imageCon.Bytes,
source.PixelWidth * 2,
0);
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Manos.Templates {
public class Token {
public Token (int line, int col, TokenType type, string value)
{
Line = line;
Column = col;
Type = type;
Value = value;
}
public Token (int line, int col, TokenType type, string value, object tok_value) : this (line, col, type, value)
{
TokenizedValue = tok_value;
}
public int Line {
get;
private set;
}
public int Column {
get;
private set;
}
public TokenType Type {
get;
private set;
}
public string Value {
get;
private set;
}
public object TokenizedValue {
get;
private set;
}
}
public class TemplateTokenizer {
private TokenOperators token_ops;
private Token current;
private int col;
private int line;
private int position;
private bool have_unget;
private int unget_value;
private TemplateEnvironment environment;
private string source;
private TextReader reader;
private StringBuilder builder;
bool in_code_block = false;
public TemplateTokenizer (TemplateEnvironment env, TextReader reader)
{
this.environment = env;
this.reader = reader;
builder = new StringBuilder ();
token_ops = new TokenOperators (environment);
}
public Token Current {
get { return current; }
}
public int Line {
get { return line; }
}
public int Column {
get { return col; }
}
public Token GetNextToken ()
{
current = _GetNextToken ();
return current;
}
private Token _GetNextToken ()
{
int c;
Token tok = null;
TokenType tok_type;
builder.Length = 0;
while ((c = ReadChar ()) != -1) {
if (in_code_block && (c == '\'' || c == '\"')) {
string str = ReadQuotedString (c);
Console.WriteLine ("READ QUOTED STRING: {0}", str);
if (str == null)
return new Token (line, col, TokenType.TOKEN_EOF, String.Empty);
tok = new Token (line, col, TokenType.TOKEN_QUOTED_STRING, str);
return tok;
}
int d = reader.Peek ();
if (in_code_block && IsNumberStartChar (c) && IsNumberChar (d)) {
object number = ReadNumber (c, d, out tok_type);
tok = new Token (line, col, tok_type, number.ToString (), number);
return tok;
}
string two_chars = String.Concat ((char) c, (char) d);
if (token_ops.DoubleCharOps.TryGetValue (two_chars, out tok_type)) {
tok = new Token (line, col, tok_type, two_chars);
reader.Read ();
UpdateInCodeBlock (tok_type);
return tok;
}
if (token_ops.SingleCharOps.TryGetValue (c, out tok_type)) {
tok = new Token (line, col, tok_type, "" + (char) c);
return tok;
}
if (in_code_block) {
if (Char.IsWhiteSpace ((char) c)) {
tok = new Token (line, col, TokenType.TOKEN_WHITESPACE, "" + (char) c);
return tok;
}
if (IsNameStartChar (c)) {
do {
builder.Append ((char) c);
c = ReadChar ();
} while (IsNameChar (c));
PutbackChar (c);
tok = new Token (line, col, TokenType.TOKEN_NAME, builder.ToString ());
return tok;
}
}
tok = new Token (line, col, TokenType.TOKEN_DATA, "" + (char) c);
return tok;
}
return new Token (line, col, TokenType.TOKEN_EOF, "");
}
private void PutbackChar (int c)
{
have_unget = true;
unget_value = c;
}
private int ReadChar ()
{
int c;
if (have_unget) {
c = unget_value;
have_unget = false;
} else {
c = reader.Read ();
}
if (c == '\r' && reader.Peek () == '\n') {
c = reader.Read ();
position++;
}
if (c == '\n'){
col = -1;
line++;
}
if (c != -1) {
col++;
position++;
}
return c;
}
private void UpdateInCodeBlock (TokenType tok_type)
{
switch (tok_type) {
case TokenType.TOKEN_BLOCK_END:
case TokenType.TOKEN_VARIABLE_END:
in_code_block = false;
break;
case TokenType.TOKEN_BLOCK_BEGIN:
case TokenType.TOKEN_VARIABLE_BEGIN:
in_code_block = true;
break;
default:
break;
}
}
private string ReadQuotedString (int c)
{
int quote_char = c;
do {
builder.Append ((char) c);
c = ReadChar ();
} while (c != quote_char && c != -1);
if (c == -1)
return null;
builder.Append ((char) c);
return builder.ToString ();
}
private static readonly string idchars = "_";
private static bool IsNameStartChar (int ch)
{
return (Char.IsLetter ((char) ch) || (idchars.IndexOf ((char) ch) != -1));
}
private static bool IsNameChar (int ch)
{
return (Char.IsLetterOrDigit ((char) ch) || (idchars.IndexOf ((char) ch) != -1));
}
private static readonly string numstartchars = "-";
private static bool IsNumberStartChar (int c)
{
return (Char.IsDigit ((char) c) || (numstartchars.IndexOf ((char) c) != -1));
}
private static readonly string numchars = ".";
private static bool IsNumberChar (int c)
{
return (Char.IsDigit ((char) c) || (numchars.IndexOf ((char) c) != -1));
}
private object ReadNumber (int c, int d, out TokenType tok_type)
{
StringBuilder builder = new StringBuilder ();
bool is_double = false;
object number;
builder.Append ((char) c);
c = ReadChar ();
while (IsNumberChar (c)) {
if (c == '.')
is_double = true;
builder.Append ((char) c);
c = ReadChar ();
}
if (is_double) {
tok_type = TokenType.TOKEN_DOUBLE;
number = Double.Parse (builder.ToString ());
} else {
tok_type = TokenType.TOKEN_INTEGER;
number = Int32.Parse (builder.ToString ());
}
PutbackChar (c);
return number;
}
}
public enum TokenType {
TOKEN_ADD,
TOKEN_ASSIGN,
TOKEN_COLON,
TOKEN_COMMA,
TOKEN_DIV,
TOKEN_DOT,
TOKEN_DOUBLE,
TOKEN_EQ,
TOKEN_FLOORDIV,
TOKEN_GT,
TOKEN_GTEQ,
TOKEN_LBRACE,
TOKEN_LBRACKET,
TOKEN_LPAREN,
TOKEN_LT,
TOKEN_LTEQ,
TOKEN_MOD,
TOKEN_MUL,
TOKEN_NE,
TOKEN_PIPE,
TOKEN_POW,
TOKEN_RBRACE,
TOKEN_RBRACKET,
TOKEN_RPAREN,
TOKEN_SEMICOLON,
TOKEN_SUB,
TOKEN_TILDE,
TOKEN_WHITESPACE,
TOKEN_INTEGER,
TOKEN_NAME,
TOKEN_STRING,
TOKEN_QUOTED_STRING,
TOKEN_OPERATOR,
TOKEN_BLOCK_BEGIN,
TOKEN_BLOCK_END,
TOKEN_VARIABLE_BEGIN,
TOKEN_VARIABLE_END,
TOKEN_RAW_BEGIN,
TOKEN_RAW_END,
TOKEN_COMMENT_BEGIN,
TOKEN_COMMENT_END,
TOKEN_COMMENT,
TOKEN_DATA,
TOKEN_INITIAL,
TOKEN_EOF,
}
public class TokenOperators {
private Dictionary<int,TokenType> single_char_ops = new Dictionary<int,TokenType> ();
private Dictionary<string,TokenType> double_char_ops = new Dictionary<string,TokenType> ();
public TokenOperators (TemplateEnvironment env)
{
single_char_ops.Add ('+', TokenType.TOKEN_ADD);
single_char_ops.Add ('-', TokenType.TOKEN_SUB);
single_char_ops.Add ('/', TokenType.TOKEN_DIV);
single_char_ops.Add ('*', TokenType.TOKEN_MUL);
single_char_ops.Add ('%', TokenType.TOKEN_MOD);
single_char_ops.Add ('~', TokenType.TOKEN_TILDE);
single_char_ops.Add ('[', TokenType.TOKEN_LBRACKET);
single_char_ops.Add (']', TokenType.TOKEN_RBRACKET);
single_char_ops.Add ('(', TokenType.TOKEN_LPAREN);
single_char_ops.Add (')', TokenType.TOKEN_RPAREN);
single_char_ops.Add ('{', TokenType.TOKEN_LBRACE);
single_char_ops.Add ('}', TokenType.TOKEN_RBRACE);
single_char_ops.Add ('>', TokenType.TOKEN_GT);
single_char_ops.Add ('<', TokenType.TOKEN_LT);
single_char_ops.Add ('=', TokenType.TOKEN_ASSIGN);
single_char_ops.Add ('.', TokenType.TOKEN_DOT);
single_char_ops.Add (':', TokenType.TOKEN_COLON);
single_char_ops.Add ('|', TokenType.TOKEN_PIPE);
single_char_ops.Add (',', TokenType.TOKEN_COMMA);
single_char_ops.Add (';', TokenType.TOKEN_SEMICOLON);
double_char_ops.Add ("//", TokenType.TOKEN_FLOORDIV);
double_char_ops.Add ("**", TokenType.TOKEN_POW);
double_char_ops.Add ("==", TokenType.TOKEN_EQ);
double_char_ops.Add ("!=", TokenType.TOKEN_NE);
double_char_ops.Add (">=", TokenType.TOKEN_GTEQ);
double_char_ops.Add ("<=", TokenType.TOKEN_LTEQ);
// These should be environment dependendant
double_char_ops.Add (env.BlockStartString, TokenType.TOKEN_BLOCK_BEGIN);
double_char_ops.Add (env.BlockEndString, TokenType.TOKEN_BLOCK_END);
double_char_ops.Add (env.VariableStartString, TokenType.TOKEN_VARIABLE_BEGIN);
double_char_ops.Add (env.VariableEndString, TokenType.TOKEN_VARIABLE_END);
double_char_ops.Add (env.CommentStartString, TokenType.TOKEN_COMMENT_BEGIN);
double_char_ops.Add (env.CommentEndString, TokenType.TOKEN_COMMENT_END);
}
public Dictionary<int,TokenType> SingleCharOps {
get { return single_char_ops; }
}
public Dictionary<string,TokenType> DoubleCharOps {
get { return double_char_ops; }
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ElementAtQueryOperator.cs
//
// <OWNER>[....]</OWNER>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// ElementAt just retrieves an element at a specific index. There is some cross-partition
/// coordination to force partitions to stop looking once a partition has found the
/// sought-after element.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class ElementAtQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
{
private readonly int m_index; // The index that we're looking for.
private readonly bool m_prematureMerge = false; // Whether to prematurely merge the input of this operator.
private readonly bool m_limitsParallelism = false; // Whether this operator limits parallelism
//---------------------------------------------------------------------------------------
// Constructs a new instance of the contains search operator.
//
// Arguments:
// child - the child tree to enumerate.
// index - index we are searching for.
//
internal ElementAtQueryOperator(IEnumerable<TSource> child, int index)
:base(child)
{
Contract.Assert(child != null, "child data source cannot be null");
Contract.Assert(index >= 0, "index can't be less than 0");
m_index = index;
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct))
{
m_prematureMerge = true;
m_limitsParallelism = childIndexState != OrdinalIndexState.Shuffled;
}
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TSource> Open(
QuerySettings settings, bool preferStriping)
{
// We just open the child operator.
QueryResults<TSource> childQueryResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource,TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
{
// If the child OOP index is not correct, reindex.
int partitionCount = inputStream.PartitionCount;
PartitionedStream<TSource, int> intKeyStream;
if (m_prematureMerge)
{
intKeyStream = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream();
Contract.Assert(intKeyStream.OrdinalIndexState == OrdinalIndexState.Indexible);
}
else
{
intKeyStream = (PartitionedStream<TSource, int>)(object)inputStream;
}
// Create a shared cancelation variable and then return a possibly wrapped new enumerator.
Shared<bool> resultFoundFlag = new Shared<bool>(false);
PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>(
partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new ElementAtQueryOperatorEnumerator(intKeyStream[i], m_index, resultFoundFlag, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
Contract.Assert(false, "This method should never be called as fallback to sequential is handled in Aggregate().");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return m_limitsParallelism; }
}
/// <summary>
/// Executes the query, either sequentially or in parallel, depending on the query execution mode and
/// whether a premature merge was inserted by this ElementAt operator.
/// </summary>
/// <param name="result">result</param>
/// <param name="withDefaultValue">withDefaultValue</param>
/// <returns>whether an element with this index exists</returns>
internal bool Aggregate(out TSource result, bool withDefaultValue)
{
// If we were to insert a premature merge before this ElementAt, and we are executing in conservative mode, run the whole query
// sequentially.
if (LimitsParallelism && SpecifiedQuerySettings.WithDefaults().ExecutionMode.Value != ParallelExecutionMode.ForceParallelism)
{
CancellationState cancelState = SpecifiedQuerySettings.CancellationState;
if (withDefaultValue)
{
IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAtOrDefault(m_index);
}
else
{
IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAt(m_index);
}
return true;
}
using (IEnumerator<TSource> e = GetEnumerator(ParallelMergeOptions.FullyBuffered))
{
if (e.MoveNext())
{
TSource current = e.Current;
Contract.Assert(!e.MoveNext(), "expected enumerator to be empty");
result = current;
return true;
}
}
result = default(TSource);
return false;
}
//---------------------------------------------------------------------------------------
// This enumerator performs the search for the element at the specified index.
//
class ElementAtQueryOperatorEnumerator : QueryOperatorEnumerator<TSource, int>
{
private QueryOperatorEnumerator<TSource, int> m_source; // The source data.
private int m_index; // The index of the element to seek.
private Shared<bool> m_resultFoundFlag; // Whether to cancel the operation.
private CancellationToken m_cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new any/all search operator.
//
internal ElementAtQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, int> source,
int index, Shared<bool> resultFoundFlag,
CancellationToken cancellationToken)
{
Contract.Assert(source != null);
Contract.Assert(index >= 0);
Contract.Assert(resultFoundFlag != null);
m_source = source;
m_index = index;
m_resultFoundFlag = resultFoundFlag;
m_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Enumerates the entire input until the element with the specified is found or another
// partition has signaled that it found the element.
//
internal override bool MoveNext(ref TSource currentElement, ref int currentKey)
{
// Just walk the enumerator until we've found the element.
int i = 0;
while (m_source.MoveNext(ref currentElement, ref currentKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(m_cancellationToken);
if (m_resultFoundFlag.Value)
{
// Another partition found the element.
break;
}
if (currentKey == m_index)
{
// We have found the element. Cancel other searches and return true.
m_resultFoundFlag.Value = true;
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(m_source != null);
m_source.Dispose();
}
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace MonoMac.OpenGL
{
/// <summary>
/// 3-component Vector of the Half type. Occupies 6 Byte total.
/// </summary>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Vector3h : ISerializable, IEquatable<Vector3h>
{
#region Public Fields
/// <summary>The X component of the Half3.</summary>
public Half X;
/// <summary>The Y component of the Half3.</summary>
public Half Y;
/// <summary>The Z component of the Half3.</summary>
public Half Z;
#endregion Public Fields
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Half value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Single value)
{
X = new Half(value);
Y = new Half(value);
Z = new Half(value);
}
/// <summary>
/// The new Half3 instance will avoid conversion and copy directly from the Half parameters.
/// </summary>
/// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param>
public Vector3h(Half x, Half y, Half z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
public Vector3h(Single x, Single y, Single z)
{
X = new Half(x);
Y = new Half(y);
Z = new Half(z);
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector3h(Single x, Single y, Single z, bool throwOnError)
{
X = new Half(x, throwOnError);
Y = new Half(y, throwOnError);
Z = new Half(z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// This is the fastest constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
public Vector3h(ref Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector3h(ref Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
public Vector3h(Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector3h(Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// This is the faster constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
#endregion Constructors
#region Swizzle
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } }
#endregion
#region Half -> Single
/// <summary>
/// Returns this Half3 instance's contents as Vector3.
/// </summary>
/// <returns>OpenTK.Vector3</returns>
public Vector3 ToVector3()
{
return new Vector3(X, Y, Z);
}
/// <summary>
/// Returns this Half3 instance's contents as Vector3d.
/// </summary>
public Vector3d ToVector3d()
{
return new Vector3d(X, Y, Z);
}
#endregion Half -> Single
#region Conversions
/// <summary>Converts OpenTK.Vector3 to OpenTK.Half3.</summary>
/// <param name="v3f">The Vector3 to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3 v3f)
{
return new Vector3h(v3f);
}
/// <summary>Converts OpenTK.Vector3d to OpenTK.Half3.</summary>
/// <param name="v3d">The Vector3d to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3d v3d)
{
return new Vector3h(v3d);
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3.</returns>
public static explicit operator Vector3(Vector3h h3)
{
Vector3 result = new Vector3();
result.X = h3.X.ToSingle();
result.Y = h3.Y.ToSingle();
result.Z = h3.Z.ToSingle();
return result;
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3d.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3d.</returns>
public static explicit operator Vector3d(Vector3h h3)
{
Vector3d result = new Vector3d();
result.X = h3.X.ToSingle();
result.Y = h3.Y.ToSingle();
result.Z = h3.Z.ToSingle();
return result;
}
#endregion Conversions
#region Constants
/// <summary>The size in bytes for an instance of the Half3 struct is 6.</summary>
public static readonly int SizeInBytes = 6;
#endregion Constants
#region ISerializable
/// <summary>Constructor used by ISerializable to deserialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Vector3h(SerializationInfo info, StreamingContext context)
{
this.X = (Half)info.GetValue("X", typeof(Half));
this.Y = (Half)info.GetValue("Y", typeof(Half));
this.Z = (Half)info.GetValue("Z", typeof(Half));
}
/// <summary>Used by ISerialize to serialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("X", this.X);
info.AddValue("Y", this.Y);
info.AddValue("Z", this.Z);
}
#endregion ISerializable
#region Binary dump
/// <summary>Updates the X,Y and Z components of this instance by reading from a Stream.</summary>
/// <param name="bin">A BinaryReader instance associated with an open Stream.</param>
public void FromBinaryStream(BinaryReader bin)
{
X.FromBinaryStream(bin);
Y.FromBinaryStream(bin);
Z.FromBinaryStream(bin);
}
/// <summary>Writes the X,Y and Z components of this instance into a Stream.</summary>
/// <param name="bin">A BinaryWriter instance associated with an open Stream.</param>
public void ToBinaryStream(BinaryWriter bin)
{
X.ToBinaryStream(bin);
Y.ToBinaryStream(bin);
Z.ToBinaryStream(bin);
}
#endregion Binary dump
#region IEquatable<Half3> Members
/// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half3 vector.</summary>
/// <param name="other">OpenTK.Half3 to compare to this instance..</param>
/// <returns>True, if other is equal to this instance; false otherwise.</returns>
public bool Equals(Vector3h other)
{
return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z));
}
#endregion
#region ToString()
/// <summary>Returns a string that contains this Half3's numbers in human-legible form.</summary>
public override string ToString()
{
return String.Format("({0}, {1}, {2})", X.ToString(), Y.ToString(), Z.ToString());
}
#endregion ToString()
#region BitConverter
/// <summary>Returns the Half3 as an array of bytes.</summary>
/// <param name="h">The Half3 to convert.</param>
/// <returns>The input as byte array.</returns>
public static byte[] GetBytes(Vector3h h)
{
byte[] result = new byte[SizeInBytes];
byte[] temp = Half.GetBytes(h.X);
result[0] = temp[0];
result[1] = temp[1];
temp = Half.GetBytes(h.Y);
result[2] = temp[0];
result[3] = temp[1];
temp = Half.GetBytes(h.Z);
result[4] = temp[0];
result[5] = temp[1];
return result;
}
/// <summary>Converts an array of bytes into Half3.</summary>
/// <param name="value">A Half3 in it's byte[] representation.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A new Half3 instance.</returns>
public static Vector3h FromBytes(byte[] value, int startIndex)
{
Vector3h h3 = new Vector3h();
h3.X = Half.FromBytes(value, startIndex);
h3.Y = Half.FromBytes(value, startIndex + 2);
h3.Z = Half.FromBytes(value, startIndex + 4);
return h3;
}
#endregion BitConverter
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
using ProjectItem = BuildVision.UI.Models.ProjectItem;
using ErrorItem = BuildVision.Contracts.ErrorItem;
using WindowState = BuildVision.UI.Models.WindowState;
using Microsoft.VisualStudio;
using System.Windows;
using System.ComponentModel;
using System.IO;
using BuildVision.Contracts;
using EnvDTE80;
using BuildVision.Common;
using BuildVision.UI;
using System.Text;
using BuildVision.Core;
using BuildVision.Helpers;
using BuildVision.Views.Settings;
using BuildVision.Tool.Models;
using BuildVision.UI.Contracts;
using BuildVision.UI.ViewModels;
using BuildVision.UI.Common.Logging;
using BuildVision.UI.Models.Indicators.Core;
using BuildVision.UI.Extensions;
using BuildVision.UI.Helpers;
using BuildVision.UI.Models;
using BuildVision.UI.Settings.Models.ToolWindow;
using System.Collections.Specialized;
namespace BuildVision.Tool
{
public class Tool
{
private readonly DTE _dte;
private readonly DTE2 _dte2;
private readonly IVsStatusbar _dteStatusBar;
private readonly ToolWindowManager _toolWindowManager;
private readonly IBuildInfo _buildContext;
private readonly IBuildDistributor _buildDistributor;
private readonly ControlViewModel _viewModel;
private readonly SolutionEvents _solutionEvents;
private bool _buildErrorIsNavigated;
private string _origTextCurrentState;
private readonly IPackageContext _packageContext;
public Tool(IPackageContext packageContext, IBuildInfo buildContext, IBuildDistributor buildDistributor, ControlViewModel viewModel)
{
_packageContext = packageContext;
_dte = packageContext.GetDTE();
_dte2 = packageContext.GetDTE2();
if (_dte == null)
throw new InvalidOperationException("Unable to get DTE instance.");
_dteStatusBar = packageContext.GetStatusBar();
if (_dteStatusBar == null)
TraceManager.TraceError("Unable to get IVsStatusbar instance.");
_toolWindowManager = new ToolWindowManager(packageContext);
_buildContext = buildContext;
_buildDistributor = buildDistributor;
_viewModel = viewModel;
_solutionEvents = _dte.Events.SolutionEvents;
Initialize();
}
private void Initialize()
{
_buildDistributor.OnBuildBegin += (s, e) => BuildEvents_OnBuildBegin();
_buildDistributor.OnBuildDone += (s, e) => BuildEvents_OnBuildDone();
_buildDistributor.OnBuildProcess += (s, e) => BuildEvents_OnBuildProcess();
_buildDistributor.OnBuildCancelled += (s, e) => BuildEvents_OnBuildCancelled();
_buildDistributor.OnBuildProjectBegin += BuildEvents_OnBuildProjectBegin;
_buildDistributor.OnBuildProjectDone += BuildEvents_OnBuildProjectDone;
_buildDistributor.OnErrorRaised += BuildEvents_OnErrorRaised;
_solutionEvents.AfterClosing += SolutionEvents_AfterClosing;
_solutionEvents.Opened += SolutionEvents_Opened;
_viewModel.CancelBuildSolution += () => RaiseCommand(VSConstants.VSStd97CmdID.CancelBuild);
_viewModel.CleanSolution += () => RaiseCommand(VSConstants.VSStd97CmdID.CleanSln);
_viewModel.RebuildSolution += () => RaiseCommand(VSConstants.VSStd97CmdID.RebuildSln);
_viewModel.BuildSolution += () => RaiseCommand(VSConstants.VSStd97CmdID.BuildSln);
_viewModel.RaiseCommandForSelectedProject += RaiseCommandForSelectedProject;
_viewModel.ProjectCopyBuildOutputFilesToClipBoard += ProjectCopyBuildOutputFilesToClipBoard;
_viewModel.ShowGeneralSettingsPage += () => _packageContext.ShowOptionPage(typeof(GeneralSettingsDialogPage));
_viewModel.ShowGridColumnsSettingsPage += () => _packageContext.ShowOptionPage(typeof(GridSettingsDialogPage));
_viewModel.CopyErrorMessageToClipboard += CopyErrorMessageToClipboard;
UpdateSolutionItem();
}
private void CopyErrorMessageToClipboard(ProjectItem projectItem)
{
try
{
var errors = new StringBuilder();
foreach(var errorItem in projectItem.ErrorsBox.Errors)
{
errors.AppendLine(string.Format("{0}({1},{2},{3},{4}): error {5}: {6}", errorItem.File, errorItem.LineNumber, errorItem.ColumnNumber, errorItem.EndLineNumber, errorItem.EndColumnNumber, errorItem.Code, errorItem.Message));
}
Clipboard.SetText(errors.ToString());
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void SolutionEvents_Opened()
{
UpdateSolutionItem();
_viewModel.ResetIndicators(ResetIndicatorMode.ResetValue);
}
private void SolutionEvents_AfterClosing()
{
_viewModel.TextCurrentState = Resources.BuildDoneText_BuildNotStarted;
_viewModel.ImageCurrentState = VectorResources.TryGet(BuildImages.BuildActionResourcesUri, "StandBy");
_viewModel.ImageCurrentStateResult = null;
UpdateSolutionItem();
_viewModel.ProjectsList.Clear();
_viewModel.ResetIndicators(ResetIndicatorMode.Disable);
_viewModel.BuildProgressViewModel.ResetTaskBarInfo();
}
private void RaiseCommandForSelectedProject(ProjectItem selectedProjectItem, int commandId)
{
try
{
SelectProjectInSolutionExplorer(selectedProjectItem);
RaiseCommand((VSConstants.VSStd97CmdID) commandId);
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void SelectProjectInSolutionExplorer(ProjectItem projectItem)
{
var solutionExplorer = _dte2.ToolWindows.SolutionExplorer;
var project = _dte.Solution.GetProject(x => x.UniqueName == projectItem.UniqueName);
var item = solutionExplorer.FindHierarchyItem(project);
if (item == null)
throw new ProjectNotFoundException($"Project '{projectItem.UniqueName}' not found in SolutionExplorer.");
solutionExplorer.Parent.Activate();
item.Select(vsUISelectionType.vsUISelectionTypeSelect);
}
private void ProjectCopyBuildOutputFilesToClipBoard(ProjectItem projItem)
{
try
{
Project project = _dte.Solution.GetProject(x => x.UniqueName == projItem.UniqueName);
BuildOutputFileTypes fileTypes = _packageContext.ControlSettings.ProjectItemSettings.CopyBuildOutputFileTypesToClipboard;
if (fileTypes.IsEmpty)
{
MessageBox.Show(@"Nothing to copy: all file types unchecked.", Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string[] filePaths = project.GetBuildOutputFilePaths(fileTypes, projItem.Configuration, projItem.Platform).ToArray();
if (filePaths.Length == 0)
{
MessageBox.Show(@"Nothing copied: selected build output groups are empty.", Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
string[] existFilePaths = filePaths.Where(File.Exists).ToArray();
if (existFilePaths.Length == 0)
{
string msg = GetCopyBuildOutputFilesToClipboardActionMessage("Nothing copied. {0} wasn't found{1}", filePaths);
MessageBox.Show(msg, Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
CopyFiles(existFilePaths);
if (existFilePaths.Length == filePaths.Length)
{
string msg = GetCopyBuildOutputFilesToClipboardActionMessage("Copied {0}{1}", existFilePaths);
MessageBox.Show(msg, Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
string[] notExistFilePaths = filePaths.Except(existFilePaths).ToArray();
string copiedMsg = GetCopyBuildOutputFilesToClipboardActionMessage("Copied {0}{1}", existFilePaths);
string notFoundMsg = GetCopyBuildOutputFilesToClipboardActionMessage("{0} wasn't found{1}", notExistFilePaths);
string msg = string.Concat(copiedMsg, Environment.NewLine, Environment.NewLine, notFoundMsg);
MessageBox.Show(msg, Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
catch (Win32Exception ex)
{
string msg = string.Format("Error copying files to the Clipboard: 0x{0:X} ({1})", ex.ErrorCode, ex.Message);
ex.Trace(msg);
MessageBox.Show(msg, Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
ex.TraceUnknownException();
MessageBox.Show(ex.Message, Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void CopyFiles(string[] files)
{
var fileCollection = new StringCollection();
fileCollection.AddRange(files);
Clipboard.Clear();
Clipboard.SetFileDropList(fileCollection);
}
private string GetCopyBuildOutputFilesToClipboardActionMessage(string template, string[] filePaths)
{
const int MaxFilePathLinesInMessage = 30;
const int MaxFilePathLengthInMessage = 60;
string filesCountArg = string.Concat(filePaths.Length, " file", filePaths.Length == 1 ? string.Empty : "s");
string filesListArg;
if (filePaths.Length < MaxFilePathLinesInMessage)
{
IEnumerable<string> shortenedFilePaths = FilePathHelper.ShortenPaths(filePaths, MaxFilePathLengthInMessage);
filesListArg = string.Concat(":", Environment.NewLine, string.Join(Environment.NewLine, shortenedFilePaths));
}
else
{
filesListArg = ".";
}
string msg = string.Format(template, filesCountArg, filesListArg);
return msg;
}
private void RaiseCommand(VSConstants.VSStd97CmdID command)
{
try
{
object customIn = null;
object customOut = null;
_dte.Commands.Raise(VSConstants.GUID_VSStandardCommandSet97.ToString(), (int)command, ref customIn, ref customOut);
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void UpdateSolutionItem()
{
ViewModelHelper.UpdateSolution(_dte.Solution, _viewModel.SolutionItem);
}
private void BuildEvents_OnBuildProjectBegin(object sender, BuildProjectEventArgs e)
{
try
{
ProjectItem currentProject = e.ProjectItem;
currentProject.State = e.ProjectState;
currentProject.BuildFinishTime = null;
currentProject.BuildStartTime = e.EventTime;
_viewModel.OnBuildProjectBegin();
if (_buildContext.BuildScope == BuildScopes.BuildScopeSolution &&
(_buildContext.BuildAction == BuildActions.BuildActionBuild ||
_buildContext.BuildAction == BuildActions.BuildActionRebuildAll))
{
currentProject.BuildOrder = _viewModel.BuildProgressViewModel.CurrentQueuePosOfBuildingProject;
}
if (!_viewModel.ProjectsList.Contains(currentProject))
_viewModel.ProjectsList.Add(currentProject);
else if (_viewModel.ControlSettings.GeneralSettings.FillProjectListOnBuildBegin)
_viewModel.OnPropertyChanged(nameof(ControlViewModel.GroupedProjectsList));
_viewModel.CurrentProject = currentProject;
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void BuildEvents_OnBuildProjectDone(object sender, BuildProjectEventArgs e)
{
if (e.ProjectState == ProjectState.BuildError && _viewModel.ControlSettings.GeneralSettings.StopBuildAfterFirstError)
_buildDistributor.CancelBuild();
try
{
ProjectItem currentProject = e.ProjectItem;
currentProject.State = e.ProjectState;
currentProject.BuildFinishTime = DateTime.Now;
currentProject.UpdatePostBuildProperties(e.BuildedProjectInfo);
if (!_viewModel.ProjectsList.Contains(currentProject))
_viewModel.ProjectsList.Add(currentProject);
var buildInfo = (IBuildInfo)sender;
if (ReferenceEquals(_viewModel.CurrentProject, e.ProjectItem) && buildInfo.BuildingProjects.Any())
_viewModel.CurrentProject = buildInfo.BuildingProjects.Last();
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
_viewModel.UpdateIndicators(_buildContext);
try
{
_viewModel.OnBuildProjectDone(e.BuildedProjectInfo);
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void BuildEvents_OnBuildBegin()
{
try
{
_buildErrorIsNavigated = false;
ApplyToolWindowStateAction(_viewModel.ControlSettings.WindowSettings.WindowActionOnBuildBegin);
UpdateSolutionItem();
string message = BuildMessages.GetBuildBeginMajorMessage(_viewModel.SolutionItem, _buildContext, _viewModel.ControlSettings.BuildMessagesSettings);
OutputInStatusBar(message, true);
_viewModel.TextCurrentState = message;
_origTextCurrentState = message;
_viewModel.ImageCurrentState = BuildImages.GetBuildBeginImage(_buildContext);
_viewModel.ImageCurrentStateResult = null;
ViewModelHelper.UpdateProjects(_viewModel.SolutionItem, _dte.Solution);
_viewModel.ProjectsList.Clear();
if (_viewModel.ControlSettings.GeneralSettings.FillProjectListOnBuildBegin)
_viewModel.ProjectsList.AddRange(_viewModel.SolutionItem.AllProjects);
_viewModel.ResetIndicators(ResetIndicatorMode.ResetValue);
OnBuildBegin(_buildContext.BuildScope);
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
public void OnBuildBegin(BuildScopes? buildScope)
{
int projectsCount = -1;
switch (buildScope)
{
case BuildScopes.BuildScopeSolution:
if (_viewModel.ControlSettings.GeneralSettings.FillProjectListOnBuildBegin)
{
projectsCount = _viewModel.ProjectsList.Count;
}
else
{
try
{
Solution solution = _dte.Solution;
if (solution != null)
projectsCount = solution.GetProjects().Count;
}
catch (Exception ex)
{
ex.Trace("Unable to count projects in solution.");
}
}
break;
case BuildScopes.BuildScopeBatch:
case BuildScopes.BuildScopeProject:
break;
default:
throw new ArgumentOutOfRangeException(nameof(buildScope));
}
_viewModel.OnBuildBegin(projectsCount, _buildContext);
}
private void OutputInStatusBar(string str, bool freeze)
{
if (!_viewModel.ControlSettings.GeneralSettings.EnableStatusBarOutput)
return;
if (_dteStatusBar == null)
return;
_dteStatusBar.FreezeOutput(0);
_dteStatusBar.SetText(str);
if (freeze)
_dteStatusBar.FreezeOutput(1);
}
private void BuildEvents_OnBuildProcess()
{
try
{
var labelsSettings = _viewModel.ControlSettings.BuildMessagesSettings;
string msg = _origTextCurrentState + BuildMessages.GetBuildBeginExtraMessage(_buildContext, labelsSettings);
_viewModel.TextCurrentState = msg;
OutputInStatusBar(msg, true);
var buildingProjects = _buildContext.BuildingProjects;
for (int i = 0; i < buildingProjects.Count; i++)
buildingProjects[i].RaiseBuildElapsedTimeChanged();
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void BuildEvents_OnBuildDone()
{
try
{
var settings = _viewModel.ControlSettings;
if (_buildContext.BuildScope == BuildScopes.BuildScopeSolution)
{
foreach (var projectItem in _viewModel.ProjectsList)
{
if (projectItem.State == ProjectState.Pending)
projectItem.State = ProjectState.Skipped;
}
}
_viewModel.UpdateIndicators(_buildContext);
var message = BuildMessages.GetBuildDoneMessage(_viewModel.SolutionItem, _buildContext, settings.BuildMessagesSettings);
var buildDoneImage = BuildImages.GetBuildDoneImage(_buildContext, _viewModel.ProjectsList, out ControlTemplate stateImage);
OutputInStatusBar(message, false);
_viewModel.TextCurrentState = message;
_viewModel.ImageCurrentState = buildDoneImage;
_viewModel.ImageCurrentStateResult = stateImage;
_viewModel.CurrentProject = null;
_viewModel.OnBuildDone(_buildContext);
int errorProjectsCount = _viewModel.ProjectsList.Count(item => item.State.IsErrorState());
if (errorProjectsCount > 0 || _buildContext.BuildIsCancelled)
ApplyToolWindowStateAction(settings.WindowSettings.WindowActionOnBuildError);
else
ApplyToolWindowStateAction(settings.WindowSettings.WindowActionOnBuildSuccess);
bool navigateToBuildFailureReason = (!_buildContext.BuildedProjects.BuildWithoutErrors
&& settings.GeneralSettings.NavigateToBuildFailureReason == NavigateToBuildFailureReasonCondition.OnBuildDone);
if (navigateToBuildFailureReason && _buildContext.BuildedProjects.Any(p => p.ErrorsBox.Errors.Any(NavigateToErrorItem)))
{
_buildErrorIsNavigated = true;
}
}
catch (Exception ex)
{
ex.TraceUnknownException();
}
}
private void BuildEvents_OnBuildCancelled()
{
_viewModel.OnBuildCancelled(_buildContext);
}
private void BuildEvents_OnErrorRaised(object sender, BuildErrorRaisedEventArgs args)
{
bool buildNeedToCancel = (args.ErrorLevel == ErrorLevel.Error && _viewModel.ControlSettings.GeneralSettings.StopBuildAfterFirstError);
if (buildNeedToCancel)
_buildDistributor.CancelBuild();
bool navigateToBuildFailureReason = (!_buildErrorIsNavigated
&& args.ErrorLevel == ErrorLevel.Error
&& _viewModel.ControlSettings.GeneralSettings.NavigateToBuildFailureReason == NavigateToBuildFailureReasonCondition.OnErrorRaised);
if (navigateToBuildFailureReason && args.ProjectInfo.ErrorsBox.Errors.Any(NavigateToErrorItem))
{
_buildErrorIsNavigated = true;
}
}
private bool NavigateToErrorItem(ErrorItem errorItem)
{
if (string.IsNullOrEmpty(errorItem?.File) || string.IsNullOrEmpty(errorItem?.ProjectFile))
return false;
try
{
var projectItem = _viewModel.ProjectsList.FirstOrDefault(x => x.FullName == errorItem.ProjectFile);
if (projectItem == null)
return false;
var project = _dte.Solution.GetProject(x => x.UniqueName == projectItem.UniqueName);
if (project == null)
return false;
return project.NavigateToErrorItem(errorItem);
}
catch (Exception ex)
{
ex.Trace("Navigate to error item exception");
return true;
}
}
private void ApplyToolWindowStateAction(WindowStateAction windowStateAction)
{
switch (windowStateAction.State)
{
case WindowState.Nothing:
break;
case WindowState.Show:
_toolWindowManager.Show();
break;
case WindowState.ShowNoActivate:
_toolWindowManager.ShowNoActivate();
break;
case WindowState.Hide:
_toolWindowManager.Hide();
break;
case WindowState.Close:
_toolWindowManager.Close();
break;
default:
throw new ArgumentOutOfRangeException(nameof(windowStateAction));
}
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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 Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.Steps
{
public class PreErrorChecking : AbstractVisitorCompilerStep
{
override public void LeaveField(Field node)
{
MakeStaticIfNeeded(node);
CantBeMarkedAbstract(node);
CantBeMarkedPartial(node);
}
override public void LeaveProperty(Property node)
{
MakeStaticIfNeeded(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CheckExplicitImpl(node);
CheckModifierCombination(node);
}
override public void LeaveConstructor(Constructor node)
{
MakeStaticIfNeeded(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CantBeMarkedFinal(node);
CannotReturnValue(node);
ConstructorCannotBePolymorphic(node);
}
override public void LeaveMethod(Method node)
{
MakeStaticIfNeeded(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CheckExplicitImpl(node);
CheckModifierCombination(node);
}
override public void LeaveEvent(Event node)
{
MakeStaticIfNeeded(node);
CantBeMarkedPartial(node);
CheckModifierCombination(node);
}
override public void LeaveInterfaceDefinition(InterfaceDefinition node)
{
CantBeMarkedAbstract(node);
CantBeMarkedTransient(node);
CantBeMarkedPartialIfNested(node);
CantBeMarkedFinal(node);
CantBeMarkedStatic(node);
}
override public void LeaveCallableDefinition(CallableDefinition node)
{
MakeStaticIfNeeded(node);
CantBeMarkedAbstract(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
}
public override void LeaveStructDefinition(StructDefinition node)
{
CantBeMarkedAbstract(node);
CantBeMarkedFinal(node);
CantBeMarkedStatic(node);
CantBeMarkedPartial(node);
}
public override void LeaveEnumDefinition(EnumDefinition node)
{
CantBeMarkedAbstract(node);
CantBeMarkedPartialIfNested(node);
CantBeMarkedFinal(node);
CantBeMarkedStatic(node);
}
override public void LeaveClassDefinition(ClassDefinition node)
{
CheckModifierCombination(node);
CantBeMarkedPartialIfNested(node);
if (node.IsStatic)
node.Modifiers |= TypeMemberModifiers.Abstract | TypeMemberModifiers.Final;
}
override public void LeaveTryStatement(TryStatement node)
{
if (node.EnsureBlock == null && node.FailureBlock == null && node.ExceptionHandlers.Count == 0)
{
Error(CompilerErrorFactory.InvalidTryStatement(node));
}
}
override public void LeaveBinaryExpression(BinaryExpression node)
{
if (BinaryOperatorType.Assign == node.Operator
&& (node.Right.NodeType != NodeType.TryCastExpression)
&& (IsTopLevelOfConditional(node)))
{
Warnings.Add(CompilerWarningFactory.EqualsInsteadOfAssign(node));
}
}
bool IsTopLevelOfConditional(Node child)
{
Node parent = child.ParentNode;
return (parent.NodeType == NodeType.IfStatement
|| parent.NodeType == NodeType.UnlessStatement
|| parent.NodeType == NodeType.ConditionalExpression
|| parent.NodeType == NodeType.StatementModifier
|| parent.NodeType == NodeType.ReturnStatement
|| parent.NodeType == NodeType.YieldStatement);
}
override public void LeaveDestructor(Destructor node)
{
if (node.Modifiers != TypeMemberModifiers.None)
{
Error(CompilerErrorFactory.InvalidDestructorModifier(node));
}
if (node.Parameters.Count != 0)
{
Error(CompilerErrorFactory.CantHaveDestructorParameters(node));
}
CannotReturnValue(node);
}
void ConstructorCannotBePolymorphic(Constructor node)
{
if (node.IsAbstract || node.IsOverride || node.IsVirtual)
{
Error(CompilerErrorFactory.ConstructorCantBePolymorphic(node, EntityFor(node)));
}
}
private void CannotReturnValue(Method node)
{
if (node.ReturnType != null)
{
Error(CompilerErrorFactory.CannotReturnValue(node));
}
}
void CantBeMarkedAbstract(TypeMember member)
{
if (member.IsAbstract)
{
Error(CompilerErrorFactory.CantBeMarkedAbstract(member));
}
}
void CantBeMarkedFinal(TypeMember member)
{
if (member.IsFinal)
{
Error(CompilerErrorFactory.CantBeMarkedFinal(member));
}
}
void CantBeMarkedTransient(TypeMember member)
{
if (member.HasTransientModifier)
Error(CompilerErrorFactory.CantBeMarkedTransient(member));
}
void MakeStaticIfNeeded(TypeMember node)
{
var declaringType = node.DeclaringType;
if (declaringType != null && declaringType.IsStatic)
{
if(node.IsStatic)
Warnings.Add(CompilerWarningFactory.StaticClassMemberRedundantlyMarkedStatic(node, declaringType.Name, node.Name));
node.Modifiers |= TypeMemberModifiers.Static;
}
}
void CheckExplicitImpl(IExplicitMember member)
{
ExplicitMemberInfo ei = member.ExplicitInfo;
if (null == ei)
{
return;
}
TypeMember node = (TypeMember)member;
if (TypeMemberModifiers.None != node.Modifiers)
{
Error(
CompilerErrorFactory.ExplicitImplMustNotHaveModifiers(
node,
ei.InterfaceType.Name,
node.Name));
}
}
void CheckModifierCombination(TypeMember member)
{
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Abstract);
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Virtual);
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Override);
InvalidCombination(member, TypeMemberModifiers.Abstract, TypeMemberModifiers.Final);
if (member.NodeType != NodeType.Field)
{
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Final);
}
}
void InvalidCombination(TypeMember member, TypeMemberModifiers mod1, TypeMemberModifiers mod2)
{
if (!member.IsModifierSet(mod1) || !member.IsModifierSet(mod2)) return;
Error(
CompilerErrorFactory.InvalidCombinationOfModifiers(
member,
EntityFor(member),
string.Format("{0}, {1}", mod1.ToString().ToLower(), mod2.ToString().ToLower())));
}
private IEntity EntityFor(TypeMember member)
{
return My<InternalTypeSystemProvider>.Instance.EntityFor(member);
}
private IMethod EntityFor(Constructor node)
{
return (IMethod)EntityFor((TypeMember)node);
}
void CantBeMarkedPartialIfNested(TypeDefinition type)
{
if (type.IsNested)
CantBeMarkedPartial(type);
}
void CantBeMarkedPartial(TypeMember member)
{
if (member.IsPartial)
Error(CompilerErrorFactory.CantBeMarkedPartial(member));
}
void CantBeMarkedStatic(TypeMember member)
{
if (member.IsStatic)
Error(CompilerErrorFactory.CantBeMarkedStatic(member));
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Runtime.Serialization;
namespace StrumpyShaderEditor
{
[DataContract(Namespace = "http://strumpy.net/ShaderEditor/")]
public abstract class Node
{
[DataMember]
public int NodeID { get; private set; }
[DataMember]
public EditorRect Position { get; private set; }
[DataMember]
private EditorString _comment;
public SubGraph Owner{ get; set; }
private EditorString Comment {
get { return _comment ?? (_comment = ""); }
}
public Rect NodePositionInGraph
{
get{
var position = Position.Value;
position.x += Owner.DrawOffset.X;
position.y += Owner.DrawOffset.Y;
return position;
}
set{
var position = value;
position.x -= Owner.DrawOffset.X;
position.y -= Owner.DrawOffset.Y;
Position = position;
}
}
//Not serialized as we generate this each draw tick
public NodeState CurrentState;// { private get; set; } // Texel - Uniform access to tint node button
private List<String> _errorMessages;
public List<String> ErrorMessages // Texel Similarly with this, I wanted to display the error message elsewhere aswell
{
get { return _errorMessages ?? (_errorMessages = new List<string>()); }
}
protected Node ()
{
Position = new EditorRect (10, 40, 30, 30);
}
protected abstract IEnumerable<OutputChannel> GetOutputChannels ();
public abstract IEnumerable<InputChannel> GetInputChannels ();
public abstract void Initialize ();
public override int GetHashCode ()
{
int nameHash = NodeTypeName == null ? 0 : NodeTypeName.GetHashCode ();
return NodeID ^ nameHash;
}
public void AddErrors( IEnumerable<string> errors )
{
ErrorMessages.AddRange( errors );
}
public void ClearErrors()
{
ErrorMessages.Clear();
}
public virtual bool NeedsTime()
{
return false;
}
public virtual bool NeedsCosTime()
{
return false;
}
public virtual bool NeedsSinTime()
{
return false;
}
public InputChannel GetInputChannel (uint channelId)
{
return GetInputChannels ().First (x => x.ChannelId == channelId);
}
public OutputChannel GetOutputChannel (uint channelId)
{
return GetOutputChannels ().First (x => x.ChannelId == channelId);
}
protected bool IsInputChannelConnected (uint channelId)
{
return GetInputChannel (channelId).IncomingConnection != null;
}
public void AssertInputChannelExists (uint channelId)
{
if (GetInputChannel (channelId) == null) {
Debug.LogError ("Channel: " + channelId + " does not exist on node " + UniqueNodeIdentifier);
}
}
public bool IsOutputChannelConnected (uint channelId)
{
foreach (var node in Owner.Nodes) {
foreach (var inChannel in node.GetInputChannels ()) {
if (inChannel.IncomingConnection != null && inChannel.IncomingConnection.NodeIdentifier == UniqueNodeIdentifier && inChannel.IncomingConnection.ChannelId == channelId) {
return true;
}
}
}
return false;
}
public void AssertOutputChannelExists (uint channelId)
{
if (GetOutputChannel (channelId) == null) {
Debug.LogError ("Channel: " + channelId + " does not exist on node " + UniqueNodeIdentifier);
}
}
public virtual IEnumerable<string> IsValid ( SubGraphType graphType )
{
return new List<string> ();
}
public void AddedToGraph (int newNodeID)
{
NodeID = newNodeID;
}
public abstract string NodeTypeName { get; }
public virtual string DisplayName {
get { return NodeTypeName; }
}
public string UniqueNodeIdentifier {
get { return NodeTypeName.RemoveWhiteSpace() + NodeID; }
}
public void DrawCommentField ()
{
GUILayout.Label ("Comment");
// Instead of NormalGUILayout for copy/paste etc
_comment = GUILayout.TextArea (Comment); // Texel Modified to text field, so it expands as needed.
}
public virtual void DrawProperties ()
{
//GUILayout.Label (UniqueNodeIdentifier);
}
public abstract string GetExpression (uint channelId);
public virtual bool RequiresInternalData {
get { return false; }
}
public virtual bool RequiresGrabPass {
get { return false; }
}
public virtual bool RequiresSceneDepth {
get { return false; }
}
public void DeltaMove (Vector2 delta)
{
Position.X += delta.x;
Position.Y += delta.y;
}
public bool ButtonAt( Vector2 location )
{
foreach( var channel in GetInputChannels() )
{
Rect channelRect = NodePositionInGraph;
channelRect.x += channel.Position.x;
channelRect.y += channel.Position.y;
channelRect.width = channel.Position.width;
channelRect.height = channel.Position.height;
if( channelRect.Contains( location ) )
{
return true;
}
}
foreach( var channel in GetOutputChannels() )
{
Rect channelRect = NodePositionInGraph;
channelRect.x += channel.Position.x;
channelRect.y += channel.Position.y;
channelRect.width = channel.Position.width;
channelRect.height = channel.Position.height;
if( channelRect.Contains( location ) )
{
return true;
}
}
return false;
}
// Texel : Shorthand for the editor window style
private static GUIStyle WindowStyle {
get { return EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).window; }
}
public void Draw ( NodeEditor editor, bool showComments, bool selected, Vector2 drawOffset )
{
GUI.skin.box.alignment = TextAnchor.UpperCenter;
const float nodeDrawWidth = 100;
const float headerHeight = 18;
const float nodeDrawHeightPerChannel = 21;
//Figure out node width:
Rect drawPos = Position;
int inChannelNum = GetInputChannels ().Count ();
int outChannelNum = GetOutputChannels ().Count ();
if (inChannelNum > 0 && outChannelNum > 0) {
drawPos.width = nodeDrawWidth * 1.36f;
} else {
drawPos.width = nodeDrawWidth;
}
int maxChannels = inChannelNum > outChannelNum ? inChannelNum : outChannelNum;
drawPos.height = headerHeight + (maxChannels * nodeDrawHeightPerChannel);
var windowName = new GUIContent (DisplayName);
float minWidth;
float maxWidth;
//GUI.skin.window.CalcMinMaxWidth (windowName, out minWidth, out maxWidth);
WindowStyle.CalcMinMaxWidth(windowName, out minWidth, out maxWidth); // Texel - Window style changes
windowName.text = windowName.text.Trim("~"[0]); // Texel - Trim padding character
drawPos.width = maxWidth > drawPos.width ? maxWidth : drawPos.width;
Position = drawPos;
var drawPosOffset = drawPos;
drawPosOffset.x += drawOffset.x;
drawPosOffset.y += drawOffset.y;
float boxOffset = 0f;
// For calculating the box vertical offset
// This area is potentially shared by the comments, so comments would be drawn below errors.
// Also made excessively large, to fail more elegantly.
switch (CurrentState) {
case (NodeState.Valid):
GUI.color = Color.white;
break;
case (NodeState.NotConnected):
GUI.color = new Color (0.8f, 0.8f, 1f);
break;
case (NodeState.CircularReferenceInGraph):
GUI.color = new Color (0.8f, 0.8f, 0f);
break;
case (NodeState.Error):
{
GUI.color = Color.red;
//GUILayout.BeginArea(new Rect(drawPos.x, drawPos.yMax, 300, 200));
foreach (var error in ErrorMessages) {
var content = new GUIContent (error);
float wMin, wMax;
GUI.skin.box.CalcMinMaxWidth (content, out wMin, out wMax);
var height = GUI.skin.box.CalcHeight (content, wMax);
GUI.Box (new Rect (drawPosOffset.x, drawPosOffset.yMax + boxOffset, wMax, height), content);
boxOffset += height;
}
break;
}
}
if( selected )
{
GUI.backgroundColor = Color.Lerp(GUI.backgroundColor,Color.green,0.5f); // Texel - Blend, rather then hard set
}
// Texel - Special case, for nodes which don't have any inputs
if (maxChannels > 0)
GUI.Box (drawPosOffset, windowName, WindowStyle);
else {
if (selected)
GUI.Box(drawPosOffset,GUIContent.none,WindowStyle);
GUIStyle empty = GUIStyle.none;
empty.clipping = TextClipping.Overflow;
GUI.Box (drawPosOffset, windowName, empty);
}
//Do custom layout to stop unity throwing errors for some strange reason
// Texel - Seperated draw size from actual size, using blank style for real buttons
var nodeIoSize = new Vector2( 15f, nodeDrawHeightPerChannel * (2f / 3f) );
var nodeIoDrawSize = new Vector2( 7f, 7f );
var currentDrawPosition = new Vector2( drawPosOffset.x, drawPosOffset.y );
currentDrawPosition.y += headerHeight;
TextAnchor oldTextAnchor = GUI.skin.label.alignment;
TextClipping oldTextClipping = GUI.skin.label.clipping;
bool oldWordWrap = GUI.skin.label.wordWrap;
GUI.skin.label.alignment = TextAnchor.UpperLeft;
GUI.skin.label.clipping = TextClipping.Overflow;
GUI.skin.label.wordWrap = false;
foreach (var channel in GetOutputChannels ())
{
var absoluteIOVisualPos =
new Rect(
currentDrawPosition.x- ( nodeIoDrawSize.x * 0.5f),
currentDrawPosition.y + nodeIoDrawSize.y/2 + 2,
nodeIoDrawSize.x,
nodeIoDrawSize.y );
var absoluteIODrawPos =
new Rect(
currentDrawPosition.x- ( nodeIoSize.x * 0.5f),
currentDrawPosition.y + 2,
nodeIoSize.x,
nodeIoSize.y );
GUI.Box( absoluteIOVisualPos, "", GUI.skin.box);
if ( GUI.Button( absoluteIODrawPos, "", GUIStyle.none) )
{
editor.SelectedOutputChannel = new OutputChannelReference( UniqueNodeIdentifier, channel.ChannelId);
}
var relativeIODrawPos = absoluteIODrawPos;
relativeIODrawPos.x -= drawPosOffset.x;
relativeIODrawPos.y -= drawPosOffset.y;
channel.Position = relativeIODrawPos;
var labelDrawPos = new Rect( currentDrawPosition.x + ( nodeIoSize.x * 0.5f), currentDrawPosition.y, drawPosOffset.width / 2f, nodeDrawHeightPerChannel );
GUI.Label(labelDrawPos, channel.DisplayName);
currentDrawPosition.y += nodeDrawHeightPerChannel;
}
//Do the other side now...
currentDrawPosition = new Vector2( drawPosOffset.x + (drawPosOffset.width / 2f), drawPosOffset.y );
currentDrawPosition.y += headerHeight;
GUI.skin.label.alignment = TextAnchor.UpperRight;
GUI.skin.label.clipping = TextClipping.Overflow;
GUI.skin.label.wordWrap = false;
foreach (var channel in GetInputChannels ())
{
var absoluteIOVisualPos =
new Rect(
drawPosOffset.xMax- ( nodeIoSize.x * 0.5f) + 3,
currentDrawPosition.y + nodeIoDrawSize.y/2 + 2,
nodeIoDrawSize.x,
nodeIoDrawSize.y );
var absoluteIODrawPos =
new Rect(
drawPosOffset.xMax- ( nodeIoSize.x * 0.5f),
currentDrawPosition.y + 2,
nodeIoSize.x,
nodeIoSize.y );
GUI.Box( absoluteIOVisualPos, "", GUI.skin.box);
if ( GUI.Button( absoluteIODrawPos, "" , GUIStyle.none) )
{
editor.SelectedInputChannel = new InputChannelReference( UniqueNodeIdentifier, channel.ChannelId );
}
var relativeIODrawPos = absoluteIODrawPos;
relativeIODrawPos.x -= drawPosOffset.x;
relativeIODrawPos.y -= drawPosOffset.y;
channel.Position = relativeIODrawPos;
var labelDrawPos = new Rect( currentDrawPosition.x, currentDrawPosition.y, (drawPosOffset.width / 2f) - ( nodeIoSize.x * 0.5f), nodeDrawHeightPerChannel );
GUI.Label(labelDrawPos, channel.DisplayName);
currentDrawPosition.y += nodeDrawHeightPerChannel;
}
GUI.color = Color.white;
GUI.skin.label.alignment = oldTextAnchor;
GUI.skin.label.clipping = oldTextClipping;
GUI.skin.label.wordWrap = oldWordWrap;
if ( showComments && Comment != "") {
// Texel - Comment Field
var oldColor = GUI.color;
GUI.color = Vector4.Scale (GUI.color, new Vector4 (0.95f, 0.95f, 0.95f, 0.7f));
var oldAnchor = GUI.skin.box.alignment;
GUI.skin.box.alignment = TextAnchor.UpperLeft;
var oldState = GUI.skin.box.normal;
// Draw the text opaque
var textColor = GUI.skin.box.normal.textColor;
textColor.a = 1f;
GUI.skin.box.normal.textColor = textColor;
//var oldWrap = GUI.skin.box.wordWrap;
GUI.skin.box.wordWrap = true;
var content = new GUIContent ( Comment);
float wMin, wMax;
GUI.skin.box.CalcMinMaxWidth (content, out wMin, out wMax);
var aWidth = Mathf.Min (drawPosOffset.width * 1.5f, wMax);
var height = GUI.skin.box.CalcHeight (content, aWidth);
GUI.Box (new Rect (drawPosOffset.x, drawPosOffset.yMax + boxOffset, aWidth, height), content);
GUI.skin.box.alignment = oldAnchor;
GUI.skin.box.normal = oldState;
GUI.skin.box.normal.textColor = textColor;
GUI.color = oldColor;
}
GUI.backgroundColor = Color.white;
}
}
}
| |
namespace PokerTell.LiveTracker.ViewModels
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;
using System.Xml.Linq;
using Infrastructure.Interfaces.LiveTracker;
using Microsoft.Practices.Composite.Events;
using PokerTell.Infrastructure.Events;
using PokerTell.LiveTracker.Events;
using PokerTell.LiveTracker.Interfaces;
using PokerTell.LiveTracker.Properties;
using Tools.FunctionalCSharp;
using Tools.Interfaces;
using Tools.IO;
using Tools.WPF;
using Tools.WPF.ViewModels;
using Tools.Xml;
public class LiveTrackerSettingsViewModel : NotifyPropertyChanged, ILiveTrackerSettingsViewModel
{
const string AutoTrackElement = "AutoTrack";
const string HandHistoryFilesPathsElement = "HandHistoryFilesPaths";
const string LiveTrackerSettings = "LiveTrackerSettings";
const string ShowHoleCardsDurationElement = "ShowHoleCardsDuration";
const string ShowLiveStatsWindowOnStartupElement = "ShowLiveStatsWindowOnStartup";
const string ShowMyStatisticsElement = "ShowMyStatistics";
const string ShowTableOverlayElement = "ShowTableOverlay";
const string GameHistoryIsPoppedInElement = "GameHistoryIsPoppedIn";
readonly IPokerRoomSettingsDetector _autoDetector;
readonly IHandHistoryFolderAutoDetectResultsViewModel _autoDetectResultsViewModel;
readonly IHandHistoryFolderAutoDetectResultsWindowManager _autoDetectResultsWindow;
readonly IEventAggregator _eventAggregator;
readonly IPokerRoomInfoLocator _pokerRoomInfoLocator;
readonly ILiveTrackerSettingsXDocumentHandler _xDocumentHandler;
ICommand _addHandHistoryPathCommand;
ICommand _autoDetectHandHistoryFoldersCommand;
bool _autoTrack;
ICommand _browseCommand;
IList<string> _handHistoryFilesPaths;
string _handHistoryPathToBeAdded;
ICommand _removeSelectedHandHistoryPathCommand;
ICommand _saveSettingsCommand;
int _showHoleCardsDuration;
bool _showLiveStatsWindowOnStartup;
bool _showMyStatistics;
bool _showTableOverlay;
readonly ILayoutAutoConfigurator _layoutAutoConfigurator;
public LiveTrackerSettingsViewModel(
IEventAggregator eventAggregator,
ILiveTrackerSettingsXDocumentHandler xDocumentHandler,
IPokerRoomSettingsDetector autoDetector,
IHandHistoryFolderAutoDetectResultsViewModel autoDetectResultsViewModel,
IHandHistoryFolderAutoDetectResultsWindowManager autoDetectResultsWindow,
ILayoutAutoConfigurator layoutAutoConfigurator,
IPokerRoomInfoLocator pokerRoomInfoLocator)
{
_eventAggregator = eventAggregator;
_xDocumentHandler = xDocumentHandler;
_autoDetector = autoDetector;
_autoDetectResultsViewModel = autoDetectResultsViewModel;
_autoDetectResultsWindow = autoDetectResultsWindow;
_layoutAutoConfigurator = layoutAutoConfigurator;
_pokerRoomInfoLocator = pokerRoomInfoLocator;
ShowHoleCardsDurations = new List<int> { 0, 3, 5, 10, 15, 20 };
}
public ICommand AddHandHistoryPathCommand
{
get
{
return _addHandHistoryPathCommand ?? (_addHandHistoryPathCommand = new SimpleCommand
{
ExecuteDelegate = arg => {
if (HandHistoryFilesPaths.Contains(HandHistoryPathToBeAdded))
{
_eventAggregator
.GetEvent<UserMessageEvent>()
.Publish(new UserMessageEventArgs(UserMessageTypes.Warning, Resources.Warning_HandHistoryFolderIsTrackedAlready));
}
else
HandHistoryFilesPaths.Add(HandHistoryPathToBeAdded.Trim().TrimEnd('\\'));
HandHistoryPathToBeAdded = null;
},
CanExecuteDelegate = arg => HandHistoryPathToBeAdded.IsExistingDirectory()
});
}
}
public ICommand AutoDetectHandHistoryFoldersCommand
{
get
{
return _autoDetectHandHistoryFoldersCommand ?? (_autoDetectHandHistoryFoldersCommand = new SimpleCommand
{
ExecuteDelegate = arg => {
DetectAndAddHandHistoryFolders();
_autoDetectResultsWindow.DataContext = _autoDetectResultsViewModel.InitializeWith(_autoDetector);
_autoDetectResultsWindow.ShowDialog();
}
});
}
}
public bool AutoTrack
{
get { return _autoTrack; }
set
{
_autoTrack = value;
RaisePropertyChanged(() => AutoTrack);
}
}
public ICommand BrowseCommand
{
get
{
return _browseCommand ?? (_browseCommand = new SimpleCommand
{
ExecuteDelegate = BrowseForDirectory
});
}
}
public IList<string> HandHistoryFilesPaths
{
get { return _handHistoryFilesPaths; }
set
{
_handHistoryFilesPaths = value;
RaisePropertyChanged(() => HandHistoryFilesPaths);
}
}
public string HandHistoryPathToBeAdded
{
get { return _handHistoryPathToBeAdded; }
set
{
_handHistoryPathToBeAdded = value;
RaisePropertyChanged(() => HandHistoryPathToBeAdded);
}
}
public ICommand RemoveSelectedHandHistoryPathCommand
{
get
{
return _removeSelectedHandHistoryPathCommand ?? (_removeSelectedHandHistoryPathCommand = new SimpleCommand
{
ExecuteDelegate = arg => {
HandHistoryFilesPaths.Remove(SelectedHandHistoryFilesPath);
SelectedHandHistoryFilesPath = null;
},
CanExecuteDelegate = arg => SelectedHandHistoryFilesPath != null
});
}
}
public ICommand SaveSettingsCommand
{
get
{
return _saveSettingsCommand ?? (_saveSettingsCommand = new SimpleCommand
{
ExecuteDelegate = arg => SaveSettings()
});
}
}
public ILiveTrackerSettingsViewModel SaveSettings()
{
var xDoc = CreateXDocumentFor(this);
_xDocumentHandler.Save(xDoc);
_eventAggregator
.GetEvent<LiveTrackerSettingsChangedEvent>()
.Publish(this);
return this;
}
public string SelectedHandHistoryFilesPath { get; set; }
public int ShowHoleCardsDuration
{
get { return _showHoleCardsDuration; }
set
{
_showHoleCardsDuration = value;
RaisePropertyChanged(() => ShowHoleCardsDuration);
}
}
ICommand _detectPreferredSeatsCommand;
public ICommand DetectPreferredSeatsCommand
{
get
{
return _detectPreferredSeatsCommand ?? (_detectPreferredSeatsCommand = new SimpleCommand {
ExecuteDelegate = arg => {
var pokerRoomsWhosePreferredSeatsWereConfigured = DetectAndSavePreferredSeats();
if (pokerRoomsWhosePreferredSeatsWereConfigured.Count() > 0)
PublishUserInfoAbout(pokerRoomsWhosePreferredSeatsWereConfigured);
else
PublishUserWarningBecauseNoneCouldBeConfigured();
}
});
}
}
void PublishUserWarningBecauseNoneCouldBeConfigured()
{
var msg = Resources.Warning_NoPreferredSeatsCouldBeConfigured;
_eventAggregator
.GetEvent<UserMessageEvent>()
.Publish(new UserMessageEventArgs(UserMessageTypes.Warning, msg));
}
void PublishUserInfoAbout(IEnumerable<string> roomsWhosePreferredSeatsWereConfigured)
{
var sb =
new StringBuilder(Resources.Info_PreferredSeatsHaveBeenConfigured)
.AppendLine()
.AppendLine();
roomsWhosePreferredSeatsWereConfigured.ForEach(room => sb.AppendLine(room));
_eventAggregator
.GetEvent<UserMessageEvent>()
.Publish(new UserMessageEventArgs(UserMessageTypes.Info, sb.ToString()));
}
public IEnumerable<int> ShowHoleCardsDurations { get; protected set; }
public bool ShowLiveStatsWindowOnStartup
{
get { return _showLiveStatsWindowOnStartup; }
set
{
_showLiveStatsWindowOnStartup = value;
RaisePropertyChanged(() => ShowLiveStatsWindowOnStartup);
}
}
public bool ShowMyStatistics
{
get { return _showMyStatistics; }
set
{
_showMyStatistics = value;
RaisePropertyChanged(() => ShowMyStatistics);
}
}
public bool ShowTableOverlay
{
get { return _showTableOverlay; }
set
{
_showTableOverlay = value;
RaisePropertyChanged(() => ShowTableOverlay);
}
}
public bool GameHistoryIsPoppedIn { get; set; }
public static XDocument CreateXDocumentFor(ILiveTrackerSettingsViewModel lts)
{
return
new XDocument(
new XElement(LiveTrackerSettings,
new XElement(AutoTrackElement, lts.AutoTrack),
new XElement(ShowHoleCardsDurationElement, lts.ShowHoleCardsDuration),
new XElement(ShowLiveStatsWindowOnStartupElement, lts.ShowLiveStatsWindowOnStartup),
new XElement(ShowTableOverlayElement, lts.ShowTableOverlay),
new XElement(ShowMyStatisticsElement, lts.ShowMyStatistics),
new XElement(GameHistoryIsPoppedInElement, lts.GameHistoryIsPoppedIn),
Utils.XElementForCollection(HandHistoryFilesPathsElement, lts.HandHistoryFilesPaths)));
}
public ILiveTrackerSettingsViewModel DetectAndAddHandHistoryFolders()
{
_autoDetector
.InitializeWith(_pokerRoomInfoLocator.SupportedPokerRoomInfos)
.DetectHandHistoryFolders();
_autoDetector.PokerRoomsWithDetectedHandHistoryDirectories.ForEach(pair => {
if (! HandHistoryFilesPaths.Contains(pair.Second))
HandHistoryFilesPaths.Add(pair.Second);
});
return this;
}
public IEnumerable<string> DetectAndSavePreferredSeats()
{
_autoDetector
.InitializeWith(_pokerRoomInfoLocator.SupportedPokerRoomInfos)
.DetectPreferredSeats();
var pokerRoomsWithDetectedPreferredSeats = _autoDetector
.PokerRoomsWithDetectedPreferredSeats;
pokerRoomsWithDetectedPreferredSeats.ForEach(room => _layoutAutoConfigurator.ConfigurePreferredSeats(room.First, room.Second));
return pokerRoomsWithDetectedPreferredSeats.Select(room => room.First);
}
public ILiveTrackerSettingsViewModel LoadSettings()
{
var xDoc = _xDocumentHandler.Load();
if (xDoc == null)
{
SetPropertiesToDefault();
return this;
}
var xml = xDoc.Element(LiveTrackerSettings);
if (xml == null)
{
SetPropertiesToDefault();
return this;
}
AutoTrack = Utils.GetBoolFrom(xml.Element(AutoTrackElement), true);
ShowLiveStatsWindowOnStartup = Utils.GetBoolFrom(xml.Element(ShowLiveStatsWindowOnStartupElement), true);
ShowTableOverlay = Utils.GetBoolFrom(xml.Element(ShowTableOverlayElement), true);
ShowMyStatistics = Utils.GetBoolFrom(xml.Element(ShowMyStatisticsElement), false);
ShowHoleCardsDuration = Utils.GetIntFrom(xml.Element(ShowHoleCardsDurationElement), 5);
GameHistoryIsPoppedIn = Utils.GetBoolFrom(xml.Element(GameHistoryIsPoppedInElement), true);
HandHistoryFilesPaths = new ObservableCollection<string>(
Utils.GetStringsFrom(xml.Element(HandHistoryFilesPathsElement), new List<string>())
.Where(path => new DirectoryInfo(path).Exists));
return this;
}
void BrowseForDirectory(object arg)
{
using (var browserDialog = new FolderBrowserDialog
{
SelectedPath = HandHistoryPathToBeAdded,
ShowNewFolderButton = false
})
{
browserDialog.ShowDialog();
HandHistoryPathToBeAdded = browserDialog.SelectedPath;
}
}
void SetPropertiesToDefault()
{
AutoTrack = true;
ShowLiveStatsWindowOnStartup = true;
ShowTableOverlay = true;
ShowMyStatistics = false;
ShowHoleCardsDuration = 5;
GameHistoryIsPoppedIn = true;
HandHistoryFilesPaths = new ObservableCollection<string>();
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Owin.Infrastructure
{
[System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
internal struct HeaderSegment : IEquatable<HeaderSegment>
{
private readonly StringSegment _formatting;
private readonly StringSegment _data;
// <summary>
// Initializes a new instance of the <see cref="T:System.Object"/> class.
// </summary>
public HeaderSegment(StringSegment formatting, StringSegment data)
{
_formatting = formatting;
_data = data;
}
public StringSegment Formatting
{
get { return _formatting; }
}
public StringSegment Data
{
get { return _data; }
}
#region Equality members
public bool Equals(HeaderSegment other)
{
return _formatting.Equals(other._formatting) && _data.Equals(other._data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is HeaderSegment && Equals((HeaderSegment)obj);
}
public override int GetHashCode()
{
unchecked
{
return (_formatting.GetHashCode() * 397) ^ _data.GetHashCode();
}
}
public static bool operator ==(HeaderSegment left, HeaderSegment right)
{
return left.Equals(right);
}
public static bool operator !=(HeaderSegment left, HeaderSegment right)
{
return !left.Equals(right);
}
#endregion
}
[System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
internal struct HeaderSegmentCollection : IEnumerable<HeaderSegment>, IEquatable<HeaderSegmentCollection>
{
private readonly string[] _headers;
public HeaderSegmentCollection(string[] headers)
{
_headers = headers;
}
#region Equality members
public bool Equals(HeaderSegmentCollection other)
{
return Equals(_headers, other._headers);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is HeaderSegmentCollection && Equals((HeaderSegmentCollection)obj);
}
public override int GetHashCode()
{
return (_headers != null ? _headers.GetHashCode() : 0);
}
public static bool operator ==(HeaderSegmentCollection left, HeaderSegmentCollection right)
{
return left.Equals(right);
}
public static bool operator !=(HeaderSegmentCollection left, HeaderSegmentCollection right)
{
return !left.Equals(right);
}
#endregion
public Enumerator GetEnumerator()
{
return new Enumerator(_headers);
}
IEnumerator<HeaderSegment> IEnumerable<HeaderSegment>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal struct Enumerator : IEnumerator<HeaderSegment>
{
private readonly string[] _headers;
private int _index;
private string _header;
private int _headerLength;
private int _offset;
private int _leadingStart;
private int _leadingEnd;
private int _valueStart;
private int _valueEnd;
private int _trailingStart;
private Mode _mode;
private static readonly string[] NoHeaders = new string[0];
public Enumerator(string[] headers)
{
_headers = headers ?? NoHeaders;
_header = string.Empty;
_headerLength = -1;
_index = -1;
_offset = -1;
_leadingStart = -1;
_leadingEnd = -1;
_valueStart = -1;
_valueEnd = -1;
_trailingStart = -1;
_mode = Mode.Leading;
}
private enum Mode
{
Leading,
Value,
ValueQuoted,
Trailing,
Produce,
}
private enum Attr
{
Value,
Quote,
Delimiter,
Whitespace
}
public HeaderSegment Current
{
get
{
return new HeaderSegment(
new StringSegment(_header, _leadingStart, _leadingEnd - _leadingStart),
new StringSegment(_header, _valueStart, _valueEnd - _valueStart));
}
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
public bool MoveNext()
{
while (true)
{
if (_mode == Mode.Produce)
{
_leadingStart = _trailingStart;
_leadingEnd = -1;
_valueStart = -1;
_valueEnd = -1;
_trailingStart = -1;
if (_offset == _headerLength &&
_leadingStart != -1 &&
_leadingStart != _offset)
{
// Also produce trailing whitespace
_leadingEnd = _offset;
return true;
}
_mode = Mode.Leading;
}
// if end of a string
if (_offset == _headerLength)
{
++_index;
_offset = -1;
_leadingStart = 0;
_leadingEnd = -1;
_valueStart = -1;
_valueEnd = -1;
_trailingStart = -1;
// if that was the last string
if (_index == _headers.Length)
{
// no more move nexts
return false;
}
// grab the next string
_header = _headers[_index] ?? string.Empty;
_headerLength = _header.Length;
}
while (true)
{
++_offset;
char ch = _offset == _headerLength ? (char)0 : _header[_offset];
// todo - array of attrs
Attr attr = char.IsWhiteSpace(ch) ? Attr.Whitespace : ch == '\"' ? Attr.Quote : (ch == ',' || ch == (char)0) ? Attr.Delimiter : Attr.Value;
switch (_mode)
{
case Mode.Leading:
switch (attr)
{
case Attr.Delimiter:
_leadingEnd = _offset;
_mode = Mode.Produce;
break;
case Attr.Quote:
_leadingEnd = _offset;
_valueStart = _offset;
_mode = Mode.ValueQuoted;
break;
case Attr.Value:
_leadingEnd = _offset;
_valueStart = _offset;
_mode = Mode.Value;
break;
case Attr.Whitespace:
// more
break;
}
break;
case Mode.Value:
switch (attr)
{
case Attr.Quote:
_mode = Mode.ValueQuoted;
break;
case Attr.Delimiter:
_valueEnd = _offset;
_trailingStart = _offset;
_mode = Mode.Produce;
break;
case Attr.Value:
// more
break;
case Attr.Whitespace:
_valueEnd = _offset;
_trailingStart = _offset;
_mode = Mode.Trailing;
break;
}
break;
case Mode.ValueQuoted:
switch (attr)
{
case Attr.Quote:
_mode = Mode.Value;
break;
case Attr.Delimiter:
if (ch == (char)0)
{
_valueEnd = _offset;
_trailingStart = _offset;
_mode = Mode.Produce;
}
break;
case Attr.Value:
case Attr.Whitespace:
// more
break;
}
break;
case Mode.Trailing:
switch (attr)
{
case Attr.Delimiter:
_mode = Mode.Produce;
break;
case Attr.Quote:
// back into value
_trailingStart = -1;
_valueEnd = -1;
_mode = Mode.ValueQuoted;
break;
case Attr.Value:
// back into value
_trailingStart = -1;
_valueEnd = -1;
_mode = Mode.Value;
break;
case Attr.Whitespace:
// more
break;
}
break;
}
if (_mode == Mode.Produce)
{
return true;
}
}
}
}
public void Reset()
{
_index = 0;
_offset = 0;
_leadingStart = 0;
_leadingEnd = 0;
_valueStart = 0;
_valueEnd = 0;
}
}
}
[System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
internal struct StringSegment : IEquatable<StringSegment>
{
private readonly string _buffer;
private readonly int _offset;
private readonly int _count;
// <summary>
// Initializes a new instance of the <see cref="T:System.Object"/> class.
// </summary>
public StringSegment(string buffer, int offset, int count)
{
_buffer = buffer;
_offset = offset;
_count = count;
}
public string Buffer
{
get { return _buffer; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
public string Value
{
get { return _offset == -1 ? null : _buffer.Substring(_offset, _count); }
}
public bool HasValue
{
get { return _offset != -1 && _count != 0 && _buffer != null; }
}
#region Equality members
public bool Equals(StringSegment other)
{
return string.Equals(_buffer, other._buffer) && _offset == other._offset && _count == other._count;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is StringSegment && Equals((StringSegment)obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (_buffer != null ? _buffer.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ _offset;
hashCode = (hashCode * 397) ^ _count;
return hashCode;
}
}
public static bool operator ==(StringSegment left, StringSegment right)
{
return left.Equals(right);
}
public static bool operator !=(StringSegment left, StringSegment right)
{
return !left.Equals(right);
}
#endregion
public bool StartsWith(string text, StringComparison comparisonType)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
int textLength = text.Length;
if (!HasValue || _count < textLength)
{
return false;
}
return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0;
}
public bool EndsWith(string text, StringComparison comparisonType)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
int textLength = text.Length;
if (!HasValue || _count < textLength)
{
return false;
}
return string.Compare(_buffer, _offset + _count - textLength, text, 0, textLength, comparisonType) == 0;
}
public bool Equals(string text, StringComparison comparisonType)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
int textLength = text.Length;
if (!HasValue || _count != textLength)
{
return false;
}
return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0;
}
public string Substring(int offset, int length)
{
return _buffer.Substring(_offset + offset, length);
}
public StringSegment Subsegment(int offset, int length)
{
return new StringSegment(_buffer, _offset + offset, length);
}
public override string ToString()
{
return Value ?? string.Empty;
}
}
internal static partial class OwinHelpers
{
private static readonly Action<string, string, object> AddCookieCallback = (name, value, state) =>
{
var dictionary = (IDictionary<string, string>)state;
if (!dictionary.ContainsKey(name))
{
dictionary.Add(name, value);
}
};
private static readonly char[] SemicolonAndComma = new[] { ';', ',' };
internal static IDictionary<string, string> GetCookies(IOwinRequest request)
{
var cookies = request.Get<IDictionary<string, string>>("Microsoft.Owin.Cookies#dictionary");
if (cookies == null)
{
cookies = new Dictionary<string, string>(StringComparer.Ordinal);
request.Set("Microsoft.Owin.Cookies#dictionary", cookies);
}
string text = GetHeader(request.Headers, "Cookie");
if (request.Get<string>("Microsoft.Owin.Cookies#text") != text)
{
cookies.Clear();
ParseDelimited(text, SemicolonAndComma, AddCookieCallback, cookies);
request.Set("Microsoft.Owin.Cookies#text", text);
}
return cookies;
}
internal static void ParseDelimited(string text, char[] delimiters, Action<string, string, object> callback, object state)
{
int textLength = text.Length;
int equalIndex = text.IndexOf('=');
if (equalIndex == -1)
{
equalIndex = textLength;
}
int scanIndex = 0;
while (scanIndex < textLength)
{
int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
if (delimiterIndex == -1)
{
delimiterIndex = textLength;
}
if (equalIndex < delimiterIndex)
{
while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
{
++scanIndex;
}
string name = text.Substring(scanIndex, equalIndex - scanIndex);
string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);
callback(
Uri.UnescapeDataString(name.Replace('+', ' ')),
Uri.UnescapeDataString(value.Replace('+', ' ')),
state);
equalIndex = text.IndexOf('=', delimiterIndex);
if (equalIndex == -1)
{
equalIndex = textLength;
}
}
scanIndex = delimiterIndex + 1;
}
}
}
internal static partial class OwinHelpers
{
public static string GetHeader(IDictionary<string, string[]> headers, string key)
{
string[] values = GetHeaderUnmodified(headers, key);
return values == null ? null : string.Join(",", values);
}
public static IEnumerable<string> GetHeaderSplit(IDictionary<string, string[]> headers, string key)
{
string[] values = GetHeaderUnmodified(headers, key);
return values == null ? null : GetHeaderSplitImplementation(values);
}
private static IEnumerable<string> GetHeaderSplitImplementation(string[] values)
{
foreach (var segment in new HeaderSegmentCollection(values))
{
if (segment.Data.HasValue)
{
yield return DeQuote(segment.Data.Value);
}
}
}
public static string[] GetHeaderUnmodified(IDictionary<string, string[]> headers, string key)
{
if (headers == null)
{
throw new ArgumentNullException("headers");
}
string[] values;
return headers.TryGetValue(key, out values) ? values : null;
}
public static void SetHeader(IDictionary<string, string[]> headers, string key, string value)
{
if (headers == null)
{
throw new ArgumentNullException("headers");
}
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentNullException("key");
}
if (string.IsNullOrWhiteSpace(value))
{
headers.Remove(key);
}
else
{
headers[key] = new[] { value };
}
}
public static void SetHeaderJoined(IDictionary<string, string[]> headers, string key, params string[] values)
{
if (headers == null)
{
throw new ArgumentNullException("headers");
}
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentNullException("key");
}
if (values == null || values.Length == 0)
{
headers.Remove(key);
}
else
{
headers[key] = new[] { string.Join(",", values.Select(value => QuoteIfNeeded(value))) };
}
}
// Quote items that contain comas and are not already quoted.
private static string QuoteIfNeeded(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
// Ignore
}
else if (value.Contains(','))
{
if (value[0] != '"' || value[value.Length - 1] != '"')
{
value = '"' + value + '"';
}
}
return value;
}
private static string DeQuote(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
// Ignore
}
else if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"')
{
value = value.Substring(1, value.Length - 2);
}
return value;
}
public static void SetHeaderUnmodified(IDictionary<string, string[]> headers, string key, params string[] values)
{
if (headers == null)
{
throw new ArgumentNullException("headers");
}
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentNullException("key");
}
if (values == null || values.Length == 0)
{
headers.Remove(key);
}
else
{
headers[key] = values;
}
}
public static void SetHeaderUnmodified(IDictionary<string, string[]> headers, string key, IEnumerable<string> values)
{
if (headers == null)
{
throw new ArgumentNullException("headers");
}
headers[key] = values.ToArray();
}
public static void AppendHeader(IDictionary<string, string[]> headers, string key, string values)
{
if (string.IsNullOrWhiteSpace(values))
{
return;
}
string existing = GetHeader(headers, key);
if (existing == null)
{
SetHeader(headers, key, values);
}
else
{
headers[key] = new[] { existing + "," + values };
}
}
public static void AppendHeaderJoined(IDictionary<string, string[]> headers, string key, params string[] values)
{
if (values == null || values.Length == 0)
{
return;
}
string existing = GetHeader(headers, key);
if (existing == null)
{
SetHeaderJoined(headers, key, values);
}
else
{
headers[key] = new[] { existing + "," + string.Join(",", values.Select(value => QuoteIfNeeded(value))) };
}
}
public static void AppendHeaderUnmodified(IDictionary<string, string[]> headers, string key, params string[] values)
{
if (values == null || values.Length == 0)
{
return;
}
string[] existing = GetHeaderUnmodified(headers, key);
if (existing == null)
{
SetHeaderUnmodified(headers, key, values);
}
else
{
SetHeaderUnmodified(headers, key, existing.Concat(values));
}
}
}
internal static partial class OwinHelpers
{
private static readonly Action<string, string, object> AppendItemCallback = (name, value, state) =>
{
var dictionary = (IDictionary<string, List<String>>)state;
List<string> existing;
if (!dictionary.TryGetValue(name, out existing))
{
dictionary.Add(name, new List<string>(1) { value });
}
else
{
existing.Add(value);
}
};
private static readonly char[] AmpersandAndSemicolon = new[] { '&', ';' };
internal static IDictionary<string, string[]> GetQuery(IOwinRequest request)
{
var query = request.Get<IDictionary<string, string[]>>("Microsoft.Owin.Query#dictionary");
if (query == null)
{
query = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
request.Set("Microsoft.Owin.Query#dictionary", query);
}
string text = request.QueryString.Value;
if (request.Get<string>("Microsoft.Owin.Query#text") != text)
{
query.Clear();
var accumulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
ParseDelimited(text, AmpersandAndSemicolon, AppendItemCallback, accumulator);
foreach (var kv in accumulator)
{
query.Add(kv.Key, kv.Value.ToArray());
}
request.Set("Microsoft.Owin.Query#text", text);
}
return query;
}
#if !NET40
internal static IFormCollection GetForm(string text)
{
IDictionary<string, string[]> form = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
var accumulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
ParseDelimited(text, new[] { '&' }, AppendItemCallback, accumulator);
foreach (var kv in accumulator)
{
form.Add(kv.Key, kv.Value.ToArray());
}
return new FormCollection(form);
}
#endif
internal static string GetJoinedValue(IDictionary<string, string[]> store, string key)
{
string[] values = GetUnmodifiedValues(store, key);
return values == null ? null : string.Join(",", values);
}
internal static string[] GetUnmodifiedValues(IDictionary<string, string[]> store, string key)
{
if (store == null)
{
throw new ArgumentNullException("store");
}
string[] values;
return store.TryGetValue(key, out values) ? values : null;
}
}
internal static partial class OwinHelpers
{
internal static string GetHost(IOwinRequest request)
{
IHeaderDictionary headers = request.Headers;
string host = GetHeader(headers, "Host");
if (!string.IsNullOrWhiteSpace(host))
{
return host;
}
string localIpAddress = request.LocalIpAddress ?? "localhost";
var localPort = request.Get<string>(OwinConstants.CommonKeys.LocalPort);
return string.IsNullOrWhiteSpace(localPort) ? localIpAddress : (localIpAddress + ":" + localPort);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using UnityApiPoc.Areas.HelpPage.ModelDescriptions;
using UnityApiPoc.Areas.HelpPage.Models;
namespace UnityApiPoc.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace MahApps.Metro.Controls
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
/// <summary>
/// Represents a base-class for time picking.
/// </summary>
[TemplatePart(Name = ElementButton, Type = typeof(Button))]
[TemplatePart(Name = ElementHourHand, Type = typeof(UIElement))]
[TemplatePart(Name = ElementHourPicker, Type = typeof(Selector))]
[TemplatePart(Name = ElementMinuteHand, Type = typeof(UIElement))]
[TemplatePart(Name = ElementSecondHand, Type = typeof(UIElement))]
[TemplatePart(Name = ElementSecondPicker, Type = typeof(Selector))]
[TemplatePart(Name = ElementMinutePicker, Type = typeof(Selector))]
[TemplatePart(Name = ElementAmPmSwitcher, Type = typeof(Selector))]
[TemplatePart(Name = ElementTextBox, Type = typeof(DatePickerTextBox))]
public abstract class TimePickerBase : Control
{
public static readonly DependencyProperty SourceHoursProperty = DependencyProperty.Register(
"SourceHours",
typeof(IEnumerable<int>),
typeof(TimePickerBase),
new FrameworkPropertyMetadata(Enumerable.Range(0, 24), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSourceHours));
public static readonly DependencyProperty SourceMinutesProperty = DependencyProperty.Register(
"SourceMinutes",
typeof(IEnumerable<int>),
typeof(TimePickerBase),
new FrameworkPropertyMetadata(Enumerable.Range(0, 60), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSource60));
public static readonly DependencyProperty SourceSecondsProperty = DependencyProperty.Register(
"SourceSeconds",
typeof(IEnumerable<int>),
typeof(TimePickerBase),
new FrameworkPropertyMetadata(Enumerable.Range(0, 60), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSource60));
public static readonly DependencyProperty IsDropDownOpenProperty = DatePicker.IsDropDownOpenProperty.AddOwner(typeof(TimePickerBase), new PropertyMetadata(default(bool)));
public static readonly DependencyProperty IsClockVisibleProperty = DependencyProperty.Register(
"IsClockVisible",
typeof(bool),
typeof(TimePickerBase),
new PropertyMetadata(true));
public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register(
"IsReadOnly",
typeof(bool),
typeof(TimePickerBase),
new PropertyMetadata(default(bool)));
public static readonly DependencyProperty HandVisibilityProperty = DependencyProperty.Register(
"HandVisibility",
typeof(TimePartVisibility),
typeof(TimePickerBase),
new PropertyMetadata(TimePartVisibility.All, OnHandVisibilityChanged));
public static readonly DependencyProperty CultureProperty = DependencyProperty.Register(
"Culture",
typeof(CultureInfo),
typeof(TimePickerBase),
new PropertyMetadata(null, OnCultureChanged));
public static readonly DependencyProperty PickerVisibilityProperty = DependencyProperty.Register(
"PickerVisibility",
typeof(TimePartVisibility),
typeof(TimePickerBase),
new PropertyMetadata(TimePartVisibility.All, OnPickerVisibilityChanged));
public static readonly RoutedEvent SelectedTimeChangedEvent = EventManager.RegisterRoutedEvent(
"SelectedTimeChanged",
RoutingStrategy.Direct,
typeof(EventHandler<TimePickerBaseSelectionChangedEventArgs<TimeSpan?>>),
typeof(TimePickerBase));
public static readonly DependencyProperty SelectedTimeProperty = DependencyProperty.Register(
"SelectedTime",
typeof(TimeSpan?),
typeof(TimePickerBase),
new FrameworkPropertyMetadata(default(TimeSpan?), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedTimeChanged, CoerceSelectedTime));
public static readonly DependencyProperty SelectedTimeFormatProperty = DependencyProperty.Register(
nameof(SelectedTimeFormat),
typeof(TimePickerFormat),
typeof(TimePickerBase),
new PropertyMetadata(TimePickerFormat.Long, OnSelectedTimeFormatChanged));
private const string ElementAmPmSwitcher = "PART_AmPmSwitcher";
private const string ElementButton = "PART_Button";
private const string ElementHourHand = "PART_HourHand";
private const string ElementHourPicker = "PART_HourPicker";
private const string ElementMinuteHand = "PART_MinuteHand";
private const string ElementMinutePicker = "PART_MinutePicker";
private const string ElementPopup = "PART_Popup";
private const string ElementSecondHand = "PART_SecondHand";
private const string ElementSecondPicker = "PART_SecondPicker";
private const string ElementTextBox = "PART_TextBox";
#region Do not change order of fields inside this region
/// <summary>
/// This readonly dependency property is to control whether to show the date-picker (in case of <see cref="DateTimePicker"/>) or hide it (in case of <see cref="TimePicker"/>.
/// </summary>
private static readonly DependencyPropertyKey IsDatePickerVisiblePropertyKey = DependencyProperty.RegisterReadOnly(
"IsDatePickerVisible", typeof(bool), typeof(TimePickerBase), new PropertyMetadata(true));
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess",Justification = "Otherwise we have \"Static member initializer refers to static member below or in other type part\" and thus resulting in having \"null\" as value")]
public static readonly DependencyProperty IsDatePickerVisibleProperty = IsDatePickerVisiblePropertyKey.DependencyProperty;
#endregion
/// <summary>
/// Represents the time 00:00:00; 12:00:00 AM respectively
/// </summary>
private static readonly TimeSpan MinTimeOfDay = TimeSpan.Zero;
/// <summary>
/// Represents the time 23:59:59.9999999; 11:59:59.9999999 PM respectively
/// </summary>
private static readonly TimeSpan MaxTimeOfDay = TimeSpan.FromDays(1) - TimeSpan.FromTicks(1);
/// <summary>
/// This list contains values from 0 to 55 with an interval of 5. It can be used to bind to <see cref="SourceMinutes"/> and <see cref="SourceSeconds"/>.
/// </summary>
/// <example>
/// <code><MahApps:TimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf5}" /></code>
/// <code><MahApps:DateTimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf5}" /></code>
/// </example>
/// <returns>
/// Returns a list containing {0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55}.
/// </returns>
public static readonly IEnumerable<int> IntervalOf5 = CreateValueList(5);
/// <summary>
/// This list contains values from 0 to 50 with an interval of 10. It can be used to bind to <see cref="SourceMinutes"/> and <see cref="SourceSeconds"/>.
/// </summary>
/// <example>
/// <code><MahApps:TimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf10}" /></code>
/// <code><MahApps:DateTimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf10}" /></code>
/// </example>
/// <returns>
/// Returns a list containing {0, 10, 20, 30, 40, 50}.
/// </returns>
public static readonly IEnumerable<int> IntervalOf10 = CreateValueList(10);
/// <summary>
/// This list contains values from 0 to 45 with an interval of 15. It can be used to bind to <see cref="SourceMinutes"/> and <see cref="SourceSeconds"/>.
/// </summary>
/// <example>
/// <code><MahApps:TimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf15}" /></code>
/// <code><MahApps:DateTimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf15}" /></code>
/// </example>
/// <returns>
/// Returns a list containing {0, 15, 30, 45}.
/// </returns>
public static readonly IEnumerable<int> IntervalOf15 = CreateValueList(15);
private Selector _ampmSwitcher;
private Button _button;
private bool _deactivateRangeBaseEvent;
private bool _deactivateTextChangedEvent;
private bool _textInputChanged;
private UIElement _hourHand;
private Selector _hourInput;
private UIElement _minuteHand;
private Selector _minuteInput;
private Popup _popup;
private UIElement _secondHand;
private Selector _secondInput;
protected DatePickerTextBox _textBox;
static TimePickerBase()
{
EventManager.RegisterClassHandler(typeof(TimePickerBase), UIElement.GotFocusEvent, new RoutedEventHandler(OnGotFocus));
DefaultStyleKeyProperty.OverrideMetadata(typeof(TimePickerBase), new FrameworkPropertyMetadata(typeof(TimePickerBase)));
VerticalContentAlignmentProperty.OverrideMetadata(typeof(TimePickerBase), new FrameworkPropertyMetadata(VerticalAlignment.Center));
LanguageProperty.OverrideMetadata(typeof(TimePickerBase), new FrameworkPropertyMetadata(OnCultureChanged));
}
protected TimePickerBase()
{
Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, this.OutsideCapturedElementHandler);
}
/// <summary>
/// Occurs when the <see cref="SelectedTime" /> property is changed.
/// </summary>
public event EventHandler<TimePickerBaseSelectionChangedEventArgs<TimeSpan?>> SelectedTimeChanged
{
add { AddHandler(SelectedTimeChangedEvent, value); }
remove { RemoveHandler(SelectedTimeChangedEvent, value); }
}
/// <summary>
/// Gets or sets a value indicating the culture to be used in string formatting operations.
/// </summary>
[Category("Behavior")]
[DefaultValue(null)]
public CultureInfo Culture
{
get { return (CultureInfo)GetValue(CultureProperty); }
set { SetValue(CultureProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating the visibility of the clock hands in the user interface (UI).
/// </summary>
/// <returns>
/// The visibility definition of the clock hands. The default is <see cref="TimePartVisibility.All" />.
/// </returns>
[Category("Appearance")]
[DefaultValue(TimePartVisibility.All)]
public TimePartVisibility HandVisibility
{
get { return (TimePartVisibility)GetValue(HandVisibilityProperty); }
set { SetValue(HandVisibilityProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the date can be selected or not. This property is read-only.
/// </summary>
public bool IsDatePickerVisible
{
get { return (bool)GetValue(IsDatePickerVisibleProperty); }
protected set { SetValue(IsDatePickerVisiblePropertyKey, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the clock of this control is visible in the user interface (UI). This is a
/// dependency property.
/// </summary>
/// <remarks>
/// If this value is set to false then <see cref="Orientation" /> is set to
/// <see cref="System.Windows.Controls.Orientation.Vertical" />
/// </remarks>
/// <returns>
/// true if the clock is visible; otherwise, false. The default value is true.
/// </returns>
[Category("Appearance")]
public bool IsClockVisible
{
get { return (bool)GetValue(IsClockVisibleProperty); }
set { SetValue(IsClockVisibleProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the drop-down for a <see cref="TimePickerBase"/> box is currently
/// open.
/// </summary>
/// <returns>true if the drop-down is open; otherwise, false. The default is false.</returns>
public bool IsDropDownOpen
{
get { return (bool)GetValue(IsDropDownOpenProperty); }
set { SetValue(IsDropDownOpenProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the contents of the <see cref="TimePickerBase" /> are not editable.
/// </summary>
/// <returns>
/// true if the <see cref="TimePickerBase" /> is read-only; otherwise, false. The default is false.
/// </returns>
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating the visibility of the selectable date-time-parts in the user interface (UI).
/// </summary>
/// <returns>
/// visibility definition of the selectable date-time-parts. The default is <see cref="TimePartVisibility.All" />.
/// </returns>
[Category("Appearance")]
[DefaultValue(TimePartVisibility.All)]
public TimePartVisibility PickerVisibility
{
get { return (TimePartVisibility)GetValue(PickerVisibilityProperty); }
set { SetValue(PickerVisibilityProperty, value); }
}
/// <summary>
/// Gets or sets the currently selected time.
/// </summary>
/// <returns>
/// The time currently selected. The default is null.
/// </returns>
public TimeSpan? SelectedTime
{
get { return (TimeSpan?)GetValue(SelectedTimeProperty); }
set { SetValue(SelectedTimeProperty, value); }
}
/// <summary>
/// Gets or sets the format that is used to display the selected time.
/// </summary>
[Category("Appearance")]
[DefaultValue(TimePickerFormat.Long)]
public TimePickerFormat SelectedTimeFormat
{
get { return (TimePickerFormat)GetValue(SelectedTimeFormatProperty); }
set { SetValue(SelectedTimeFormatProperty, value); }
}
/// <summary>
/// Gets or sets a collection used to generate the content for selecting the hours.
/// </summary>
/// <returns>
/// A collection that is used to generate the content for selecting the hours. The default is a list of interger from 0
/// to 23 if <see cref="IsMilitaryTime" /> is false or a list of interger from
/// 1 to 12 otherwise..
/// </returns>
[Category("Common")]
public IEnumerable<int> SourceHours
{
get { return (IEnumerable<int>)GetValue(SourceHoursProperty); }
set { SetValue(SourceHoursProperty, value); }
}
/// <summary>
/// Gets or sets a collection used to generate the content for selecting the minutes.
/// </summary>
/// <returns>
/// A collection that is used to generate the content for selecting the minutes. The default is a list of int from
/// 0 to 59.
/// </returns>
[Category("Common")]
public IEnumerable<int> SourceMinutes
{
get { return (IEnumerable<int>)GetValue(SourceMinutesProperty); }
set { SetValue(SourceMinutesProperty, value); }
}
/// <summary>
/// Gets or sets a collection used to generate the content for selecting the seconds.
/// </summary>
/// <returns>
/// A collection that is used to generate the content for selecting the minutes. The default is a list of int from
/// 0 to 59.
/// </returns>
[Category("Common")]
public IEnumerable<int> SourceSeconds
{
get { return (IEnumerable<int>)GetValue(SourceSecondsProperty); }
set { SetValue(SourceSecondsProperty, value); }
}
/// <summary>
/// Gets a value indicating whether the <see cref="DateTimeFormatInfo.AMDesignator" /> that is specified by the
/// <see cref="CultureInfo" />
/// set by the <see cref="Culture" /> (<see cref="FrameworkElement.Language" /> if null) has not a value.
/// </summary>
public bool IsMilitaryTime
{
get
{
var dateTimeFormat = this.SpecificCultureInfo.DateTimeFormat;
return !string.IsNullOrEmpty(dateTimeFormat.AMDesignator) && (dateTimeFormat.ShortTimePattern.Contains("h") || dateTimeFormat.LongTimePattern.Contains("h"));
}
}
protected internal Popup Popup
{
get { return _popup; }
}
protected CultureInfo SpecificCultureInfo
{
get { return Culture ?? Language.GetSpecificCulture(); }
}
/// <summary>
/// When overridden in a derived class, is invoked whenever application code or internal processes call
/// <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />.
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
UnSubscribeEvents();
_popup = GetTemplateChild(ElementPopup) as Popup;
_button = GetTemplateChild(ElementButton) as Button;
_hourInput = GetTemplateChild(ElementHourPicker) as Selector;
_minuteInput = GetTemplateChild(ElementMinutePicker) as Selector;
_secondInput = GetTemplateChild(ElementSecondPicker) as Selector;
_hourHand = GetTemplateChild(ElementHourHand) as FrameworkElement;
_ampmSwitcher = GetTemplateChild(ElementAmPmSwitcher) as Selector;
_minuteHand = GetTemplateChild(ElementMinuteHand) as FrameworkElement;
_secondHand = GetTemplateChild(ElementSecondHand) as FrameworkElement;
_textBox = GetTemplateChild(ElementTextBox) as DatePickerTextBox;
SetHandVisibility(HandVisibility);
SetPickerVisibility(PickerVisibility);
SetHourPartValues(SelectedTime.GetValueOrDefault());
WriteValueToTextBox();
SetDefaultTimeOfDayValues();
SubscribeEvents();
ApplyCulture();
ApplyBindings();
}
protected virtual void ApplyBindings()
{
if (Popup != null)
{
Popup.SetBinding(Popup.IsOpenProperty, GetBinding(IsDropDownOpenProperty));
}
}
protected virtual void ApplyCulture()
{
_deactivateRangeBaseEvent = true;
if (_ampmSwitcher != null)
{
_ampmSwitcher.Items.Clear();
if (!string.IsNullOrEmpty(SpecificCultureInfo.DateTimeFormat.AMDesignator))
{
_ampmSwitcher.Items.Add(SpecificCultureInfo.DateTimeFormat.AMDesignator);
}
if (!string.IsNullOrEmpty(SpecificCultureInfo.DateTimeFormat.PMDesignator))
{
_ampmSwitcher.Items.Add(SpecificCultureInfo.DateTimeFormat.PMDesignator);
}
}
SetAmPmVisibility();
CoerceValue(SourceHoursProperty);
if (SelectedTime.HasValue)
{
SetHourPartValues(SelectedTime.Value);
}
SetDefaultTimeOfDayValues();
_deactivateRangeBaseEvent = false;
WriteValueToTextBox();
}
protected Binding GetBinding(DependencyProperty property)
{
return new Binding(property.Name) { Source = this };
}
protected virtual string GetValueForTextBox()
{
var format = SelectedTimeFormat == TimePickerFormat.Long ? string.Intern(SpecificCultureInfo.DateTimeFormat.LongTimePattern) : string.Intern(SpecificCultureInfo.DateTimeFormat.ShortTimePattern);
var valueForTextBox = (DateTime.MinValue + SelectedTime)?.ToString(string.Intern(format), SpecificCultureInfo);
return valueForTextBox;
}
protected virtual void OnTextBoxLostFocus(object sender, RoutedEventArgs e)
{
var text = string.Intern($"{DateTime.MinValue.ToString(SpecificCultureInfo.DateTimeFormat.ShortDatePattern)} {((DatePickerTextBox)sender).Text}");
DateTime dt;
if (DateTime.TryParse(text, SpecificCultureInfo, DateTimeStyles.None, out dt))
{
SelectedTime = dt.TimeOfDay;
}
else
{
if (SelectedTime == null)
{
// if already null, overwrite wrong data in textbox
WriteValueToTextBox();
}
SelectedTime = null;
}
}
protected virtual void OnRangeBaseValueChanged(object sender, SelectionChangedEventArgs e)
{
SelectedTime = this.GetSelectedTimeFromGUI();
}
protected virtual void OnSelectedTimeChanged(TimePickerBaseSelectionChangedEventArgs<TimeSpan?> e)
{
RaiseEvent(e);
}
private static void OnSelectedTimeFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tp = d as TimePickerBase;
if (tp != null)
{
tp.WriteValueToTextBox();
}
}
protected void SetDefaultTimeOfDayValues()
{
SetDefaultTimeOfDayValue(_hourInput);
SetDefaultTimeOfDayValue(_minuteInput);
SetDefaultTimeOfDayValue(_secondInput);
SetDefaultTimeOfDayValue(_ampmSwitcher);
}
protected virtual void SubscribeEvents()
{
SubscribeRangeBaseValueChanged(_hourInput, _minuteInput, _secondInput, _ampmSwitcher);
if (_button != null)
{
_button.Click += OnButtonClicked;
}
if (_textBox != null)
{
_textBox.TextChanged += OnTextChanged;
_textBox.LostFocus += InternalOnTextBoxLostFocus;
}
}
protected virtual void UnSubscribeEvents()
{
UnsubscribeRangeBaseValueChanged(_hourInput, _minuteInput, _secondInput, _ampmSwitcher);
if (_button != null)
{
_button.Click -= OnButtonClicked;
}
if (_textBox != null)
{
_textBox.TextChanged -= OnTextChanged;
_textBox.LostFocus -= InternalOnTextBoxLostFocus;
}
}
protected virtual void WriteValueToTextBox()
{
if (_textBox != null)
{
_deactivateTextChangedEvent = true;
_textBox.Text = GetValueForTextBox();
_deactivateTextChangedEvent = false;
}
}
private static IList<int> CreateValueList(int interval)
{
return Enumerable.Repeat(interval, 60 / interval)
.Select((value, index) => value * index)
.ToList();
}
private static object CoerceSelectedTime(DependencyObject d, object basevalue)
{
var timeOfDay = (TimeSpan?)basevalue;
if (timeOfDay < MinTimeOfDay)
{
return MinTimeOfDay;
}
else if (timeOfDay > MaxTimeOfDay)
{
return MaxTimeOfDay;
}
return timeOfDay;
}
private static object CoerceSource60(DependencyObject d, object basevalue)
{
var list = basevalue as IEnumerable<int>;
if (list != null)
{
return list.Where(i => i >= 0 && i < 60);
}
return Enumerable.Empty<int>();
}
private static object CoerceSourceHours(DependencyObject d, object basevalue)
{
var timePickerBase = d as TimePickerBase;
var hourList = basevalue as IEnumerable<int>;
if (timePickerBase != null && hourList != null)
{
if (timePickerBase.IsMilitaryTime)
{
return hourList.Where(i => i > 0 && i <= 12).OrderBy(i => i, new AmPmComparer());
}
return hourList.Where(i => i >= 0 && i < 24);
}
return Enumerable.Empty<int>();
}
private void InternalOnTextBoxLostFocus(object sender, RoutedEventArgs e)
{
if (_textInputChanged)
{
_textInputChanged = false;
OnTextBoxLostFocus(sender, e);
}
}
private void InternalOnRangeBaseValueChanged(object sender, SelectionChangedEventArgs e)
{
if (!_deactivateRangeBaseEvent)
{
OnRangeBaseValueChanged(sender, e);
}
}
private static void OnCultureChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var timePartPickerBase = (TimePickerBase)d;
if (e.NewValue is XmlLanguage)
{
timePartPickerBase.Language = (XmlLanguage)e.NewValue;
}
else if (e.NewValue is CultureInfo)
{
timePartPickerBase.Language = XmlLanguage.GetLanguage(((CultureInfo)e.NewValue).IetfLanguageTag);
}
else
{
timePartPickerBase.Language = XmlLanguage.Empty;
}
timePartPickerBase.ApplyCulture();
}
protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e)
{
base.OnIsKeyboardFocusWithinChanged(e);
// To hide the popup when the user e.g. alt+tabs, monitor for when the window becomes a background window.
if (!(bool)e.NewValue)
{
this.IsDropDownOpen = false;
}
}
private void OutsideCapturedElementHandler(object sender, MouseButtonEventArgs e)
{
this.IsDropDownOpen = false;
}
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
TimePickerBase picker = (TimePickerBase)sender;
if (!e.Handled && picker.Focusable && (picker._textBox != null))
{
if (Equals(e.OriginalSource, picker))
{
// MoveFocus takes a TraversalRequest as its argument.
var request = new TraversalRequest((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next);
// Gets the element with keyboard focus.
var elementWithFocus = Keyboard.FocusedElement as UIElement;
// Change keyboard focus.
elementWithFocus?.MoveFocus(request);
e.Handled = true;
}
else if (Equals(e.OriginalSource, picker._textBox))
{
picker._textBox.SelectAll();
e.Handled = true;
}
}
}
private static void OnHandVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TimePickerBase)d).SetHandVisibility((TimePartVisibility)e.NewValue);
}
private static void OnPickerVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TimePickerBase)d).SetPickerVisibility((TimePartVisibility)e.NewValue);
}
private static void OnSelectedTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var timePartPickerBase = (TimePickerBase)d;
if (timePartPickerBase._deactivateRangeBaseEvent)
{
return;
}
timePartPickerBase.SetHourPartValues((e.NewValue as TimeSpan?).GetValueOrDefault(TimeSpan.Zero));
timePartPickerBase.OnSelectedTimeChanged(new TimePickerBaseSelectionChangedEventArgs<TimeSpan?>(SelectedTimeChangedEvent, (TimeSpan?)e.OldValue, (TimeSpan?)e.NewValue));
timePartPickerBase.WriteValueToTextBox();
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (!_deactivateTextChangedEvent)
{
_textInputChanged = true;
}
}
private static void SetVisibility(UIElement partHours, UIElement partMinutes, UIElement partSeconds, TimePartVisibility visibility)
{
if (partHours != null)
{
partHours.Visibility = visibility.HasFlag(TimePartVisibility.Hour) ? Visibility.Visible : Visibility.Collapsed;
}
if (partMinutes != null)
{
partMinutes.Visibility = visibility.HasFlag(TimePartVisibility.Minute) ? Visibility.Visible : Visibility.Collapsed;
}
if (partSeconds != null)
{
partSeconds.Visibility = visibility.HasFlag(TimePartVisibility.Second) ? Visibility.Visible : Visibility.Collapsed;
}
}
private static bool IsValueSelected(Selector selector)
{
return selector != null && selector.SelectedItem != null;
}
private static void SetDefaultTimeOfDayValue(Selector selector)
{
if (selector != null)
{
if (selector.SelectedValue == null)
{
selector.SelectedIndex = 0;
}
}
}
protected TimeSpan? GetSelectedTimeFromGUI()
{
{
if (IsValueSelected(_hourInput) &&
IsValueSelected(_minuteInput) &&
IsValueSelected(_secondInput))
{
var hours = (int)_hourInput.SelectedItem;
var minutes = (int)_minuteInput.SelectedItem;
var seconds = (int)_secondInput.SelectedItem;
hours += GetAmPmOffset(hours);
return new TimeSpan(hours, minutes, seconds);
}
return SelectedTime;
}
}
/// <summary>
/// Gets the offset from the selected <paramref name="currentHour" /> to use it in <see cref="TimeSpan" /> as hour
/// parameter.
/// </summary>
/// <param name="currentHour">The current hour.</param>
/// <returns>
/// An integer representing the offset to add to the hour that is selected in the hour-picker for setting the correct
/// <see cref="DateTime.TimeOfDay" />. The offset is determined as follows:
/// <list type="table">
/// <listheader>
/// <term>Condition</term><description>Offset</description>
/// </listheader>
/// <item>
/// <term><see cref="IsMilitaryTime" /> is false</term><description>0</description>
/// </item>
/// <item>
/// <term>Selected hour is between 1 AM and 11 AM</term><description>0</description>
/// </item>
/// <item>
/// <term>Selected hour is 12 AM</term><description>-12h</description>
/// </item>
/// <item>
/// <term>Selected hour is between 12 PM and 11 PM</term><description>+12h</description>
/// </item>
/// </list>
/// </returns>
private int GetAmPmOffset(int currentHour)
{
if (IsMilitaryTime)
{
if (currentHour == 12)
{
if (Equals(_ampmSwitcher.SelectedItem, SpecificCultureInfo.DateTimeFormat.AMDesignator))
{
return -12;
}
}
else if (Equals(_ampmSwitcher.SelectedItem, SpecificCultureInfo.DateTimeFormat.PMDesignator))
{
return 12;
}
}
return 0;
}
private void OnButtonClicked(object sender, RoutedEventArgs e)
{
IsDropDownOpen = !IsDropDownOpen;
if (Popup != null)
{
Popup.IsOpen = IsDropDownOpen;
}
}
private void SetAmPmVisibility()
{
if (_ampmSwitcher != null)
{
if (!PickerVisibility.HasFlag(TimePartVisibility.Hour))
{
_ampmSwitcher.Visibility = Visibility.Collapsed;
}
else
{
_ampmSwitcher.Visibility = IsMilitaryTime ? Visibility.Visible : Visibility.Collapsed;
}
}
}
private void SetHandVisibility(TimePartVisibility visibility)
{
SetVisibility(_hourHand, _minuteHand, _secondHand, visibility);
}
private void SetHourPartValues(TimeSpan timeOfDay)
{
if (this._deactivateRangeBaseEvent)
{
return;
}
_deactivateRangeBaseEvent = true;
if (_hourInput != null)
{
if (IsMilitaryTime)
{
_ampmSwitcher.SelectedValue = timeOfDay.Hours < 12 ? SpecificCultureInfo.DateTimeFormat.AMDesignator : SpecificCultureInfo.DateTimeFormat.PMDesignator;
if (timeOfDay.Hours == 0 || timeOfDay.Hours == 12)
{
_hourInput.SelectedValue = 12;
}
else
{
_hourInput.SelectedValue = timeOfDay.Hours % 12;
}
}
else
{
_hourInput.SelectedValue = timeOfDay.Hours;
}
}
if (_minuteInput != null)
{
_minuteInput.SelectedValue = timeOfDay.Minutes;
}
if (_secondInput != null)
{
_secondInput.SelectedValue = timeOfDay.Seconds;
}
_deactivateRangeBaseEvent = false;
}
private void SetPickerVisibility(TimePartVisibility visibility)
{
SetVisibility(_hourInput, _minuteInput, _secondInput, visibility);
SetAmPmVisibility();
}
private void SubscribeRangeBaseValueChanged(params Selector[] selectors)
{
foreach (var selector in selectors.Where(i => i != null))
{
selector.SelectionChanged += InternalOnRangeBaseValueChanged;
}
}
private void UnsubscribeRangeBaseValueChanged(params Selector[] selectors)
{
foreach (var selector in selectors.Where(i => i != null))
{
selector.SelectionChanged -= InternalOnRangeBaseValueChanged;
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.ML.Data.Buffer.CODEC
{
/// <summary>
/// A CODEC used to read/write data from/to a CSV data file. There are two
/// constructors provided, one is for reading, the other for writing. Make sure
/// you use the correct one for your intended purpose.
///
/// This CODEC is typically used with the BinaryDataLoader, to load external data
/// into the Encog binary training format.
/// </summary>
public class CSVDataCODEC : IDataSetCODEC
{
/// <summary>
/// The external CSV file.
/// </summary>
private readonly String _file;
/// <summary>
/// The CSV format to use.
/// </summary>
private readonly CSVFormat _format;
/// <summary>
/// True, if headers are present in the CSV file.
/// </summary>
private readonly bool _headers;
/// <summary>
/// The size of the ideal data.
/// </summary>
private int _idealCount;
/// <summary>
/// The size of the input data.
/// </summary>
private int _inputCount;
/// <summary>
/// A file used to output the CSV file.
/// </summary>
private TextWriter _output;
/// <summary>
/// The utility to assist in reading the CSV file.
/// </summary>
private ReadCSV _readCSV;
/// <summary>
/// Should a significance column be expected.
/// </summary>
private bool _significance;
/// <summary>
/// Create a CODEC to load data from CSV to binary.
/// </summary>
/// <param name="file">The CSV file to load.</param>
/// <param name="format">The format that the CSV file is in.</param>
/// <param name="headers">True, if there are headers.</param>
/// <param name="inputCount">The number of input columns.</param>
/// <param name="idealCount">The number of ideal columns.</param>
/// <param name="significance">Is there a signficance column.</param>
public CSVDataCODEC(
String file,
CSVFormat format,
bool headers,
int inputCount, int idealCount, bool significance)
{
if (_inputCount != 0)
{
throw new BufferedDataError(
"To export CSV, you must use the CSVDataCODEC constructor that does not specify input or ideal sizes.");
}
_file = file;
_format = format;
_inputCount = inputCount;
_idealCount = idealCount;
_headers = headers;
_significance = significance;
}
/// <summary>
/// Constructor to create CSV from binary.
/// </summary>
/// <param name="file">The CSV file to create.</param>
/// <param name="format">The format for that CSV file.</param>
public CSVDataCODEC(String file, CSVFormat format, bool significance)
{
_file = file;
_format = format;
_significance = significance;
}
#region IDataSetCODEC Members
/// <inheritdoc/>
public bool Read(double[] input, double[] ideal, ref double significance)
{
if (_readCSV.Next())
{
int index = 0;
for (int i = 0; i < input.Length; i++)
{
input[i] = _readCSV.GetDouble(index++);
}
for (int i = 0; i < ideal.Length; i++)
{
ideal[i] = _readCSV.GetDouble(index++);
}
if( _significance )
{
significance = _readCSV.GetDouble(index++);
}
else
{
significance = 1;
}
return true;
}
return false;
}
/// <inheritdoc/>
public void Write(double[] input, double[] ideal, double significance)
{
if (_significance)
{
var record = new double[input.Length + ideal.Length + 1];
EngineArray.ArrayCopy(input, record);
EngineArray.ArrayCopy(ideal, 0, record, input.Length, ideal.Length);
record[record.Length - 1] = significance;
var result = new StringBuilder();
NumberList.ToList(_format, result, record);
_output.WriteLine(result.ToString());
}
else
{
var record = new double[input.Length + ideal.Length];
EngineArray.ArrayCopy(input, record);
EngineArray.ArrayCopy(ideal, 0, record, input.Length, ideal.Length);
var result = new StringBuilder();
NumberList.ToList(_format, result, record);
_output.WriteLine(result.ToString());
}
}
/// <summary>
/// Prepare to write to a CSV file.
/// </summary>
/// <param name="recordCount">The total record count, that will be written.</param>
/// <param name="inputSize">The input size.</param>
/// <param name="idealSize">The ideal size.</param>
public void PrepareWrite(
int recordCount,
int inputSize,
int idealSize)
{
try
{
_inputCount = inputSize;
_idealCount = idealSize;
_output = new StreamWriter(new FileStream(_file, FileMode.Create));
}
catch (IOException ex)
{
throw new BufferedDataError(ex);
}
}
/// <summary>
/// Prepare to read from the CSV file.
/// </summary>
public void PrepareRead()
{
if (_inputCount == 0)
{
throw new BufferedDataError(
"To import CSV, you must use the CSVDataCODEC constructor that specifies input and ideal sizes.");
}
_readCSV = new ReadCSV(_file, _headers,
_format);
}
/// <inheritDoc/>
public int InputSize
{
get { return _inputCount; }
}
/// <inheritDoc/>
public int IdealSize
{
get { return _idealCount; }
}
/// <inheritDoc/>
public void Close()
{
if (_readCSV != null)
{
_readCSV.Close();
_readCSV = null;
}
if (_output != null)
{
_output.Close();
_output = null;
}
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Filename: SIPParameters.cs
//
// Description: SIP parameters as used in Contact, To, From and Via SIP headers.
//
// History:
// 06 May 2006 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery PTY LTD.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using SIPSorcery.Sys;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.SIP
{
/// <summary>
/// Represents a series of name value pairs that are optionally included in SIP URIs and also as an additional
/// optional setting on some SIP Headers (Contact, To, From, Via).
/// This class also treats the header value of a SIP URI as a special case of a SIP parameter. The difference between
/// a paramter and a SIP URI header is the start and delimiter characters used.
///
/// SIP URI with parameters:
/// sip:1234@sip.com;key1=value1;key2=value2
///
/// SIP URI with headers:
/// sip:1234@sip.com?key1=value1&key2=value2
///
/// SIP URI with parameters and headers (paramters always come first):
/// sip:1234@sip.com;key1=value1;key2=value2?key1=value1&key2=value2
/// </summary>
/// <bnf>
/// generic-param = token [ EQUAL gen-value ]
/// gen-value = token / host / quoted-string
/// </bnf>
[DataContract]
public class SIPParameters
{
private const char TAG_NAME_VALUE_SEPERATOR = '=';
private const char QUOTE = '"';
private const char BACK_SLASH = '\\';
private const char DEFAULT_PARAMETER_DELIMITER = ';';
private static ILog logger = AssemblyState.logger;
[DataMember]
public char TagDelimiter = DEFAULT_PARAMETER_DELIMITER;
//[IgnoreDataMember]
[DataMember]
public Dictionary<string, string> m_dictionary = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
[IgnoreDataMember]
public int Count
{
get { return (m_dictionary != null) ? m_dictionary.Count : 0; }
}
/// <summary>
/// Parses the name value pairs from a SIP parameter or header string.
/// </summary>
public SIPParameters(string sipString, char delimiter)
{
Initialise(sipString, delimiter);
}
private void Initialise(string sipString, char delimiter)
{
TagDelimiter = delimiter;
string[] keyValuePairs = GetKeyValuePairsFromQuoted(sipString, delimiter);
if (keyValuePairs != null && keyValuePairs.Length > 0)
{
foreach (string keyValuePair in keyValuePairs)
{
AddKeyValuePair(keyValuePair, m_dictionary);
}
}
}
public static string[] GetKeyValuePairsFromQuoted(string quotedString, char delimiter)
{
try
{
List<string> keyValuePairList = new List<string>();
if (quotedString == null || quotedString.Trim().Length == 0)
{
return null;
}
else if(quotedString.IndexOf(delimiter) == -1)
{
//return quotedString.Split(delimiter);
return new string[] {quotedString};
}
else
{
int startParameterPosn = 0;
int inParameterPosn = 0;
bool inQuotedStr = false;
while (inParameterPosn != -1 && inParameterPosn < quotedString.Length)
{
inParameterPosn = quotedString.IndexOfAny(new char[] { delimiter, QUOTE }, inParameterPosn);
// Determine if the delimiter position represents the end of the parameter or is in a quoted string.
if (inParameterPosn != -1)
{
if (inParameterPosn <= startParameterPosn && quotedString[inParameterPosn] == delimiter)
{
// Initial or doubled up Parameter delimiter character, ignore and move on.
inQuotedStr = false;
inParameterPosn++;
startParameterPosn = inParameterPosn;
}
else if (quotedString[inParameterPosn] == QUOTE)
{
if (inQuotedStr && inParameterPosn > 0 && quotedString[inParameterPosn - 1] != BACK_SLASH)
{
// If in a quoted string and this quote has not been escaped close the quoted string.
inQuotedStr = false;
}
else if (inQuotedStr && inParameterPosn > 0 && quotedString[inParameterPosn - 1] == BACK_SLASH)
{
// Do nothing, quote has been escaped in a quoted string.
}
else if (!inQuotedStr)
{
// Start quoted string.
inQuotedStr = true;
}
inParameterPosn++;
}
else
{
if (!inQuotedStr)
{
// Parameter delimiter found and not in quoted string therefore this is a parameter separator.
string keyValuePair = quotedString.Substring(startParameterPosn, inParameterPosn - startParameterPosn);
keyValuePairList.Add(keyValuePair);
inParameterPosn++;
startParameterPosn = inParameterPosn;
}
else
{
// Do nothing, separator character is within a quoted string.
inParameterPosn++;
}
}
}
}
// Add the last parameter.
if (startParameterPosn < quotedString.Length)
{
// Parameter delimiter found and not in quoted string therefore this is a parameter separator.
keyValuePairList.Add(quotedString.Substring(startParameterPosn));
}
}
return keyValuePairList.ToArray();
}
catch (Exception excp)
{
logger.Error("Exception GetKeyValuePairsFromQuoted. " + excp.Message);
throw excp;
}
}
private void AddKeyValuePair(string keyValuePair, Dictionary<string, string> dictionary)
{
if (keyValuePair != null && keyValuePair.Trim().Length > 0)
{
int seperatorPosn = keyValuePair.IndexOf(TAG_NAME_VALUE_SEPERATOR);
if (seperatorPosn != -1)
{
string keyName = keyValuePair.Substring(0, seperatorPosn).Trim();
// If this is not the parameter that is being removed put it back on.
if (!dictionary.ContainsKey(keyName))
{
dictionary.Add(keyName, keyValuePair.Substring(seperatorPosn + 1).Trim());
}
}
else
{
// Keys with no values are valid in SIP so they get added to the collection with a null value.
if (!dictionary.ContainsKey(keyValuePair))
{
dictionary.Add(keyValuePair, null);
}
}
}
}
public void Set(string name, string value)
{
if (m_dictionary.ContainsKey(name))
{
m_dictionary[name] = value;
}
else
{
m_dictionary.Add(name, value);
}
}
public string Get(string name)
{
if (m_dictionary != null || m_dictionary.Count == 0)
{
if (m_dictionary.ContainsKey(name))
{
return SIPEscape.SIPURIParameterUnescape(m_dictionary[name]);
}
else
{
return null;
}
}
else
{
return null;
}
}
public bool Has(string name)
{
if (m_dictionary != null)
{
return m_dictionary.ContainsKey(name);
}
else
{
return false;
}
}
public void Remove(string name)
{
if (name != null)
{
m_dictionary.Remove(name);
}
}
public void RemoveAll()
{
m_dictionary = new Dictionary<string, string>();
}
public string[] GetKeys()
{
if (m_dictionary == null || m_dictionary.Count == 0)
{
return null;
}
else
{
string[] keys = new string[m_dictionary.Count];
int index = 0;
foreach (KeyValuePair<string, string> entry in m_dictionary)
{
keys[index++] = entry.Key as string;
}
return keys;
}
}
public new string ToString() {
string paramStr = null;
if (m_dictionary != null) {
foreach (KeyValuePair<string, string> param in m_dictionary) {
if (param.Value != null && param.Value.Trim().Length > 0) {
paramStr += TagDelimiter + param.Key + TAG_NAME_VALUE_SEPERATOR + SIPEscape.SIPURIParameterEscape(param.Value);
}
else {
paramStr += TagDelimiter + param.Key;
}
}
}
return paramStr;
}
public override int GetHashCode()
{
if (m_dictionary != null && m_dictionary.Count > 0)
{
SortedList sortedParams = new SortedList();
foreach (KeyValuePair<string, string> param in m_dictionary)
{
sortedParams.Add(param.Key.ToLower(), (string)param.Value);
}
StringBuilder sortedParamBuilder = new StringBuilder();
foreach (DictionaryEntry sortedEntry in sortedParams)
{
sortedParamBuilder.Append((string)sortedEntry.Key + (string)sortedEntry.Value);
}
return sortedParamBuilder.ToString().GetHashCode();
}
else
{
return 0;
}
}
public SIPParameters CopyOf()
{
SIPParameters copy = new SIPParameters(ToString(), TagDelimiter);
return copy;
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPParamsUnitTest
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void SampleTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
}
[Test]
public void RouteParamExtractTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string routeParam = ";lr;server=hippo";
SIPParameters serverParam = new SIPParameters(routeParam, ';');
string serverParamValue = serverParam.Get("server");
Console.WriteLine("Parameter string=" + serverParam.ToString() + ".");
Console.WriteLine("The server parameter is=" + serverParamValue + ".");
Assert.IsTrue(serverParamValue == "hippo", "The server parameter was not correctly extracted.");
}
[Test]
public void QuotedStringParamExtractTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string methodsParam = ";methods=\"INVITE, MESSAGE, INFO, SUBSCRIBE, OPTIONS, BYE, CANCEL, NOTIFY, ACK, REFER\"";
SIPParameters serverParam = new SIPParameters(methodsParam, ';');
string methodsParamValue = serverParam.Get("methods");
Console.WriteLine("Parameter string=" + serverParam.ToString() + ".");
Console.WriteLine("The methods parameter is=" + methodsParamValue + ".");
Assert.IsTrue(methodsParamValue == "\"INVITE, MESSAGE, INFO, SUBSCRIBE, OPTIONS, BYE, CANCEL, NOTIFY, ACK, REFER\"", "The method parameter was not correctly extracted.");
}
[Test]
public void UserFieldWithNamesExtractTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string userField = "\"Joe Bloggs\" <sip:joe@bloggs.com>;allow=\"options, invite, cancel\"";
string[] keyValuePairs = GetKeyValuePairsFromQuoted(userField, ',');
Console.WriteLine("KeyValuePair count=" + keyValuePairs.Length + ".");
Console.WriteLine("First KetValuePair=" + keyValuePairs[0] + ".");
Assert.IsTrue(keyValuePairs.Length == 1, "An incorrect number of key value pairs was extracted");
}
[Test]
public void MultipleUserFieldWithNamesExtractTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string userField = "\"Joe Bloggs\" <sip:joe@bloggs.com>;allow=\"options, invite, cancel\" , \"Jane Doe\" <sip:jabe@doe.com>";
string[] keyValuePairs = GetKeyValuePairsFromQuoted(userField, ',');
Console.WriteLine("KeyValuePair count=" + keyValuePairs.Length + ".");
Console.WriteLine("First KetValuePair=" + keyValuePairs[0] + ".");
Console.WriteLine("Second KetValuePair=" + keyValuePairs[1] + ".");
Assert.IsTrue(keyValuePairs.Length == 2, "An incorrect number of key value pairs was extracted");
}
[Test]
public void MultipleUserFieldWithNamesExtraWhitespaceExtractTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string userField = " \"Joe Bloggs\" <sip:joe@bloggs.com>;allow=\"options, invite, cancel\" \t, \"Jane Doe\" <sip:jabe@doe.com>";
string[] keyValuePairs = GetKeyValuePairsFromQuoted(userField, ',');
Console.WriteLine("KeyValuePair count=" + keyValuePairs.Length + ".");
Console.WriteLine("First KetValuePair=" + keyValuePairs[0] + ".");
Console.WriteLine("Second KetValuePair=" + keyValuePairs[1] + ".");
Assert.IsTrue(keyValuePairs.Length == 2, "An incorrect number of key value pairs was extracted");
}
[Test]
public void GetHashCodeEqualityUnittest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string testParamStr1 = ";lr;server=hippo;ftag=12345";
SIPParameters testParam1 = new SIPParameters(testParamStr1, ';');
string testParamStr2 = ";lr;server=hippo;ftag=12345";
SIPParameters testParam2 = new SIPParameters(testParamStr2, ';');
Assert.IsTrue(testParam1.GetHashCode() == testParam2.GetHashCode(), "The parameters had different hashcode values.");
}
[Test]
public void GetHashCodeDiffOrderEqualityUnittest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string testParamStr1 = ";lr;server=hippo;ftag=12345";
SIPParameters testParam1 = new SIPParameters(testParamStr1, ';');
string testParamStr2 = "ftag=12345;lr;server=hippo;";
SIPParameters testParam2 = new SIPParameters(testParamStr2, ';');
Assert.IsTrue(testParam1.GetHashCode() == testParam2.GetHashCode(), "The parameters had different hashcode values.");
}
[Test]
public void GetHashCodeDiffCaseEqualityUnittest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string testParamStr1 = ";LR;Server=hippo;FTag=12345";
SIPParameters testParam1 = new SIPParameters(testParamStr1, ';');
Console.WriteLine("Parameter 1:" + testParam1.ToString());
string testParamStr2 = "ftag=12345;lr;server=hippo;";
SIPParameters testParam2 = new SIPParameters(testParamStr2, ';');
Console.WriteLine("Parameter 2:" + testParam2.ToString());
Assert.IsTrue(testParam1.GetHashCode() == testParam2.GetHashCode(), "The parameters had different hashcode values.");
}
[Test]
public void GetHashCodeDiffValueCaseEqualityUnittest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string testParamStr1 = ";LR;Server=hippo;FTag=12345";
SIPParameters testParam1 = new SIPParameters(testParamStr1, ';');
Console.WriteLine("Parameter 1:" + testParam1.ToString());
string testParamStr2 = "ftag=12345;lr;server=HiPPo;";
SIPParameters testParam2 = new SIPParameters(testParamStr2, ';');
Console.WriteLine("Parameter 2:" + testParam2.ToString());
Assert.IsTrue(testParam1.GetHashCode() != testParam2.GetHashCode(), "The parameters had different hashcode values.");
}
[Test]
public void EmptyValueParametersUnittest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string testParamStr1 = ";emptykey;Server=hippo;FTag=12345";
SIPParameters testParam1 = new SIPParameters(testParamStr1, ';');
Console.WriteLine("Parameter 1:" + testParam1.ToString());
Assert.IsTrue(testParam1.Has("emptykey"), "The empty parameter \"emptykey\" was not correctly extracted from the paramter string.");
Assert.IsTrue(Regex.Match(testParam1.ToString(), "emptykey").Success, "The emptykey name was not in the output parameter string.");
}
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using ExcelDataReader.Portable.Core;
using ExcelDataReader.Portable.Core.BinaryFormat;
using ExcelDataReader.Portable.Data;
using ExcelDataReader.Portable.Exceptions;
using ExcelDataReader.Portable.Log;
using ExcelDataReader.Portable.Misc;
namespace ExcelDataReader.Portable
{
/// <summary>
/// ExcelDataReader Class
/// </summary>
public class ExcelBinaryReader : IExcelDataReader
{
#region Members
private Stream m_file;
private XlsHeader m_hdr;
private List<XlsWorksheet> m_sheets;
private XlsBiffStream m_stream;
//private DataSet m_workbookData;
private XlsWorkbookGlobals m_globals;
private ushort m_version;
private Encoding m_encoding;
private bool m_isValid;
private bool m_isClosed;
private readonly Encoding m_Default_Encoding = Encoding.Unicode;
private string m_exceptionMessage;
private object[] m_cellsValues;
private uint[] m_dbCellAddrs;
private int m_dbCellAddrsIndex;
private bool m_canRead;
private int m_SheetIndex;
private int m_depth;
private int m_cellOffset;
private int m_maxCol;
private int m_maxRow;
private bool m_noIndex;
private XlsBiffRow m_currentRowRecord;
private ReadOption readOption = ReadOption.Strict;
private bool m_IsFirstRead;
private const string WORKBOOK = "Workbook";
private const string BOOK = "Book";
private const string COLUMN = "Column";
private bool disposed;
private readonly IDataHelper dataHelper;
private bool convertOaDate = true;
#endregion
public ExcelBinaryReader(IDataHelper dataHelper)
{
this.dataHelper = dataHelper;
m_encoding = m_Default_Encoding;
m_version = 0x0600;
m_isValid = true;
m_SheetIndex = -1;
m_IsFirstRead = true;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
//if (m_workbookData != null) m_workbookData.Dispose();
if (m_sheets != null) m_sheets.Clear();
}
//m_workbookData = null;
m_sheets = null;
m_stream = null;
m_globals = null;
m_encoding = null;
m_hdr = null;
disposed = true;
}
}
~ExcelBinaryReader()
{
Dispose(false);
}
#endregion
#region Private methods
private int findFirstDataCellOffset(int startOffset)
{
//seek to the first dbcell record
var record = m_stream.ReadAt(startOffset);
while (!(record is XlsBiffDbCell))
{
if (m_stream.Position >= m_stream.Size)
return -1;
if (record is XlsBiffEOF)
return -1;
record = m_stream.Read();
}
XlsBiffDbCell startCell = (XlsBiffDbCell)record;
XlsBiffRow row = null;
int offs = startCell.RowAddress;
do
{
row = m_stream.ReadAt(offs) as XlsBiffRow;
if (row == null) break;
offs += row.Size;
} while (null != row);
return offs;
}
private void readWorkBookGlobals()
{
//Read Header
try
{
m_hdr = XlsHeader.ReadHeader(m_file);
}
catch (HeaderException ex)
{
fail(ex.Message);
return;
}
catch (FormatException ex)
{
fail(ex.Message);
return;
}
XlsRootDirectory dir = new XlsRootDirectory(m_hdr);
XlsDirectoryEntry workbookEntry = dir.FindEntry(WORKBOOK) ?? dir.FindEntry(BOOK);
if (workbookEntry == null)
{ fail(Errors.ErrorStreamWorkbookNotFound); return; }
if (workbookEntry.EntryType != STGTY.STGTY_STREAM)
{ fail(Errors.ErrorWorkbookIsNotStream); return; }
m_stream = new XlsBiffStream(m_hdr, workbookEntry.StreamFirstSector, workbookEntry.IsEntryMiniStream, dir, this);
m_globals = new XlsWorkbookGlobals();
m_stream.Seek(0, SeekOrigin.Begin);
XlsBiffRecord rec = m_stream.Read();
XlsBiffBOF bof = rec as XlsBiffBOF;
if (bof == null || bof.Type != BIFFTYPE.WorkbookGlobals)
{ fail(Errors.ErrorWorkbookGlobalsInvalidData); return; }
bool sst = false;
m_version = bof.Version;
m_sheets = new List<XlsWorksheet>();
while (null != (rec = m_stream.Read()))
{
switch (rec.ID)
{
case BIFFRECORDTYPE.INTERFACEHDR:
m_globals.InterfaceHdr = (XlsBiffInterfaceHdr)rec;
break;
case BIFFRECORDTYPE.BOUNDSHEET:
XlsBiffBoundSheet sheet = (XlsBiffBoundSheet)rec;
if (sheet.Type != XlsBiffBoundSheet.SheetType.Worksheet) break;
sheet.IsV8 = isV8();
sheet.UseEncoding = m_encoding;
this.Log().Debug("BOUNDSHEET IsV8={0}", sheet.IsV8);
m_sheets.Add(new XlsWorksheet(m_globals.Sheets.Count, sheet));
m_globals.Sheets.Add(sheet);
break;
case BIFFRECORDTYPE.MMS:
m_globals.MMS = rec;
break;
case BIFFRECORDTYPE.COUNTRY:
m_globals.Country = rec;
break;
case BIFFRECORDTYPE.CODEPAGE:
m_globals.CodePage = (XlsBiffSimpleValueRecord)rec;
//note: the format spec states that for BIFF8 this is always UTF-16.
//as PCL does not supported codepage numbers, it is best to assume UTF-16 for encoding
//try
//{
// m_encoding = Encoding.GetEncoding(m_globals.CodePage.Value);
//}
//catch (ArgumentException)
//{
// // Warning - Password protection
//}
break;
case BIFFRECORDTYPE.FONT:
case BIFFRECORDTYPE.FONT_V34:
m_globals.Fonts.Add(rec);
break;
case BIFFRECORDTYPE.FORMAT_V23:
{
var fmt = (XlsBiffFormatString) rec;
//fmt.UseEncoding = m_encoding;
m_globals.Formats.Add((ushort) m_globals.Formats.Count, fmt);
}
break;
case BIFFRECORDTYPE.FORMAT:
{
var fmt = (XlsBiffFormatString) rec;
m_globals.Formats.Add(fmt.Index, fmt);
}
break;
case BIFFRECORDTYPE.XF:
case BIFFRECORDTYPE.XF_V4:
case BIFFRECORDTYPE.XF_V3:
case BIFFRECORDTYPE.XF_V2:
m_globals.ExtendedFormats.Add(rec);
break;
case BIFFRECORDTYPE.SST:
m_globals.SST = (XlsBiffSST)rec;
sst = true;
break;
case BIFFRECORDTYPE.CONTINUE:
if (!sst) break;
XlsBiffContinue contSST = (XlsBiffContinue)rec;
m_globals.SST.Append(contSST);
break;
case BIFFRECORDTYPE.EXTSST:
m_globals.ExtSST = rec;
sst = false;
break;
case BIFFRECORDTYPE.PROTECT:
case BIFFRECORDTYPE.PASSWORD:
case BIFFRECORDTYPE.PROT4REVPASSWORD:
//IsProtected
break;
case BIFFRECORDTYPE.EOF:
if (m_globals.SST != null)
m_globals.SST.ReadStrings();
return;
default:
continue;
}
}
}
private bool readWorkSheetGlobals(XlsWorksheet sheet, out XlsBiffIndex idx, out XlsBiffRow row)
{
idx = null;
row = null;
m_stream.Seek((int)sheet.DataOffset, SeekOrigin.Begin);
XlsBiffBOF bof = m_stream.Read() as XlsBiffBOF;
if (bof == null || bof.Type != BIFFTYPE.Worksheet) return false;
//DumpBiffRecords();
XlsBiffRecord rec = m_stream.Read();
if (rec == null) return false;
if (rec is XlsBiffIndex)
{
idx = rec as XlsBiffIndex;
}
else if (rec is XlsBiffUncalced)
{
// Sometimes this come before the index...
idx = m_stream.Read() as XlsBiffIndex;
}
//if (null == idx)
//{
// // There is a record before the index! Chech his type and see the MS Biff Documentation
// return false;
//}
if (idx != null)
{
idx.IsV8 = isV8();
this.Log().Debug("INDEX IsV8={0}", idx.IsV8);
}
XlsBiffRecord trec;
XlsBiffDimensions dims = null;
do
{
trec = m_stream.Read();
if (trec.ID == BIFFRECORDTYPE.DIMENSIONS)
{
dims = (XlsBiffDimensions)trec;
break;
}
} while (trec != null && trec.ID != BIFFRECORDTYPE.ROW);
//if we are already on row record then set that as the row, otherwise step forward till we get to a row record
if (trec.ID == BIFFRECORDTYPE.ROW)
row = (XlsBiffRow)trec;
XlsBiffRow rowRecord = null;
while (rowRecord == null)
{
if (m_stream.Position >= m_stream.Size)
break;
var thisRec = m_stream.Read();
this.Log().Debug("finding rowRecord offset {0}, rec: {1}", thisRec.Offset, thisRec.ID);
if (thisRec is XlsBiffEOF)
break;
rowRecord = thisRec as XlsBiffRow;
}
if (rowRecord != null)
this.Log().Debug("Got row {0}, rec: id={1},rowindex={2}, rowColumnStart={3}, rowColumnEnd={4}", rowRecord.Offset, rowRecord.ID, rowRecord.RowIndex, rowRecord.FirstDefinedColumn, rowRecord.LastDefinedColumn);
row = rowRecord;
if (dims != null) {
dims.IsV8 = isV8();
this.Log().Debug("dims IsV8={0}", dims.IsV8);
m_maxCol = dims.LastColumn - 1;
//handle case where sheet reports last column is 1 but there are actually more
if (m_maxCol <= 0 && rowRecord != null)
{
m_maxCol = rowRecord.LastDefinedColumn;
}
m_maxRow = (int)dims.LastRow;
sheet.Dimensions = dims;
} else {
m_maxCol = 256;
m_maxRow = (int)idx.LastExistingRow;
}
if (idx != null && idx.LastExistingRow <= idx.FirstExistingRow)
{
return false;
}
else if (row == null)
{
return false;
}
m_depth = 0;
return true;
}
private void DumpBiffRecords()
{
XlsBiffRecord rec = null;
var startPos = m_stream.Position;
do
{
rec = m_stream.Read();
this.Log().Debug(rec.ID.ToString());
} while (rec != null && m_stream.Position < m_stream.Size);
m_stream.Seek(startPos, SeekOrigin.Begin);
}
private bool readWorkSheetRow()
{
m_cellsValues = new object[m_maxCol];
while (m_cellOffset < m_stream.Size)
{
XlsBiffRecord rec = m_stream.ReadAt(m_cellOffset);
m_cellOffset += rec.Size;
if ((rec is XlsBiffDbCell) || (rec is XlsBiffMSODrawing)) { break; };
if (rec is XlsBiffEOF) { return false; };
XlsBiffBlankCell cell = rec as XlsBiffBlankCell;
if ((null == cell) || (cell.ColumnIndex >= m_maxCol)) continue;
if (cell.RowIndex != m_depth) { m_cellOffset -= rec.Size; break; };
pushCellValue(cell);
}
m_depth++;
return m_depth < m_maxRow;
}
private void pushCellValue(XlsBiffBlankCell cell)
{
double _dValue;
this.Log().Debug("pushCellValue {0}", cell.ID);
switch (cell.ID)
{
case BIFFRECORDTYPE.BOOLERR:
if (cell.ReadByte(7) == 0)
m_cellsValues[cell.ColumnIndex] = cell.ReadByte(6) != 0;
break;
case BIFFRECORDTYPE.BOOLERR_OLD:
if (cell.ReadByte(8) == 0)
m_cellsValues[cell.ColumnIndex] = cell.ReadByte(7) != 0;
break;
case BIFFRECORDTYPE.INTEGER:
case BIFFRECORDTYPE.INTEGER_OLD:
m_cellsValues[cell.ColumnIndex] = ((XlsBiffIntegerCell)cell).Value;
break;
case BIFFRECORDTYPE.NUMBER:
case BIFFRECORDTYPE.NUMBER_OLD:
_dValue = ((XlsBiffNumberCell)cell).Value;
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_dValue : tryConvertOADateTime(_dValue, cell.XFormat);
this.Log().Debug("VALUE: {0}", _dValue);
break;
case BIFFRECORDTYPE.LABEL:
case BIFFRECORDTYPE.LABEL_OLD:
case BIFFRECORDTYPE.RSTRING:
m_cellsValues[cell.ColumnIndex] = ((XlsBiffLabelCell)cell).Value;
this.Log().Debug("VALUE: {0}", m_cellsValues[cell.ColumnIndex]);
break;
case BIFFRECORDTYPE.LABELSST:
string tmp = m_globals.SST.GetString(((XlsBiffLabelSSTCell)cell).SSTIndex);
this.Log().Debug("VALUE: {0}", tmp);
m_cellsValues[cell.ColumnIndex] = tmp;
break;
case BIFFRECORDTYPE.RK:
_dValue = ((XlsBiffRKCell)cell).Value;
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_dValue : tryConvertOADateTime(_dValue, cell.XFormat);
this.Log().Debug("VALUE: {0}", _dValue);
break;
case BIFFRECORDTYPE.MULRK:
XlsBiffMulRKCell _rkCell = (XlsBiffMulRKCell)cell;
for (ushort j = cell.ColumnIndex; j <= _rkCell.LastColumnIndex; j++)
{
_dValue = _rkCell.GetValue(j);
this.Log().Debug("VALUE[{1}]: {0}", _dValue, j);
m_cellsValues[j] = !ConvertOaDate ? _dValue : tryConvertOADateTime(_dValue, _rkCell.GetXF(j));
}
break;
case BIFFRECORDTYPE.BLANK:
case BIFFRECORDTYPE.BLANK_OLD:
case BIFFRECORDTYPE.MULBLANK:
// Skip blank cells
break;
case BIFFRECORDTYPE.FORMULA:
case BIFFRECORDTYPE.FORMULA_OLD:
object _oValue = ((XlsBiffFormulaCell)cell).Value;
if (null != _oValue && _oValue is FORMULAERROR)
{
_oValue = null;
}
else
{
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_oValue : tryConvertOADateTime(_oValue, (ushort)(cell.XFormat));//date time offset
}
this.Log().Debug("VALUE: {0}", _oValue);
break;
default:
break;
}
}
private bool moveToNextRecord()
{
//if sheet has no index
if (m_noIndex)
{
this.Log().Debug("No index");
return moveToNextRecordNoIndex();
}
//if sheet has index
if (null == m_dbCellAddrs ||
m_dbCellAddrsIndex == m_dbCellAddrs.Length ||
m_depth == m_maxRow) return false;
m_canRead = readWorkSheetRow();
//read last row
if (!m_canRead && m_depth > 0) m_canRead = true;
if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1))
{
m_dbCellAddrsIndex++;
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
if (m_cellOffset < 0)
return false;
m_canRead = readWorkSheetRow();
}
return m_canRead;
}
private bool moveToNextRecordNoIndex()
{
//seek from current row record to start of cell data where that cell relates to the next row record
XlsBiffRow rowRecord = m_currentRowRecord;
if (rowRecord == null)
return false;
if (rowRecord.RowIndex < m_depth)
{
m_stream.Seek(rowRecord.Offset + rowRecord.Size, SeekOrigin.Begin);
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
rowRecord = record as XlsBiffRow;
} while (rowRecord == null || rowRecord.RowIndex < m_depth);
}
m_currentRowRecord = rowRecord;
//m_depth = m_currentRowRecord.RowIndex;
//we have now found the row record for the new row, the we need to seek forward to the first cell record
XlsBiffBlankCell cell = null;
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
if (record.IsCell)
{
var candidateCell = record as XlsBiffBlankCell;
if (candidateCell != null)
{
if (candidateCell.RowIndex == m_currentRowRecord.RowIndex)
cell = candidateCell;
}
}
} while (cell == null);
m_cellOffset = cell.Offset;
m_canRead = readWorkSheetRow();
//read last row
//if (!m_canRead && m_depth > 0) m_canRead = true;
//if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1))
//{
// m_dbCellAddrsIndex++;
// m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
// m_canRead = readWorkSheetRow();
//}
return m_canRead;
}
private void initializeSheetRead()
{
if (m_SheetIndex == ResultsCount) return;
m_dbCellAddrs = null;
m_IsFirstRead = false;
if (m_SheetIndex == -1) m_SheetIndex = 0;
XlsBiffIndex idx;
if (!readWorkSheetGlobals(m_sheets[m_SheetIndex], out idx, out m_currentRowRecord))
{
//read next sheet
m_SheetIndex++;
initializeSheetRead();
return;
};
if (idx == null)
{
//no index, but should have the first row record
m_noIndex = true;
}
else
{
m_dbCellAddrs = idx.DbCellAddresses;
m_dbCellAddrsIndex = 0;
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
if (m_cellOffset < 0)
{
fail("Badly formed binary file. Has INDEX but no DBCELL");
return;
}
}
}
private void fail(string message)
{
m_exceptionMessage = message;
m_isValid = false;
m_file.Dispose();
m_isClosed = true;
m_sheets = null;
m_stream = null;
m_globals = null;
m_encoding = null;
m_hdr = null;
}
private object tryConvertOADateTime(double value, ushort XFormat)
{
ushort format = 0;
if (XFormat >= 0 && XFormat < m_globals.ExtendedFormats.Count)
{
var rec = m_globals.ExtendedFormats[XFormat];
switch (rec.ID)
{
case BIFFRECORDTYPE.XF_V2:
format = (ushort) (rec.ReadByte(2) & 0x3F);
break;
case BIFFRECORDTYPE.XF_V3:
if ((rec.ReadByte(3) & 4) == 0)
return value;
format = rec.ReadByte(1);
break;
case BIFFRECORDTYPE.XF_V4:
if ((rec.ReadByte(5) & 4) == 0)
return value;
format = rec.ReadByte(1);
break;
default:
if ((rec.ReadByte(m_globals.Sheets[m_globals.Sheets.Count-1].IsV8 ? 9 : 7) & 4) == 0)
return value;
format = rec.ReadUInt16(2);
break;
}
}
else
{
format = XFormat;
}
switch (format)
{
// numeric built in formats
case 0: //"General";
case 1: //"0";
case 2: //"0.00";
case 3: //"#,##0";
case 4: //"#,##0.00";
case 5: //"\"$\"#,##0_);(\"$\"#,##0)";
case 6: //"\"$\"#,##0_);[Red](\"$\"#,##0)";
case 7: //"\"$\"#,##0.00_);(\"$\"#,##0.00)";
case 8: //"\"$\"#,##0.00_);[Red](\"$\"#,##0.00)";
case 9: //"0%";
case 10: //"0.00%";
case 11: //"0.00E+00";
case 12: //"# ?/?";
case 13: //"# ??/??";
case 0x30:// "##0.0E+0";
case 0x25:// "_(#,##0_);(#,##0)";
case 0x26:// "_(#,##0_);[Red](#,##0)";
case 0x27:// "_(#,##0.00_);(#,##0.00)";
case 40:// "_(#,##0.00_);[Red](#,##0.00)";
case 0x29:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)";
case 0x2a:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)";
case 0x2b:// "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)";
case 0x2c:// "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)";
return value;
// date formats
case 14: //this.GetDefaultDateFormat();
case 15: //"D-MM-YY";
case 0x10: // "D-MMM";
case 0x11: // "MMM-YY";
case 0x12: // "h:mm AM/PM";
case 0x13: // "h:mm:ss AM/PM";
case 20: // "h:mm";
case 0x15: // "h:mm:ss";
case 0x16: // string.Format("{0} {1}", this.GetDefaultDateFormat(), this.GetDefaultTimeFormat());
case 0x2d: // "mm:ss";
case 0x2e: // "[h]:mm:ss";
case 0x2f: // "mm:ss.0";
return Helpers.ConvertFromOATime(value);
case 0x31:// "@";
return value.ToString();
default:
XlsBiffFormatString fmtString;
if (m_globals.Formats.TryGetValue(format, out fmtString) )
{
var fmt = fmtString.Value;
var formatReader = new FormatReader() {FormatString = fmt};
if (formatReader.IsDateFormatString())
return Helpers.ConvertFromOATime(value);
}
return value;
}
}
private object tryConvertOADateTime(object value, ushort XFormat)
{
double _dValue;
if (double.TryParse(value.ToString(), out _dValue))
return tryConvertOADateTime(_dValue, XFormat);
return value;
}
public bool isV8()
{
return m_version >= 0x600;
}
#endregion
#region IExcelDataReader Members
public void Initialize(Stream fileStream)
{
m_file = fileStream;
readWorkBookGlobals();
// set the sheet index to the index of the first sheet.. this is so that properties such as Name which use m_sheetIndex reflect the first sheet in the file without having to perform a read() operation
m_SheetIndex = 0;
}
//public DataSet AsDataSet()
//{
// return AsDataSet(false);
//}
//public DataSet AsDataSet(bool convertOADateTime)
//{
// if (!m_isValid) return null;
// if (m_isClosed) return m_workbookData;
// ConvertOaDate = convertOADateTime;
// m_workbookData = new DataSet();
// for (int index = 0; index < ResultsCount; index++)
// {
// DataTable table = readWholeWorkSheet(m_sheets[index]);
// if (null != table)
// m_workbookData.Tables.Add(table);
// }
// m_file.Close();
// m_isClosed = true;
// m_workbookData.AcceptChanges();
// Helpers.FixDataTypes(m_workbookData);
// return m_workbookData;
//}
public string ExceptionMessage
{
get { return m_exceptionMessage; }
}
public string Name
{
get
{
if (null != m_sheets && m_sheets.Count > 0)
return m_sheets[m_SheetIndex].Name;
else
return null;
}
}
public string VisibleState
{
get
{
if (null != m_sheets && m_sheets.Count > 0)
return m_sheets[m_SheetIndex].VisibleState;
else
return null;
}
}
public bool IsValid
{
get { return m_isValid; }
}
public void Close()
{
m_file.Dispose();
m_isClosed = true;
}
public int Depth
{
get { return m_depth; }
}
public int ResultsCount
{
get { return m_globals.Sheets.Count; }
}
public bool IsClosed
{
get { return m_isClosed; }
}
public bool NextResult()
{
if (m_SheetIndex >= (this.ResultsCount - 1)) return false;
m_SheetIndex++;
m_IsFirstRead = true;
return true;
}
public bool Read()
{
if (!m_isValid) return false;
if (m_IsFirstRead) initializeSheetRead();
return moveToNextRecord();
}
public int FieldCount
{
get { return m_maxCol; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(m_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
// requested change: 3
object val = m_cellsValues[i];
if (val is DateTime)
{
// if the value is already a datetime.. return it without further conversion
return (DateTime)val;
}
// otherwise proceed with conversion attempts
string valString = val.ToString();
double dVal;
try
{
dVal = double.Parse(valString);
}
catch (FormatException)
{
return DateTime.Parse(valString);
}
return DateTimeHelper.FromOADate(dVal);
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(m_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(m_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(m_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(m_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(m_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(m_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return m_cellsValues[i].ToString();
}
public object GetValue(int i)
{
return m_cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == m_cellsValues[i]) || (dataHelper.IsDBNull(m_cellsValues[i]));
}
public object this[int i]
{
get { return m_cellsValues[i]; }
}
#endregion
#region Not Supported IDataReader Members
//public DataTable GetSchemaTable()
//{
// throw new NotSupportedException();
//}
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
//public IDataReader GetData(int i)
//{
// throw new NotSupportedException();
//}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
#region IExcelDataReader Members
public bool IsFirstRowAsColumnNames { get; set; }
public bool ConvertOaDate
{
get { return convertOaDate; }
set { convertOaDate = value; }
}
public ReadOption ReadOption
{
get { return readOption; }
set { readOption = value; }
}
#endregion
#region Dataset
public void LoadDataSet(IDatasetHelper datasetHelper)
{
LoadDataSet(datasetHelper, false);
}
public void LoadDataSet(IDatasetHelper datasetHelper, bool convertOADateTime)
{
if (!m_isValid)
{
datasetHelper.IsValid = false;
}
datasetHelper.IsValid = true;
if (m_isClosed) return;
ConvertOaDate = convertOADateTime;
datasetHelper.CreateNew();
//m_workbookData = new DataSet();
for (int index = 0; index < ResultsCount; index++)
{
readWholeWorkSheet(m_sheets[index], datasetHelper);
}
m_file.Dispose();
m_isClosed = true;
datasetHelper.DatasetLoadComplete();
}
private void readWholeWorkSheet(XlsWorksheet sheet, IDatasetHelper datasetHelper)
{
XlsBiffIndex idx;
if (!readWorkSheetGlobals(sheet, out idx, out m_currentRowRecord))
{
datasetHelper.IsValid = false;
return;
}
//DataTable table = new DataTable(sheet.Name);
datasetHelper.CreateNewTable(sheet.Name);
datasetHelper.AddExtendedPropertyToTable("visiblestate", sheet.VisibleState);
bool triggerCreateColumns = true;
if (idx != null)
readWholeWorkSheetWithIndex(idx, triggerCreateColumns, datasetHelper);
else
readWholeWorkSheetNoIndex(triggerCreateColumns, datasetHelper);
datasetHelper.EndLoadTable();
}
//TODO: quite a bit of duplication with the noindex version
private void readWholeWorkSheetWithIndex(XlsBiffIndex idx, bool triggerCreateColumns, IDatasetHelper datasetHelper)
{
m_dbCellAddrs = idx.DbCellAddresses;
for (int index = 0; index < m_dbCellAddrs.Length; index++)
{
if (m_depth == m_maxRow) break;
// init reading data
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[index]);
if (m_cellOffset < 0)
return;
//DataTable columns
if (triggerCreateColumns)
{
if (IsFirstRowAsColumnNames && readWorkSheetRow() || (IsFirstRowAsColumnNames && m_maxRow == 1))
{
for (int i = 0; i < m_maxCol; i++)
{
if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0)
datasetHelper.AddColumn(m_cellsValues[i].ToString());
else
datasetHelper.AddColumn(string.Concat(COLUMN, i));
}
}
else
{
for (int i = 0; i < m_maxCol; i++)
{
datasetHelper.AddColumn(null);
}
}
triggerCreateColumns = false;
datasetHelper.BeginLoadData();
//table.BeginLoadData();
}
while (readWorkSheetRow())
{
datasetHelper.AddRow(m_cellsValues);
}
//add the row
if (m_depth > 0 && !(IsFirstRowAsColumnNames && m_maxRow == 1))
{
datasetHelper.AddRow(m_cellsValues);
}
}
}
private void readWholeWorkSheetNoIndex(bool triggerCreateColumns, IDatasetHelper datasetHelper)
{
while (Read())
{
if (m_depth == m_maxRow) break;
bool justAddedColumns = false;
//DataTable columns
if (triggerCreateColumns)
{
if (IsFirstRowAsColumnNames || (IsFirstRowAsColumnNames && m_maxRow == 1))
{
for (int i = 0; i < m_maxCol; i++)
{
if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0)
datasetHelper.AddColumn(m_cellsValues[i].ToString());
else
datasetHelper.AddColumn(string.Concat(COLUMN, i));
}
justAddedColumns = true;
}
else
{
for (int i = 0; i < m_maxCol; i++)
{
datasetHelper.AddColumn(null);
}
}
triggerCreateColumns = false;
datasetHelper.BeginLoadData();
}
if (!justAddedColumns && m_depth > 0 && !(IsFirstRowAsColumnNames && m_maxRow == 1))
{
datasetHelper.AddRow(m_cellsValues);
}
}
if (m_depth > 0 && !(IsFirstRowAsColumnNames && m_maxRow == 1))
{
datasetHelper.AddRow(m_cellsValues);
}
}
#endregion
}
/// <summary>
/// Strict is as normal, Loose is more forgiving and will not cause an exception if a record size takes it beyond the end of the file. It will be trunacted in this case (SQl Reporting Services)
/// </summary>
public enum ReadOption
{
Strict,
Loose
}
}
| |
#region Using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using Janus.Windows.Common;
using TribalWars.Controls;
using TribalWars.Maps.AttackPlans.Controls;
using TribalWars.Maps.Icons;
using TribalWars.Maps.Manipulators.Implementations;
using TribalWars.Maps.Manipulators.Managers;
using TribalWars.Tools;
using TribalWars.Villages;
using TribalWars.Villages.Units;
using TribalWars.Worlds;
#endregion
namespace TribalWars.Maps.AttackPlans
{
/// <summary>
/// The managing attackmanipulator
/// </summary>
public class AttackManipulatorManager : ManipulatorManagerBase
{
#region Constants
/// <summary>
/// When searching for the fastest villages that can still make it for
/// the given travel time, add this many possible attackers per click
/// </summary>
private const int AutoFindAmountOfAttackers = 10;
/// <summary>
/// When searching for the fastest villages that can still make it for
/// the given travel time, add this many possible attackers per click
/// when none are found that can still reach in time
/// </summary>
private const int AutoFindAmountOfAttackersWhenNone = 3;
private const int DefaultArrivalTimeServerOffset = 8;
/// <summary>
/// Auto find functionality: only add attackers that have
/// more then this amount in seconds left before 'send time'
/// </summary>
private const int AutoFindMinimumAmountOfSecondsLeft = 0;
#endregion
#region Fields
private readonly AttackManipulator _attacker;
private readonly List<Village> _attackersPool;
#endregion
#region Properties
public UnitTypes DefaultSpeed { get; set; }
/// <summary>
/// Global attack planner configuration
/// </summary>
public AttackManipulator.SettingsInfo Settings
{
get { return _attacker.Settings; }
}
public bool IsAttackersPoolEmpty
{
get { return !_attackersPool.Any(); }
}
public ICollection<Village> AttackersPool
{
get { return _attackersPool; }
}
public AttackPlan ActivePlan
{
get { return _attacker.ActivePlan; }
}
#endregion
#region Constructors
public AttackManipulatorManager(Map map)
: base(map, true)
{
_attackersPool = new List<Village>();
UseLegacyXmlWriter = false;
// Active manipulators
var mover = new MapMoverManipulator(map, false, false, true);
var dragger = new MapDraggerManipulator(map, this);
_attacker = new AttackManipulator(map);
AddManipulator(_attacker);
AddManipulator(mover);
AddManipulator(dragger);
}
#endregion
#region Methods
public DateTime GetDefaultArrivalTime()
{
if (_attacker.ActivePlan == null)
{
return World.Default.Settings.ServerTime.AddHours(DefaultArrivalTimeServerOffset);
}
else
{
return _attacker.ActivePlan.ArrivalTime;
}
}
public IEnumerable<AttackPlan> GetPlans()
{
return _attacker.GetPlans();
}
/// <summary>
/// Gets the first plan where the village is either the target
/// or one of the attackers
/// </summary>
public AttackPlan GetPlan(Village village, out bool isActivePlan, out AttackPlanFrom attacker, bool cycleVillage)
{
var plan = _attacker.GetPlan(village, out attacker, cycleVillage);
isActivePlan = plan == _attacker.ActivePlan;
return plan;
}
protected override SuperTipSettings BuildTooltip(Village village)
{
AttackPlanFrom attacker;
AttackPlan plan = _attacker.GetPlan(village, out attacker, false);
if (plan == null)
{
return base.BuildTooltip(village);
}
var settings = new SuperTipSettings();
settings.ToolTipStyle = ToolTipStyle.Standard;
settings.HeaderImage = Properties.Resources.FlagGreen;
var str = new System.Text.StringBuilder();
if (attacker == null)
{
settings.HeaderText = plan.Target.Tooltip.Title;
}
else
{
settings.HeaderText = attacker.Attacker.Tooltip.Title;
str.AppendFormat(ControlsRes.AttackManipulatorManager_Tooltip_Target, plan.Target.Tooltip.Title);
str.Append(Environment.NewLine);
}
str.AppendFormat(ControlsRes.AttackManipulatorManager_Tooltip_Points, Common.GetPrettyNumber(plan.Target.Points));
str.Append(Environment.NewLine);
str.AppendFormat(ControlsRes.AttackManipulatorManager_Tooltip_ArrivalDate, plan.ArrivalTime.GetPrettyDate());
if (attacker != null)
{
settings.Image = attacker.SlowestUnit.Image;
str.Append(Environment.NewLine);
str.Append(Environment.NewLine);
str.AppendFormat(ControlsRes.AttackManipulatorManager_Tooltip_TravelTime, attacker.TravelTime);
str.Append(Environment.NewLine);
str.AppendFormat(ControlsRes.AttackManipulatorManager_Tooltip_SendOn, attacker.FormattedSendDate());
}
else
{
str.Append(Environment.NewLine);
str.Append(Environment.NewLine);
if (!plan.Attacks.Any())
{
str.AppendFormat("");
str.AppendLine();
str.AppendFormat("");
if (World.Default.You.Empty)
{
str.AppendLine();
str.AppendLine();
str.Append(ControlsRes.AttackManipulatorManager_Tooltip_Help_NoYou);
}
}
else
{
IOrderedEnumerable<AttackPlanFrom> attacks = plan.Attacks.OrderByDescending(x => x.TravelTime);
IEnumerable<IGrouping<Unit, AttackPlanFrom>> unitsSent;
if (plan.Attacks.Any(x => x.SlowestUnit.Type == UnitTypes.Snob))
{
settings.Image = WorldUnits.Default[UnitTypes.Snob].Image;
unitsSent = attacks.GroupBy(x => x.SlowestUnit);
}
else
{
unitsSent = attacks.GroupBy(x => x.SlowestUnit);
}
foreach (var unitSent in unitsSent)
{
str.AppendFormat("{0}: {1}", unitSent.Key.Name, unitSent.Count());
str.AppendLine();
}
if (!string.IsNullOrWhiteSpace(plan.Comments))
{
settings.FooterText = plan.Comments;
settings.FooterImage = Other.Note;
}
}
}
settings.Text = str.ToString();
if (!string.IsNullOrEmpty(village.Tooltip.Footer))
{
if (!string.IsNullOrWhiteSpace(settings.FooterText))
{
settings.FooterText += "\n\n";
settings.FooterText += village.Tooltip.Footer;
}
else
{
settings.FooterText = village.Tooltip.Footer;
}
settings.FooterImage = village.Tooltip.FooterImage;
}
return settings;
}
public override IContextMenu GetContextMenu(Point location, Village village)
{
if (village == null)
{
return new NoVillageAttackContextMenu(this);
}
bool isYourVillage = village.HasPlayer && village.Player == World.Default.You;
bool villageIsNotTheTarget = _attacker.ActivePlan != null && _attacker.ActivePlan.Target != village;
int villageUsedInAttackCount = _attacker.VillageUsedCount(village);
bool hasExistingAttacker = villageUsedInAttackCount != 1 || (villageUsedInAttackCount == 1 && !_attacker.IsAddingTarget);
if (isYourVillage && villageIsNotTheTarget && !hasExistingAttacker)
{
// Right click on a village you own = add new attacker
// So: show no contextmenu
return null;
}
return base.GetContextMenu(location, village);
}
#endregion
#region Persistence
protected override string WriteXmlCore()
{
return _attacker.WriteXml();
}
protected override void ReadXmlCore(XDocument doc)
{
_attacker.ReadXml(doc);
}
#endregion
#region Finding Attackers
public void AddToAttackersPool(IEnumerable<Village> villages)
{
villages = villages.Where(x => !_attackersPool.Contains(x));
_attackersPool.AddRange(villages.Distinct());
}
public IEnumerable<Travelfun> GetAttackersFromYou(AttackPlan plan, Unit slowestUnit, VillageType? villageType)
{
return GetAttackers(World.Default.You, plan, slowestUnit, villageType);
}
public IEnumerable<Travelfun> GetAttackersFromPool(AttackPlan plan, Unit slowestUnit, VillageType? villageType, out bool depleted)
{
var attackers = GetAttackers(_attackersPool, plan, slowestUnit, villageType).ToArray();
_attackersPool.RemoveAll(attackers.Select(x => x.Village).Contains);
depleted = !_attackersPool.Any();
return attackers;
}
/// <summary>
/// When looking for attacks on Ram speed, also include villages that won't reach Ram but do Sword/Axe
/// </summary>
private static Unit[] GetAcceptableSpeeds(Unit selectedUnit)
{
var acceptableSpeeds = new List<Unit>();
if (selectedUnit == null)
{
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Axe]);
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Sword]);
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Light]);
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Heavy]);
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Ram]);
}
else
{
acceptableSpeeds.Add(selectedUnit);
switch (selectedUnit.Type)
{
case UnitTypes.Axe:
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Light]);
break;
case UnitTypes.Spear:
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Heavy]);
break;
case UnitTypes.Sword:
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Spear]);
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Heavy]);
break;
case UnitTypes.Knight:
case UnitTypes.Snob:
case UnitTypes.Spy:
case UnitTypes.Catapult:
break;
case UnitTypes.Ram:
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Axe]);
acceptableSpeeds.Add(WorldUnits.Default[UnitTypes.Sword]);
break;
}
}
return acceptableSpeeds.ToArray();
}
public class Travelfun
{
public Village Village { get; set; }
public Unit Speed { get; set; }
public TimeSpan TravelTime { get; set; }
public TimeSpan TimeBeforeNeedToSend { get; set; }
}
private IEnumerable<Travelfun> GetAttackers(IEnumerable<Village> searchIn, AttackPlan plan, Unit slowestUnit, VillageType? villageType)
{
Unit[] acceptableSpeeds = GetAcceptableSpeeds(slowestUnit);
Village[] villagesAlreadyUsed =
GetPlans().SelectMany(x => x.Attacks)
.Select(x => x.Attacker)
.ToArray();
var matchingVillages =
(from village in searchIn
where !villagesAlreadyUsed.Contains(village)
select village);
if (villageType != null)
{
matchingVillages = matchingVillages.Where(x => x.Type.HasFlag(villageType));
}
var villagesWithAllSpeeds =
from village in matchingVillages
from speed in acceptableSpeeds
let travelTime = Village.TravelTime(plan.Target, village, speed)
select new Travelfun
{
Village = village,
Speed = speed,
TravelTime = travelTime,
TimeBeforeNeedToSend = plan.ArrivalTime - World.Default.Settings.ServerTime.Add(travelTime)
};
var villagesWithBestSpeed =
villagesWithAllSpeeds
.GroupBy(x => x.Village)
.Select(x => GetBestSpeedMatch(x.ToList()));
var villages =
villagesWithBestSpeed
.OrderBy(x => x.TimeBeforeNeedToSend)
.ToArray();
if (!villages.Any(x => x.TimeBeforeNeedToSend.TotalSeconds > AutoFindMinimumAmountOfSecondsLeft))
{
return villages.OrderByDescending(x => x.TimeBeforeNeedToSend).Take(AutoFindAmountOfAttackersWhenNone);
}
else
{
return villages.Where(x => x.TimeBeforeNeedToSend.TotalSeconds > AutoFindMinimumAmountOfSecondsLeft).Take(AutoFindAmountOfAttackers);
}
}
private static Travelfun GetBestSpeedMatch(ICollection<Travelfun> speeds)
{
speeds = speeds.OrderBy(t => t.TimeBeforeNeedToSend).ToList();
if (!speeds.Any(x => x.TimeBeforeNeedToSend.TotalSeconds > AutoFindMinimumAmountOfSecondsLeft))
{
return speeds.OrderByDescending(x => x.TimeBeforeNeedToSend).FirstOrDefault();
}
else
{
return speeds.FirstOrDefault(x => x.TimeBeforeNeedToSend.TotalSeconds > AutoFindMinimumAmountOfSecondsLeft);
}
}
#endregion
}
}
| |
#pragma warning disable 1634, 1691
using System;
using System.Diagnostics;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Workflow.Runtime;
using System.Security.Principal;
using System.Threading;
using System.Globalization;
namespace System.Workflow.Activities
{
internal interface IMethodResponseMessage
{
void SendResponse(ICollection outArgs);
void SendException(Exception exception);
Exception Exception { get; }
ICollection OutArgs { get; }
}
[Serializable]
internal sealed class MethodMessage : IMethodMessage, IMethodResponseMessage
{
[NonSerialized]
Type interfaceType;
[NonSerialized]
string methodName;
[NonSerialized]
object[] args;
[NonSerialized]
ManualResetEvent returnValueSignalEvent;
object[] clonedArgs;
LogicalCallContext callContext;
ICollection outArgs;
Exception exception;
[NonSerialized]
bool responseSet = false;
Guid callbackCookie;
[NonSerialized]
MethodMessage previousMessage = null;
static Dictionary<Guid, MethodMessage> staticMethodMessageMap = new Dictionary<Guid, MethodMessage>();
static Object syncRoot = new Object();
internal MethodMessage(Type interfaceType, string methodName,
object[] args, String identity) :
this(interfaceType, methodName, args, identity, false)
{
}
internal MethodMessage(Type interfaceType, string methodName,
object[] args, String identity, bool responseRequired)
{
this.interfaceType = interfaceType;
this.methodName = methodName;
this.args = args;
callContext = GetLogicalCallContext();
if (responseRequired)
returnValueSignalEvent = new ManualResetEvent(false);
PopulateIdentity(callContext, identity);
Clone();
}
[OnSerializing]
void OnSerializing(StreamingContext context)
{
if (returnValueSignalEvent != null && !responseSet)
{
callbackCookie = Guid.NewGuid();
lock (syncRoot)
{
staticMethodMessageMap.Add(callbackCookie, previousMessage ?? this);
}
}
}
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
if (callbackCookie != Guid.Empty)
{
lock (syncRoot)
{
if (staticMethodMessageMap.TryGetValue(callbackCookie, out previousMessage))
staticMethodMessageMap.Remove(callbackCookie);
}
if (previousMessage != null)
{
this.responseSet = previousMessage.responseSet;
this.returnValueSignalEvent = previousMessage.returnValueSignalEvent;
}
}
callbackCookie = Guid.Empty;
}
string IMethodMessage.GetArgName(int index)
{
throw new NotImplementedException();
}
object IMethodMessage.GetArg(int argNum)
{
return this.clonedArgs[argNum];
}
string IMethodMessage.Uri
{
#pragma warning disable 56503
// not implemented
get { throw new NotImplementedException(); }
#pragma warning restore 56503
}
string IMethodMessage.MethodName
{
get { return this.methodName; }
}
string IMethodMessage.TypeName
{
get
{
return (this.interfaceType.ToString());
}
}
object IMethodMessage.MethodSignature
{
#pragma warning disable 56503
get { throw new NotImplementedException(); }
#pragma warning restore 56503
}
object[] IMethodMessage.Args
{
get
{
return this.clonedArgs;
}
}
object Clone()
{
object[] clones = new object[this.args.Length];
for (int i = 0; i < this.args.Length; i++)
{
clones[i] = Clone(this.args[i]);
}
this.clonedArgs = clones;
return clones;
}
object Clone(object source)
{
if (source == null || source.GetType().IsValueType)
return source;
ICloneable clone = source as ICloneable;
if (clone != null)
return clone.Clone();
BinaryFormatter formatter = new BinaryFormatter();
System.IO.MemoryStream stream = new System.IO.MemoryStream(1024);
try
{
formatter.Serialize(stream, source);
}
catch (SerializationException e)
{
throw new InvalidOperationException(SR.GetString(SR.Error_EventArgumentSerializationException), e);
}
stream.Position = 0;
object cloned = formatter.Deserialize(stream);
return cloned;
}
int IMethodMessage.ArgCount
{
get { return this.clonedArgs.Length; }
}
bool IMethodMessage.HasVarArgs
{
#pragma warning disable 56503
get { throw new NotImplementedException(); }
#pragma warning restore 56503
}
LogicalCallContext IMethodMessage.LogicalCallContext
{
get { return callContext; }
}
MethodBase IMethodMessage.MethodBase
{
#pragma warning disable 56503
get { throw new NotImplementedException(); }
#pragma warning restore 56503
}
IDictionary System.Runtime.Remoting.Messaging.IMessage.Properties
{
#pragma warning disable 56503
get { throw new NotImplementedException(); }
#pragma warning restore 56503
}
void PopulateIdentity(LogicalCallContext callContext, String identity)
{
callContext.SetData(IdentityContextData.IdentityContext, new IdentityContextData(identity));
}
static LogicalCallContext singletonCallContext;
static Object syncObject = new Object();
static LogicalCallContext GetLogicalCallContext()
{
lock (syncObject)
{
if (singletonCallContext == null)
{
CallContextProxy contextProxy = new CallContextProxy(typeof(IDisposable));
IDisposable disposable = (IDisposable)contextProxy.GetTransparentProxy();
disposable.Dispose();
singletonCallContext = contextProxy.CallContext;
}
return singletonCallContext.Clone() as LogicalCallContext;
}
}
#region IMethodResponseMessage implementation
internal IMethodResponseMessage WaitForResponseMessage()
{
// todo wait for certain timeout
this.returnValueSignalEvent.WaitOne();
this.returnValueSignalEvent = null;
return this;
}
public void SendResponse(ICollection outArgs)
{
if (this.returnValueSignalEvent == null)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_WorkflowInstanceDehydratedBeforeSendingResponse)));
if (!this.responseSet)
{
this.OutArgs = outArgs;
this.returnValueSignalEvent.Set();
this.responseSet = true;
}
}
public void SendException(Exception exception)
{
if (this.returnValueSignalEvent == null)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_WorkflowInstanceDehydratedBeforeSendingResponse)));
if (!this.responseSet)
{
this.Exception = exception;
this.returnValueSignalEvent.Set();
this.responseSet = true;
}
}
public Exception Exception
{
get
{
return this.exception;
}
private set
{
if (previousMessage != null)
previousMessage.Exception = value;
this.exception = value;
}
}
public ICollection OutArgs
{
get
{
return this.outArgs;
}
private set
{
if (previousMessage != null)
previousMessage.OutArgs = value;
this.outArgs = value;
}
}
#endregion
private sealed class CallContextProxy : System.Runtime.Remoting.Proxies.RealProxy
{
LogicalCallContext callContext;
internal LogicalCallContext CallContext
{
get
{
return callContext;
}
}
internal CallContextProxy(Type proxiedType)
: base(proxiedType)
{
}
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
{
IMethodCallMessage methodCallMessage = msg as IMethodCallMessage;
this.callContext = methodCallMessage.LogicalCallContext.Clone() as LogicalCallContext;
return new ReturnMessage(null, null, 0, methodCallMessage.LogicalCallContext, methodCallMessage);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
namespace QuantConnect.Tests.Indicators
{
/// <summary>
/// Provides helper methods for testing indicatora
/// </summary>
public static class TestHelper
{
/// <summary>
/// Gets a stream of IndicatorDataPoints that can be fed to an indicator. The data stream starts at {DateTime.Today, 1m} and
/// increasing at {1 second, 1m}
/// </summary>
/// <param name="count">The number of data points to stream</param>
/// <param name="valueProducer">Function to produce the value of the data, null to use the index</param>
/// <returns>A stream of IndicatorDataPoints</returns>
public static IEnumerable<IndicatorDataPoint> GetDataStream(int count, Func<int, decimal> valueProducer = null)
{
var reference = DateTime.Today;
valueProducer = valueProducer ?? (x => x);
for (int i = 0; i < count; i++)
{
yield return new IndicatorDataPoint(reference.AddSeconds(i), valueProducer.Invoke(i));
}
}
/// <summary>
/// Compare the specified indicator against external data using the spy_with_indicators.txt file.
/// The 'Close' column will be fed to the indicator as input
/// </summary>
/// <param name="indicator">The indicator under test</param>
/// <param name="targetColumn">The column with the correct answers</param>
/// <param name="epsilon">The maximum delta between expected and actual</param>
public static void TestIndicator(IndicatorBase<IndicatorDataPoint> indicator, string targetColumn, double epsilon = 1e-3)
{
TestIndicator(indicator, "spy_with_indicators.txt", targetColumn, (i, expected) => Assert.AreEqual(expected, (double) i.Current.Value, epsilon));
}
/// <summary>
/// Compare the specified indicator against external data using the specificied comma delimited text file.
/// The 'Close' column will be fed to the indicator as input
/// </summary>
/// <param name="indicator">The indicator under test</param>
/// <param name="externalDataFilename"></param>
/// <param name="targetColumn">The column with the correct answers</param>
/// <param name="customAssertion">Sets custom assertion logic, parameter is the indicator, expected value from the file</param>
public static void TestIndicator(IndicatorBase<IndicatorDataPoint> indicator, string externalDataFilename, string targetColumn, Action<IndicatorBase<IndicatorDataPoint>, double> customAssertion)
{
// assumes the Date is in the first index
bool first = true;
int closeIndex = -1;
int targetIndex = -1;
foreach (var line in File.ReadLines(Path.Combine("TestData", externalDataFilename)))
{
string[] parts = line.Split(new[] {','}, StringSplitOptions.None);
if (first)
{
first = false;
for (int i = 0; i < parts.Length; i++)
{
if (parts[i].Trim() == "Close")
{
closeIndex = i;
}
if (parts[i].Trim() == targetColumn)
{
targetIndex = i;
}
}
if (closeIndex*targetIndex < 0)
{
Assert.Fail("Didn't find one of 'Close' or '{0}' in the header: " + line, targetColumn);
}
continue;
}
decimal close = decimal.Parse(parts[closeIndex], CultureInfo.InvariantCulture);
DateTime date = Time.ParseDate(parts[0]);
var data = new IndicatorDataPoint(date, close);
indicator.Update(data);
if (!indicator.IsReady || parts[targetIndex].Trim() == string.Empty)
{
continue;
}
double expected = double.Parse(parts[targetIndex], CultureInfo.InvariantCulture);
customAssertion.Invoke(indicator, expected);
}
}
/// <summary>
/// Compare the specified indicator against external data using the specificied comma delimited text file.
/// The 'Close' column will be fed to the indicator as input
/// </summary>
/// <param name="indicator">The indicator under test</param>
/// <param name="externalDataFilename"></param>
/// <param name="targetColumn">The column with the correct answers</param>
/// <param name="epsilon">The maximum delta between expected and actual</param>
public static void TestIndicator(IndicatorBase<TradeBar> indicator, string externalDataFilename, string targetColumn, double epsilon = 1e-3)
{
TestIndicator(indicator, externalDataFilename, targetColumn, (i, expected) => Assert.AreEqual(expected, (double)i.Current.Value, epsilon, "Failed at " + i.Current.Time.ToString("o")));
}
/// <summary>
/// Compare the specified indicator against external data using the specificied comma delimited text file.
/// The 'Close' column will be fed to the indicator as input
/// </summary>
/// <param name="indicator">The indicator under test</param>
/// <param name="externalDataFilename"></param>
/// <param name="targetColumn">The column with the correct answers</param>
/// <param name="selector">A function that receives the indicator as input and outputs a value to match the target column</param>
/// <param name="epsilon">The maximum delta between expected and actual</param>
public static void TestIndicator<T>(T indicator, string externalDataFilename, string targetColumn, Func<T, double> selector, double epsilon = 1e-3)
where T : Indicator
{
TestIndicator(indicator, externalDataFilename, targetColumn, (i, expected) => Assert.AreEqual(expected, selector(indicator), epsilon, "Failed at " + i.Current.Time.ToString("o")));
}
/// <summary>
/// Compare the specified indicator against external data using the specificied comma delimited text file.
/// The 'Close' column will be fed to the indicator as input
/// </summary>
/// <param name="indicator">The indicator under test</param>
/// <param name="externalDataFilename"></param>
/// <param name="targetColumn">The column with the correct answers</param>
/// <param name="customAssertion">Sets custom assertion logic, parameter is the indicator, expected value from the file</param>
public static void TestIndicator(IndicatorBase<TradeBar> indicator, string externalDataFilename, string targetColumn, Action<IndicatorBase<TradeBar>, double> customAssertion)
{
bool first = true;
int targetIndex = -1;
bool fileHasVolume = false;
foreach (var line in File.ReadLines(Path.Combine("TestData", externalDataFilename)))
{
var parts = line.Split(',');
if (first)
{
fileHasVolume = parts[5].Trim() == "Volume";
first = false;
for (int i = 0; i < parts.Length; i++)
{
if (parts[i].Trim() == targetColumn)
{
targetIndex = i;
break;
}
}
continue;
}
var tradebar = new TradeBar
{
Time = Time.ParseDate(parts[0]),
Open = parts[1].ToDecimal(),
High = parts[2].ToDecimal(),
Low = parts[3].ToDecimal(),
Close = parts[4].ToDecimal(),
Volume = fileHasVolume ? long.Parse(parts[5], NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture) : 0
};
indicator.Update(tradebar);
if (!indicator.IsReady || parts[targetIndex].Trim() == string.Empty)
{
continue;
}
double expected = double.Parse(parts[targetIndex], CultureInfo.InvariantCulture);
customAssertion.Invoke(indicator, expected);
}
}
public static IEnumerable<IReadOnlyDictionary<string, string>> GetCsvFileStream(string externalDataFilename)
{
var enumerator = File.ReadLines(Path.Combine("TestData", externalDataFilename)).GetEnumerator();
if (!enumerator.MoveNext())
{
yield break;
}
string[] header = enumerator.Current.Split(',');
while (enumerator.MoveNext())
{
var values = enumerator.Current.Split(',');
var headerAndValues = header.Zip(values, (h, v) => new {h, v});
var dictionary = headerAndValues.ToDictionary(x => x.h.Trim(), x => x.v.Trim(), StringComparer.OrdinalIgnoreCase);
yield return new ReadOnlyDictionary<string, string>(dictionary);
}
}
/// <summary>
/// Gets a stream of trade bars from the specified file
/// </summary>
public static IEnumerable<TradeBar> GetTradeBarStream(string externalDataFilename, bool fileHasVolume = true)
{
return GetCsvFileStream(externalDataFilename).Select(values => new TradeBar
{
Time = Time.ParseDate(values.GetCsvValue("date", "time")),
Open = values.GetCsvValue("open").ToDecimal(),
High = values.GetCsvValue("high").ToDecimal(),
Low = values.GetCsvValue("low").ToDecimal(),
Close = values.GetCsvValue("close").ToDecimal(),
Volume = fileHasVolume ? long.Parse(values.GetCsvValue("volume"), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture) : 0
});
}
/// <summary>
/// Asserts that the indicator has zero samples, is not ready, and has the default value
/// </summary>
/// <param name="indicator">The indicator to assert</param>
public static void AssertIndicatorIsInDefaultState<T>(IndicatorBase<T> indicator)
where T : BaseData
{
Assert.AreEqual(0m, indicator.Current.Value);
Assert.AreEqual(DateTime.MinValue, indicator.Current.Time);
Assert.AreEqual(0, indicator.Samples);
Assert.IsFalse(indicator.IsReady);
}
/// <summary>
/// Gets a customAssertion action which will gaurantee that the delta between the expected and the
/// actual continues to decrease with a lower bound as specified by the epsilon parameter. This is useful
/// for testing indicators which retain theoretically infinite information via methods such as exponential smoothing
/// </summary>
/// <param name="epsilon">The largest increase in the delta permitted</param>
/// <returns></returns>
public static Action<IndicatorBase<IndicatorDataPoint>, double> AssertDeltaDecreases(double epsilon)
{
double delta = double.MaxValue;
return (indicator, expected) =>
{
// the delta should be forever decreasing
var currentDelta = Math.Abs((double) indicator.Current.Value - expected);
if (currentDelta - delta > epsilon)
{
Assert.Fail("The delta increased!");
//Console.WriteLine(indicator.Value.Time.Date.ToShortDateString() + " - " + indicator.Value.Data.ToString("000.000") + " \t " + expected.ToString("000.000") + " \t " + currentDelta.ToString("0.000"));
}
delta = currentDelta;
};
}
/// <summary>
/// Grabs the first value from the set of keys
/// </summary>
private static string GetCsvValue(this IReadOnlyDictionary<string, string> dictionary, params string[] keys)
{
string value = null;
if (keys.Any(key => dictionary.TryGetValue(key, out value)))
{
return value;
}
throw new ArgumentException("Unable to find column: " + string.Join(", ", keys));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// 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.
//
// Author:
//
// Jordi Mas i Hernandez, jordimash@gmail.com
//
using System.Runtime.InteropServices;
using System.Collections;
using System.Drawing.Printing;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Printing
{
/// <summary>
/// This class is designed to cache the values retrieved by the
/// native printing services, as opposed to GlobalPrintingServices, which
/// doesn't cache any values.
/// </summary>
internal static class PrintingServices
{
#region Private Fields
private static readonly Hashtable doc_info = new Hashtable();
private static readonly bool cups_installed = CheckCupsInstalled();
private static readonly Hashtable installed_printers = new Hashtable();
private static string default_printer = string.Empty;
#endregion
#region Properties
internal static PrinterSettings.StringCollection InstalledPrinters
{
get
{
LoadPrinters();
PrinterSettings.StringCollection list = new PrinterSettings.StringCollection(Array.Empty<string>());
foreach (object key in installed_printers.Keys)
{
list.Add(key.ToString());
}
return list;
}
}
internal static string DefaultPrinter
{
get
{
if (installed_printers.Count == 0)
LoadPrinters();
return default_printer;
}
}
#endregion
#region Methods
/// <summary>
/// Do a cups call to check if it is installed
/// </summary>
private static bool CheckCupsInstalled()
{
try
{
LibcupsNative.cupsGetDefault();
}
catch (DllNotFoundException)
{
System.Diagnostics.Debug.WriteLine("libcups not found. To have printing support, you need cups installed");
return false;
}
return true;
}
/// <summary>
/// Open the printer's PPD file
/// </summary>
/// <param name="printer">Printer name, returned from cupsGetDests</param>
private static IntPtr OpenPrinter(string printer)
{
try
{
IntPtr ptr = LibcupsNative.cupsGetPPD(printer);
string ppd_filename = Marshal.PtrToStringAnsi(ptr);
IntPtr ppd_handle = LibcupsNative.ppdOpenFile(ppd_filename);
return ppd_handle;
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
}
return IntPtr.Zero;
}
/// <summary>
/// Close the printer file
/// </summary>
/// <param name="handle">PPD handle</param>
private static void ClosePrinter(ref IntPtr handle)
{
try
{
if (handle != IntPtr.Zero)
LibcupsNative.ppdClose(handle);
}
finally
{
handle = IntPtr.Zero;
}
}
private static int OpenDests(ref IntPtr ptr)
{
try
{
return LibcupsNative.cupsGetDests(ref ptr);
}
catch
{
ptr = IntPtr.Zero;
}
return 0;
}
private static void CloseDests(ref IntPtr ptr, int count)
{
try
{
if (ptr != IntPtr.Zero)
LibcupsNative.cupsFreeDests(count, ptr);
}
finally
{
ptr = IntPtr.Zero;
}
}
/// <summary>
/// Checks if a printer has a valid PPD file. Caches the result unless force is true
/// </summary>
/// <param name="printer">Printer name</param>
internal static bool IsPrinterValid(string printer)
{
if (!cups_installed || printer == null | printer == string.Empty)
return false;
return installed_printers.Contains(printer);
}
/// <summary>
/// Loads the printer settings and initializes the PrinterSettings and PageSettings fields
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to initialize</param>
internal static void LoadPrinterSettings(string printer, PrinterSettings settings)
{
if (cups_installed == false || (printer == null) || (printer == string.Empty))
return;
if (installed_printers.Count == 0)
LoadPrinters();
if (((SysPrn.Printer)installed_printers[printer]).Settings != null)
{
SysPrn.Printer p = (SysPrn.Printer)installed_printers[printer];
settings.can_duplex = p.Settings.can_duplex;
settings.is_plotter = p.Settings.is_plotter;
settings.landscape_angle = p.Settings.landscape_angle;
settings.maximum_copies = p.Settings.maximum_copies;
settings.paper_sizes = p.Settings.paper_sizes;
settings.paper_sources = p.Settings.paper_sources;
settings.printer_capabilities = p.Settings.printer_capabilities;
settings.printer_resolutions = p.Settings.printer_resolutions;
settings.supports_color = p.Settings.supports_color;
return;
}
settings.PrinterCapabilities.Clear();
IntPtr dests = IntPtr.Zero, ptr = IntPtr.Zero, ptr_printer, ppd_handle = IntPtr.Zero;
string name = string.Empty;
CUPS_DESTS printer_dest;
PPD_FILE ppd;
int ret = 0, cups_dests_size;
NameValueCollection options, paper_names, paper_sources;
try
{
ret = OpenDests(ref dests);
if (ret == 0)
return;
cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
ptr = dests;
for (int i = 0; i < ret; i++)
{
ptr_printer = (IntPtr)Marshal.ReadIntPtr(ptr);
if (Marshal.PtrToStringAnsi(ptr_printer).Equals(printer))
{
name = printer;
break;
}
ptr = (IntPtr)((long)ptr + cups_dests_size);
}
if (!name.Equals(printer))
{
return;
}
ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
return;
printer_dest = (CUPS_DESTS)Marshal.PtrToStructure(ptr, typeof(CUPS_DESTS));
options = new NameValueCollection();
paper_names = new NameValueCollection();
paper_sources = new NameValueCollection();
string defsize;
string defsource;
LoadPrinterOptions(printer_dest.options, printer_dest.num_options, ppd_handle, options,
paper_names, out defsize,
paper_sources, out defsource);
if (settings.paper_sizes == null)
settings.paper_sizes = new PrinterSettings.PaperSizeCollection(Array.Empty<PaperSize>());
else
settings.paper_sizes.Clear();
if (settings.paper_sources == null)
settings.paper_sources = new PrinterSettings.PaperSourceCollection(Array.Empty<PaperSource>());
else
settings.paper_sources.Clear();
settings.DefaultPageSettings.PaperSource = LoadPrinterPaperSources(settings, defsource, paper_sources);
settings.DefaultPageSettings.PaperSize = LoadPrinterPaperSizes(ppd_handle, settings, defsize, paper_names);
LoadPrinterResolutionsAndDefault(printer, settings, ppd_handle);
ppd = (PPD_FILE)Marshal.PtrToStructure(ppd_handle, typeof(PPD_FILE));
settings.landscape_angle = ppd.landscape;
settings.supports_color = (ppd.color_device == 0) ? false : true;
settings.can_duplex = options["Duplex"] != null;
ClosePrinter(ref ppd_handle);
((SysPrn.Printer)installed_printers[printer]).Settings = settings;
}
finally
{
CloseDests(ref dests, ret);
}
}
/// <summary>
/// Loads the global options of a printer plus the paper types and trays supported,
/// and sets the default paper size and source tray.
/// </summary>
/// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
/// <param name="numOptions">The number of options of the printer</param>
/// <param name="ppd">A ppd handle for the printer, returned by ppdOpen</param>
/// <param name="list">The list of options</param>
/// <param name="paper_names">A list of types of paper (PageSize)</param>
/// <param name="defsize">The default paper size, set by LoadOptionList</param>
/// <param name="paper_sources">A list of trays(InputSlot) </param>
/// <param name="defsource">The default source tray, set by LoadOptionList</param>
private static void LoadPrinterOptions(IntPtr options, int numOptions, IntPtr ppd,
NameValueCollection list,
NameValueCollection paper_names, out string defsize,
NameValueCollection paper_sources, out string defsource)
{
CUPS_OPTIONS cups_options;
string option_name, option_value;
int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
LoadOptionList(ppd, "PageSize", paper_names, out defsize);
LoadOptionList(ppd, "InputSlot", paper_sources, out defsource);
for (int j = 0; j < numOptions; j++)
{
cups_options = (CUPS_OPTIONS)Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
option_name = Marshal.PtrToStringAnsi(cups_options.name);
option_value = Marshal.PtrToStringAnsi(cups_options.val);
if (option_name == "PageSize")
defsize = option_value;
else if (option_name == "InputSlot")
defsource = option_value;
#if PrintDebug
Console.WriteLine("{0} = {1}", option_name, option_value);
#endif
list.Add(option_name, option_value);
options = (IntPtr)((long)options + cups_size);
}
}
/// <summary>
/// Loads the global options of a printer.
/// </summary>
/// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
/// <param name="numOptions">The number of options of the printer</param>
private static NameValueCollection LoadPrinterOptions(IntPtr options, int numOptions)
{
CUPS_OPTIONS cups_options;
string option_name, option_value;
int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
NameValueCollection list = new NameValueCollection();
for (int j = 0; j < numOptions; j++)
{
cups_options = (CUPS_OPTIONS)Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
option_name = Marshal.PtrToStringAnsi(cups_options.name);
option_value = Marshal.PtrToStringAnsi(cups_options.val);
#if PrintDebug
Console.WriteLine("{0} = {1}", option_name, option_value);
#endif
list.Add(option_name, option_value);
options = (IntPtr)((long)options + cups_size);
}
return list;
}
/// <summary>
/// Loads a printer's options (selection of paper sizes, paper sources, etc)
/// and sets the default option from the selected list.
/// </summary>
/// <param name="ppd">Printer ppd file handle</param>
/// <param name="option_name">Name of the option group to load</param>
/// <param name="list">List of loaded options</param>
/// <param name="defoption">The default option from the loaded options list</param>
private static void LoadOptionList(IntPtr ppd, string option_name, NameValueCollection list, out string defoption)
{
IntPtr ptr = IntPtr.Zero;
PPD_OPTION ppd_option;
PPD_CHOICE choice;
int choice_size = Marshal.SizeOf(typeof(PPD_CHOICE));
defoption = null;
ptr = LibcupsNative.ppdFindOption(ppd, option_name);
if (ptr != IntPtr.Zero)
{
ppd_option = (PPD_OPTION)Marshal.PtrToStructure(ptr, typeof(PPD_OPTION));
#if PrintDebug
Console.WriteLine (" OPTION key:{0} def:{1} text: {2}", ppd_option.keyword, ppd_option.defchoice, ppd_option.text);
#endif
defoption = ppd_option.defchoice;
ptr = ppd_option.choices;
for (int c = 0; c < ppd_option.num_choices; c++)
{
choice = (PPD_CHOICE)Marshal.PtrToStructure(ptr, typeof(PPD_CHOICE));
list.Add(choice.choice, choice.text);
#if PrintDebug
Console.WriteLine (" choice:{0} - text: {1}", choice.choice, choice.text);
#endif
ptr = (IntPtr)((long)ptr + choice_size);
}
}
}
/// <summary>
/// Loads a printer's available resolutions
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to fill</param>
internal static void LoadPrinterResolutions(string printer, PrinterSettings settings)
{
IntPtr ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
return;
LoadPrinterResolutionsAndDefault(printer, settings, ppd_handle);
ClosePrinter(ref ppd_handle);
}
/// <summary>
/// Create a PrinterResolution from a string Resolution that is set in the PPD option.
/// An example of Resolution is "600x600dpi" or "600dpi". Returns null if malformed or "Unknown".
/// </summary>
private static PrinterResolution ParseResolution(string resolution)
{
if (string.IsNullOrEmpty(resolution))
return null;
int dpiIndex = resolution.IndexOf("dpi");
if (dpiIndex == -1)
{
// Resolution is "Unknown" or unparsable
return null;
}
resolution = resolution.Substring(0, dpiIndex);
int x_resolution, y_resolution;
try
{
if (resolution.Contains("x")) // string.Contains(char) is .NetCore2.1+ specific
{
string[] resolutions = resolution.Split(new[] { 'x' });
x_resolution = Convert.ToInt32(resolutions[0]);
y_resolution = Convert.ToInt32(resolutions[1]);
}
else
{
x_resolution = Convert.ToInt32(resolution);
y_resolution = x_resolution;
}
}
catch (Exception)
{
return null;
}
return new PrinterResolution(PrinterResolutionKind.Custom, x_resolution, y_resolution);
}
/// <summary>
/// Loads a printer's paper sizes. Returns the default PaperSize, and fills a list of paper_names for use in dialogues
/// </summary>
/// <param name="ppd_handle">PPD printer file handle</param>
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_size">Default paper size, from the global options of the printer</param>
/// <param name="paper_names">List of available paper sizes that gets filled</param>
private static PaperSize LoadPrinterPaperSizes(IntPtr ppd_handle, PrinterSettings settings,
string def_size, NameValueCollection paper_names)
{
IntPtr ptr;
string real_name;
PPD_FILE ppd;
PPD_SIZE size;
PaperSize ps;
PaperSize defsize = new PaperSize(GetPaperKind(827, 1169), "A4", 827, 1169);
ppd = (PPD_FILE)Marshal.PtrToStructure(ppd_handle, typeof(PPD_FILE));
ptr = ppd.sizes;
float w, h;
for (int i = 0; i < ppd.num_sizes; i++)
{
size = (PPD_SIZE)Marshal.PtrToStructure(ptr, typeof(PPD_SIZE));
real_name = paper_names[size.name];
w = size.width * 100 / 72;
h = size.length * 100 / 72;
PaperKind kind = GetPaperKind((int)w, (int)h);
ps = new PaperSize(kind, real_name, (int)w, (int)h);
ps.RawKind = (int)kind;
if (def_size == ps.Kind.ToString())
defsize = ps;
settings.paper_sizes.Add(ps);
ptr = (IntPtr)((long)ptr + Marshal.SizeOf(size));
}
return defsize;
}
/// <summary>
/// Loads a printer's paper sources (trays). Returns the default PaperSource, and fills a list of paper_sources for use in dialogues
/// </summary>
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_source">Default paper source, from the global options of the printer</param>
/// <param name="paper_sources">List of available paper sizes that gets filled</param>
private static PaperSource LoadPrinterPaperSources(PrinterSettings settings, string def_source,
NameValueCollection paper_sources)
{
PaperSourceKind kind;
PaperSource defsource = null;
foreach (string source in paper_sources)
{
switch (source)
{
case "Auto":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Standard":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Tray":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Envelope":
kind = PaperSourceKind.Envelope;
break;
case "Manual":
kind = PaperSourceKind.Manual;
break;
default:
kind = PaperSourceKind.Custom;
break;
}
settings.paper_sources.Add(new PaperSource(kind, paper_sources[source]));
if (def_source == source)
defsource = settings.paper_sources[settings.paper_sources.Count - 1];
}
if (defsource == null && settings.paper_sources.Count > 0)
return settings.paper_sources[0];
return defsource;
}
/// <summary>
/// Sets the available resolutions and default resolution from a
/// printer's PPD file into settings.
/// </summary>
private static void LoadPrinterResolutionsAndDefault(string printer,
PrinterSettings settings, IntPtr ppd_handle)
{
if (settings.printer_resolutions == null)
settings.printer_resolutions = new PrinterSettings.PrinterResolutionCollection(Array.Empty<PrinterResolution>());
else
settings.printer_resolutions.Clear();
var printer_resolutions = new NameValueCollection();
string defresolution;
LoadOptionList(ppd_handle, "Resolution", printer_resolutions, out defresolution);
foreach (var resolution in printer_resolutions.Keys)
{
var new_resolution = ParseResolution(resolution.ToString());
settings.PrinterResolutions.Add(new_resolution);
}
var default_resolution = ParseResolution(defresolution);
if (default_resolution == null)
default_resolution = ParseResolution("300dpi");
if (printer_resolutions.Count == 0)
settings.PrinterResolutions.Add(default_resolution);
settings.DefaultPageSettings.PrinterResolution = default_resolution;
}
/// <summary>
/// </summary>
private static void LoadPrinters()
{
installed_printers.Clear();
if (cups_installed == false)
return;
IntPtr dests = IntPtr.Zero, ptr_printers;
CUPS_DESTS printer;
int n_printers = 0;
int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
string name, first, type, status, comment;
first = type = status = comment = string.Empty;
int state = 0;
try
{
n_printers = OpenDests(ref dests);
ptr_printers = dests;
for (int i = 0; i < n_printers; i++)
{
printer = (CUPS_DESTS)Marshal.PtrToStructure(ptr_printers, typeof(CUPS_DESTS));
name = Marshal.PtrToStringAnsi(printer.name);
if (printer.is_default == 1)
default_printer = name;
if (first.Equals(string.Empty))
first = name;
NameValueCollection options = LoadPrinterOptions(printer.options, printer.num_options);
if (options["printer-state"] != null)
state = int.Parse(options["printer-state"]);
if (options["printer-comment"] != null)
comment = options["printer-state"];
switch (state)
{
case 4:
status = "Printing";
break;
case 5:
status = "Stopped";
break;
default:
status = "Ready";
break;
}
installed_printers.Add(name, new SysPrn.Printer(string.Empty, type, status, comment));
ptr_printers = (IntPtr)((long)ptr_printers + cups_dests_size);
}
}
finally
{
CloseDests(ref dests, n_printers);
}
if (default_printer.Equals(string.Empty))
default_printer = first;
}
/// <summary>
/// Gets a printer's settings for use in the print dialogue
/// </summary>
/// <param name="printer"></param>
/// <param name="port"></param>
/// <param name="type"></param>
/// <param name="status"></param>
/// <param name="comment"></param>
internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
int count = 0, state = -1;
bool found = false;
CUPS_DESTS cups_dests;
IntPtr dests = IntPtr.Zero, ptr_printers, ptr_printer;
int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
if (cups_installed == false)
return;
try
{
count = OpenDests(ref dests);
if (count == 0)
return;
ptr_printers = dests;
for (int i = 0; i < count; i++)
{
ptr_printer = (IntPtr)Marshal.ReadIntPtr(ptr_printers);
if (Marshal.PtrToStringAnsi(ptr_printer).Equals(printer))
{
found = true;
break;
}
ptr_printers = (IntPtr)((long)ptr_printers + cups_dests_size);
}
if (!found)
return;
cups_dests = (CUPS_DESTS)Marshal.PtrToStructure(ptr_printers, typeof(CUPS_DESTS));
NameValueCollection options = LoadPrinterOptions(cups_dests.options, cups_dests.num_options);
if (options["printer-state"] != null)
state = int.Parse(options["printer-state"]);
if (options["printer-comment"] != null)
comment = options["printer-state"];
switch (state)
{
case 4:
status = "Printing";
break;
case 5:
status = "Stopped";
break;
default:
status = "Ready";
break;
}
}
finally
{
CloseDests(ref dests, count);
}
}
/// <summary>
/// Returns the appropriate PaperKind for the width and height
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
private static PaperKind GetPaperKind(int width, int height)
{
if (width == 827 && height == 1169)
return PaperKind.A4;
if (width == 583 && height == 827)
return PaperKind.A5;
if (width == 717 && height == 1012)
return PaperKind.B5;
if (width == 693 && height == 984)
return PaperKind.B5Envelope;
if (width == 638 && height == 902)
return PaperKind.C5Envelope;
if (width == 449 && height == 638)
return PaperKind.C6Envelope;
if (width == 1700 && height == 2200)
return PaperKind.CSheet;
if (width == 433 && height == 866)
return PaperKind.DLEnvelope;
if (width == 2200 && height == 3400)
return PaperKind.DSheet;
if (width == 3400 && height == 4400)
return PaperKind.ESheet;
if (width == 725 && height == 1050)
return PaperKind.Executive;
if (width == 850 && height == 1300)
return PaperKind.Folio;
if (width == 850 && height == 1200)
return PaperKind.GermanStandardFanfold;
if (width == 1700 && height == 1100)
return PaperKind.Ledger;
if (width == 850 && height == 1400)
return PaperKind.Legal;
if (width == 927 && height == 1500)
return PaperKind.LegalExtra;
if (width == 850 && height == 1100)
return PaperKind.Letter;
if (width == 927 && height == 1200)
return PaperKind.LetterExtra;
if (width == 850 && height == 1269)
return PaperKind.LetterPlus;
if (width == 387 && height == 750)
return PaperKind.MonarchEnvelope;
if (width == 387 && height == 887)
return PaperKind.Number9Envelope;
if (width == 413 && height == 950)
return PaperKind.Number10Envelope;
if (width == 450 && height == 1037)
return PaperKind.Number11Envelope;
if (width == 475 && height == 1100)
return PaperKind.Number12Envelope;
if (width == 500 && height == 1150)
return PaperKind.Number14Envelope;
if (width == 363 && height == 650)
return PaperKind.PersonalEnvelope;
if (width == 1000 && height == 1100)
return PaperKind.Standard10x11;
if (width == 1000 && height == 1400)
return PaperKind.Standard10x14;
if (width == 1100 && height == 1700)
return PaperKind.Standard11x17;
if (width == 1200 && height == 1100)
return PaperKind.Standard12x11;
if (width == 1500 && height == 1100)
return PaperKind.Standard15x11;
if (width == 900 && height == 1100)
return PaperKind.Standard9x11;
if (width == 550 && height == 850)
return PaperKind.Statement;
if (width == 1100 && height == 1700)
return PaperKind.Tabloid;
if (width == 1487 && height == 1100)
return PaperKind.USStandardFanfold;
return PaperKind.Custom;
}
#endregion
#region Print job methods
private static string tmpfile;
/// <summary>
/// Gets a pointer to an options list parsed from the printer's current settings, to use when setting up the printing job
/// </summary>
/// <param name="printer_settings"></param>
/// <param name="page_settings"></param>
/// <param name="options"></param>
internal static int GetCupsOptions(PrinterSettings printer_settings, PageSettings page_settings, out IntPtr options)
{
options = IntPtr.Zero;
PaperSize size = page_settings.PaperSize;
int width = size.Width * 72 / 100;
int height = size.Height * 72 / 100;
var sb = new StringBuilder();
sb.Append("copies=").Append(printer_settings.Copies).Append(' ')
.Append("Collate=").Append(printer_settings.Collate).Append(' ')
.Append("ColorModel=").Append(page_settings.Color ? "Color" : "Black").Append(' ')
.Append("PageSize=Custom.").Append(width).Append('x').Append(height).Append(' ')
.Append("landscape=").Append(page_settings.Landscape);
if (printer_settings.CanDuplex)
{
if (printer_settings.Duplex == Duplex.Simplex)
{
sb.Append(" Duplex=None");
}
else
{
sb.Append(" Duplex=DuplexNoTumble");
}
}
return LibcupsNative.cupsParseOptions(sb.ToString(), 0, ref options);
}
internal static bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
{
DOCINFO doc = (DOCINFO)doc_info[gr.Hdc];
doc.title = doc_name;
return true;
}
internal static bool EndDoc(GraphicsPrinter gr)
{
DOCINFO doc = (DOCINFO)doc_info[gr.Hdc];
gr.Graphics.Dispose(); // Dispose object to force surface finish
IntPtr options;
int options_count = GetCupsOptions(doc.settings, doc.default_page_settings, out options);
LibcupsNative.cupsPrintFile(doc.settings.PrinterName, doc.filename, doc.title, options_count, options);
LibcupsNative.cupsFreeOptions(options_count, options);
doc_info.Remove(gr.Hdc);
if (tmpfile != null)
{
try
{ File.Delete(tmpfile); }
catch { }
}
return true;
}
internal static bool StartPage(GraphicsPrinter gr)
{
return true;
}
internal static bool EndPage(GraphicsPrinter gr)
{
Gdip.GdipGetPostScriptSavePage(gr.Hdc);
return true;
}
// Unfortunately, PrinterSettings and PageSettings couldn't be referencing each other,
// thus we need to pass them separately
internal static IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
{
IntPtr graphics = IntPtr.Zero;
string name;
if (!settings.PrintToFile)
{
StringBuilder sb = new StringBuilder(1024);
int length = sb.Capacity;
LibcupsNative.cupsTempFd(sb, length);
name = sb.ToString();
tmpfile = name;
}
else
name = settings.PrintFileName;
PaperSize psize = default_page_settings.PaperSize;
int width, height;
if (default_page_settings.Landscape)
{ // Swap in case of landscape
width = psize.Height;
height = psize.Width;
}
else
{
width = psize.Width;
height = psize.Height;
}
Gdip.GdipGetPostScriptGraphicsContext(name,
width * 72 / 100,
height * 72 / 100,
default_page_settings.PrinterResolution.X,
default_page_settings.PrinterResolution.Y, ref graphics);
DOCINFO doc = new DOCINFO();
doc.filename = name;
doc.settings = settings;
doc.default_page_settings = default_page_settings;
doc_info.Add(graphics, doc);
return graphics;
}
#endregion
#pragma warning disable 649
#region Struct
public struct DOCINFO
{
public PrinterSettings settings;
public PageSettings default_page_settings;
public string title;
public string filename;
}
public struct PPD_SIZE
{
public int marked;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
public string name;
public float width;
public float length;
public float left;
public float bottom;
public float right;
public float top;
}
public struct PPD_GROUP
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 40)]
public string text;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
public string name;
public int num_options;
public IntPtr options;
public int num_subgroups;
public IntPtr subgrups;
}
public struct PPD_OPTION
{
public byte conflicted;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string keyword;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string defchoice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string text;
public int ui;
public int section;
public float order;
public int num_choices;
public IntPtr choices;
}
public struct PPD_CHOICE
{
public byte marked;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string choice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string text;
public IntPtr code;
public IntPtr option;
}
public struct PPD_FILE
{
public int language_level;
public int color_device;
public int variable_sizes;
public int accurate_screens;
public int contone_only;
public int landscape;
public int model_number;
public int manual_copies;
public int throughput;
public int colorspace;
public IntPtr patches;
public int num_emulations;
public IntPtr emulations;
public IntPtr jcl_begin;
public IntPtr jcl_ps;
public IntPtr jcl_end;
public IntPtr lang_encoding;
public IntPtr lang_version;
public IntPtr modelname;
public IntPtr ttrasterizer;
public IntPtr manufacturer;
public IntPtr product;
public IntPtr nickname;
public IntPtr shortnickname;
public int num_groups;
public IntPtr groups;
public int num_sizes;
public IntPtr sizes;
/* There is more data after this that we are not using*/
}
public struct CUPS_OPTIONS
{
public IntPtr name;
public IntPtr val;
}
public struct CUPS_DESTS
{
public IntPtr name;
public IntPtr instance;
public int is_default;
public int num_options;
public IntPtr options;
}
#endregion
#pragma warning restore 649
internal static void LoadDefaultResolutions(PrinterSettings.PrinterResolutionCollection col)
{
col.Add(new PrinterResolution(PrinterResolutionKind.High, (int)PrinterResolutionKind.High, -1));
col.Add(new PrinterResolution(PrinterResolutionKind.Medium, (int)PrinterResolutionKind.Medium, -1));
col.Add(new PrinterResolution(PrinterResolutionKind.Low, (int)PrinterResolutionKind.Low, -1));
col.Add(new PrinterResolution(PrinterResolutionKind.Draft, (int)PrinterResolutionKind.Draft, -1));
}
}
internal class SysPrn
{
internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
PrintingServices.GetPrintDialogInfo(printer, ref port, ref type, ref status, ref comment);
}
internal class Printer
{
public readonly string Comment;
public readonly string Port;
public readonly string Type;
public readonly string Status;
public PrinterSettings Settings;
public Printer(string port, string type, string status, string comment)
{
Port = port;
Type = type;
Status = status;
Comment = comment;
}
}
}
internal class GraphicsPrinter
{
private Graphics graphics;
private IntPtr hDC;
internal GraphicsPrinter(Graphics gr, IntPtr dc)
{
graphics = gr;
hDC = dc;
}
internal Graphics Graphics
{
get { return graphics; }
set { graphics = value; }
}
internal IntPtr Hdc { get { return hDC; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Vegvesen.Web.Areas.HelpPage.ModelDescriptions;
using Vegvesen.Web.Areas.HelpPage.Models;
namespace Vegvesen.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Util
{
using System;
using System.Collections;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using NPOI.HSSF.Record;
/// <summary>
/// Various utility functions that make working with a cells and rows easier. The various
/// methods that deal with style's allow you to Create your HSSFCellStyles as you need them.
/// When you apply a style change to a cell, the code will attempt to see if a style already
/// exists that meets your needs. If not, then it will Create a new style. This is to prevent
/// creating too many styles. there is an upper limit in Excel on the number of styles that
/// can be supported.
/// @author Eric Pugh epugh@upstate.com
/// </summary>
public class HSSFCellUtil
{
public const string ALIGNMENT = "alignment";
public const string BORDER_BOTTOM = "borderBottom";
public const string BORDER_LEFT = "borderLeft";
public const string BORDER_RIGHT = "borderRight";
public const string BORDER_TOP = "borderTop";
public const string BOTTOM_BORDER_COLOR = "bottomBorderColor";
public const string DATA_FORMAT = "dataFormat";
public const string FILL_BACKGROUND_COLOR = "fillBackgroundColor";
public const string FILL_FOREGROUND_COLOR = "fillForegroundColor";
public const string FILL_PATTERN = "fillPattern";
public const string FONT = "font";
public const string HIDDEN = "hidden";
public const string INDENTION = "indention";
public const string LEFT_BORDER_COLOR = "leftBorderColor";
public const string LOCKED = "locked";
public const string RIGHT_BORDER_COLOR = "rightBorderColor";
public const string ROTATION = "rotation";
public const string TOP_BORDER_COLOR = "topBorderColor";
public const string VERTICAL_ALIGNMENT = "verticalAlignment";
public const string WRAP_TEXT = "wrapText";
private static UnicodeMapping[] unicodeMappings;
static HSSFCellUtil()
{
unicodeMappings = new UnicodeMapping[15];
unicodeMappings[0] = um("alpha", "\u03B1");
unicodeMappings[1] = um("beta", "\u03B2");
unicodeMappings[2] = um("gamma", "\u03B3");
unicodeMappings[3] = um("delta", "\u03B4");
unicodeMappings[4] = um("epsilon", "\u03B5");
unicodeMappings[5] = um("zeta", "\u03B6");
unicodeMappings[6] = um("eta", "\u03B7");
unicodeMappings[7] = um("theta", "\u03B8");
unicodeMappings[8] = um("iota", "\u03B9");
unicodeMappings[9] = um("kappa", "\u03BA");
unicodeMappings[10] = um("lambda", "\u03BB");
unicodeMappings[11] = um("mu", "\u03BC");
unicodeMappings[12] = um("nu", "\u03BD");
unicodeMappings[13] = um("xi", "\u03BE");
unicodeMappings[14] = um("omicron", "\u03BF");
}
private class UnicodeMapping
{
public String entityName;
public String resolvedValue;
public UnicodeMapping(String pEntityName, String pResolvedValue)
{
entityName = "&" + pEntityName + ";";
resolvedValue = pResolvedValue;
}
}
private HSSFCellUtil()
{
// no instances of this class
}
/// <summary>
/// Get a row from the spreadsheet, and Create it if it doesn't exist.
/// </summary>
/// <param name="rowCounter">The 0 based row number</param>
/// <param name="sheet">The sheet that the row is part of.</param>
/// <returns>The row indicated by the rowCounter</returns>
public static IRow GetRow(int rowCounter, HSSFSheet sheet)
{
IRow row = sheet.GetRow(rowCounter);
if (row == null)
{
row = sheet.CreateRow(rowCounter);
}
return row;
}
/// <summary>
/// Get a specific cell from a row. If the cell doesn't exist,
/// </summary>
/// <param name="row">The row that the cell is part of</param>
/// <param name="column">The column index that the cell is in.</param>
/// <returns>The cell indicated by the column.</returns>
public static ICell GetCell(IRow row, int column)
{
ICell cell = row.GetCell(column);
if (cell == null)
{
cell = row.CreateCell(column);
}
return cell;
}
/// <summary>
/// Creates a cell, gives it a value, and applies a style if provided
/// </summary>
/// <param name="row">the row to Create the cell in</param>
/// <param name="column">the column index to Create the cell in</param>
/// <param name="value">The value of the cell</param>
/// <param name="style">If the style is not null, then Set</param>
/// <returns>A new HSSFCell</returns>
public static ICell CreateCell(IRow row, int column, String value, HSSFCellStyle style)
{
ICell cell = GetCell(row, column);
cell.SetCellValue(new HSSFRichTextString(value));
if (style != null)
{
cell.CellStyle = (style);
}
return cell;
}
/// <summary>
/// Create a cell, and give it a value.
/// </summary>
/// <param name="row">the row to Create the cell in</param>
/// <param name="column">the column index to Create the cell in</param>
/// <param name="value">The value of the cell</param>
/// <returns>A new HSSFCell.</returns>
public static ICell CreateCell(IRow row, int column, String value)
{
return CreateCell(row, column, value, null);
}
/// <summary>
/// Translate color palette entries from the source to the destination sheet
/// </summary>
private static void RemapCellStyle(HSSFCellStyle stylish, Dictionary<short, short> paletteMap)
{
if (paletteMap.ContainsKey(stylish.BorderDiagonalColor))
{
stylish.BorderDiagonalColor = paletteMap[stylish.BorderDiagonalColor];
}
if (paletteMap.ContainsKey(stylish.BottomBorderColor))
{
stylish.BottomBorderColor = paletteMap[stylish.BottomBorderColor];
}
if (paletteMap.ContainsKey(stylish.FillBackgroundColor))
{
stylish.FillBackgroundColor = paletteMap[stylish.FillBackgroundColor];
}
if (paletteMap.ContainsKey(stylish.FillForegroundColor))
{
stylish.FillForegroundColor = paletteMap[stylish.FillForegroundColor];
}
if (paletteMap.ContainsKey(stylish.LeftBorderColor))
{
stylish.LeftBorderColor = paletteMap[stylish.LeftBorderColor];
}
if (paletteMap.ContainsKey(stylish.RightBorderColor))
{
stylish.RightBorderColor = paletteMap[stylish.RightBorderColor];
}
if (paletteMap.ContainsKey(stylish.TopBorderColor))
{
stylish.TopBorderColor = paletteMap[stylish.TopBorderColor];
}
}
public static void CopyCell(HSSFCell oldCell, HSSFCell newCell, IDictionary<Int32, HSSFCellStyle> styleMap, Dictionary<short, short> paletteMap, Boolean keepFormulas)
{
if (styleMap != null)
{
if (oldCell.CellStyle != null)
{
if (oldCell.Sheet.Workbook == newCell.Sheet.Workbook)
{
newCell.CellStyle = oldCell.CellStyle;
}
else
{
int styleHashCode = oldCell.CellStyle.GetHashCode();
if (styleMap.ContainsKey(styleHashCode))
{
newCell.CellStyle = styleMap[styleHashCode];
}
else
{
HSSFCellStyle newCellStyle = (HSSFCellStyle)newCell.Sheet.Workbook.CreateCellStyle();
newCellStyle.CloneStyleFrom(oldCell.CellStyle);
RemapCellStyle(newCellStyle, paletteMap); //Clone copies as-is, we need to remap colors manually
newCell.CellStyle = newCellStyle;
//Clone of cell style always clones the font. This makes my life easier
IFont theFont = newCellStyle.GetFont(newCell.Sheet.Workbook);
if (theFont.Color > 0 && paletteMap.ContainsKey(theFont.Color))
{
theFont.Color = paletteMap[theFont.Color]; //Remap font color
}
styleMap.Add(styleHashCode, newCellStyle);
}
}
}
else
{
newCell.CellStyle = null;
}
}
switch (oldCell.CellType)
{
case CellType.String:
HSSFRichTextString rts= oldCell.RichStringCellValue as HSSFRichTextString;
newCell.SetCellValue(rts);
if(rts!=null)
{
for (int j = 0; j < rts.NumFormattingRuns; j++)
{
short fontIndex = rts.GetFontOfFormattingRun(j);
int startIndex = rts.GetIndexOfFormattingRun(j);
int endIndex = 0;
if (j + 1 == rts.NumFormattingRuns)
{
endIndex = rts.Length;
}
else
{
endIndex = rts.GetIndexOfFormattingRun(j+1);
}
FontRecord fr = newCell.BoundWorkbook.CreateNewFont();
fr.CloneStyleFrom(oldCell.BoundWorkbook.GetFontRecordAt(fontIndex));
HSSFFont font = new HSSFFont((short)(newCell.BoundWorkbook.GetFontIndex(fr)), fr);
newCell.RichStringCellValue.ApplyFont(startIndex,endIndex, font);
}
}
break;
case CellType.Numeric:
newCell.SetCellValue(oldCell.NumericCellValue);
break;
case CellType.Blank:
newCell.SetCellType(CellType.Blank);
break;
case CellType.Boolean:
newCell.SetCellValue(oldCell.BooleanCellValue);
break;
case CellType.Error:
newCell.SetCellValue(oldCell.ErrorCellValue);
break;
case CellType.Formula:
if (keepFormulas)
{
newCell.SetCellType(CellType.Formula);
newCell.CellFormula = oldCell.CellFormula;
}
else
{
try
{
newCell.SetCellType(CellType.Numeric);
newCell.SetCellValue(oldCell.NumericCellValue);
}
catch (Exception)
{
newCell.SetCellType(CellType.String);
newCell.SetCellValue(oldCell.ToString());
}
}
break;
default:
break;
}
}
/// <summary>
/// Take a cell, and align it.
/// </summary>
/// <param name="cell">the cell to Set the alignment for</param>
/// <param name="workbook">The workbook that is being worked with.</param>
/// <param name="align">the column alignment to use.</param>
public static void SetAlignment(ICell cell, HSSFWorkbook workbook, short align)
{
SetCellStyleProperty(cell, workbook, ALIGNMENT, align);
}
/// <summary>
/// Take a cell, and apply a font to it
/// </summary>
/// <param name="cell">the cell to Set the alignment for</param>
/// <param name="workbook">The workbook that is being worked with.</param>
/// <param name="font">The HSSFFont that you want to Set...</param>
public static void SetFont(ICell cell, HSSFWorkbook workbook, HSSFFont font)
{
SetCellStyleProperty(cell, workbook, FONT, font);
}
private static bool CompareHashTableKeyValueIsEqual(Hashtable a, Hashtable b)
{
foreach (DictionaryEntry a_entry in a)
{
foreach (DictionaryEntry b_entry in b)
{
if (a_entry.Key.ToString() == b_entry.Key.ToString())
{
if ((a_entry.Value is short && b_entry.Value is short
&& (short)a_entry.Value != (short)b_entry.Value) ||
(a_entry.Value is bool && b_entry.Value is bool
&& (bool)a_entry.Value != (bool)b_entry.Value))
{
return false;
}
}
}
}
return true;
}
/**
* This method attempt to find an already existing HSSFCellStyle that matches
* what you want the style to be. If it does not find the style, then it
* Creates a new one. If it does Create a new one, then it applies the
* propertyName and propertyValue to the style. This is necessary because
* Excel has an upper limit on the number of Styles that it supports.
*
*@param workbook The workbook that is being worked with.
*@param propertyName The name of the property that is to be
* changed.
*@param propertyValue The value of the property that is to be
* changed.
*@param cell The cell that needs it's style changes
*@exception NestableException Thrown if an error happens.
*/
public static void SetCellStyleProperty(ICell cell, HSSFWorkbook workbook, String propertyName, Object propertyValue)
{
ICellStyle originalStyle = cell.CellStyle;
ICellStyle newStyle = null;
Hashtable values = GetFormatProperties(originalStyle);
values[propertyName] = propertyValue;
// index seems like what index the cellstyle is in the list of styles for a workbook.
// not good to compare on!
short numberCellStyles = workbook.NumCellStyles;
for (short i = 0; i < numberCellStyles; i++)
{
ICellStyle wbStyle = workbook.GetCellStyleAt(i);
Hashtable wbStyleMap = GetFormatProperties(wbStyle);
// if (wbStyleMap.Equals(values))
if (CompareHashTableKeyValueIsEqual(wbStyleMap, values))
{
newStyle = wbStyle;
break;
}
}
if (newStyle == null)
{
newStyle = workbook.CreateCellStyle();
SetFormatProperties(newStyle, workbook, values);
}
cell.CellStyle = (newStyle);
}
/// <summary>
/// Returns a map containing the format properties of the given cell style.
/// </summary>
/// <param name="style">cell style</param>
/// <returns>map of format properties (String -> Object)</returns>
private static Hashtable GetFormatProperties(ICellStyle style)
{
Hashtable properties = new Hashtable();
PutShort(properties, ALIGNMENT, (short)style.Alignment);
PutShort(properties, BORDER_BOTTOM, (short)style.BorderBottom);
PutShort(properties, BORDER_LEFT, (short)style.BorderLeft);
PutShort(properties, BORDER_RIGHT, (short)style.BorderRight);
PutShort(properties, BORDER_TOP, (short)style.BorderTop);
PutShort(properties, BOTTOM_BORDER_COLOR, style.BottomBorderColor);
PutShort(properties, DATA_FORMAT, style.DataFormat);
PutShort(properties, FILL_BACKGROUND_COLOR, style.FillBackgroundColor);
PutShort(properties, FILL_FOREGROUND_COLOR, style.FillForegroundColor);
PutShort(properties, FILL_PATTERN, (short)style.FillPattern);
PutShort(properties, FONT, style.FontIndex);
PutBoolean(properties, HIDDEN, style.IsHidden);
PutShort(properties, INDENTION, style.Indention);
PutShort(properties, LEFT_BORDER_COLOR, style.LeftBorderColor);
PutBoolean(properties, LOCKED, style.IsLocked);
PutShort(properties, RIGHT_BORDER_COLOR, style.RightBorderColor);
PutShort(properties, ROTATION, style.Rotation);
PutShort(properties, TOP_BORDER_COLOR, style.TopBorderColor);
PutShort(properties, VERTICAL_ALIGNMENT, (short)style.VerticalAlignment);
PutBoolean(properties, WRAP_TEXT, style.WrapText);
return properties;
}
/// <summary>
/// Sets the format properties of the given style based on the given map.
/// </summary>
/// <param name="style">The cell style</param>
/// <param name="workbook">The parent workbook.</param>
/// <param name="properties">The map of format properties (String -> Object).</param>
private static void SetFormatProperties(
ICellStyle style, HSSFWorkbook workbook, Hashtable properties)
{
style.Alignment = (HorizontalAlignment)GetShort(properties, ALIGNMENT);
style.BorderBottom = (BorderStyle)GetShort(properties, BORDER_BOTTOM);
style.BorderLeft = (BorderStyle)GetShort(properties, BORDER_LEFT);
style.BorderRight = (BorderStyle)GetShort(properties, BORDER_RIGHT);
style.BorderTop = (BorderStyle)GetShort(properties, BORDER_TOP);
style.BottomBorderColor = (GetShort(properties, BOTTOM_BORDER_COLOR));
style.DataFormat = (GetShort(properties, DATA_FORMAT));
style.FillBackgroundColor = (GetShort(properties, FILL_BACKGROUND_COLOR));
style.FillForegroundColor = (GetShort(properties, FILL_FOREGROUND_COLOR));
style.FillPattern = (FillPattern)GetShort(properties, FILL_PATTERN);
style.SetFont(workbook.GetFontAt(GetShort(properties, FONT)));
style.IsHidden = (GetBoolean(properties, HIDDEN));
style.Indention = (GetShort(properties, INDENTION));
style.LeftBorderColor = (GetShort(properties, LEFT_BORDER_COLOR));
style.IsLocked = (GetBoolean(properties, LOCKED));
style.RightBorderColor = (GetShort(properties, RIGHT_BORDER_COLOR));
style.Rotation = (GetShort(properties, ROTATION));
style.TopBorderColor = (GetShort(properties, TOP_BORDER_COLOR));
style.VerticalAlignment = (VerticalAlignment)GetShort(properties, VERTICAL_ALIGNMENT);
style.WrapText = (GetBoolean(properties, WRAP_TEXT));
}
/// <summary>
/// Utility method that returns the named short value form the given map.
/// Returns zero if the property does not exist, or is not a {@link Short}.
/// </summary>
/// <param name="properties">The map of named properties (String -> Object)</param>
/// <param name="name">The property name.</param>
/// <returns>property value, or zero</returns>
private static short GetShort(Hashtable properties, String name)
{
Object value = properties[name];
if (value is short)
{
return (short)value;
}
else
{
return 0;
}
}
/// <summary>
/// Utility method that returns the named boolean value form the given map.
/// Returns false if the property does not exist, or is not a {@link Boolean}.
/// </summary>
/// <param name="properties">map of properties (String -> Object)</param>
/// <param name="name">The property name.</param>
/// <returns>property value, or false</returns>
private static bool GetBoolean(Hashtable properties, String name)
{
Object value = properties[name];
if (value is Boolean)
{
return ((Boolean)value);
}
else
{
return false;
}
}
/// <summary>
/// Utility method that Puts the named short value to the given map.
/// </summary>
/// <param name="properties">The map of properties (String -> Object).</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
private static void PutShort(Hashtable properties, String name, short value)
{
properties[name] = value;
}
/// <summary>
/// Utility method that Puts the named boolean value to the given map.
/// </summary>
/// <param name="properties">map of properties (String -> Object)</param>
/// <param name="name">property name</param>
/// <param name="value">property value</param>
private static void PutBoolean(Hashtable properties, String name, bool value)
{
properties[name] = value;
}
/// <summary>
/// Looks for text in the cell that should be unicode, like alpha; and provides the
/// unicode version of it.
/// </summary>
/// <param name="cell">The cell to check for unicode values</param>
/// <returns>transalted to unicode</returns>
public static ICell TranslateUnicodeValues(ICell cell)
{
String s = cell.RichStringCellValue.String;
bool foundUnicode = false;
String lowerCaseStr = s.ToLower();
for (int i = 0; i < unicodeMappings.Length; i++)
{
UnicodeMapping entry = unicodeMappings[i];
String key = entry.entityName;
if (lowerCaseStr.IndexOf(key, StringComparison.Ordinal) != -1)
{
s = s.Replace(key, entry.resolvedValue);
foundUnicode = true;
}
}
if (foundUnicode)
{
cell.SetCellValue(new HSSFRichTextString(s));
}
return cell;
}
private static UnicodeMapping um(String entityName, String resolvedValue)
{
return new UnicodeMapping(entityName, resolvedValue);
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateConstructor;
using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateConstructor
{
public class GenerateConstructorTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
null, new GenerateConstructorCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithSimpleArgument()
{
await TestAsync(
@"class C { void M() { new [|C|](1); } }",
@"class C { private int v; public C(int v) { this.v = v; } void M() { new C(1); } }");
}
[Fact, WorkItem(910589), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithNoArgs()
{
await TestAsync(
@"class C { public C(int v) { } void M() { new [|C|](); } }",
@"class C { public C() { } public C(int v) { } void M() { new C(); } }");
}
[Fact, WorkItem(910589), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithNamedArg()
{
await TestAsync(
@"class C { void M() { new [|C(foo: 1)|]; } }",
@"class C { private int foo; public C(int foo) { this.foo = foo; } void M() { new C(foo: 1); } }");
}
[Fact, WorkItem(910589), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField1()
{
await TestAsync(
@"class C { void M() { new [|D(foo: 1)|]; } } class D { private int foo; }",
@"class C { void M() { new D(foo: 1); } } class D { private int foo; public D(int foo) { this.foo = foo; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField2()
{
await TestAsync(
@"class C { void M() { new [|D|](1); } } class D { private string v; }",
@"class C { void M() { new D(1); } } class D { private string v; private int v1; public D(int v1) { this.v1 = v1; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField3()
{
await TestAsync(
@"class C { void M() { new [|D|](1); } } class B { protected int v; } class D : B { }",
@"class C { void M() { new D(1); } } class B { protected int v; } class D : B { public D(int v) { this.v = v; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField4()
{
await TestAsync(
@"class C { void M() { new [|D|](1); } } class B { private int v; } class D : B { }",
@"class C { void M() { new D(1); } } class B { private int v; } class D : B { private int v; public D(int v) { this.v = v; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField5()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class D { int X; }",
@"class C { void M(int X) { new D(X); } } class D { int X; public D(int x) { X = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField5WithQualification()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class D { int X; }",
@"class C { void M(int X) { new D(X); } } class D { int X; public D(int x) { this.X = x; } }",
options: new Dictionary<OptionKey, object> { { new OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, "C#"), true } });
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField6()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { private int X; } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { private int X; } class D : B { private int x; public D(int x) { this.x = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField7()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected int X; } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { protected int X; } class D : B { public D(int x) { X = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField7WithQualification()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected int X; } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { protected int X; } class D : B { public D(int x) { this.X = x; } }",
options: new Dictionary<OptionKey, object> { { new OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, "C#"), true } });
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField8()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected static int x; } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { protected static int x; } class D : B { private int x1; public D(int x1) { this.x1 = x1; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingField9()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected int x; } class D : B { int X; }",
@"class C { void M(int X) { new D(X); } } class B { protected int x; } class D : B { int X; public D(int x) { this.x = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty1()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class D { public int X { get; private set; } }",
@"class C { void M(int X) { new D(X); } } class D { public D(int x) { X = x; } public int X { get; private set; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty1WithQualification()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class D { public int X { get; private set; } }",
@"class C { void M(int X) { new D(X); } } class D { public D(int x) { this.X = x; } public int X { get; private set; } }",
options: new Dictionary<OptionKey, object> { { new OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, "C#"), true } });
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty2()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { public int X { get; private set; } } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { public int X { get; private set; } } class D : B { private int x; public D(int x) { this.x = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty3()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { public int X { get; protected set; } } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { public int X { get; protected set; } } class D : B { public D(int x) { X = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty3WithQualification()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { public int X { get; protected set; } } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { public int X { get; protected set; } } class D : B { public D(int x) { this.X = x; } }",
options: new Dictionary<OptionKey, object> { { new OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, "C#"), true } });
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty4()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected int X { get; set; } } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { protected int X { get; set; } } class D : B { public D(int x) { X = x; } }");
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty4WithQualification()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected int X { get; set; } } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { protected int X { get; set; } } class D : B { public D(int x) { this.X = x; } }",
options: new Dictionary<OptionKey, object> { { new OptionKey(SimplificationOptions.QualifyMemberAccessWithThisOrMe, "C#"), true } });
}
[WorkItem(539444)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithExistingProperty5()
{
await TestAsync(
@"class C { void M(int X) { new [|D|](X); } } class B { protected int X { get; } } class D : B { }",
@"class C { void M(int X) { new D(X); } } class B { protected int X { get; } } class D : B { private int x; public D(int x) { this.x = x; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithOutParam()
{
await TestAsync(
@"class C { void M(int i) { new [|D|](out i); } } class D { }",
@"class C { void M(int i) { new D(out i); } } class D { public D(out int i) { i = 0; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithBaseDelegatingConstructor1()
{
await TestAsync(
@"class C { void M() { new [|D|](1); } } class B { protected B(int x) { } } class D : B { }",
@"class C { void M() { new D(1); } } class B { protected B(int x) { } } class D : B { public D(int x) : base(x) { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestWithBaseDelegatingConstructor2()
{
await TestAsync(
@"class C { void M() { new [|D|](1); } } class B { private B(int x) { } } class D : B { }",
@"class C { void M() { new D(1); } } class B { private B(int x) { } } class D : B { private int v; public D(int v) { this.v = v; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestStructInLocalInitializerWithSystemType()
{
await TestAsync(
@"struct S { void M() { S s = new [|S|](System.DateTime.Now); } }",
@"using System; struct S { private DateTime now; public S(DateTime now) { this.now = now; } void M() { S s = new S(System.DateTime.Now); } }");
}
[WorkItem(539489)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestEscapedName()
{
await TestAsync(
@"class C { void M() { new [|@C|](1); } }",
@"class C { private int v; public C(int v) { this.v = v; } void M() { new @C(1); } }");
}
[WorkItem(539489)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestEscapedKeyword()
{
await TestAsync(
@"class @int { void M() { new [|@int|](1); } }",
@"class @int { private int v; public @int(int v) { this.v = v; } void M() { new @int(1); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestIsSymbolAccessibleWithInternalField()
{
await TestAsync(
@"class Base { internal long field ; void Main ( ) { int field = 5 ; new [|Derived|] ( field ) ; } } class Derived : Base { } ",
@"class Base { internal long field ; void Main ( ) { int field = 5 ; new Derived ( field ) ; } } class Derived : Base { public Derived ( int field ) { this . field = field ; } } ");
}
[WorkItem(539548)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestFormatting()
{
await TestAsync(
@"class C
{
void M()
{
new [|C|](1);
}
}",
@"class C
{
private int v;
public C(int v)
{
this.v = v;
}
void M()
{
new C(1);
}
}",
compareTokens: false);
}
[WorkItem(5864, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestNotOnStructConstructor()
{
await TestMissingAsync(
@"struct Struct { void Main ( ) { Struct s = new [|Struct|] ( ) ; } } ");
}
[WorkItem(539787)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateIntoCorrectPart()
{
await TestAsync(
@"partial class C { } partial class C { void Method ( ) { C c = new [|C|] ( ""a"" ) ; } } ",
@"partial class C { } partial class C { private string v ; public C ( string v ) { this . v = v ; } void Method ( ) { C c = new C ( ""a"" ) ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestDelegateToSmallerConstructor1()
{
await TestAsync(
@"class A { void M ( ) { Delta d1 = new Delta ( ""ss"" , 3 ) ; Delta d2 = new [|Delta|] ( ""ss"" , 5 , true ) ; } } class Delta { private string v1 ; private int v2 ; public Delta ( string v1 , int v2 ) { this . v1 = v1 ; this . v2 = v2 ; } } ",
@"class A { void M ( ) { Delta d1 = new Delta ( ""ss"" , 3 ) ; Delta d2 = new Delta ( ""ss"" , 5 , true ) ; } } class Delta { private bool v ; private string v1 ; private int v2 ; public Delta ( string v1 , int v2 ) { this . v1 = v1 ; this . v2 = v2 ; } public Delta ( string v1 , int v2 , bool v ) : this ( v1 , v2 ) { this . v = v ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestDelegateToSmallerConstructor2()
{
await TestAsync(
@"class A { void M ( ) { Delta d1 = new Delta ( ""ss"" , 3 ) ; Delta d2 = new [|Delta|] ( ""ss"" , 5 , true ) ; } } class Delta { private string a ; private int b ; public Delta ( string a , int b ) { this . a = a ; this . b = b ; } } ",
@"class A { void M ( ) { Delta d1 = new Delta ( ""ss"" , 3 ) ; Delta d2 = new Delta ( ""ss"" , 5 , true ) ; } } class Delta { private string a ; private int b ; private bool v ; public Delta ( string a , int b ) { this . a = a ; this . b = b ; } public Delta ( string a , int b , bool v) : this ( a , b ) { this . v = v ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestDelegateToSmallerConstructor3()
{
await TestAsync(
@"class A { void M ( ) { var d1 = new Base ( ""ss"" , 3 ) ; var d2 = new [|Delta|] ( ""ss"" , 5 , true ) ; } } class Base { private string v1 ; private int v2 ; public Base ( string v1 , int v2 ) { this . v1 = v1 ; this . v2 = v2 ; } } class Delta : Base { } ",
@"class A { void M ( ) { var d1 = new Base ( ""ss"" , 3 ) ; var d2 = new Delta ( ""ss"" , 5 , true ) ; } } class Base { private string v1 ; private int v2 ; public Base ( string v1 , int v2 ) { this . v1 = v1 ; this . v2 = v2 ; } } class Delta : Base { private bool v ; public Delta ( string v1 , int v2 , bool v ) : base ( v1 , v2 ) { this . v = v ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestDelegateToSmallerConstructor4()
{
await TestAsync(
@"class A { void M ( ) { Delta d1 = new Delta ( ""ss"" , 3 ) ; Delta d2 = new [|Delta|] ( ""ss"" , 5 , true ) ; } } class Delta { private string v1 ; private int v2 ; public Delta ( string v1 , int v2 ) { this . v1 = v1 ; this . v2 = v2 ; } } ",
@"class A { void M ( ) { Delta d1 = new Delta ( ""ss"" , 3 ) ; Delta d2 = new Delta ( ""ss"" , 5 , true ) ; } } class Delta { private bool v ; private string v1 ; private int v2 ; public Delta ( string v1 , int v2 ) { this . v1 = v1 ; this . v2 = v2 ; } public Delta ( string v1 , int v2 , bool v ) : this ( v1 , v2 ) { this . v = v ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateFromThisInitializer1()
{
await TestAsync(
@"class C { public C ( ) [|: this ( 4 )|] { } } ",
@"class C { private int v ; public C ( ) : this ( 4 ) { } public C ( int v ) { this . v = v ; } } ");
}
[Fact, WorkItem(910589), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateFromThisInitializer2()
{
await TestAsync(
@"class C { public C ( int i ) [|: this ( )|] { } } ",
@"class C { public C ( ) { } public C ( int i ) : this ( ) { } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateFromBaseInitializer1()
{
await TestAsync(
@"class C : B { public C ( int i ) [|: base ( i )|] { } } class B { } ",
@"class C : B { public C ( int i ) : base ( i ) { } } class B { private int i ; public B ( int i ) { this . i = i ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateFromBaseInitializer2()
{
await TestAsync(
@"class C : B { public C ( int i ) [|: base ( i )|] { } } class B { int i ; } ",
@"class C : B { public C ( int i ) : base ( i ) { } } class B { int i ; public B ( int i ) { this . i = i ; } } ");
}
[WorkItem(539969)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestNotOnExistingConstructor()
{
await TestMissingAsync(
@"class C { private class D { } } class A { void M ( ) { C . D d = new C . [|D|] ( ) ; } } ");
}
[WorkItem(539972)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestUnavailableTypeParameters()
{
await TestAsync(
@"class C < T1 , T2 > { public void Foo ( T1 t1 , T2 t2 ) { A a = new [|A|] ( t1 , t2 ) ; } } internal class A { } ",
@"class C < T1 , T2 > { public void Foo ( T1 t1 , T2 t2 ) { A a = new A ( t1 , t2 ) ; } } internal class A { private object t1 ; private object t2 ; public A ( object t1 , object t2 ) { this . t1 = t1 ; this . t2 = t2 ; } } ");
}
[WorkItem(541020)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateCallToDefaultConstructorInStruct()
{
await TestAsync(
@"class Program { void Main ( ) { Apartment Metropolitan = new Apartment ( [|""Pine""|] ) ; } } struct Apartment { private int v1 ; public Apartment ( int v1 ) { this . v1 = v1 ; } } ",
@"class Program { void Main ( ) { Apartment Metropolitan = new Apartment ( ""Pine"" ) ; } } struct Apartment { private string v ; private int v1 ; public Apartment ( string v ) : this ( ) { this . v = v ; } public Apartment ( int v1 ) { this . v1 = v1 ; } }");
}
[WorkItem(541121)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestReadonlyFieldDelegation()
{
await TestAsync(
@"class C { private readonly int x ; void Test ( ) { int x = 10 ; C c = new [|C|] ( x ) ; } } ",
@"class C { private readonly int x ; public C ( int x ) { this . x = x ; } void Test ( ) { int x = 10 ; C c = new C ( x ) ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestNoGenerationIntoEntirelyHiddenType()
{
await TestMissingAsync(
@"
class C
{
void Foo()
{
new [|D|](1, 2, 3);
}
}
#line hidden
class D
{
}
#line default
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestNestedConstructorCall()
{
await TestAsync(
@"
class C
{
void Foo()
{
var d = new D([|v|]: new D(u: 1));
}
}
class D
{
private int u;
public D(int u)
{
}
}
",
@"
class C
{
void Foo()
{
var d = new D(v: new D(u: 1));
}
}
class D
{
private int u;
private D v;
public D(D v)
{
this.v = v;
}
public D(int u)
{
}
}
");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithArgument()
{
await TestAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute {} [[|MyAttribute(123)|]] class D {} ",
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private int v; public MyAttribute(int v) { this.v = v; } } [MyAttribute(123)] class D {} ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithMultipleArguments()
{
await TestAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute {} [[|MyAttribute(true, 1, ""hello"")|]] class D {} ",
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private bool v1; private int v2; private string v3; public MyAttribute(bool v1, int v2, string v3) { this.v1 = v1; this.v2 = v2; this.v3 = v3; } } [MyAttribute(true, 1, ""hello"")] class D {} ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithNamedArguments()
{
await TestAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute {} [[|MyAttribute(true, 1, topic = ""hello"")|]] class D {} ",
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private string topic; private bool v1; private int v2; public MyAttribute(bool v1, int v2, string topic) { this.v1 = v1; this.v2 = v2; this.topic = topic; } } [MyAttribute(true, 1, topic = ""hello"")] class D {} ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithAdditionalConstructors()
{
await TestAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private int v; public MyAttribute(int v) { this.v = v; } } [[|MyAttribute(true, 1)|]] class D {} ",
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private int v; private bool v1; private int v2; public MyAttribute(int v) { this.v = v; } public MyAttribute(bool v1, int v2) { this.v1 = v1; this.v2 = v2; } } [MyAttribute(true, 1)] class D {} ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithOverloading()
{
await TestAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private int v; public MyAttribute(int v) { this.v = v; } } [[|MyAttribute(true)|]] class D {} ",
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttribute : Attribute { private int v; private bool v1; public MyAttribute(bool v1) { this.v1 = v1; } public MyAttribute(int v) { this.v = v; } } [MyAttribute(true)] class D {} ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithOverloadingMultipleParameters()
{
await TestAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { private bool v1; private int v2; public MyAttrAttribute(bool v1, int v2) { this.v1 = v1; this.v2 = v2; } } [|[MyAttrAttribute(1,true)]|] class D { } ",
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { private int v; private bool v1; private int v2; private bool v3; public MyAttrAttribute(int v, bool v3) { this.v = v; this.v3 = v3; } public MyAttrAttribute(bool v1, int v2) { this.v1 = v1; this.v2 = v2; } } [MyAttrAttribute(1,true)] class D { } ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithAllValidParameters()
{
await TestAsync(
@"using System; enum A { A1 } [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { } [|[MyAttrAttribute(new int[] { 1, 2, 3}, A.A1, true, (byte)1, 'a', (short)12, (int) 1, (long) 5L, 5D, 3.5F, ""hello"")]|] class D { } ",
@"using System; enum A { A1 } [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { private A a1; private int[] v1; private string v10; private bool v2; private byte v3; private char v4; private short v5; private int v6; private long v7; private double v8; private float v9; public MyAttrAttribute(int[] v1, A a1, bool v2, byte v3, char v4, short v5, int v6, long v7, double v8, float v9, string v10) { this.v1 = v1; this.a1 = a1; this.v2 = v2; this.v3 = v3; this.v4 = v4; this.v5 = v5; this.v6 = v6; this.v7 = v7; this.v8 = v8; this.v9 = v9; this.v10 = v10; } } [MyAttrAttribute(new int[] { 1, 2, 3 }, A.A1, true, (byte)1, 'a', (short)12, (int)1, (long)5L, 5D, 3.5F, ""hello"")] class D { } ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithDelegation()
{
await TestMissingAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { } [|[MyAttrAttribute(()=>{return;})]|] class D { } ");
}
[WorkItem(530003)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestAttributesWithLambda()
{
await TestMissingAsync(
@"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { } [|[MyAttrAttribute(()=>5)]|] class D { } ");
}
[WorkItem(889349)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestConstructorGenerationForDifferentNamedParameter()
{
await TestAsync(
@"
class Program
{
static void Main(string[] args)
{
var ss = new [|Program(wde: 1)|];
}
Program(int s)
{
}
}
",
@"
class Program
{
private int wde;
static void Main(string[] args)
{
var ss = new Program(wde: 1);
}
Program(int s)
{
}
public Program(int wde)
{
this.wde = wde;
}
}
", compareTokens: false);
}
[WorkItem(528257)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateInInaccessibleType()
{
await TestAsync(
@"class Foo { class Bar { } } class A { static void Main(string[] args) { var s = new [|Foo.Bar(5)|]; } }",
@"class Foo { class Bar { private int v; public Bar(int v) { this.v = v; } } } class A { static void Main(string[] args) { var s = new Foo.Bar(5); } }");
}
public partial class GenerateConstructorTestsWithFindMissingIdentifiersAnalyzer : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpUnboundIdentifiersDiagnosticAnalyzer(), new GenerateConstructorCodeFixProvider());
}
[WorkItem(1241, @"https://github.com/dotnet/roslyn/issues/1241")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateConstructorInIncompleteLambda()
{
await TestAsync(
@"using System . Threading . Tasks ; class C { C ( ) { Task . Run ( ( ) => { new [|C|] ( 0 ) } ) ; } } ",
@"using System . Threading . Tasks ; class C { private int v ; public C ( int v ) { this . v = v ; } C ( ) { Task . Run ( ( ) => { new C ( 0 ) } ) ; } } ");
}
}
[WorkItem(5274, "https://github.com/dotnet/roslyn/issues/5274")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateIntoDerivedClassWithAbstractBase()
{
await TestAsync(
@"
class Class1
{
private void Foo(string value)
{
var rewriter = new [|Derived|](value);
}
private class Derived : Base
{
}
public abstract partial class Base
{
private readonly bool _val;
public Base(bool val = false)
{
_val = val;
}
}
}",
@"
class Class1
{
private void Foo(string value)
{
var rewriter = new Derived(value);
}
private class Derived : Base
{
private string value;
public Derived(string value)
{
this.value = value;
}
}
public abstract partial class Base
{
private readonly bool _val;
public Base(bool val = false)
{
_val = val;
}
}
}");
}
[WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateFromDerivedClass()
{
await TestAsync(
@"
class Base
{
public Base(string value)
{
}
}
class [||]Derived : Base
{
}",
@"
class Base
{
public Base(string value)
{
}
}
class Derived : Base
{
public Derived(string value) : base(value)
{
}
}");
}
[WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateFromDerivedClass2()
{
await TestAsync(
@"
class Base
{
public Base(int a, string value = null)
{
}
}
class [||]Derived : Base
{
}",
@"
class Base
{
public Base(int a, string value = null)
{
}
}
class Derived : Base
{
public Derived(int a, string value = null) : base(a, value)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)]
public async Task TestGenerateWithIncorrectConstructorArguments_Crash()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; using System . Linq ; using System . Threading . Tasks ; abstract class Y { class X : Y { void M ( ) { new X ( new [|string|] ( ) ) ; } } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; using System . Threading . Tasks ; abstract class Y { class X : Y { private string v ; public X ( string v ) { this . v = v ; } void M ( ) { new X ( new string ( ) ) ; } } } ");
}
}
}
| |
//! \file ImageLAG.cs
//! \date 2020 Mar 29
//! \brief Strikes image format.
//
// Copyright (C) 2020 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.Strikes
{
internal class LagMetaData : ImageMetaData
{
public int ScanLineSize;
public bool HasPalette;
public bool HasAlpha;
public int LastChunkSize;
public int ChunkCount;
}
[Export(typeof(ImageFormat))]
public class LagFormat : ImageFormat
{
public override string Tag { get { return "LAG"; } }
public override string Description { get { return "Strikes image format"; } }
public override uint Signature { get { return 0x414C1001; } }
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (0x20);
int bpp = header[10] & 0x1F;
if (!(bpp == 24 || bpp == 16 || bpp == 8))
return null;
return new LagMetaData
{
Width = BigEndian.ToUInt16 (header, 4),
Height = BigEndian.ToUInt16 (header, 6),
BPP = bpp,
ScanLineSize = BigEndian.ToUInt16 (header, 8),
HasPalette = (header[10] & 0x80) != 0,
HasAlpha = (header[10] & 0x20) != 0,
LastChunkSize = BigEndian.ToInt32 (header, 0x14),
ChunkCount = BigEndian.ToUInt16 (header, 0x18),
};
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new LagReader (file, (LagMetaData)info);
var pixels = reader.Unpack();
return ImageData.Create (info, reader.Format, reader.Palette, pixels);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("LagFormat.Write not implemented");
}
}
internal class LagReader
{
IBinaryStream m_input;
byte[] m_output;
LagMetaData m_info;
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public LagReader (IBinaryStream input, LagMetaData info)
{
m_input = input;
m_info = info;
m_output = new byte[4 * m_info.Width * m_info.Height];
switch (m_info.BPP)
{
case 24:
if (m_info.HasAlpha)
Format = PixelFormats.Bgra32;
else
Format = PixelFormats.Bgr24;
break;
default:
throw new NotImplementedException ("Not supported LAG color depth.");
}
}
public byte[] Unpack ()
{
m_input.Position = 0x20;
if (m_info.HasPalette)
Palette = ImageFormat.ReadPalette (m_input.AsStream, 0x100, PaletteFormat.Bgr);
var buffer = ReadChunks();
using (var input = new BinMemoryStream (buffer))
{
int g_pos = m_info.iWidth;
int b_pos = m_info.iWidth * 2;
int a_pos = m_info.iWidth * 3;
var scanline = new byte[m_info.ScanLineSize * 2];
var unpack_buffer = new byte[scanline.Length];
int dst = 0;
for (int y = 0; y < m_info.iHeight; ++y)
{
int packed_size = Binary.BigEndian (input.ReadInt24() << 8);
byte flags = input.ReadUInt8();
if (packed_size > scanline.Length)
break;
input.Read (scanline, 0, packed_size);
if ((flags & 4) != 0) // LZSS compression
{
packed_size = PckOpener.LzssUnpack (scanline, packed_size, unpack_buffer);
var swap = scanline;
scanline = unpack_buffer;
unpack_buffer = swap;
}
if ((flags & 2) != 0) // RLE compression
{
packed_size = RleUnpack (scanline, packed_size, unpack_buffer);
var swap = scanline;
scanline = unpack_buffer;
unpack_buffer = swap;
}
if ((flags & 1) != 0)
{
RestoreScanline (scanline, packed_size);
}
switch (m_info.BPP)
{
case 24:
{
int src_r = 0;
int src_g = g_pos;
int src_b = b_pos;
int src_a = a_pos;
for (int x = 0; x < m_info.iWidth; ++x)
{
m_output[dst++] = scanline[src_b++];
m_output[dst++] = scanline[src_g++];
m_output[dst++] = scanline[src_r++];
if (m_info.HasAlpha)
m_output[dst++] = scanline[src_a++];
}
break;
}
default:
throw new NotImplementedException ("Not supported LAG color depth.");
}
}
}
return m_output;
}
byte[] ReadChunks ()
{
var buffer = new byte[0x10000 * m_info.ChunkCount + m_info.LastChunkSize];
int dst = 0;
for (int i = 0; i <= m_info.ChunkCount; ++i)
{
int length = Binary.BigEndian (m_input.ReadInt32());
bool is_compressed = length < 0;
length &= 0x7FFFFFFF;
if (is_compressed)
{
int unpacked_size = Math.Min (0x10000, buffer.Length - dst);
using (var region = new StreamRegion (m_input.AsStream, m_input.Position, length, true))
using (var zinput = new ZLibStream (region, CompressionMode.Decompress, true))
{
dst += zinput.Read (buffer, dst, unpacked_size);
}
}
else
{
dst += m_input.Read (buffer, dst, length);
}
}
return buffer;
}
int RleUnpack (byte[] input, int in_length, byte[] output)
{
int dst = 0;
int src = 0;
while (src < in_length && dst < output.Length)
{
byte code = input[src++];
if (src >= in_length)
break;
int count = (code & 0x3F) + 1;
if (dst + count > output.Length)
break;
int val;
int i;
switch ((code & 0xC0) >> 6)
{
case 0:
for (i = 0; i < count; ++i)
{
int n = i & 3;
if (n == 0)
val = (input[src] & 0xC0) >> 6;
else if (n == 1)
val = (input[src] & 0x30) >> 4;
else if (n == 2)
val = (input[src] & 0xC) >> 2;
else
val = input[src++] & 3;
if ((val & 2) != 0)
val |= 0xFC;
output[dst++] = (byte)val;
}
if ((i & 3) != 0)
++src;
break;
case 1:
for (i = 0; i < count; ++i)
{
if ((i & 1) != 0)
val = input[src++] & 0xF;
else
val = (input[src] & 0xF0) >> 4;
if ((val & 8) != 0)
val |= 0xF0;
output[dst++] = (byte)val;
}
if ((i & 1) != 0)
++src;
break;
case 2:
for (i = 0; i < count; ++i)
{
int n = i & 3;
if (n == 0)
{
val = (input[src] & 0xFC) >> 2;
}
else if (n == 1)
{
byte v = input[src++];
val = ((input[src] & 0xF0) >> 4) | (v & 3) << 4;
}
else if (n == 2)
{
byte v = input[src++];
val = ((input[src] & 0xC0) >> 6) | (v & 0xF) << 2;
}
else
{
val = input[src++] & 0x3F;
}
if ((val & 0x20) != 0)
val |= 0xC0;
output[dst++] = (byte)val;
}
if ((i & 3) != 0)
++src;
break;
case 3:
Buffer.BlockCopy (input, src, output, dst, count);
src += count;
dst += count;
break;
}
}
return dst;
}
void RestoreScanline (byte[] input, int in_length)
{
for (int pos = 1; pos < in_length; ++pos)
{
input[pos] += input[pos-1];
}
}
}
}
| |
// ****************************************************************
// Copyright 2002-2011, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
namespace NUnit.Util
{
using System;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Configuration;
using NUnit.Core;
using NUnit.Core.Filters;
/// <summary>
/// TestLoader handles interactions between a test runner and a
/// client program - typically the user interface - for the
/// purpose of loading, unloading and running tests.
///
/// It implemements the EventListener interface which is used by
/// the test runner and repackages those events, along with
/// others as individual events that clients may subscribe to
/// in collaboration with a TestEventDispatcher helper object.
///
/// TestLoader is quite handy for use with a gui client because
/// of the large number of events it supports. However, it has
/// no dependencies on ui components and can be used independently.
/// </summary>
public class TestLoader : MarshalByRefObject, NUnit.Core.EventListener, ITestLoader, IService
{
static Logger log = InternalTrace.GetLogger(typeof(TestLoader));
#region Instance Variables
/// <summary>
/// Our event dispatching helper object
/// </summary>
private TestEventDispatcher events;
/// <summary>
/// Our TestRunnerFactory
/// </summary>
private ITestRunnerFactory factory;
/// <summary>
/// Loads and executes tests. Non-null when
/// we have loaded a test.
/// </summary>
private TestRunner testRunner = null;
/// <summary>
/// Our current test project, if we have one.
/// </summary>
private NUnitProject testProject = null;
/// <summary>
/// The currently loaded test, returned by the testrunner
/// </summary>
//private ITest loadedTest = null;
/// <summary>
/// The test name that was specified when loading
/// </summary>
private string loadedTestName = null;
/// <summary>
/// The currently executing test
/// </summary>
private string currentTestName;
/// <summary>
/// The currently set runtime framework
/// </summary>
private RuntimeFramework currentRuntime;
/// <summary>
/// Result of the last test run
/// </summary>
private TestResult testResult = null;
/// <summary>
/// The last exception received when trying to load, unload or run a test
/// </summary>
private Exception lastException = null;
/// <summary>
/// Watcher fires when the assembly changes
/// </summary>
private IAssemblyWatcher watcher;
/// <summary>
/// Assembly changed during a test and
/// needs to be reloaded later
/// </summary>
private bool reloadPending = false;
/// <summary>
/// Trace setting to use for running tests
/// </summary>
private bool tracing;
/// <summary>
/// LoggingThreshold to use for running tests
/// </summary>
private LoggingThreshold logLevel;
/// <summary>
/// The last filter used for a run - used to
/// rerun tests when a change occurs
/// </summary>
private ITestFilter lastFilter;
/// <summary>
/// The last trace setting used for a run
/// </summary>
private bool lastTracing;
/// <summary>
/// Last logging level used for a run
/// </summary>
private LoggingThreshold lastLogLevel;
/// <summary>
/// The runtime framework being used for the currently
/// loaded tests, or the current framework if no tests
/// are loaded.
/// </summary>
private RuntimeFramework currentFramework = RuntimeFramework.CurrentFramework;
#endregion
#region Constructors
public TestLoader()
: this( new TestEventDispatcher() ) { }
public TestLoader(TestEventDispatcher eventDispatcher)
: this(eventDispatcher, new AssemblyWatcher()) { }
public TestLoader(IAssemblyWatcher assemblyWatcher)
: this(new TestEventDispatcher(), assemblyWatcher) { }
public TestLoader(TestEventDispatcher eventDispatcher, IAssemblyWatcher assemblyWatcher)
{
this.events = eventDispatcher;
this.watcher = assemblyWatcher;
this.factory = new DefaultTestRunnerFactory();
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
}
#endregion
#region Properties
public bool IsProjectLoaded
{
get { return testProject != null; }
}
public bool IsTestLoaded
{
get { return testRunner != null && testRunner.Test != null; }
}
public ITest LoadedTest
{
get { return testRunner == null ? null : testRunner.Test; }
}
public bool Running
{
get { return testRunner != null && testRunner.Running; }
}
public NUnitProject TestProject
{
get { return testProject; }
}
public ITestEvents Events
{
get { return events; }
}
public string TestFileName
{
get { return testProject.ProjectPath; }
}
public TestResult TestResult
{
get { return testResult; }
}
public Exception LastException
{
get { return lastException; }
}
public IList AssemblyInfo
{
get { return testRunner == null ? new TestAssemblyInfo[0] : testRunner.AssemblyInfo; }
}
public int TestCount
{
get { return LoadedTest == null ? 0 : LoadedTest.TestCount; }
}
public RuntimeFramework CurrentFramework
{
get { return currentFramework; }
}
public bool IsTracingEnabled
{
get { return tracing; }
set { tracing = value; }
}
public LoggingThreshold LoggingThreshold
{
get { return logLevel; }
set { logLevel = value; }
}
#endregion
#region EventListener Handlers
public void RunStarted(string name, int testCount)
{
log.Debug("Got RunStarted Event");
events.FireRunStarting( name, testCount );
}
public void RunFinished(NUnit.Core.TestResult testResult)
{
this.testResult = testResult;
events.FireRunFinished(testResult);
}
public void RunFinished(Exception exception)
{
this.lastException = exception;
events.FireRunFinished( exception );
}
/// <summary>
/// Trigger event when each test starts
/// </summary>
/// <param name="testName">TestName of the Test that is starting</param>
public void TestStarted(TestName testName)
{
this.currentTestName = testName.FullName;
events.FireTestStarting( testName );
}
/// <summary>
/// Trigger event when each test finishes
/// </summary>
/// <param name="result">Result of the case that finished</param>
public void TestFinished(TestResult result)
{
events.FireTestFinished( result );
}
/// <summary>
/// Trigger event when each suite starts
/// </summary>
/// <param name="suite">Suite that is starting</param>
public void SuiteStarted(TestName suiteName)
{
events.FireSuiteStarting( suiteName );
}
/// <summary>
/// Trigger event when each suite finishes
/// </summary>
/// <param name="result">Result of the suite that finished</param>
public void SuiteFinished(TestResult result)
{
events.FireSuiteFinished( result );
}
/// <summary>
/// Trigger event when an unhandled exception (other than ThreadAbordException) occurs during a test
/// </summary>
/// <param name="exception">The unhandled exception</param>
public void UnhandledException(Exception exception)
{
events.FireTestException( this.currentTestName, exception );
}
void OnUnhandledException( object sender, UnhandledExceptionEventArgs args )
{
switch( args.ExceptionObject.GetType().FullName )
{
case "System.Threading.ThreadAbortException":
break;
case "NUnit.Framework.AssertionException":
default:
Exception ex = args.ExceptionObject as Exception;
events.FireTestException( this.currentTestName, ex);
break;
}
}
/// <summary>
/// Trigger event when output occurs during a test
/// </summary>
/// <param name="testOutput">The test output</param>
public void TestOutput(TestOutput testOutput)
{
events.FireTestOutput( testOutput );
}
#endregion
#region Methods for Loading and Unloading Projects
/// <summary>
/// Create a new project with default naming
/// </summary>
public void NewProject()
{
log.Info("Creating empty project");
try
{
events.FireProjectLoading( "New Project" );
OnProjectLoad( Services.ProjectService.NewProject() );
}
catch( Exception exception )
{
log.Error("Project creation failed", exception);
lastException = exception;
events.FireProjectLoadFailed( "New Project", exception );
}
}
/// <summary>
/// Create a new project using a given path
/// </summary>
public void NewProject( string filePath )
{
log.Info("Creating project " + filePath);
try
{
events.FireProjectLoading( filePath );
NUnitProject project = new NUnitProject( filePath );
project.Configs.Add( "Debug" );
project.Configs.Add( "Release" );
project.IsDirty = false;
OnProjectLoad( project );
}
catch( Exception exception )
{
log.Error("Project creation failed", exception);
lastException = exception;
events.FireProjectLoadFailed( filePath, exception );
}
}
/// <summary>
/// Load a new project, optionally selecting the config and fire events
/// </summary>
public void LoadProject( string filePath, string configName )
{
try
{
log.Info("Loading project {0}, {1} config", filePath, configName == null ? "default" : configName);
events.FireProjectLoading(filePath);
NUnitProject newProject = Services.ProjectService.LoadProject( filePath );
if ( configName != null )
{
newProject.SetActiveConfig( configName );
newProject.IsDirty = false;
}
OnProjectLoad( newProject );
}
catch( Exception exception )
{
log.Error("Project load failed", exception);
lastException = exception;
events.FireProjectLoadFailed( filePath, exception );
}
}
/// <summary>
/// Load a new project using the default config and fire events
/// </summary>
public void LoadProject( string filePath )
{
LoadProject( filePath, null );
}
/// <summary>
/// Load a project from a list of assemblies and fire events
/// </summary>
public void LoadProject( string[] assemblies )
{
try
{
log.Info("Loading multiple assemblies as new project");
events.FireProjectLoading( "New Project" );
NUnitProject newProject = Services.ProjectService.WrapAssemblies( assemblies );
OnProjectLoad( newProject );
}
catch( Exception exception )
{
log.Error("Project load failed", exception);
lastException = exception;
events.FireProjectLoadFailed( "New Project", exception );
}
}
/// <summary>
/// Unload the current project and fire events
/// </summary>
public void UnloadProject()
{
string testFileName = TestFileName;
log.Info("Unloading project " + testFileName);
try
{
events.FireProjectUnloading( testFileName );
if ( IsTestLoaded )
UnloadTest();
testProject = null;
events.FireProjectUnloaded( testFileName );
}
catch (Exception exception )
{
log.Error("Project unload failed", exception);
lastException = exception;
events.FireProjectUnloadFailed( testFileName, exception );
}
}
/// <summary>
/// Common operations done each time a project is loaded
/// </summary>
/// <param name="testProject">The newly loaded project</param>
private void OnProjectLoad( NUnitProject testProject )
{
if ( IsProjectLoaded )
UnloadProject();
this.testProject = testProject;
events.FireProjectLoaded( TestFileName );
}
#endregion
#region Methods for Loading and Unloading Tests
public void LoadTest()
{
LoadTest( null );
}
public void LoadTest( string testName )
{
log.Info("Loading tests for " + Path.GetFileName(TestFileName));
long startTime = DateTime.Now.Ticks;
try
{
events.FireTestLoading( TestFileName );
TestPackage package = MakeTestPackage(testName);
if (testRunner != null)
testRunner.Dispose();
testRunner = factory.MakeTestRunner(package);
bool loaded = testRunner.Load(package);
loadedTestName = testName;
testResult = null;
reloadPending = false;
if ( Services.UserSettings.GetSetting( "Options.TestLoader.ReloadOnChange", true ) )
InstallWatcher( );
if (loaded)
{
this.currentFramework = package.Settings.Contains("RuntimeFramework")
? package.Settings["RuntimeFramework"] as RuntimeFramework
: RuntimeFramework.CurrentFramework;
testProject.HasChangesRequiringReload = false;
events.FireTestLoaded(TestFileName, LoadedTest);
}
else
{
lastException = new ApplicationException(string.Format("Unable to find test {0} in assembly", testName));
events.FireTestLoadFailed(TestFileName, lastException);
}
}
catch( FileNotFoundException exception )
{
log.Error("File not found", exception);
lastException = exception;
foreach( string assembly in TestProject.ActiveConfig.Assemblies )
{
if ( Path.GetFileNameWithoutExtension( assembly ) == exception.FileName &&
!PathUtils.SamePathOrUnder( testProject.ActiveConfig.BasePath, assembly ) )
{
lastException = new ApplicationException( string.Format( "Unable to load {0} because it is not located under the AppBase", exception.FileName ), exception );
break;
}
}
events.FireTestLoadFailed( TestFileName, lastException );
double loadTime = (double)(DateTime.Now.Ticks - startTime) / (double)TimeSpan.TicksPerSecond;
log.Info("Load completed in {0} seconds", loadTime);
}
catch( Exception exception )
{
log.Error("Failed to load test", exception);
lastException = exception;
events.FireTestLoadFailed( TestFileName, exception );
}
}
/// <summary>
/// Unload the current test suite and fire the Unloaded event
/// </summary>
public void UnloadTest( )
{
if( IsTestLoaded )
{
log.Info("Unloading tests for " + Path.GetFileName(TestFileName));
// Hold the name for notifications after unload
string fileName = TestFileName;
try
{
events.FireTestUnloading( fileName );
RemoveWatcher();
testRunner.Unload();
testRunner.Dispose();
testRunner = null;
loadedTestName = null;
testResult = null;
reloadPending = false;
events.FireTestUnloaded( fileName );
log.Info("Unload complete");
}
catch( Exception exception )
{
log.Error("Failed to unload tests", exception);
lastException = exception;
events.FireTestUnloadFailed( fileName, exception );
}
}
}
/// <summary>
/// Return true if the current project can be reloaded under
/// the specified CLR version.
/// </summary>
public bool CanReloadUnderRuntimeVersion(Version version)
{
if (!Services.TestAgency.IsRuntimeVersionSupported(version))
return false;
if (AssemblyInfo.Count == 0)
return false;
foreach (TestAssemblyInfo info in AssemblyInfo)
if (info == null || info.ImageRuntimeVersion > version)
return false;
return true;
}
/// <summary>
/// Reload the current test on command
/// </summary>
public void ReloadTest(RuntimeFramework framework)
{
log.Info("Reloading tests for " + Path.GetFileName(TestFileName));
try
{
events.FireTestReloading( TestFileName );
TestPackage package = MakeTestPackage(loadedTestName);
if (framework != null)
package.Settings["RuntimeFramework"] = framework;
RemoveWatcher();
testRunner.Unload();
if (!factory.CanReuse(testRunner, package))
{
testRunner.Dispose();
testRunner = factory.MakeTestRunner(package);
}
if (testRunner.Load(package))
this.currentFramework = package.Settings.Contains("RuntimeFramework")
? package.Settings["RuntimeFramework"] as RuntimeFramework
: RuntimeFramework.CurrentFramework;
currentRuntime = framework;
reloadPending = false;
if (Services.UserSettings.GetSetting("Options.TestLoader.ReloadOnChange", true))
InstallWatcher();
testProject.HasChangesRequiringReload = false;
events.FireTestReloaded(TestFileName, LoadedTest);
log.Info("Reload complete");
}
catch( Exception exception )
{
log.Error("Reload failed", exception);
lastException = exception;
events.FireTestReloadFailed( TestFileName, exception );
}
}
public void ReloadTest()
{
ReloadTest(currentRuntime);
}
/// <summary>
/// Handle watcher event that signals when the loaded assembly
/// file has changed. Make sure it's a real change before
/// firing the SuiteChangedEvent. Since this all happens
/// asynchronously, we use an event to let ui components
/// know that the failure happened.
/// </summary>
public void OnTestChanged( string testFileName )
{
log.Info("Assembly changed: {0}", testFileName);
if ( Running )
reloadPending = true;
else
{
ReloadTest();
if (lastFilter != null && Services.UserSettings.GetSetting("Options.TestLoader.RerunOnChange", false))
testRunner.BeginRun( this, lastFilter, lastTracing, lastLogLevel );
}
}
#endregion
#region Methods for Running Tests
/// <summary>
/// Run selected tests using a filter
/// </summary>
/// <param name="filter">The filter to be used</param>
public void RunTests( ITestFilter filter )
{
if ( !Running && LoadedTest != null)
{
if (reloadPending || Services.UserSettings.GetSetting("Options.TestLoader.ReloadOnRun", false))
ReloadTest();
// Save args for automatic rerun
this.lastFilter = filter;
this.lastTracing = tracing;
this.lastLogLevel = logLevel;
testRunner.BeginRun(this, filter, tracing, logLevel);
}
}
/// <summary>
/// Cancel the currently running test.
/// Fail silently if there is none to
/// allow for latency in the UI.
/// </summary>
public void CancelTestRun()
{
if ( Running )
testRunner.CancelRun();
}
public IList GetCategories()
{
CategoryManager categoryManager = new CategoryManager();
categoryManager.AddAllCategories( this.LoadedTest );
ArrayList list = new ArrayList( categoryManager.Categories );
list.Sort();
return list;
}
public void SaveLastResult( string fileName )
{
new XmlResultWriter( fileName ).SaveTestResult(this.testResult);
}
#endregion
#region Helper Methods
/// <summary>
/// Install our watcher object so as to get notifications
/// about changes to a test.
/// </summary>
private void InstallWatcher()
{
if (watcher != null)
{
watcher.Stop();
watcher.FreeResources();
watcher.Setup(1000, TestProject.ActiveConfig.Assemblies.ToArray());
watcher.AssemblyChanged += new AssemblyChangedHandler(OnTestChanged);
watcher.Start();
}
}
/// <summary>
/// Stop and remove our current watcher object.
/// </summary>
private void RemoveWatcher()
{
if (watcher != null)
{
watcher.Stop();
watcher.FreeResources();
watcher.AssemblyChanged -= new AssemblyChangedHandler(OnTestChanged);
}
}
private TestPackage MakeTestPackage( string testName )
{
TestPackage package = TestProject.ActiveConfig.MakeTestPackage();
package.TestName = testName;
ISettings userSettings = Services.UserSettings;
package.Settings["MergeAssemblies"] = userSettings.GetSetting("Options.TestLoader.MergeAssemblies", false);
package.Settings["AutoNamespaceSuites"] = userSettings.GetSetting("Options.TestLoader.AutoNamespaceSuites", true);
package.Settings["ShadowCopyFiles"] = userSettings.GetSetting("Options.TestLoader.ShadowCopyFiles", true);
ProcessModel processModel = (ProcessModel)userSettings.GetSetting("Options.TestLoader.ProcessModel", ProcessModel.Default);
DomainUsage domainUsage = (DomainUsage)userSettings.GetSetting("Options.TestLoader.DomainUsage", DomainUsage.Default);
if (processModel != ProcessModel.Default && // Ignore default setting
!package.Settings.Contains("ProcessModel")) // Ignore global setting if package has a setting
{
package.Settings["ProcessModel"] = processModel;
}
// NOTE: This code ignores DomainUsage.None because TestLoader
// is only called from the GUI and the GUI can't support that setting.
// TODO: Move this logic to the GUI if TestLoader is used more widely
if (domainUsage != DomainUsage.Default && // Ignore default setting
domainUsage != DomainUsage.None && // Ignore DomainUsage.None in Gui
(processModel != ProcessModel.Multiple ||
domainUsage != DomainUsage.Multiple) && // Both process and domain may not be multiple
!package.Settings.Contains("DomainUsage")) // Ignore global setting if package has a setting
{
package.Settings["DomainUsage"] = domainUsage;
}
if (!package.Settings.Contains("WorkDirectory"))
package.Settings["WorkDirectory"] = Environment.CurrentDirectory;
//if (NUnitConfiguration.ApartmentState != System.Threading.ApartmentState.Unknown)
// package.Settings["ApartmentState"] = NUnitConfiguration.ApartmentState;
return package;
}
#endregion
#region InitializeLifetimeService Override
public override object InitializeLifetimeService()
{
return null;
}
#endregion
#region IService Members
public void UnloadService()
{
// TODO: Add TestLoader.UnloadService implementation
}
public void InitializeService()
{
// TODO: Add TestLoader.InitializeService implementation
}
#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.
namespace System.Security {
using System.Security.Cryptography;
using System.Runtime.InteropServices;
#if FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ExceptionServices;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Text;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
public sealed class SecureString: IDisposable {
[System.Security.SecurityCritical] // auto-generated
private SafeBSTRHandle m_buffer;
[ContractPublicPropertyName("Length")]
private int m_length;
private bool m_readOnly;
private bool m_encrypted;
static bool supportedOnCurrentPlatform = EncryptionSupported();
const int BlockSize = (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE /2; // a char is two bytes
const int MaxLength = 65536;
const uint ProtectionScope = Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS;
[System.Security.SecuritySafeCritical] // auto-generated
static SecureString()
{
}
[System.Security.SecurityCritical] // auto-generated
unsafe static bool EncryptionSupported() {
// check if the enrypt/decrypt function is supported on current OS
bool supported = true;
try {
Win32Native.SystemFunction041(
SafeBSTRHandle.Allocate(null , (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE),
Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE,
Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS);
}
catch (EntryPointNotFoundException) {
supported = false;
}
return supported;
}
[System.Security.SecurityCritical] // auto-generated
internal SecureString(SecureString str) {
AllocateBuffer(str.BufferLength);
SafeBSTRHandle.Copy(str.m_buffer, this.m_buffer);
m_length = str.m_length;
m_encrypted = str.m_encrypted;
}
[System.Security.SecuritySafeCritical] // auto-generated
public SecureString() {
CheckSupportedOnCurrentPlatform();
// allocate the minimum block size for calling protectMemory
AllocateBuffer(BlockSize);
m_length = 0;
}
[System.Security.SecurityCritical] // auto-generated
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
private unsafe void InitializeSecureString(char* value, int length)
{
CheckSupportedOnCurrentPlatform();
AllocateBuffer(length);
m_length = length;
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy(bufferPtr, (byte*)value, length * 2);
}
catch (Exception) {
ProtectMemory();
throw;
}
finally
{
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
ProtectMemory();
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe SecureString(char* value, int length) {
if( value == null) {
throw new ArgumentNullException(nameof(value));
}
if( length < 0) {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if( length > MaxLength) {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Length"));
}
Contract.EndContractBlock();
// Refactored since HandleProcessCorruptedStateExceptionsAttribute applies to methods only (yet).
InitializeSecureString(value, length);
}
public int Length {
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
get {
EnsureNotDisposed();
return m_length;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void AppendChar(char c) {
EnsureNotDisposed();
EnsureNotReadOnly();
EnsureCapacity(m_length + 1);
RuntimeHelpers.PrepareConstrainedRegions();
try {
UnProtectMemory();
m_buffer.Write<char>((uint)m_length * sizeof(char), c);
m_length++;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
}
}
// clears the current contents. Only available if writable
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void Clear() {
EnsureNotDisposed();
EnsureNotReadOnly();
m_length = 0;
m_buffer.ClearBuffer();
m_encrypted = false;
}
// Do a deep-copy of the SecureString
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public SecureString Copy() {
EnsureNotDisposed();
return new SecureString(this);
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void Dispose() {
if(m_buffer != null && !m_buffer.IsInvalid) {
m_buffer.Close();
m_buffer = null;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void InsertAt( int index, char c ) {
if( index < 0 || index > m_length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
EnsureNotDisposed();
EnsureNotReadOnly();
EnsureCapacity(m_length + 1);
unsafe {
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = m_length; i > index; i--) {
pBuffer[i] = pBuffer[i - 1];
}
pBuffer[index] = c;
++m_length;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public bool IsReadOnly() {
EnsureNotDisposed();
return m_readOnly;
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void MakeReadOnly() {
EnsureNotDisposed();
m_readOnly = true;
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void RemoveAt( int index ) {
EnsureNotDisposed();
EnsureNotReadOnly();
if( index < 0 || index >= m_length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
unsafe
{
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = index; i < m_length - 1; i++)
{
pBuffer[i] = pBuffer[i + 1];
}
pBuffer[--m_length] = (char)0;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void SetAt( int index, char c ) {
if( index < 0 || index >= m_length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
Contract.Assert(index <= Int32.MaxValue / sizeof(char));
EnsureNotDisposed();
EnsureNotReadOnly();
RuntimeHelpers.PrepareConstrainedRegions();
try {
UnProtectMemory();
m_buffer.Write<char>((uint)index * sizeof(char), c);
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
}
}
private int BufferLength {
[System.Security.SecurityCritical] // auto-generated
get {
Contract.Assert(m_buffer != null, "Buffer is not initialized!");
return m_buffer.Length;
}
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void AllocateBuffer(int size) {
uint alignedSize = GetAlignedSize(size);
m_buffer = SafeBSTRHandle.Allocate(null, alignedSize);
if (m_buffer.IsInvalid) {
throw new OutOfMemoryException();
}
}
private void CheckSupportedOnCurrentPlatform() {
if( !supportedOnCurrentPlatform) {
throw new NotSupportedException(Environment.GetResourceString("Arg_PlatformSecureString"));
}
Contract.EndContractBlock();
}
[System.Security.SecurityCritical] // auto-generated
private void EnsureCapacity(int capacity) {
if( capacity > MaxLength) {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
Contract.EndContractBlock();
if( capacity <= m_buffer.Length) {
return;
}
SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(null, GetAlignedSize(capacity));
if (newBuffer.IsInvalid) {
throw new OutOfMemoryException();
}
SafeBSTRHandle.Copy(m_buffer, newBuffer);
m_buffer.Close();
m_buffer = newBuffer;
}
[System.Security.SecurityCritical] // auto-generated
private void EnsureNotDisposed() {
if( m_buffer == null) {
throw new ObjectDisposedException(null);
}
Contract.EndContractBlock();
}
private void EnsureNotReadOnly() {
if( m_readOnly) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static uint GetAlignedSize( int size) {
Contract.Assert(size >= 0, "size must be non-negative");
uint alignedSize = ((uint)size / BlockSize) * BlockSize;
if( (size % BlockSize != 0) || size == 0) { // if size is 0, set allocated size to blocksize
alignedSize += BlockSize;
}
return alignedSize;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe int GetAnsiByteCount() {
const uint CP_ACP = 0;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = WC_NO_BEST_FIT_CHARS;
uint DefaultCharUsed = (uint)'?';
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_buffer.AcquirePointer(ref bufferPtr);
return Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
(char*) bufferPtr,
m_length,
null,
0,
IntPtr.Zero,
new IntPtr((void*)&DefaultCharUsed));
}
finally {
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
[System.Security.SecurityCritical] // auto-generated
private unsafe void GetAnsiBytes( byte * ansiStrPtr, int byteCount) {
const uint CP_ACP = 0;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = WC_NO_BEST_FIT_CHARS;
uint DefaultCharUsed = (uint)'?';
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_buffer.AcquirePointer(ref bufferPtr);
Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
(char*) bufferPtr,
m_length,
ansiStrPtr,
byteCount - 1,
IntPtr.Zero,
new IntPtr((void*)&DefaultCharUsed));
*(ansiStrPtr + byteCount - 1) = (byte)0;
}
finally {
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private void ProtectMemory() {
Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0 || m_encrypted) {
return;
}
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
// RtlEncryptMemory return an NTSTATUS
int status = Win32Native.SystemFunction040(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope);
if (status < 0) { // non-negative numbers indicate success
#if FEATURE_CORECLR
throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status));
#else
throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
#endif
}
m_encrypted = true;
}
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal unsafe IntPtr ToBSTR() {
EnsureNotDisposed();
int length = m_length;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
ptr = Win32Native.SysAllocStringLen(null, length);
}
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
result = ptr;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
Win32Native.SysFreeString(ptr);
}
}
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal unsafe IntPtr ToUniStr(bool allocateFromHeap) {
EnsureNotDisposed();
int length = m_length;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
if( allocateFromHeap) {
ptr = Marshal.AllocHGlobal((length + 1) * 2);
}
else {
ptr = Marshal.AllocCoTaskMem((length + 1) * 2);
}
}
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
char * endptr = (char *) ptr.ToPointer();
*(endptr + length) = '\0';
result = ptr;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
if( allocateFromHeap) {
Marshal.FreeHGlobal(ptr);
}
else {
Marshal.FreeCoTaskMem(ptr);
}
}
}
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal unsafe IntPtr ToAnsiStr(bool allocateFromHeap) {
EnsureNotDisposed();
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
int byteCount = 0;
RuntimeHelpers.PrepareConstrainedRegions();
try {
// GetAnsiByteCount uses the string data, so the calculation must happen after we are decrypted.
UnProtectMemory();
// allocating an extra char for terminating zero
byteCount = GetAnsiByteCount() + 1;
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
if( allocateFromHeap) {
ptr = Marshal.AllocHGlobal(byteCount);
}
else {
ptr = Marshal.AllocCoTaskMem(byteCount);
}
}
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
GetAnsiBytes((byte *)ptr.ToPointer(), byteCount);
result = ptr;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount);
if( allocateFromHeap) {
Marshal.FreeHGlobal(ptr);
}
else {
Marshal.FreeCoTaskMem(ptr);
}
}
}
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void UnProtectMemory() {
Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0) {
return;
}
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
if (m_encrypted) {
// RtlEncryptMemory return an NTSTATUS
int status = Win32Native.SystemFunction041(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope);
if (status < 0)
{ // non-negative numbers indicate success
#if FEATURE_CORECLR
throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status));
#else
throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
#endif
}
m_encrypted = false;
}
}
}
}
[System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeBSTRHandle : SafeBuffer {
internal SafeBSTRHandle () : base(true) {}
internal static SafeBSTRHandle Allocate(String src, uint len)
{
SafeBSTRHandle bstr = SysAllocStringLen(src, len);
bstr.Initialize(len * sizeof(char));
return bstr;
}
[DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern SafeBSTRHandle SysAllocStringLen(String src, uint len); // BSTR
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
Win32Native.ZeroMemory(handle, (UIntPtr) (Win32Native.SysStringLen(handle) * 2));
Win32Native.SysFreeString(handle);
return true;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe void ClearBuffer() {
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
AcquirePointer(ref bufferPtr);
Win32Native.ZeroMemory((IntPtr)bufferPtr, (UIntPtr) (Win32Native.SysStringLen((IntPtr)bufferPtr) * 2));
}
finally
{
if (bufferPtr != null)
ReleasePointer();
}
}
internal unsafe int Length {
get {
return (int) Win32Native.SysStringLen(this);
}
}
internal unsafe static void Copy(SafeBSTRHandle source, SafeBSTRHandle target) {
byte* sourcePtr = null, targetPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
source.AcquirePointer(ref sourcePtr);
target.AcquirePointer(ref targetPtr);
Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2);
}
finally
{
if (sourcePtr != null)
source.ReleasePointer();
if (targetPtr != null)
target.ReleasePointer();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SafeBeaches.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("Navigation/PolyNavAgent")]
///Place this on a game object to find it's path
public class PolyNavAgent : MonoBehaviour{
///The max speed
public float maxSpeed = 3.5f;
///The object mass
public float mass = 20;
///The distance to stop at from the goal
public float stoppingDistance = 0.1f;
///The distance to start slowing down
public float slowingDistance = 1;
///The rate at which it will slow down
public float decelerationRate = 2;
///Go to closer point if requested is invalid?
public bool closerPointOnInvalid = false;
///Rotate transform as well?
public bool rotateTransform = false;
///Speed to rotate at
public float rotateSpeed = 350;
///The avoidance radius of the agent. 0 for no avoidance
public float avoidRadius = 0;
///The lookahead distance for Slowing down and agent avoidance. Set to 0 to eliminate the slowdown but the avoidance as well
public float lookAheadDistance = 1;
///If true will send messages to the game object to catch
public bool sendMessages = true;
///Will debug the path (gizmos)
public bool debugPath = true;
private Vector2 velocity = Vector2.zero;
private float maxForce = 100;
private int requests = 0;
private List<Vector2> _activePath = new List<Vector2>();
private Vector2 _primeGoal = new Vector2(Mathf.Infinity, Mathf.Infinity);
private GameObject _messageReceiver;
private Transform _transform;
private Action<bool> reachedCallback;
private static List<PolyNavAgent> allAgents = new List<PolyNavAgent>();
///The position of the agent
public Vector2 position{
get {return _transform.position;}
set {_transform.position = value;}
}
///The current active path of the agent
public List<Vector2> activePath{
get
{
return _activePath;
}
set
{
_activePath = value;
if (_activePath.Count > 0)
_activePath.RemoveAt(0);
}
}
///The current goal of the agent
public Vector2 primeGoal{
get { return _primeGoal;}
set { _primeGoal = value;}
}
///Is a path pending?
public bool pathPending{
get { return requests > 0;}
}
///The PolyNav singleton
public PolyNav2D polyNav{
get {return PolyNav2D.current;}
}
///Does the agent has a path?
public bool hasPath{
get { return activePath.Count > 0;}
}
///The point that the agent is currenty going to
public Vector2 nextPoint{
get
{
if (hasPath)
return activePath[0];
return position;
}
}
///The remaining distance of the active path. 0 if none
public float remainingDistance{
get
{
if (!hasPath)
return 0;
float dist= Vector2.Distance(position, activePath[0]);
for (int i= 0; i < activePath.Count; i++)
dist += Vector2.Distance(activePath[i], activePath[i == activePath.Count - 1? i : i + 1]);
return dist;
}
}
///The moving direction of the agent
public Vector2 movingDirection{
get
{
if (hasPath)
return velocity.normalized;
return Vector2.zero;
}
}
///The current speed of the agent
public float currentSpeed{
get {return velocity.magnitude;}
}
private GameObject messageReceiver{
get { return _messageReceiver? _messageReceiver : this.gameObject; }
set { _messageReceiver = value; }
}
//////
//////
void OnEnable(){
allAgents.Add(this);
}
void OnDisable(){
allAgents.Remove(this);
}
void Awake(){
_transform = transform;
}
///Set the destination for the agent. As a result the agent starts moving
public bool SetDestination(Vector2 goal){
return SetDestination(goal, null);
}
///Set the destination for the agent. As a result the agent starts moving. Only the callback from the last SetDestination will be called upon arrival
public bool SetDestination(Vector2 goal, Action<bool> callback){
if (!polyNav){
Debug.LogError("No PolyNav2D in scene!");
return false;
}
//goal is almost the same as the last goal. Nothing happens for performace in case it's called frequently
if ((goal - primeGoal).magnitude < Mathf.Epsilon)
return true;
reachedCallback = callback;
primeGoal = goal;
//goal is almost the same as agent position. We consider arrived immediately
if ((goal - position).magnitude < stoppingDistance){
OnArrived();
return true;
}
//check if goal is valid
if (!polyNav.PointIsValid(goal)){
if (closerPointOnInvalid){
SetDestination(polyNav.GetCloserEdgePoint(goal), callback);
return true;
} else {
OnInvalid();
return false;
}
}
//if a path is pending dont calculate new path
//the prime goal will be repathed anyway
if (requests > 0)
return true;
//compute path
requests++;
polyNav.FindPath(position, goal, SetPath);
return true;
}
///Clears the path and as a result the agent is stop moving
public void Stop(){
activePath.Clear();
velocity = Vector2.zero;
requests = 0;
primeGoal = position;
}
///Set the game object which to receive messages if sendMessages is set to true
public void SetMessageReceiver(GameObject go){
messageReceiver = go;
}
//the callback from polyNav for when path is ready to use
void SetPath(List<Vector2> path){
//in case the agent stoped somehow, but a path was pending
if (requests == 0)
return;
requests --;
if (path.Count == 0){
OnInvalid();
return;
}
activePath = path;
Message("OnNavigationStarted");
}
//main loop
void LateUpdate(){
if (!polyNav)
return;
//when there is no path just restrict
if (!hasPath){
Restrict();
return;
}
//calculate velocities
if (remainingDistance < slowingDistance){
velocity += Arrive(nextPoint) / mass;
} else {
velocity += Seek(nextPoint) / mass;
}
velocity = Truncate(velocity, maxSpeed);
//
//slow down if wall ahead
LookAhead();
//move the agent
position += velocity * Time.deltaTime;
//restrict just after movement
Restrict();
//rotate if must
if (rotateTransform){
float rot = -Mathf.Atan2(movingDirection.x, movingDirection.y) * 180 / Mathf.PI;
float newZ = Mathf.MoveTowardsAngle(transform.localEulerAngles.z, rot, rotateSpeed * Time.deltaTime);
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, newZ);
}
//repath if there is no LOS with the next point
if (polyNav.CheckLOS(position, nextPoint) == false)
Repath();
//in case after repath-ing there is no path
if (!hasPath){
OnArrived();
return;
}
//Check and remove if we reached a point. proximity distance depents
float proximity = (activePath[activePath.Count -1] == nextPoint)? stoppingDistance : 0.05f;
if ((position - nextPoint).magnitude <= proximity){
activePath.RemoveAt(0);
//if it was last point, means we dont still have an activePath
if (!hasPath){
OnArrived();
return;
} else {
//repath after a point is reached
Repath();
Message("OnNavigationPointReached");
}
}
//little trick. Check the next waypoint ahead of the current for LOS and if true consider the current reached.
//helps for tight corners and when agent has big innertia
if (activePath.Count > 1 && polyNav.CheckLOS(position, activePath[1])){
activePath.RemoveAt(0);
Message("OnNavigationPointReached");
}
}
//recalculate path to prime goal if there is no pending requests
void Repath(){
if (requests > 0)
return;
requests ++;
polyNav.FindPath(position, primeGoal, SetPath);
}
//stop the agent and callback + message
void OnArrived(){
Stop();
if (reachedCallback != null)
reachedCallback(true);
Message("OnDestinationReached");
}
//stop the agent and callback + message
void OnInvalid(){
Stop();
if (reachedCallback != null)
reachedCallback(false);
Message("OnDestinationInvalid");
}
//helper function for send messages
void Message(string msg){
if (sendMessages)
messageReceiver.SendMessage(msg, SendMessageOptions.DontRequireReceiver);
}
//seeking a target
Vector2 Seek(Vector2 pos){
Vector2 desiredVelocity= (pos - position).normalized * maxSpeed;
Vector2 steer= desiredVelocity - velocity;
steer = Truncate(steer, maxForce);
return steer;
}
//slowing at target's arrival
Vector2 Arrive(Vector2 pos){
var desiredVelocity = (pos - position);
float dist= desiredVelocity.magnitude;
if (dist > 0){
var reqSpeed = dist / (decelerationRate * 0.3f);
reqSpeed = Mathf.Min(reqSpeed, maxSpeed);
desiredVelocity *= reqSpeed / dist;
}
Vector2 steer= desiredVelocity - velocity;
steer = Truncate(steer, maxForce);
return steer;
}
//slowing when there is an obstacle ahead.
void LookAhead(){
if (lookAheadDistance <= 0)
return;
var currentLookAheadDistance= Mathf.Lerp(0, lookAheadDistance, velocity.magnitude/maxSpeed);
var lookAheadPos= position + velocity.normalized * currentLookAheadDistance;
Debug.DrawLine(position, lookAheadPos, Color.blue);
if (!polyNav.PointIsValid(lookAheadPos))
velocity -= (lookAheadPos - position);
if (avoidRadius > 0){
for (int i = 0; i < allAgents.Count; i++){
var otherAgent = allAgents[i];
if (otherAgent == this || otherAgent.avoidRadius <= 0)
continue;
var mlt = otherAgent.avoidRadius + this.avoidRadius;
var dist = (lookAheadPos - otherAgent.position).magnitude;
var str = (lookAheadPos - otherAgent.position).normalized * mlt;
var steer = Vector3.Lerp( (Vector3)str, Vector3.zero, dist/mlt);
velocity += (Vector2)steer;
Debug.DrawLine(otherAgent.position, otherAgent.position + str, new Color(1,0,0,0.1f));
}
}
}
//keep agent within valid area
void Restrict(){
if (!polyNav.PointIsValid(position))
position = polyNav.GetCloserEdgePoint(position);
}
//limit the magnitude of a vector
Vector2 Truncate(Vector2 vec, float max){
if (vec.magnitude > max) {
vec.Normalize();
vec *= max;
}
return vec;
}
////////////////////////////////////////
///////////GUI AND EDITOR STUFF/////////
////////////////////////////////////////
void OnDrawGizmos(){
Gizmos.color = new Color(1,1,1,0.1f);
Gizmos.DrawWireSphere(transform.position, avoidRadius);
if (!hasPath)
return;
if (debugPath){
Gizmos.color = new Color(1f, 1f, 1f, 0.2f);
Gizmos.DrawLine(position, activePath[0]);
for (int i= 0; i < activePath.Count; i++)
Gizmos.DrawLine(activePath[i], activePath[(i == activePath.Count - 1)? i : i + 1]);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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 DiscUtils.Streams;
namespace DiscUtils.Vdi
{
/// <summary>
/// Represents a single VirtualBox disk (.vdi file).
/// </summary>
public sealed class DiskImageFile : VirtualDiskLayer
{
private HeaderRecord _header;
/// <summary>
/// Indicates if this object controls the lifetime of the stream.
/// </summary>
private readonly Ownership _ownsStream;
private PreHeaderRecord _preHeader;
private Stream _stream;
/// <summary>
/// Indicates if a write occurred, indicating the marker in the header needs
/// to be updated.
/// </summary>
private bool _writeOccurred;
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="stream">The stream to interpret.</param>
public DiskImageFile(Stream stream)
{
_stream = stream;
ReadHeader();
}
/// <summary>
/// Initializes a new instance of the DiskImageFile class.
/// </summary>
/// <param name="stream">The stream to interpret.</param>
/// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param>
public DiskImageFile(Stream stream, Ownership ownsStream)
{
_stream = stream;
_ownsStream = ownsStream;
ReadHeader();
}
internal override long Capacity
{
get { return _header.DiskSize; }
}
/// <summary>
/// Gets (a guess at) the geometry of the virtual disk.
/// </summary>
public override Geometry Geometry
{
get
{
if (_header.LChsGeometry != null && _header.LChsGeometry.Cylinders != 0)
{
return _header.LChsGeometry.ToGeometry(_header.DiskSize);
}
if (_header.LegacyGeometry.Cylinders != 0)
{
return _header.LegacyGeometry.ToGeometry(_header.DiskSize);
}
return GeometryRecord.FromCapacity(_header.DiskSize).ToGeometry(_header.DiskSize);
}
}
/// <summary>
/// Gets a value indicating if the layer only stores meaningful sectors.
/// </summary>
public override bool IsSparse
{
get { return _header.ImageType != ImageType.Fixed; }
}
/// <summary>
/// Gets a value indicating whether the file is a differencing disk.
/// </summary>
public override bool NeedsParent
{
get { return _header.ImageType == ImageType.Differencing || _header.ImageType == ImageType.Undo; }
}
internal override FileLocator RelativeFileLocator
{
// Differencing disks not yet supported.
get { return null; }
}
/// <summary>
/// Initializes a stream as a fixed-sized VDI file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <returns>An object that accesses the stream as a VDI file.</returns>
public static DiskImageFile InitializeFixed(Stream stream, Ownership ownsStream, long capacity)
{
PreHeaderRecord preHeader = PreHeaderRecord.Initialized();
HeaderRecord header = HeaderRecord.Initialized(ImageType.Fixed, ImageFlags.None, capacity, 1024 * 1024, 0);
byte[] blockTable = new byte[header.BlockCount * 4];
for (int i = 0; i < header.BlockCount; ++i)
{
EndianUtilities.WriteBytesLittleEndian((uint)i, blockTable, i * 4);
}
header.BlocksAllocated = header.BlockCount;
stream.Position = 0;
preHeader.Write(stream);
header.Write(stream);
stream.Position = header.BlocksOffset;
stream.Write(blockTable, 0, blockTable.Length);
long totalSize = header.DataOffset + header.BlockSize * (long)header.BlockCount;
if (stream.Length < totalSize)
{
stream.SetLength(totalSize);
}
return new DiskImageFile(stream, ownsStream);
}
/// <summary>
/// Initializes a stream as a dynamically-sized VDI file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <returns>An object that accesses the stream as a VDI file.</returns>
public static DiskImageFile InitializeDynamic(Stream stream, Ownership ownsStream, long capacity)
{
PreHeaderRecord preHeader = PreHeaderRecord.Initialized();
HeaderRecord header = HeaderRecord.Initialized(ImageType.Dynamic, ImageFlags.None, capacity, 1024 * 1024, 0);
byte[] blockTable = new byte[header.BlockCount * 4];
for (int i = 0; i < blockTable.Length; ++i)
{
blockTable[i] = 0xFF;
}
header.BlocksAllocated = 0;
stream.Position = 0;
preHeader.Write(stream);
header.Write(stream);
stream.Position = header.BlocksOffset;
stream.Write(blockTable, 0, blockTable.Length);
return new DiskImageFile(stream, ownsStream);
}
/// <summary>
/// Opens the content of the disk image file as a stream.
/// </summary>
/// <param name="parent">The parent file's content (if any).</param>
/// <param name="ownsParent">Whether the created stream assumes ownership of parent stream.</param>
/// <returns>The new content stream.</returns>
public override SparseStream OpenContent(SparseStream parent, Ownership ownsParent)
{
if (parent != null && ownsParent == Ownership.Dispose)
{
// Not needed until differencing disks supported.
parent.Dispose();
}
DiskStream stream = new DiskStream(_stream, Ownership.None, _header);
stream.WriteOccurred += OnWriteOccurred;
return stream;
}
/// <summary>
/// Gets the possible locations of the parent file (if any).
/// </summary>
/// <returns>Array of strings, empty if no parent.</returns>
public override string[] GetParentLocations()
{
// Until diff/undo supported
return new string[0];
}
/// <summary>
/// Disposes of underlying resources.
/// </summary>
/// <param name="disposing">Set to <c>true</c> if called within Dispose(),
/// else <c>false</c>.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_writeOccurred && _stream != null)
{
_header.ModificationId = Guid.NewGuid();
_stream.Position = PreHeaderRecord.Size;
_header.Write(_stream);
}
if (_ownsStream == Ownership.Dispose && _stream != null)
{
_stream.Dispose();
_stream = null;
}
}
}
finally
{
base.Dispose(disposing);
}
}
private void ReadHeader()
{
_stream.Position = 0;
_preHeader = new PreHeaderRecord();
_preHeader.Read(_stream);
_header = new HeaderRecord();
_header.Read(_preHeader.Version, _stream);
}
private void OnWriteOccurred(object sender, EventArgs e)
{
_writeOccurred = true;
}
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Linq;
using OpenTK;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Mania.MathUtils;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Mania.Beatmaps.Patterns.Legacy
{
internal class HitObjectPatternGenerator : PatternGenerator
{
public PatternType StairType { get; private set; }
private readonly PatternType convertType;
public HitObjectPatternGenerator(FastRandom random, HitObject hitObject, Beatmap beatmap, int availableColumns, Pattern previousPattern, double previousTime, Vector2 previousPosition, double density, PatternType lastStair)
: base(random, hitObject, beatmap, availableColumns, previousPattern)
{
if (previousTime > hitObject.StartTime) throw new ArgumentOutOfRangeException(nameof(previousTime));
if (density < 0) throw new ArgumentOutOfRangeException(nameof(density));
StairType = lastStair;
TimingControlPoint timingPoint = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime);
EffectControlPoint effectPoint = beatmap.ControlPointInfo.EffectPointAt(hitObject.StartTime);
var positionData = hitObject as IHasPosition;
float positionSeparation = ((positionData?.Position ?? Vector2.Zero) - previousPosition).Length;
double timeSeparation = hitObject.StartTime - previousTime;
if (timeSeparation <= 80)
{
// More than 187 BPM
convertType |= PatternType.ForceNotStack | PatternType.KeepSingle;
}
else if (timeSeparation <= 95)
{
// More than 157 BPM
convertType |= PatternType.ForceNotStack | PatternType.KeepSingle | lastStair;
}
else if (timeSeparation <= 105)
{
// More than 140 BPM
convertType |= PatternType.ForceNotStack | PatternType.LowProbability;
}
else if (timeSeparation <= 125)
{
// More than 120 BPM
convertType |= PatternType.ForceNotStack;
}
else if (timeSeparation <= 135 && positionSeparation < 20)
{
// More than 111 BPM stream
convertType |= PatternType.Cycle | PatternType.KeepSingle;
}
else if (timeSeparation <= 150 && positionSeparation < 20)
{
// More than 100 BPM stream
convertType |= PatternType.ForceStack | PatternType.LowProbability;
}
else if (positionSeparation < 20 && density >= timingPoint.BeatLength / 2.5)
{
// Low density stream
convertType |= PatternType.Reverse | PatternType.LowProbability;
}
else if (density < timingPoint.BeatLength / 2.5 || effectPoint.KiaiMode)
{
// High density
}
else
convertType |= PatternType.LowProbability;
}
public override Pattern Generate()
{
int lastColumn = PreviousPattern.HitObjects.FirstOrDefault()?.Column ?? 0;
if ((convertType & PatternType.Reverse) > 0 && PreviousPattern.HitObjects.Any())
{
// Generate a new pattern by copying the last hit objects in reverse-column order
var pattern = new Pattern();
for (int i = RandomStart; i < AvailableColumns; i++)
if (PreviousPattern.ColumnHasObject(i))
addToPattern(pattern, RandomStart + AvailableColumns - i - 1);
return pattern;
}
if ((convertType & PatternType.Cycle) > 0 && PreviousPattern.HitObjects.Count() == 1
// If we convert to 7K + 1, let's not overload the special key
&& (AvailableColumns != 8 || lastColumn != 0)
// Make sure the last column was not the centre column
&& (AvailableColumns % 2 == 0 || lastColumn != AvailableColumns / 2))
{
// Generate a new pattern by cycling backwards (similar to Reverse but for only one hit object)
var pattern = new Pattern();
int column = RandomStart + AvailableColumns - lastColumn - 1;
addToPattern(pattern, column);
return pattern;
}
if ((convertType & PatternType.ForceStack) > 0 && PreviousPattern.HitObjects.Any())
{
// Generate a new pattern by placing on the already filled columns
var pattern = new Pattern();
for (int i = RandomStart; i < AvailableColumns; i++)
if (PreviousPattern.ColumnHasObject(i))
addToPattern(pattern, i);
return pattern;
}
if ((convertType & PatternType.Stair) > 0 && PreviousPattern.HitObjects.Count() == 1)
{
// Generate a new pattern by placing on the next column, cycling back to the start if there is no "next"
var pattern = new Pattern();
int targetColumn = lastColumn + 1;
if (targetColumn == AvailableColumns)
{
targetColumn = RandomStart;
StairType = PatternType.ReverseStair;
}
addToPattern(pattern, targetColumn);
return pattern;
}
if ((convertType & PatternType.ReverseStair) > 0 && PreviousPattern.HitObjects.Count() == 1)
{
// Generate a new pattern by placing on the previous column, cycling back to the end if there is no "previous"
var pattern = new Pattern();
int targetColumn = lastColumn - 1;
if (targetColumn == RandomStart - 1)
{
targetColumn = AvailableColumns - 1;
StairType = PatternType.Stair;
}
addToPattern(pattern, targetColumn);
return pattern;
}
if ((convertType & PatternType.KeepSingle) > 0)
return generateRandomNotes(1);
if ((convertType & PatternType.Mirror) > 0)
{
if (ConversionDifficulty > 6.5)
return generateRandomPatternWithMirrored(0.12, 0.38, 0.12);
if (ConversionDifficulty > 4)
return generateRandomPatternWithMirrored(0.12, 0.17, 0);
return generateRandomPatternWithMirrored(0.12, 0, 0);
}
if (ConversionDifficulty > 6.5)
{
if ((convertType & PatternType.LowProbability) > 0)
return generateRandomPattern(0.78, 0.42, 0, 0);
return generateRandomPattern(1, 0.62, 0, 0);
}
if (ConversionDifficulty > 4)
{
if ((convertType & PatternType.LowProbability) > 0)
return generateRandomPattern(0.35, 0.08, 0, 0);
return generateRandomPattern(0.52, 0.15, 0, 0);
}
if (ConversionDifficulty > 2)
{
if ((convertType & PatternType.LowProbability) > 0)
return generateRandomPattern(0.18, 0, 0, 0);
return generateRandomPattern(0.45, 0, 0, 0);
}
return generateRandomPattern(0, 0, 0, 0);
}
/// <summary>
/// Generates random notes.
/// <para>
/// This will generate as many as it can up to <paramref name="noteCount"/>, accounting for
/// any stacks if <see cref="convertType"/> is forcing no stacks.
/// </para>
/// </summary>
/// <param name="noteCount">The amount of notes to generate.</param>
/// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
private Pattern generateRandomNotes(int noteCount)
{
var pattern = new Pattern();
bool allowStacking = (convertType & PatternType.ForceNotStack) == 0;
if (!allowStacking)
noteCount = Math.Min(noteCount, AvailableColumns - RandomStart - PreviousPattern.ColumnWithObjects);
int nextColumn = GetColumn((HitObject as IHasXPosition)?.X ?? 0, true);
for (int i = 0; i < noteCount; i++)
{
while (pattern.ColumnHasObject(nextColumn) || PreviousPattern.ColumnHasObject(nextColumn) && !allowStacking)
{
if ((convertType & PatternType.Gathered) > 0)
{
nextColumn++;
if (nextColumn == AvailableColumns)
nextColumn = RandomStart;
}
else
nextColumn = Random.Next(RandomStart, AvailableColumns);
}
addToPattern(pattern, nextColumn);
}
return pattern;
}
/// <summary>
/// Whether this hit object can generate a note in the special column.
/// </summary>
private bool hasSpecialColumn => HitObject.Samples.Any(s => s.Name == SampleInfo.HIT_CLAP) && HitObject.Samples.Any(s => s.Name == SampleInfo.HIT_FINISH);
/// <summary>
/// Generates a random pattern.
/// </summary>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <param name="p4">Probability for 4 notes to be generated.</param>
/// <param name="p5">Probability for 5 notes to be generated.</param>
/// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
private Pattern generateRandomPattern(double p2, double p3, double p4, double p5)
{
var pattern = new Pattern();
pattern.Add(generateRandomNotes(getRandomNoteCount(p2, p3, p4, p5)));
if (RandomStart > 0 && hasSpecialColumn)
addToPattern(pattern, 0);
return pattern;
}
/// <summary>
/// Generates a random pattern which has both normal and mirrored notes.
/// </summary>
/// <param name="centreProbability">The probability for a note to be added to the centre column.</param>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
private Pattern generateRandomPatternWithMirrored(double centreProbability, double p2, double p3)
{
var pattern = new Pattern();
bool addToCentre;
int noteCount = getRandomNoteCountMirrored(centreProbability, p2, p3, out addToCentre);
int columnLimit = (AvailableColumns % 2 == 0 ? AvailableColumns : AvailableColumns - 1) / 2;
int nextColumn = Random.Next(RandomStart, columnLimit);
for (int i = 0; i < noteCount; i++)
{
while (pattern.ColumnHasObject(nextColumn))
nextColumn = Random.Next(RandomStart, columnLimit);
// Add normal note
addToPattern(pattern, nextColumn);
// Add mirrored note
addToPattern(pattern, RandomStart + AvailableColumns - nextColumn - 1);
}
if (addToCentre)
addToPattern(pattern, AvailableColumns / 2);
if (RandomStart > 0 && hasSpecialColumn)
addToPattern(pattern, 0);
return pattern;
}
/// <summary>
/// Generates a count of notes to be generated from a list of probabilities.
/// </summary>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <param name="p4">Probability for 4 notes to be generated.</param>
/// <param name="p5">Probability for 5 notes to be generated.</param>
/// <returns>The amount of notes to be generated.</returns>
private int getRandomNoteCount(double p2, double p3, double p4, double p5)
{
switch (AvailableColumns)
{
case 2:
p2 = 0;
p3 = 0;
p4 = 0;
p5 = 0;
break;
case 3:
p2 = Math.Max(p2, 0.1);
p3 = 0;
p4 = 0;
p5 = 0;
break;
case 4:
p2 = Math.Max(p2, 0.23);
p3 = Math.Max(p3, 0.04);
p4 = 0;
p5 = 0;
break;
case 5:
p3 = Math.Max(p3, 0.15);
p4 = Math.Max(p4, 0.03);
p5 = 0;
break;
}
if (HitObject.Samples.Any(s => s.Name == SampleInfo.HIT_CLAP))
p2 = 1;
return GetRandomNoteCount(p2, p3, p4, p5);
}
/// <summary>
/// Generates a count of notes to be generated from a list of probabilities.
/// </summary>
/// <param name="centreProbability">The probability for a note to be added to the centre column.</param>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <param name="addToCentre">Whether to add a note to the centre column.</param>
/// <returns>The amount of notes to be generated. The note to be added to the centre column will NOT be part of this count.</returns>
private int getRandomNoteCountMirrored(double centreProbability, double p2, double p3, out bool addToCentre)
{
addToCentre = false;
if ((convertType & PatternType.ForceNotStack) > 0)
return getRandomNoteCount(p2 / 2, p2, (p2 + p3) / 2, p3);
switch (AvailableColumns)
{
case 2:
centreProbability = 0;
p2 = 0;
p3 = 0;
break;
case 3:
centreProbability = Math.Max(centreProbability, 0.03);
p2 = Math.Max(p2, 0.1);
p3 = 0;
break;
case 4:
centreProbability = 0;
p2 = Math.Max(p2 * 2, 0.2);
p3 = 0;
break;
case 5:
centreProbability = Math.Max(centreProbability, 0.03);
p3 = 0;
break;
case 6:
centreProbability = 0;
p2 = Math.Max(p2 * 2, 0.5);
p3 = Math.Max(p3 * 2, 0.15);
break;
}
double centreVal = Random.NextDouble();
int noteCount = GetRandomNoteCount(p2, p3);
addToCentre = AvailableColumns % 2 != 0 && noteCount != 3 && centreVal > 1 - centreProbability;
return noteCount;
}
/// <summary>
/// Constructs and adds a note to a pattern.
/// </summary>
/// <param name="pattern">The pattern to add to.</param>
/// <param name="column">The column to add the note to.</param>
private void addToPattern(Pattern pattern, int column)
{
pattern.Add(new Note
{
StartTime = HitObject.StartTime,
Samples = HitObject.Samples,
Column = column
});
}
}
}
| |
//-----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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 Microsoft.IdentityModel.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
namespace System.IdentityModel.Test
{
/// <summary>
/// Test some key extensibility scenarios
/// </summary>
[TestClass]
public class ExtensibilityTests
{
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
public TestContext TestContext { get; set; }
[ClassInitialize]
public static void ClassSetup(TestContext testContext)
{ }
[ClassCleanup]
public static void ClassCleanup()
{ }
[TestInitialize]
public void Initialize()
{
_testContextProvider = new TestContextProvider(TestContext);
}
[TestMethod]
[TestProperty("TestCaseID", "65A4AD1F-100F-41C3-AD84-4FE08C1F9A6D")]
[Description("Extensibility tests for JwtSecurityTokenHandler")]
public void JwtSecurityTokenHandler_Extensibility()
{
DerivedJwtSecurityTokenHandler handler = new DerivedJwtSecurityTokenHandler()
{
DerivedTokenType = typeof(DerivedJwtSecurityToken)
};
JwtSecurityToken jwt =
new JwtSecurityToken
(
issuer: Issuers.GotJwt,
audience: Audiences.AuthFactors,
claims: ClaimSets.Simple(Issuers.GotJwt, Issuers.GotJwt),
signingCredentials: KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2,
expires: DateTime.UtcNow + TimeSpan.FromHours(10),
notBefore: DateTime.UtcNow
);
string encodedJwt = handler.WriteToken(jwt);
TokenValidationParameters tvp = new TokenValidationParameters()
{
IssuerSigningKey = KeyingMaterial.DefaultSymmetricSecurityKey_256,
ValidateAudience = false,
ValidIssuer = Issuers.GotJwt,
};
ValidateDerived(encodedJwt, handler, tvp, ExpectedException.NoExceptionExpected);
}
private void ValidateDerived(string jwt, DerivedJwtSecurityTokenHandler handler, TokenValidationParameters validationParameters, ExpectedException expectedException)
{
try
{
SecurityToken validatedToken;
handler.ValidateToken(jwt, validationParameters, out validatedToken);
Assert.IsNotNull(handler.Jwt as DerivedJwtSecurityToken);
Assert.IsTrue(handler.ReadTokenCalled);
Assert.IsFalse(handler.ValidateAudienceCalled);
Assert.IsTrue(handler.ValidateIssuerCalled);
Assert.IsTrue(handler.ValidateIssuerSigningKeyCalled);
Assert.IsTrue(handler.ValidateLifetimeCalled);
Assert.IsTrue(handler.ValidateSignatureCalled);
expectedException.ProcessNoException();
}
catch (Exception ex)
{
expectedException.ProcessException(ex);
}
}
[TestMethod]
[TestProperty("TestCaseID", "65A4AD1F-100F-41C3-AD84-4FE08C1F9A6D")]
[Description("Extensibility tests for NamedKeySecurityKeyIdentifierClause")]
public void NamedKeySecurityKeyIdentifierClause_Extensibility()
{
string clauseName = "kid";
string keyId = Issuers.GotJwt;
NamedKeySecurityKeyIdentifierClause clause = new NamedKeySecurityKeyIdentifierClause(clauseName, keyId);
SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(clause);
SigningCredentials signingCredentials = new SigningCredentials(KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest, keyIdentifier);
JwtHeader jwtHeader = new JwtHeader(signingCredentials);
SecurityKeyIdentifier ski = jwtHeader.SigningKeyIdentifier;
Assert.AreEqual(ski.Count, 1, "ski.Count != 1 ");
NamedKeySecurityKeyIdentifierClause clauseOut = ski.Find<NamedKeySecurityKeyIdentifierClause>();
Assert.IsNotNull(clauseOut, "NamedKeySecurityKeyIdentifierClause not found");
Assert.AreEqual(clauseOut.Name, clauseName, "clauseOut.Id != clauseId");
Assert.AreEqual(clauseOut.Id, keyId, "clauseOut.KeyIdentifier != keyId");
NamedKeySecurityToken NamedKeySecurityToken = new NamedKeySecurityToken(clauseName, keyId, new SecurityKey[] { KeyingMaterial.DefaultSymmetricSecurityKey_256 });
Assert.IsTrue(NamedKeySecurityToken.MatchesKeyIdentifierClause(clause), "NamedKeySecurityToken.MatchesKeyIdentifierClause( clause ), failed");
List<SecurityKey> list = new List<SecurityKey>() { KeyingMaterial.DefaultSymmetricSecurityKey_256 };
Dictionary<string, IList<SecurityKey>> keys = new Dictionary<string, IList<SecurityKey>>() { { "kid", list }, };
NamedKeyIssuerTokenResolver nkitr = new NamedKeyIssuerTokenResolver(keys: keys);
SecurityKey sk = nkitr.ResolveSecurityKey(clause);
Assert.IsNotNull(sk, "NamedKeySecurityToken.MatchesKeyIdentifierClause( clause ), failed");
}
[TestMethod]
[TestProperty("TestCaseID", "C4FC2FC1-5AB0-4A73-A620-59D1FBF92D7A")]
[Description("Algorithm names can be mapped inbound and outbound (AsymmetricSignatureProvider)")]
public void AsymmetricSignatureProvider_Extensibility()
{
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
string newAlgorithmValue = "bobsYourUncle";
string originalAlgorithmValue = ReplaceAlgorithm(SecurityAlgorithms.RsaSha256Signature, newAlgorithmValue, JwtSecurityTokenHandler.OutboundAlgorithmMap);
JwtSecurityToken jwt = handler.CreateToken(issuer: IdentityUtilities.DefaultIssuer, audience: IdentityUtilities.DefaultAudience, signingCredentials: KeyingMaterial.DefaultX509SigningCreds_2048_RsaSha2_Sha2) as JwtSecurityToken;
ReplaceAlgorithm(SecurityAlgorithms.RsaSha256Signature, originalAlgorithmValue, JwtSecurityTokenHandler.OutboundAlgorithmMap);
// outbound mapped algorithm is "bobsYourUncle", inbound map will not find this
ExpectedException expectedException = ExpectedException.SignatureVerificationFailedException(substringExpected: "IDX10502:", innerTypeExpected: typeof(InvalidOperationException));
RunAlgorithmMappingTest(jwt.RawData, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, handler, expectedException);
// inbound is mapped to Rsa256
originalAlgorithmValue = ReplaceAlgorithm(newAlgorithmValue, SecurityAlgorithms.RsaSha256Signature, JwtSecurityTokenHandler.InboundAlgorithmMap);
RunAlgorithmMappingTest(jwt.RawData, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, handler, ExpectedException.NoExceptionExpected);
ReplaceAlgorithm(newAlgorithmValue, originalAlgorithmValue, JwtSecurityTokenHandler.InboundAlgorithmMap);
}
[TestMethod]
[TestProperty("TestCaseID", "A8068888-87D8-49D6-919F-CDF9AAC26F57")]
[Description("Algorithm names can be mapped inbound and outbound (SymmetricSignatureProvider)")]
public void SymmetricSignatureProvider_Extensibility()
{
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
string newAlgorithmValue = "bobsYourUncle";
string originalAlgorithmValue = ReplaceAlgorithm(SecurityAlgorithms.HmacSha256Signature, newAlgorithmValue, JwtSecurityTokenHandler.OutboundAlgorithmMap);
JwtSecurityToken jwt = handler.CreateToken(issuer: IdentityUtilities.DefaultIssuer, audience: IdentityUtilities.DefaultAudience, signingCredentials: KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2) as JwtSecurityToken;
ReplaceAlgorithm(SecurityAlgorithms.HmacSha256Signature, originalAlgorithmValue, JwtSecurityTokenHandler.OutboundAlgorithmMap);
// outbound mapped algorithm is "bobsYourUncle", inbound map will not find this
ExpectedException expectedException = ExpectedException.SignatureVerificationFailedException(innerTypeExpected: typeof(InvalidOperationException), substringExpected: "IDX10503:");
RunAlgorithmMappingTest(jwt.RawData, IdentityUtilities.DefaultSymmetricTokenValidationParameters, handler, expectedException);
// inbound is mapped Hmac
originalAlgorithmValue = ReplaceAlgorithm(newAlgorithmValue, SecurityAlgorithms.HmacSha256Signature, JwtSecurityTokenHandler.InboundAlgorithmMap);
RunAlgorithmMappingTest(jwt.RawData, IdentityUtilities.DefaultSymmetricTokenValidationParameters, handler, ExpectedException.NoExceptionExpected);
ReplaceAlgorithm(newAlgorithmValue, originalAlgorithmValue, JwtSecurityTokenHandler.InboundAlgorithmMap);
}
private void RunAlgorithmMappingTest(string jwt, TokenValidationParameters validationParameters, JwtSecurityTokenHandler handler, ExpectedException expectedException)
{
try
{
SecurityToken validatedToken;
handler.ValidateToken(jwt, validationParameters, out validatedToken);
expectedException.ProcessNoException();
}
catch (Exception ex)
{
expectedException.ProcessException(ex);
}
}
private string ReplaceAlgorithm(string algorithmKey, string newAlgorithmValue, IDictionary<string, string> algorithmMap)
{
string originalAlgorithmValue = null;
if (algorithmMap.TryGetValue(algorithmKey, out originalAlgorithmValue))
{
algorithmMap.Remove(algorithmKey);
}
if (!string.IsNullOrWhiteSpace(newAlgorithmValue))
{
algorithmMap.Add(algorithmKey, newAlgorithmValue);
}
return originalAlgorithmValue;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.CRLDPConfigurationBinding", Namespace="urn:iControl")]
public partial class ManagementCRLDPConfiguration : iControlInterface {
public ManagementCRLDPConfiguration() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void add_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("add_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginadd_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endadd_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void create(
string [] config_names,
string [] [] servers
) {
this.Invoke("create", new object [] {
config_names,
servers});
}
public System.IAsyncResult Begincreate(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_configurations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void delete_all_configurations(
) {
this.Invoke("delete_all_configurations", new object [0]);
}
public System.IAsyncResult Begindelete_all_configurations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_configurations", new object[0], callback, asyncState);
}
public void Enddelete_all_configurations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void delete_configuration(
string [] config_names
) {
this.Invoke("delete_configuration", new object [] {
config_names});
}
public System.IAsyncResult Begindelete_configuration(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_configuration", new object[] {
config_names}, callback, asyncState);
}
public void Enddelete_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_cache_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_cache_timeout(
string [] config_names
) {
object [] results = this.Invoke("get_cache_timeout", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_cache_timeout(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cache_timeout", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_cache_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_connection_timeout(
string [] config_names
) {
object [] results = this.Invoke("get_connection_timeout", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_connection_timeout(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_timeout", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_connection_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] config_names
) {
object [] results = this.Invoke("get_description", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_server(
string [] config_names
) {
object [] results = this.Invoke("get_server", new object [] {
config_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_server(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_server", new object[] {
config_names}, callback, asyncState);
}
public string [] [] Endget_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_update_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_update_interval(
string [] config_names
) {
object [] results = this.Invoke("get_update_interval", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_update_interval(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_update_interval", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_update_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_use_issuer_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_use_issuer_state(
string [] config_names
) {
object [] results = this.Invoke("get_use_issuer_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_use_issuer_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_use_issuer_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_use_issuer_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_servers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void remove_all_servers(
string [] config_names
) {
this.Invoke("remove_all_servers", new object [] {
config_names});
}
public System.IAsyncResult Beginremove_all_servers(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_servers", new object[] {
config_names}, callback, asyncState);
}
public void Endremove_all_servers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void remove_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("remove_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginremove_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endremove_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cache_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void set_cache_timeout(
string [] config_names,
long [] timeouts
) {
this.Invoke("set_cache_timeout", new object [] {
config_names,
timeouts});
}
public System.IAsyncResult Beginset_cache_timeout(string [] config_names,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cache_timeout", new object[] {
config_names,
timeouts}, callback, asyncState);
}
public void Endset_cache_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void set_connection_timeout(
string [] config_names,
long [] timeouts
) {
this.Invoke("set_connection_timeout", new object [] {
config_names,
timeouts});
}
public System.IAsyncResult Beginset_connection_timeout(string [] config_names,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_timeout", new object[] {
config_names,
timeouts}, callback, asyncState);
}
public void Endset_connection_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void set_description(
string [] config_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
config_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] config_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
config_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_update_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void set_update_interval(
string [] config_names,
long [] intervals
) {
this.Invoke("set_update_interval", new object [] {
config_names,
intervals});
}
public System.IAsyncResult Beginset_update_interval(string [] config_names,long [] intervals, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_update_interval", new object[] {
config_names,
intervals}, callback, asyncState);
}
public void Endset_update_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_use_issuer_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CRLDPConfiguration",
RequestNamespace="urn:iControl:Management/CRLDPConfiguration", ResponseNamespace="urn:iControl:Management/CRLDPConfiguration")]
public void set_use_issuer_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_use_issuer_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_use_issuer_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_use_issuer_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_use_issuer_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
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 InvestmentApi.Web.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 System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
using System.Reflection;
using Signum.Entities.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Collections.Concurrent;
namespace Signum.Entities
{
[Serializable, DescriptionOptions(DescriptionOptions.All), InTypeScript(false)]
public abstract class Entity : ModifiableEntity, IEntity
{
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal PrimaryKey? id;
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never), ColumnName("ToStr")]
protected internal string? toStr; //for queries and lites on entities with non-expression ToString
[HiddenProperty, Description("Id")]
public PrimaryKey Id
{
get
{
if (id == null)
throw new InvalidOperationException("{0} is new and has no Id".FormatWith(this.GetType().Name));
return id.Value;
}
internal set { id = value; } //Use SetId method to change the Id
}
[HiddenProperty]
public PrimaryKey? IdOrNull
{
get { return id; }
}
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool isNew = true;
[HiddenProperty]
public bool IsNew
{
get { return isNew; }
internal set { isNew = value; }
}
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal long ticks;
[HiddenProperty]
public long Ticks
{
get { return ticks; }
set { ticks = value; }
}
protected bool SetIfNew<T>(ref T field, T value, [CallerMemberName]string? automaticPropertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
if (!IsNew)
{
throw new InvalidOperationException("Attempt to modify '{0}' when the entity is not new".FormatWith(automaticPropertyName));
}
return base.Set<T>(ref field, value, automaticPropertyName!);
}
public override string ToString()
{
return BaseToString();
}
public string BaseToString()
{
return "{0} ({1})".FormatWith(GetType().NiceName(), id.HasValue ? id.ToString() : LiteMessage.New_G.NiceToString().ForGenderAndNumber(this.GetType().GetGender()));
}
public override bool Equals(object? obj)
{
if(obj == this)
return true;
if(obj == null)
return false;
if (obj is Entity ident && ident.GetType() == this.GetType() && this.id != null && this.id == ident.id)
return true;
return false;
}
public virtual Dictionary<Guid, IntegrityCheck>? EntityIntegrityCheck()
{
using (Mixins.OfType<CorruptMixin>().Any(c => c.Corrupt) ? Corruption.AllowScope() : null)
{
return EntityIntegrityCheckBase();
}
}
internal virtual Dictionary<Guid, IntegrityCheck>? EntityIntegrityCheckBase()
{
using (HeavyProfiler.LogNoStackTrace("EntityIntegrityCheckBase", () => GetType().Name))
return GraphExplorer.EntityIntegrityCheck(GraphExplorer.FromRootEntity(this));
}
public override int GetHashCode()
{
return id == null ?
base.GetHashCode() :
StringHashEncoder.GetHashCode32(GetType().FullName!) ^ id.Value.GetHashCode();
}
public void SetGraphErrors(IntegrityCheckException ex)
{
GraphExplorer.SetValidationErrors(GraphExplorer.FromRoot(this), ex);
}
}
[InTypeScript(false)]
public interface IEntity : IModifiableEntity, IRootEntity
{
PrimaryKey Id { get; }
[HiddenProperty]
PrimaryKey? IdOrNull { get; }
[HiddenProperty]
bool IsNew { get; }
[HiddenProperty]
string ToStringProperty { get; }
}
public interface IRootEntity
{
}
public static class UnsafeEntityExtensions
{
public static T SetId<T>(this T entity, PrimaryKey? id)
where T : Entity
{
entity.id = id;
return entity;
}
public static T SetReadonly<T, V>(this T entity, Expression<Func<T, V>> readonlyProperty, V value)
where T : ModifiableEntity
{
return SetReadonly(entity, readonlyProperty, value, true);
}
public static T SetReadonly<T, V>(this T entity, Expression<Func<T, V>> readonlyProperty, V value, bool setSelfModified)
where T : ModifiableEntity
{
var pi = ReflectionTools.BasePropertyInfo(readonlyProperty);
Action<T, V> setter = ReadonlySetterCache<T>.Setter<V>(pi);
setter(entity, value);
if (setSelfModified)
entity.SetSelfModified();
return entity;
}
static class ReadonlySetterCache<T> where T : ModifiableEntity
{
static ConcurrentDictionary<string, Delegate> cache = new ConcurrentDictionary<string, Delegate>();
internal static Action<T, V> Setter<V>(PropertyInfo pi)
{
return (Action<T, V>)cache.GetOrAdd(pi.Name, s => ReflectionTools.CreateSetter<T, V>(Reflector.FindFieldInfo(typeof(T), pi))!);
}
}
public static T SetIsNew<T>(this T entity, bool isNew = true)
where T : Entity
{
entity.IsNew = isNew;
entity.SetSelfModified();
return entity;
}
public static T SetNotModified<T>(this T mod)
where T : Modifiable
{
if (mod is Entity)
((Entity)(Modifiable)mod).IsNew = false;
mod.Modified = ModifiedState.Clean; /*Compiler bug*/
return mod;
}
public static T SetModified<T>(this T entity)
where T : Modifiable
{
entity.Modified = ModifiedState.Modified;
return entity;
}
public static T SetNotModifiedGraph<T>(this T entity, PrimaryKey id)
where T : Entity
{
foreach (var item in GraphExplorer.FromRoot(entity).Where(a => a.Modified != ModifiedState.Sealed))
{
item.SetNotModified();
if (item is Entity e && e.IdOrNull == null)
e.SetId(new PrimaryKey("invalidId"));
}
entity.SetId(id);
return entity;
}
}
public static class EntityContext
{
public static PrimaryKey EntityId(object obj)
{
throw new InvalidOperationException("EntityContext.EntityId can only be called inside LINQ queries");
}
public static PrimaryKey? MListRowId(object obj)
{
throw new NotImplementedException("EntityContext.MListRowId can only be called inside LINQ queries");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.